You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2410 lines
60 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. #!/usr/bin/env sh
  2. VER=2.2.4
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  7. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  8. DEFAULT_USER_AGENT="$PROJECT_ENTRY client: $PROJECT"
  9. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  10. VTYPE_HTTP="http-01"
  11. VTYPE_DNS="dns-01"
  12. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  13. END_CSR="-----END CERTIFICATE REQUEST-----"
  14. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  15. END_CERT="-----END CERTIFICATE-----"
  16. if [ -z "$AGREEMENT" ] ; then
  17. AGREEMENT="$DEFAULT_AGREEMENT"
  18. fi
  19. _URGLY_PRINTF=""
  20. if [ "$(printf '\x41')" != 'A' ] ; then
  21. _URGLY_PRINTF=1
  22. fi
  23. _info() {
  24. if [ -z "$2" ] ; then
  25. echo "[$(date)] $1"
  26. else
  27. echo "[$(date)] $1"="'$2'"
  28. fi
  29. }
  30. _err() {
  31. _info "$@" >&2
  32. return 1
  33. }
  34. _debug() {
  35. if [ -z "$DEBUG" ] ; then
  36. return
  37. fi
  38. _err "$@"
  39. return 0
  40. }
  41. _debug2() {
  42. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  43. _debug "$@"
  44. fi
  45. return
  46. }
  47. _startswith(){
  48. _str="$1"
  49. _sub="$2"
  50. echo $_str | grep ^$_sub >/dev/null 2>&1
  51. }
  52. _contains(){
  53. _str="$1"
  54. _sub="$2"
  55. echo $_str | grep $_sub >/dev/null 2>&1
  56. }
  57. _hasfield() {
  58. _str="$1"
  59. _field="$2"
  60. _sep="$3"
  61. if [ -z "$_field" ] ; then
  62. _err "Usage: str field [sep]"
  63. return 1
  64. fi
  65. if [ -z "$_sep" ] ; then
  66. _sep=","
  67. fi
  68. for f in $(echo "$_str" | tr ',' ' ') ; do
  69. if [ "$f" = "$_field" ] ; then
  70. _debug "'$_str' contains '$_field'"
  71. return 0 #contains ok
  72. fi
  73. done
  74. _debug "'$_str' does not contain '$_field'"
  75. return 1 #not contains
  76. }
  77. _exists(){
  78. cmd="$1"
  79. if [ -z "$cmd" ] ; then
  80. _err "Usage: _exists cmd"
  81. return 1
  82. fi
  83. if type command >/dev/null 2>&1 ; then
  84. command -v $cmd >/dev/null 2>&1
  85. else
  86. type $cmd >/dev/null 2>&1
  87. fi
  88. ret="$?"
  89. _debug2 "$cmd exists=$ret"
  90. return $ret
  91. }
  92. #a + b
  93. _math(){
  94. expr "$@"
  95. }
  96. _h_char_2_dec() {
  97. _ch=$1
  98. case "${_ch}" in
  99. a|A)
  100. echo -n 10
  101. ;;
  102. b|B)
  103. echo -n 11
  104. ;;
  105. c|C)
  106. echo -n 12
  107. ;;
  108. d|D)
  109. echo -n 13
  110. ;;
  111. e|E)
  112. echo -n 14
  113. ;;
  114. f|F)
  115. echo -n 15
  116. ;;
  117. *)
  118. echo -n $_ch
  119. ;;
  120. esac
  121. }
  122. _h2b() {
  123. hex=$(cat)
  124. i=1
  125. j=2
  126. if _exists let ; then
  127. uselet="1"
  128. fi
  129. _debug uselet "$uselet"
  130. _debug _URGLY_PRINTF "$_URGLY_PRINTF"
  131. while [ '1' ] ; do
  132. if [ -z "$_URGLY_PRINTF" ] ; then
  133. h=$(printf $hex | cut -c $i-$j)
  134. if [ -z "$h" ] ; then
  135. break;
  136. fi
  137. printf "\x$h"
  138. else
  139. ic=$(printf $hex | cut -c $i)
  140. jc=$(printf $hex | cut -c $j)
  141. if [ -z "$ic$jc" ] ; then
  142. break;
  143. fi
  144. ic="$(_h_char_2_dec $ic)"
  145. jc="$(_h_char_2_dec $jc)"
  146. printf '\'"$(printf %o "$(_math $ic \* 16 + $jc)")"
  147. fi
  148. if [ "$uselet" ] ; then
  149. let "i+=2" >/dev/null
  150. let "j+=2" >/dev/null
  151. else
  152. i="$(_math $i + 2)"
  153. j="$(_math $j + 2)"
  154. fi
  155. done
  156. }
  157. #options file
  158. _sed_i() {
  159. options="$1"
  160. filename="$2"
  161. if [ -z "$filename" ] ; then
  162. _err "Usage:_sed_i options filename"
  163. return 1
  164. fi
  165. _debug2 options "$options"
  166. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  167. _debug "Using sed -i"
  168. sed -i "$options" "$filename"
  169. else
  170. _debug "No -i support in sed"
  171. text="$(cat $filename)"
  172. echo "$text" | sed "$options" > "$filename"
  173. fi
  174. }
  175. #Usage: file startline endline
  176. _getfile() {
  177. filename="$1"
  178. startline="$2"
  179. endline="$3"
  180. if [ -z "$endline" ] ; then
  181. _err "Usage: file startline endline"
  182. return 1
  183. fi
  184. i="$(grep -n -- "$startline" $filename | cut -d : -f 1)"
  185. if [ -z "$i" ] ; then
  186. _err "Can not find start line: $startline"
  187. return 1
  188. fi
  189. i="$(_math $i + 1)"
  190. _debug i $i
  191. j="$(grep -n -- "$endline" $filename | cut -d : -f 1)"
  192. if [ -z "$j" ] ; then
  193. _err "Can not find end line: $endline"
  194. return 1
  195. fi
  196. j="$(_math $j - 1)"
  197. _debug j $j
  198. sed -n $i,${j}p "$filename"
  199. }
  200. #Usage: multiline
  201. _base64() {
  202. if [ "$1" ] ; then
  203. openssl base64 -e
  204. else
  205. openssl base64 -e | tr -d '\r\n'
  206. fi
  207. }
  208. #Usage: multiline
  209. _dbase64() {
  210. if [ "$1" ] ; then
  211. openssl base64 -d -A
  212. else
  213. openssl base64 -d
  214. fi
  215. }
  216. #Usage: hashalg
  217. #Output Base64-encoded digest
  218. _digest() {
  219. alg="$1"
  220. if [ -z "$alg" ] ; then
  221. _err "Usage: _digest hashalg"
  222. return 1
  223. fi
  224. if [ "$alg" = "sha256" ] ; then
  225. openssl dgst -sha256 -binary | _base64
  226. else
  227. _err "$alg is not supported yet"
  228. return 1
  229. fi
  230. }
  231. #Usage: keyfile hashalg
  232. #Output: Base64-encoded signature value
  233. _sign() {
  234. keyfile="$1"
  235. alg="$2"
  236. if [ -z "$alg" ] ; then
  237. _err "Usage: _sign keyfile hashalg"
  238. return 1
  239. fi
  240. if [ "$alg" = "sha256" ] ; then
  241. openssl dgst -sha256 -sign "$keyfile" | _base64
  242. else
  243. _err "$alg is not supported yet"
  244. return 1
  245. fi
  246. }
  247. _ss() {
  248. _port="$1"
  249. if _exists "ss" ; then
  250. _debug "Using: ss"
  251. ss -ntpl | grep :$_port" "
  252. return 0
  253. fi
  254. if _exists "netstat" ; then
  255. _debug "Using: netstat"
  256. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  257. #for windows version netstat tool
  258. netstat -anb -p tcp | grep "LISTENING" | grep :$_port" "
  259. else
  260. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  261. netstat -an -p tcp | grep LISTEN | grep :$_port" "
  262. else
  263. netstat -ntpl | grep :$_port" "
  264. fi
  265. fi
  266. return 0
  267. fi
  268. return 1
  269. }
  270. toPkcs() {
  271. domain="$1"
  272. pfxPassword="$2"
  273. if [ -z "$domain" ] ; then
  274. echo "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  275. return 1
  276. fi
  277. _initpath "$domain"
  278. if [ "$pfxPassword" ] ; then
  279. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  280. else
  281. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  282. fi
  283. if [ "$?" = "0" ] ; then
  284. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  285. fi
  286. }
  287. #domain [2048]
  288. createAccountKey() {
  289. _info "Creating account key"
  290. if [ -z "$1" ] ; then
  291. echo Usage: $PROJECT_ENTRY --createAccountKey -d domain.com [--accountkeylength 2048]
  292. return
  293. fi
  294. account=$1
  295. length=$2
  296. _debug account "$account"
  297. _debug length "$length"
  298. if _startswith "$length" "ec-" ; then
  299. length=2048
  300. fi
  301. if [ -z "$2" ] || [ "$2" = "no" ] ; then
  302. _info "Use default length 2048"
  303. length=2048
  304. fi
  305. _initpath
  306. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  307. _info "Account key exists, skip"
  308. return
  309. else
  310. #generate account key
  311. openssl genrsa $length 2>/dev/null > "$ACCOUNT_KEY_PATH"
  312. fi
  313. }
  314. #domain length
  315. createDomainKey() {
  316. _info "Creating domain key"
  317. if [ -z "$1" ] ; then
  318. echo Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]
  319. return
  320. fi
  321. domain=$1
  322. length=$2
  323. isec=""
  324. if _startswith "$length" "ec-" ; then
  325. isec="1"
  326. length=$(printf $length | cut -d '-' -f 2-100)
  327. eccname="$length"
  328. fi
  329. if [ -z "$length" ] ; then
  330. if [ "$isec" ] ; then
  331. length=256
  332. else
  333. length=2048
  334. fi
  335. fi
  336. _info "Use length $length"
  337. if [ "$isec" ] ; then
  338. if [ "$length" = "256" ] ; then
  339. eccname="prime256v1"
  340. fi
  341. if [ "$length" = "384" ] ; then
  342. eccname="secp384r1"
  343. fi
  344. if [ "$length" = "521" ] ; then
  345. eccname="secp521r1"
  346. fi
  347. _info "Using ec name: $eccname"
  348. fi
  349. _initpath $domain
  350. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  351. #generate account key
  352. if [ "$isec" ] ; then
  353. openssl ecparam -name $eccname -genkey 2>/dev/null > "$CERT_KEY_PATH"
  354. else
  355. openssl genrsa $length 2>/dev/null > "$CERT_KEY_PATH"
  356. fi
  357. else
  358. if [ "$IS_RENEW" ] ; then
  359. _info "Domain key exists, skip"
  360. return 0
  361. else
  362. _err "Domain key exists, do you want to overwrite the key?"
  363. _err "Add '--force', and try again."
  364. return 1
  365. fi
  366. fi
  367. }
  368. # domain domainlist
  369. createCSR() {
  370. _info "Creating csr"
  371. if [ -z "$1" ] ; then
  372. echo Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]
  373. return
  374. fi
  375. domain=$1
  376. _initpath $domain
  377. domainlist=$2
  378. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  379. _info "CSR exists, skip"
  380. return
  381. fi
  382. if [ -z "$domainlist" ] || [ "$domainlist" = "no" ]; then
  383. #single domain
  384. _info "Single domain" $domain
  385. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$DOMAIN_SSL_CONF"
  386. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  387. else
  388. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  389. #multi
  390. _info "Multi domain" "$alt"
  391. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n[SAN]\nsubjectAltName=$alt" > "$DOMAIN_SSL_CONF"
  392. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -reqexts SAN -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  393. fi
  394. }
  395. _urlencode() {
  396. __n=$(cat)
  397. echo $__n | tr '/+' '_-' | tr -d '= '
  398. }
  399. _time2str() {
  400. #BSD
  401. if date -u -d@$1 2>/dev/null ; then
  402. return
  403. fi
  404. #Linux
  405. if date -u -r $1 2>/dev/null ; then
  406. return
  407. fi
  408. }
  409. _stat() {
  410. #Linux
  411. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  412. return
  413. fi
  414. #BSD
  415. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  416. return
  417. fi
  418. }
  419. #keyfile
  420. _calcjwk() {
  421. keyfile="$1"
  422. if [ -z "$keyfile" ] ; then
  423. _err "Usage: _calcjwk keyfile"
  424. return 1
  425. fi
  426. EC_SIGN=""
  427. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  428. _debug "RSA key"
  429. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  430. if [ "${#pub_exp}" = "5" ] ; then
  431. pub_exp=0$pub_exp
  432. fi
  433. _debug2 pub_exp "$pub_exp"
  434. e=$(echo $pub_exp | _h2b | _base64)
  435. _debug2 e "$e"
  436. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  437. _debug2 modulus "$modulus"
  438. n=$(echo -n $modulus| _h2b | _base64 | _urlencode )
  439. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  440. _debug2 jwk "$jwk"
  441. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  442. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  443. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  444. _debug "EC key"
  445. EC_SIGN="1"
  446. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  447. _debug2 crv $crv
  448. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  449. pubi=$(_math $pubi + 1)
  450. _debug2 pubi $pubi
  451. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  452. pubj=$(_math $pubj + 1)
  453. _debug2 pubj $pubj
  454. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  455. _debug2 pubtext "$pubtext"
  456. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  457. xlen=$(_math $xlen / 4)
  458. _debug2 xlen $xlen
  459. xend=$(_math $xend + 1)
  460. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  461. _debug2 x $x
  462. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  463. _debug2 x64 $x64
  464. xend=$(_math $xend + 1)
  465. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  466. _debug2 y $y
  467. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  468. _debug2 y64 $y64
  469. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  470. _debug2 jwk "$jwk"
  471. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  472. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  473. else
  474. _err "Only RSA or EC key is supported."
  475. return 1
  476. fi
  477. _debug2 HEADER "$HEADER"
  478. }
  479. # body url [needbase64] [POST]
  480. _post() {
  481. body="$1"
  482. url="$2"
  483. needbase64="$3"
  484. httpmethod="$4"
  485. if [ -z "$httpmethod" ] ; then
  486. httpmethod="POST"
  487. fi
  488. _debug $httpmethod
  489. if _exists "curl" ; then
  490. CURL="$CURL --dump-header $HTTP_HEADER "
  491. if [ "$needbase64" ] ; then
  492. response="$($CURL -A "User-Agent: $USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" --data "$body" $url | _base64)"
  493. else
  494. response="$($CURL -A "User-Agent: $USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" --data "$body" $url)"
  495. fi
  496. else
  497. if [ "$needbase64" ] ; then
  498. response="$($WGET -S -O - --user-agent="$USER_AGENT" --method $httpmethod --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --body-data="$body" $url 2>"$HTTP_HEADER" | _base64)"
  499. else
  500. response="$($WGET -S -O - --user-agent="$USER_AGENT" --method $httpmethod --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --body-data="$body" $url 2>"$HTTP_HEADER")"
  501. fi
  502. _sed_i "s/^ *//g" "$HTTP_HEADER"
  503. fi
  504. echo -n "$response"
  505. }
  506. # url getheader
  507. _get() {
  508. _debug GET
  509. url="$1"
  510. onlyheader="$2"
  511. _debug url $url
  512. if _exists "curl" ; then
  513. if [ "$onlyheader" ] ; then
  514. $CURL -I -A "User-Agent: $USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" $url
  515. else
  516. $CURL -A "User-Agent: $USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" $url
  517. fi
  518. else
  519. _debug "WGET" "$WGET"
  520. if [ "$onlyheader" ] ; then
  521. $WGET --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  522. else
  523. $WGET --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - $url
  524. fi
  525. fi
  526. ret=$?
  527. return $ret
  528. }
  529. # url payload needbase64 keyfile
  530. _send_signed_request() {
  531. url=$1
  532. payload=$2
  533. needbase64=$3
  534. keyfile=$4
  535. if [ -z "$keyfile" ] ; then
  536. keyfile="$ACCOUNT_KEY_PATH"
  537. fi
  538. _debug url $url
  539. _debug payload "$payload"
  540. if ! _calcjwk "$keyfile" ; then
  541. return 1
  542. fi
  543. payload64=$(echo -n $payload | _base64 | _urlencode)
  544. _debug2 payload64 $payload64
  545. nonceurl="$API/directory"
  546. nonce="$(_get $nonceurl "onlyheader" | grep -o "Replay-Nonce:.*$" | head -1 | tr -d "\r\n" | cut -d ' ' -f 2)"
  547. _debug nonce "$nonce"
  548. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  549. _debug2 protected "$protected"
  550. protected64="$(printf "$protected" | _base64 | _urlencode)"
  551. _debug2 protected64 "$protected64"
  552. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  553. _debug2 sig "$sig"
  554. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  555. _debug2 body "$body"
  556. response="$(_post "$body" $url "$needbase64" )"
  557. responseHeaders="$(cat $HTTP_HEADER)"
  558. _debug2 responseHeaders "$responseHeaders"
  559. _debug2 response "$response"
  560. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  561. _debug code $code
  562. }
  563. #setopt "file" "opt" "=" "value" [";"]
  564. _setopt() {
  565. __conf="$1"
  566. __opt="$2"
  567. __sep="$3"
  568. __val="$4"
  569. __end="$5"
  570. if [ -z "$__opt" ] ; then
  571. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  572. return
  573. fi
  574. if [ ! -f "$__conf" ] ; then
  575. touch "$__conf"
  576. fi
  577. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  578. _debug2 OK
  579. if _contains "$__val" "&" ; then
  580. __val="$(echo $__val | sed 's/&/\\&/g')"
  581. fi
  582. text="$(cat $__conf)"
  583. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  584. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  585. if _contains "$__val" "&" ; then
  586. __val="$(echo $__val | sed 's/&/\\&/g')"
  587. fi
  588. text="$(cat $__conf)"
  589. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  590. else
  591. _debug2 APP
  592. echo "$__opt$__sep$__val$__end" >> "$__conf"
  593. fi
  594. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  595. }
  596. #_savedomainconf key value
  597. #save to domain.conf
  598. _savedomainconf() {
  599. key="$1"
  600. value="$2"
  601. if [ "$DOMAIN_CONF" ] ; then
  602. _setopt "$DOMAIN_CONF" "$key" "=" "\"$value\""
  603. else
  604. _err "DOMAIN_CONF is empty, can not save $key=$value"
  605. fi
  606. }
  607. #_cleardomainconf key
  608. _cleardomainconf() {
  609. key="$1"
  610. if [ "$DOMAIN_CONF" ] ; then
  611. _sed_i "s/^$key.*$//" "$DOMAIN_CONF"
  612. else
  613. _err "DOMAIN_CONF is empty, can not save $key=$value"
  614. fi
  615. }
  616. #_saveaccountconf key value
  617. _saveaccountconf() {
  618. key="$1"
  619. value="$2"
  620. if [ "$ACCOUNT_CONF_PATH" ] ; then
  621. _setopt "$ACCOUNT_CONF_PATH" "$key" "=" "\"$value\""
  622. else
  623. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  624. fi
  625. }
  626. _startserver() {
  627. content="$1"
  628. _debug "startserver: $$"
  629. nchelp="$(nc -h 2>&1)"
  630. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  631. _NC="nc -q 1 -l"
  632. else
  633. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  634. _NC="nc -c -l"
  635. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  636. _NC="nc -N -l"
  637. else
  638. _NC="nc -l"
  639. fi
  640. fi
  641. _debug "_NC" "$_NC"
  642. # while true ; do
  643. if [ "$DEBUG" ] ; then
  644. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort ; then
  645. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort ;
  646. fi
  647. else
  648. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  649. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  650. fi
  651. fi
  652. if [ "$?" != "0" ] ; then
  653. _err "nc listen error."
  654. exit 1
  655. fi
  656. # done
  657. }
  658. _stopserver(){
  659. pid="$1"
  660. _debug "pid" "$pid"
  661. if [ -z "$pid" ] ; then
  662. return
  663. fi
  664. _get "http://localhost:$Le_HTTPPort" >/dev/null 2>&1
  665. }
  666. _initpath() {
  667. if [ -z "$LE_WORKING_DIR" ] ; then
  668. LE_WORKING_DIR=$HOME/.$PROJECT_NAME
  669. fi
  670. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  671. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  672. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ] ; then
  673. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  674. fi
  675. fi
  676. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  677. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  678. fi
  679. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  680. . "$ACCOUNT_CONF_PATH"
  681. fi
  682. if [ "$IN_CRON" ] ; then
  683. if [ ! "$_USER_PATH_EXPORTED" ] ; then
  684. _USER_PATH_EXPORTED=1
  685. export PATH="$USER_PATH:$PATH"
  686. fi
  687. fi
  688. if [ -z "$API" ] ; then
  689. if [ -z "$STAGE" ] ; then
  690. API="$DEFAULT_CA"
  691. else
  692. API="$STAGE_CA"
  693. _info "Using stage api:$API"
  694. fi
  695. fi
  696. if [ -z "$ACME_DIR" ] ; then
  697. ACME_DIR="/home/.acme"
  698. fi
  699. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  700. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  701. fi
  702. if [ -z "$USER_AGENT" ] ; then
  703. USER_AGENT="$DEFAULT_USER_AGENT"
  704. fi
  705. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  706. WGET="wget -q"
  707. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  708. WGET="$WGET -d "
  709. fi
  710. dp="$LE_WORKING_DIR/curl.dump"
  711. CURL="curl -L --silent"
  712. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  713. CURL="$CURL -L --trace-ascii $dp "
  714. fi
  715. _DEFAULT_ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  716. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  717. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  718. fi
  719. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  720. if [ -z "$CERT_HOME" ] ; then
  721. CERT_HOME="$_DEFAULT_CERT_HOME"
  722. fi
  723. domain="$1"
  724. if [ -z "$domain" ] ; then
  725. return 0
  726. fi
  727. domainhome="$CERT_HOME/$domain"
  728. mkdir -p "$domainhome"
  729. if [ -z "$DOMAIN_PATH" ] ; then
  730. DOMAIN_PATH="$domainhome"
  731. fi
  732. if [ -z "$DOMAIN_CONF" ] ; then
  733. DOMAIN_CONF="$domainhome/$domain.conf"
  734. fi
  735. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  736. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  737. fi
  738. if [ -z "$CSR_PATH" ] ; then
  739. CSR_PATH="$domainhome/$domain.csr"
  740. fi
  741. if [ -z "$CERT_KEY_PATH" ] ; then
  742. CERT_KEY_PATH="$domainhome/$domain.key"
  743. fi
  744. if [ -z "$CERT_PATH" ] ; then
  745. CERT_PATH="$domainhome/$domain.cer"
  746. fi
  747. if [ -z "$CA_CERT_PATH" ] ; then
  748. CA_CERT_PATH="$domainhome/ca.cer"
  749. fi
  750. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  751. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  752. fi
  753. if [ -z "$CERT_PFX_PATH" ] ; then
  754. CERT_PFX_PATH="$domainhome/$domain.pfx"
  755. fi
  756. }
  757. _apachePath() {
  758. if ! _exists apachectl ; then
  759. _err "'apachecrl not found. It seems that apache is not installed, or you are not root user.'"
  760. _err "Please use webroot mode to try again."
  761. return 1
  762. fi
  763. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  764. if _startswith "$httpdconfname" '/' ; then
  765. httpdconf="$httpdconfname"
  766. httpdconfname="$(basename $httpdconfname)"
  767. else
  768. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  769. httpdconf="$httpdroot/$httpdconfname"
  770. fi
  771. if [ ! -f $httpdconf ] ; then
  772. _err "Apache Config file not found" $httpdconf
  773. return 1
  774. fi
  775. return 0
  776. }
  777. _restoreApache() {
  778. if [ -z "$usingApache" ] ; then
  779. return 0
  780. fi
  781. _initpath
  782. if ! _apachePath ; then
  783. return 1
  784. fi
  785. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  786. _debug "No config file to restore."
  787. return 0
  788. fi
  789. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" > "$httpdconf"
  790. _debug "Restored: $httpdconf."
  791. if ! apachectl -t ; then
  792. _err "Sorry, restore apache config error, please contact me."
  793. return 1;
  794. fi
  795. _debug "Restored successfully."
  796. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  797. return 0
  798. }
  799. _setApache() {
  800. _initpath
  801. if ! _apachePath ; then
  802. return 1
  803. fi
  804. #backup the conf
  805. _debug "Backup apache config file" $httpdconf
  806. cp $httpdconf $APACHE_CONF_BACKUP_DIR/
  807. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  808. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  809. _info "The backup file will be deleted on sucess, just forget it."
  810. #add alias
  811. apacheVer="$(apachectl -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  812. _debug "apacheVer" "$apacheVer"
  813. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  814. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  815. if [ "$apacheVer" ] && [ "$apacheMajer" -ge "2" ] && [ "$apacheMinor" -ge "4" ] ; then
  816. echo "
  817. Alias /.well-known/acme-challenge $ACME_DIR
  818. <Directory $ACME_DIR >
  819. Require all granted
  820. </Directory>
  821. " >> $httpdconf
  822. else
  823. echo "
  824. Alias /.well-known/acme-challenge $ACME_DIR
  825. <Directory $ACME_DIR >
  826. Order allow,deny
  827. Allow from all
  828. </Directory>
  829. " >> $httpdconf
  830. fi
  831. if ! apachectl -t ; then
  832. _err "Sorry, apache config error, please contact me."
  833. _restoreApache
  834. return 1;
  835. fi
  836. if [ ! -d "$ACME_DIR" ] ; then
  837. mkdir -p "$ACME_DIR"
  838. chmod 755 "$ACME_DIR"
  839. fi
  840. if ! apachectl graceful ; then
  841. _err "Sorry, apachectl graceful error, please contact me."
  842. _restoreApache
  843. return 1;
  844. fi
  845. usingApache="1"
  846. return 0
  847. }
  848. _clearup() {
  849. _stopserver $serverproc
  850. serverproc=""
  851. _restoreApache
  852. }
  853. # webroot removelevel tokenfile
  854. _clearupwebbroot() {
  855. __webroot="$1"
  856. if [ -z "$__webroot" ] ; then
  857. _debug "no webroot specified, skip"
  858. return 0
  859. fi
  860. if [ "$2" = '1' ] ; then
  861. _debug "remove $__webroot/.well-known"
  862. rm -rf "$__webroot/.well-known"
  863. elif [ "$2" = '2' ] ; then
  864. _debug "remove $__webroot/.well-known/acme-challenge"
  865. rm -rf "$__webroot/.well-known/acme-challenge"
  866. elif [ "$2" = '3' ] ; then
  867. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  868. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  869. else
  870. _info "Skip for removelevel:$2"
  871. fi
  872. return 0
  873. }
  874. issue() {
  875. if [ -z "$2" ] ; then
  876. echo "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  877. return 1
  878. fi
  879. Le_Webroot="$1"
  880. Le_Domain="$2"
  881. Le_Alt="$3"
  882. Le_Keylength="$4"
  883. Le_RealCertPath="$5"
  884. Le_RealKeyPath="$6"
  885. Le_RealCACertPath="$7"
  886. Le_ReloadCmd="$8"
  887. Le_RealFullChainPath="$9"
  888. #remove these later.
  889. if [ "$Le_Webroot" = "dns-cf" ] ; then
  890. Le_Webroot="dns_cf"
  891. fi
  892. if [ "$Le_Webroot" = "dns-dp" ] ; then
  893. Le_Webroot="dns_dp"
  894. fi
  895. if [ "$Le_Webroot" = "dns-cx" ] ; then
  896. Le_Webroot="dns_cx"
  897. fi
  898. _initpath $Le_Domain
  899. if [ -f "$DOMAIN_CONF" ] ; then
  900. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2 | tr -d "'\"")
  901. _debug Le_NextRenewTime "$Le_NextRenewTime"
  902. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ $(date -u "+%s" ) -lt $Le_NextRenewTime ] ; then
  903. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  904. return 2
  905. fi
  906. fi
  907. _savedomainconf "Le_Domain" "$Le_Domain"
  908. _savedomainconf "Le_Alt" "$Le_Alt"
  909. _savedomainconf "Le_Webroot" "$Le_Webroot"
  910. _savedomainconf "Le_Keylength" "$Le_Keylength"
  911. if [ "$Le_Alt" = "no" ] ; then
  912. Le_Alt=""
  913. fi
  914. if [ "$Le_Keylength" = "no" ] ; then
  915. Le_Keylength=""
  916. fi
  917. if _hasfield "$Le_Webroot" "no" ; then
  918. _info "Standalone mode."
  919. if ! _exists "nc" ; then
  920. _err "Please install netcat(nc) tools first."
  921. return 1
  922. fi
  923. if [ -z "$Le_HTTPPort" ] ; then
  924. Le_HTTPPort=80
  925. fi
  926. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  927. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  928. if [ "$netprc" ] ; then
  929. _err "$netprc"
  930. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  931. _err "Please stop it first"
  932. return 1
  933. fi
  934. fi
  935. if _hasfield "$Le_Webroot" "apache" ; then
  936. if ! _setApache ; then
  937. _err "set up apache error. Report error to me."
  938. return 1
  939. fi
  940. else
  941. usingApache=""
  942. fi
  943. if [ ! -f "$ACCOUNT_KEY_PATH" ] ; then
  944. if ! createAccountKey $Le_Domain $Le_Keylength ; then
  945. _err "Create account key error."
  946. if [ "$usingApache" ] ; then
  947. _restoreApache
  948. fi
  949. return 1
  950. fi
  951. fi
  952. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  953. if [ "$usingApache" ] ; then
  954. _restoreApache
  955. fi
  956. return 1
  957. fi
  958. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  959. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  960. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  961. accountkeyhash="$(echo $accountkeyhash$API | _digest "sha256" )"
  962. if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
  963. _info "Registering account"
  964. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  965. if [ "$ACCOUNT_EMAIL" ] ; then
  966. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  967. fi
  968. _send_signed_request "$API/acme/new-reg" "$regjson"
  969. if [ "$code" = "" ] || [ "$code" = '201' ] ; then
  970. _info "Registered"
  971. echo $response > $LE_WORKING_DIR/account.json
  972. elif [ "$code" = '409' ] ; then
  973. _info "Already registered"
  974. else
  975. _err "Register account Error: $response"
  976. _clearup
  977. return 1
  978. fi
  979. ACCOUNT_KEY_HASH="$accountkeyhash"
  980. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  981. else
  982. _info "Skip register account key"
  983. fi
  984. if [ ! -f "$CERT_KEY_PATH" ] ; then
  985. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  986. _err "Create domain key error."
  987. _clearup
  988. return 1
  989. fi
  990. fi
  991. if ! createCSR $Le_Domain $Le_Alt ; then
  992. _err "Create CSR error."
  993. _clearup
  994. return 1
  995. fi
  996. vlist="$Le_Vlist"
  997. # verify each domain
  998. _info "Verify each domain"
  999. sep='#'
  1000. if [ -z "$vlist" ] ; then
  1001. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  1002. _index=1
  1003. _currentRoot=""
  1004. for d in $alldomains
  1005. do
  1006. _info "Getting webroot for domain" $d
  1007. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  1008. _debug _w "$_w"
  1009. if [ "$_w" ] ; then
  1010. _currentRoot="$_w"
  1011. fi
  1012. _debug "_currentRoot" "$_currentRoot"
  1013. _index=$(_math $_index + 1)
  1014. vtype="$VTYPE_HTTP"
  1015. if _startswith "$_currentRoot" "dns" ; then
  1016. vtype="$VTYPE_DNS"
  1017. fi
  1018. _info "Getting token for domain" $d
  1019. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  1020. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  1021. _err "new-authz error: $response"
  1022. _clearup
  1023. return 1
  1024. fi
  1025. entry="$(printf "$response" | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  1026. _debug entry "$entry"
  1027. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  1028. _debug token $token
  1029. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  1030. _debug uri $uri
  1031. keyauthorization="$token.$thumbprint"
  1032. _debug keyauthorization "$keyauthorization"
  1033. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  1034. _debug dvlist "$dvlist"
  1035. vlist="$vlist$dvlist,"
  1036. done
  1037. #add entry
  1038. dnsadded=""
  1039. ventries=$(echo "$vlist" | tr ',' ' ' )
  1040. for ventry in $ventries
  1041. do
  1042. d=$(echo $ventry | cut -d $sep -f 1)
  1043. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1044. vtype=$(echo $ventry | cut -d $sep -f 4)
  1045. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1046. if [ "$vtype" = "$VTYPE_DNS" ] ; then
  1047. dnsadded='0'
  1048. txtdomain="_acme-challenge.$d"
  1049. _debug txtdomain "$txtdomain"
  1050. txt="$(echo -n $keyauthorization | _digest "sha256" | _urlencode)"
  1051. _debug txt "$txt"
  1052. #dns
  1053. #1. check use api
  1054. d_api=""
  1055. if [ -f "$LE_WORKING_DIR/$d/$_currentRoot" ] ; then
  1056. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  1057. elif [ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ] ; then
  1058. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  1059. elif [ -f "$LE_WORKING_DIR/$_currentRoot" ] ; then
  1060. d_api="$LE_WORKING_DIR/$_currentRoot"
  1061. elif [ -f "$LE_WORKING_DIR/$_currentRoot.sh" ] ; then
  1062. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  1063. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ] ; then
  1064. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  1065. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ] ; then
  1066. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  1067. fi
  1068. _debug d_api "$d_api"
  1069. if [ "$d_api" ] ; then
  1070. _info "Found domain api file: $d_api"
  1071. else
  1072. _err "Add the following TXT record:"
  1073. _err "Domain: $txtdomain"
  1074. _err "TXT value: $txt"
  1075. _err "Please be aware that you prepend _acme-challenge. before your domain"
  1076. _err "so the resulting subdomain will be: $txtdomain"
  1077. continue
  1078. fi
  1079. (
  1080. if ! . $d_api ; then
  1081. _err "Load file $d_api error. Please check your api file and try again."
  1082. return 1
  1083. fi
  1084. addcommand="${_currentRoot}_add"
  1085. if ! _exists $addcommand ; then
  1086. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1087. return 1
  1088. fi
  1089. if ! $addcommand $txtdomain $txt ; then
  1090. _err "Error add txt for domain:$txtdomain"
  1091. return 1
  1092. fi
  1093. )
  1094. if [ "$?" != "0" ] ; then
  1095. _clearup
  1096. return 1
  1097. fi
  1098. dnsadded='1'
  1099. fi
  1100. done
  1101. if [ "$dnsadded" = '0' ] ; then
  1102. _savedomainconf "Le_Vlist" "$vlist"
  1103. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1104. _err "Please add the TXT records to the domains, and retry again."
  1105. _clearup
  1106. return 1
  1107. fi
  1108. fi
  1109. if [ "$dnsadded" = '1' ] ; then
  1110. _info "Sleep 60 seconds for the txt records to take effect"
  1111. sleep 60
  1112. fi
  1113. _debug "ok, let's start to verify"
  1114. ventries=$(echo "$vlist" | tr ',' ' ' )
  1115. for ventry in $ventries
  1116. do
  1117. d=$(echo $ventry | cut -d $sep -f 1)
  1118. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1119. uri=$(echo $ventry | cut -d $sep -f 3)
  1120. vtype=$(echo $ventry | cut -d $sep -f 4)
  1121. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1122. _info "Verifying:$d"
  1123. _debug "d" "$d"
  1124. _debug "keyauthorization" "$keyauthorization"
  1125. _debug "uri" "$uri"
  1126. removelevel=""
  1127. token=""
  1128. _debug "_currentRoot" "$_currentRoot"
  1129. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1130. if [ "$_currentRoot" = "no" ] ; then
  1131. _info "Standalone mode server"
  1132. _startserver "$keyauthorization" &
  1133. if [ "$?" != "0" ] ; then
  1134. _clearup
  1135. return 1
  1136. fi
  1137. serverproc="$!"
  1138. sleep 2
  1139. _debug serverproc $serverproc
  1140. else
  1141. if [ "$_currentRoot" = "apache" ] ; then
  1142. wellknown_path="$ACME_DIR"
  1143. else
  1144. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1145. if [ ! -d "$_currentRoot/.well-known" ] ; then
  1146. removelevel='1'
  1147. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ] ; then
  1148. removelevel='2'
  1149. else
  1150. removelevel='3'
  1151. fi
  1152. fi
  1153. _debug wellknown_path "$wellknown_path"
  1154. token="$(printf "$keyauthorization" | cut -d '.' -f 1)"
  1155. _debug "writing token:$token to $wellknown_path/$token"
  1156. mkdir -p "$wellknown_path"
  1157. printf "$keyauthorization" > "$wellknown_path/$token"
  1158. if [ ! "$usingApache" ] ; then
  1159. webroot_owner=$(_stat $_currentRoot)
  1160. _debug "Changing owner/group of .well-known to $webroot_owner"
  1161. chown -R $webroot_owner "$_currentRoot/.well-known"
  1162. fi
  1163. fi
  1164. fi
  1165. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  1166. if [ ! -z "$code" ] && [ ! "$code" = '202' ] ; then
  1167. _err "$d:Challenge error: $response"
  1168. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1169. _clearup
  1170. return 1
  1171. fi
  1172. waittimes=0
  1173. if [ -z "$MAX_RETRY_TIMES" ] ; then
  1174. MAX_RETRY_TIMES=30
  1175. fi
  1176. while [ "1" ] ; do
  1177. waittimes=$(_math $waittimes + 1)
  1178. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ] ; then
  1179. _err "$d:Timeout"
  1180. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1181. _clearup
  1182. return 1
  1183. fi
  1184. _debug "sleep 5 secs to verify"
  1185. sleep 5
  1186. _debug "checking"
  1187. response="$(_get $uri)"
  1188. if [ "$?" != "0" ] ; then
  1189. _err "$d:Verify error:$response"
  1190. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1191. _clearup
  1192. return 1
  1193. fi
  1194. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  1195. if [ "$status" = "valid" ] ; then
  1196. _info "Success"
  1197. _stopserver $serverproc
  1198. serverproc=""
  1199. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1200. break;
  1201. fi
  1202. if [ "$status" = "invalid" ] ; then
  1203. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  1204. _err "$d:Verify error:$error"
  1205. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1206. _clearup
  1207. return 1;
  1208. fi
  1209. if [ "$status" = "pending" ] ; then
  1210. _info "Pending"
  1211. else
  1212. _err "$d:Verify error:$response"
  1213. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1214. _clearup
  1215. return 1
  1216. fi
  1217. done
  1218. done
  1219. _clearup
  1220. _info "Verify finished, start to sign."
  1221. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1222. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  1223. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1224. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  1225. if [ "$Le_LinkCert" ] ; then
  1226. echo "$BEGIN_CERT" > "$CERT_PATH"
  1227. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1228. echo "$END_CERT" >> "$CERT_PATH"
  1229. _info "Cert success."
  1230. cat "$CERT_PATH"
  1231. _info "Your cert is in $CERT_PATH"
  1232. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1233. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ] ; then
  1234. USER_PATH="$PATH"
  1235. _saveaccountconf "USER_PATH" "$USER_PATH"
  1236. fi
  1237. fi
  1238. if [ -z "$Le_LinkCert" ] ; then
  1239. response="$(echo $response | _dbase64 "multiline" )"
  1240. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1241. return 1
  1242. fi
  1243. _cleardomainconf "Le_Vlist"
  1244. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1245. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  1246. if [ "$Le_LinkIssuer" ] ; then
  1247. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1248. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1249. echo "$END_CERT" >> "$CA_CERT_PATH"
  1250. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1251. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1252. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1253. fi
  1254. Le_CertCreateTime=$(date -u "+%s")
  1255. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  1256. Le_CertCreateTimeStr=$(date -u )
  1257. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  1258. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "80" ] ; then
  1259. Le_RenewalDays=80
  1260. fi
  1261. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  1262. Le_NextRenewTime=$(_math $Le_CertCreateTime + $Le_RenewalDays \* 24 \* 60 \* 60)
  1263. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  1264. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1265. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  1266. _output="$(installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" 2>&1)"
  1267. _ret="$?"
  1268. if [ "$_ret" = "9" ] ; then
  1269. #ignore the empty install error.
  1270. return 0
  1271. fi
  1272. if [ "$_ret" != "0" ] ; then
  1273. _err "$_output"
  1274. return 1
  1275. fi
  1276. }
  1277. renew() {
  1278. Le_Domain="$1"
  1279. if [ -z "$Le_Domain" ] ; then
  1280. _err "Usage: $PROJECT_ENTRY --renew -d domain.com"
  1281. return 1
  1282. fi
  1283. _initpath $Le_Domain
  1284. if [ ! -f "$DOMAIN_CONF" ] ; then
  1285. _info "$Le_Domain is not a issued domain, skip."
  1286. return 0;
  1287. fi
  1288. . "$DOMAIN_CONF"
  1289. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  1290. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1291. return 2
  1292. fi
  1293. IS_RENEW="1"
  1294. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1295. local res=$?
  1296. IS_RENEW=""
  1297. return $res
  1298. }
  1299. renewAll() {
  1300. _initpath
  1301. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1302. d=$(echo $d | cut -d '/' -f 1)
  1303. (
  1304. _info "Renew: $d"
  1305. renew "$d"
  1306. )
  1307. done
  1308. }
  1309. installcert() {
  1310. Le_Domain="$1"
  1311. if [ -z "$Le_Domain" ] ; then
  1312. echo "Usage: $PROJECT_ENTRY --installcert -d domain.com [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  1313. return 1
  1314. fi
  1315. Le_RealCertPath="$2"
  1316. Le_RealKeyPath="$3"
  1317. Le_RealCACertPath="$4"
  1318. Le_ReloadCmd="$5"
  1319. Le_RealFullChainPath="$6"
  1320. _initpath $Le_Domain
  1321. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  1322. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  1323. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  1324. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  1325. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  1326. if [ "$Le_RealCertPath" = "no" ] ; then
  1327. Le_RealCertPath=""
  1328. fi
  1329. if [ "$Le_RealKeyPath" = "no" ] ; then
  1330. Le_RealKeyPath=""
  1331. fi
  1332. if [ "$Le_RealCACertPath" = "no" ] ; then
  1333. Le_RealCACertPath=""
  1334. fi
  1335. if [ "$Le_ReloadCmd" = "no" ] ; then
  1336. Le_ReloadCmd=""
  1337. fi
  1338. if [ "$Le_RealFullChainPath" = "no" ] ; then
  1339. Le_RealFullChainPath=""
  1340. fi
  1341. _installed="0"
  1342. if [ "$Le_RealCertPath" ] ; then
  1343. _installed=1
  1344. _info "Installing cert to:$Le_RealCertPath"
  1345. if [ -f "$Le_RealCertPath" ] ; then
  1346. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  1347. fi
  1348. cat "$CERT_PATH" > "$Le_RealCertPath"
  1349. fi
  1350. if [ "$Le_RealCACertPath" ] ; then
  1351. _installed=1
  1352. _info "Installing CA to:$Le_RealCACertPath"
  1353. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ] ; then
  1354. echo "" >> "$Le_RealCACertPath"
  1355. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1356. else
  1357. if [ -f "$Le_RealCACertPath" ] ; then
  1358. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1359. fi
  1360. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1361. fi
  1362. fi
  1363. if [ "$Le_RealKeyPath" ] ; then
  1364. _installed=1
  1365. _info "Installing key to:$Le_RealKeyPath"
  1366. if [ -f "$Le_RealKeyPath" ] ; then
  1367. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1368. fi
  1369. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1370. fi
  1371. if [ "$Le_RealFullChainPath" ] ; then
  1372. _installed=1
  1373. _info "Installing full chain to:$Le_RealFullChainPath"
  1374. if [ -f "$Le_RealFullChainPath" ] ; then
  1375. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  1376. fi
  1377. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  1378. fi
  1379. if [ "$Le_ReloadCmd" ] ; then
  1380. _installed=1
  1381. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1382. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd") ; then
  1383. _info "Reload success."
  1384. else
  1385. _err "Reload error for :$Le_Domain"
  1386. fi
  1387. fi
  1388. if [ "$_installed" = "0" ] ; then
  1389. _err "Nothing to install. You don't specify any parameter."
  1390. return 9
  1391. fi
  1392. }
  1393. installcronjob() {
  1394. _initpath
  1395. if ! _exists "crontab" ; then
  1396. _err "crontab doesn't exist, so, we can not install cron jobs."
  1397. _err "All your certs will not be renewed automatically."
  1398. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  1399. return 1
  1400. fi
  1401. _info "Installing cron job"
  1402. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  1403. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ] ; then
  1404. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  1405. else
  1406. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  1407. return 1
  1408. fi
  1409. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  1410. fi
  1411. if [ "$?" != "0" ] ; then
  1412. _err "Install cron job failed. You need to manually renew your certs."
  1413. _err "Or you can add cronjob by yourself:"
  1414. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  1415. return 1
  1416. fi
  1417. }
  1418. uninstallcronjob() {
  1419. if ! _exists "crontab" ; then
  1420. return
  1421. fi
  1422. _info "Removing cron job"
  1423. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  1424. if [ "$cr" ] ; then
  1425. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  1426. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  1427. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1428. fi
  1429. _initpath
  1430. }
  1431. revoke() {
  1432. Le_Domain="$1"
  1433. if [ -z "$Le_Domain" ] ; then
  1434. echo "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  1435. return 1
  1436. fi
  1437. _initpath $Le_Domain
  1438. if [ ! -f "$DOMAIN_CONF" ] ; then
  1439. _err "$Le_Domain is not a issued domain, skip."
  1440. return 1;
  1441. fi
  1442. if [ ! -f "$CERT_PATH" ] ; then
  1443. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  1444. return 1
  1445. fi
  1446. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  1447. if [ -z "$cert" ] ; then
  1448. _err "Cert for $Le_Domain is empty found, skip."
  1449. return 1
  1450. fi
  1451. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  1452. uri="$API/acme/revoke-cert"
  1453. _info "Try domain key first."
  1454. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  1455. if [ -z "$response" ] ; then
  1456. _info "Revoke success."
  1457. rm -f $CERT_PATH
  1458. return 0
  1459. else
  1460. _err "Revoke error by domain key."
  1461. _err "$resource"
  1462. fi
  1463. fi
  1464. _info "Then try account key."
  1465. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  1466. if [ -z "$response" ] ; then
  1467. _info "Revoke success."
  1468. rm -f $CERT_PATH
  1469. return 0
  1470. else
  1471. _err "Revoke error."
  1472. _debug "$resource"
  1473. fi
  1474. fi
  1475. return 1
  1476. }
  1477. # Detect profile file if not specified as environment variable
  1478. _detect_profile() {
  1479. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  1480. echo "$PROFILE"
  1481. return
  1482. fi
  1483. local DETECTED_PROFILE
  1484. DETECTED_PROFILE=''
  1485. local SHELLTYPE
  1486. SHELLTYPE="$(basename "/$SHELL")"
  1487. if [ "$SHELLTYPE" = "bash" ] ; then
  1488. if [ -f "$HOME/.bashrc" ] ; then
  1489. DETECTED_PROFILE="$HOME/.bashrc"
  1490. elif [ -f "$HOME/.bash_profile" ] ; then
  1491. DETECTED_PROFILE="$HOME/.bash_profile"
  1492. fi
  1493. elif [ "$SHELLTYPE" = "zsh" ] ; then
  1494. DETECTED_PROFILE="$HOME/.zshrc"
  1495. fi
  1496. if [ -z "$DETECTED_PROFILE" ] ; then
  1497. if [ -f "$HOME/.profile" ] ; then
  1498. DETECTED_PROFILE="$HOME/.profile"
  1499. elif [ -f "$HOME/.bashrc" ] ; then
  1500. DETECTED_PROFILE="$HOME/.bashrc"
  1501. elif [ -f "$HOME/.bash_profile" ] ; then
  1502. DETECTED_PROFILE="$HOME/.bash_profile"
  1503. elif [ -f "$HOME/.zshrc" ] ; then
  1504. DETECTED_PROFILE="$HOME/.zshrc"
  1505. fi
  1506. fi
  1507. if [ ! -z "$DETECTED_PROFILE" ] ; then
  1508. echo "$DETECTED_PROFILE"
  1509. fi
  1510. }
  1511. _initconf() {
  1512. _initpath
  1513. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1514. echo "#ACCOUNT_CONF_PATH=xxxx
  1515. #Account configurations:
  1516. #Here are the supported macros, uncomment them to make them take effect.
  1517. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1518. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1519. #CERT_HOME=\"/path/to/cert/home\"
  1520. #STAGE=1 # Use the staging api
  1521. #FORCE=1 # Force to issue cert
  1522. #DEBUG=1 # Debug mode
  1523. #ACCOUNT_KEY_HASH=account key hash
  1524. USER_AGENT=\"$USER_AGENT\"
  1525. #USER_PATH=""
  1526. #dns api
  1527. #######################
  1528. #Cloudflare:
  1529. #api key
  1530. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1531. #account email
  1532. #CF_Email=\"xxxx@sss.com\"
  1533. #######################
  1534. #Dnspod.cn:
  1535. #api key id
  1536. #DP_Id=\"1234\"
  1537. #api key
  1538. #DP_Key=\"sADDsdasdgdsf\"
  1539. #######################
  1540. #Cloudxns.com:
  1541. #CX_Key=\"1234\"
  1542. #
  1543. #CX_Secret=\"sADDsdasdgdsf\"
  1544. " > $ACCOUNT_CONF_PATH
  1545. fi
  1546. }
  1547. _precheck() {
  1548. if ! _exists "curl" && ! _exists "wget"; then
  1549. _err "Please install curl or wget first, we need to access http resources."
  1550. return 1
  1551. fi
  1552. if ! _exists "crontab" ; then
  1553. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1554. _err "We need to set cron job to renew the certs automatically."
  1555. _err "Otherwise, your certs will not be able to be renewed automatically."
  1556. if [ -z "$FORCE" ] ; then
  1557. _err "Please add '--force' and try install again to go without crontab."
  1558. _err "./$PROJECT_ENTRY --install --force"
  1559. return 1
  1560. fi
  1561. fi
  1562. if ! _exists "openssl" ; then
  1563. _err "Please install openssl first."
  1564. _err "We need openssl to generate keys."
  1565. return 1
  1566. fi
  1567. if ! _exists "nc" ; then
  1568. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1569. _err "We use nc for standalone server if you use standalone mode."
  1570. _err "If you don't use standalone mode, just ignore this warning."
  1571. fi
  1572. return 0
  1573. }
  1574. _setShebang() {
  1575. _file="$1"
  1576. _shebang="$2"
  1577. if [ -z "$_shebang" ] ; then
  1578. _err "Usage: file shebang"
  1579. return 1
  1580. fi
  1581. cp "$_file" "$_file.tmp"
  1582. echo "$_shebang" > "$_file"
  1583. sed -n 2,99999p "$_file.tmp" >> "$_file"
  1584. rm -f "$_file.tmp"
  1585. }
  1586. _installalias() {
  1587. _initpath
  1588. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1589. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ] ; then
  1590. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  1591. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  1592. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  1593. fi
  1594. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  1595. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1596. _profile="$(_detect_profile)"
  1597. if [ "$_profile" ] ; then
  1598. _debug "Found profile: $_profile"
  1599. _setopt "$_profile" ". \"$_envfile\""
  1600. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  1601. else
  1602. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  1603. fi
  1604. #for csh
  1605. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  1606. _csh_profile="$HOME/.cshrc"
  1607. if [ -f "$_csh_profile" ] ; then
  1608. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  1609. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1610. _setopt "$_csh_profile" "source \"$_cshfile\""
  1611. fi
  1612. }
  1613. install() {
  1614. if ! _initpath ; then
  1615. _err "Install failed."
  1616. return 1
  1617. fi
  1618. if ! _precheck ; then
  1619. _err "Pre-check failed, can not install."
  1620. return 1
  1621. fi
  1622. #convert from le
  1623. if [ -d "$HOME/.le" ] ; then
  1624. for envfile in "le.env" "le.sh.env"
  1625. do
  1626. if [ -f "$HOME/.le/$envfile" ] ; then
  1627. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  1628. _upgrading="1"
  1629. _info "You are upgrading from le.sh"
  1630. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  1631. mv "$HOME/.le" "$LE_WORKING_DIR"
  1632. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1633. break;
  1634. fi
  1635. fi
  1636. done
  1637. fi
  1638. _info "Installing to $LE_WORKING_DIR"
  1639. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1640. _err "Can not craete working dir: $LE_WORKING_DIR"
  1641. return 1
  1642. fi
  1643. chmod 700 "$LE_WORKING_DIR"
  1644. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  1645. if [ "$?" != "0" ] ; then
  1646. _err "Install failed, can not copy $PROJECT_ENTRY"
  1647. return 1
  1648. fi
  1649. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  1650. _installalias
  1651. if [ -d "dnsapi" ] ; then
  1652. mkdir -p $LE_WORKING_DIR/dnsapi
  1653. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1654. fi
  1655. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1656. _initconf
  1657. fi
  1658. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ] ; then
  1659. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  1660. fi
  1661. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ] ; then
  1662. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  1663. fi
  1664. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ] ; then
  1665. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  1666. fi
  1667. installcronjob
  1668. if [ -z "$NO_DETECT_SH" ] ; then
  1669. #Modify shebang
  1670. if _exists bash ; then
  1671. _info "Good, bash is installed, change the shebang to use bash as prefered."
  1672. _shebang='#!/usr/bin/env bash'
  1673. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  1674. if [ -d "$LE_WORKING_DIR/dnsapi" ] ; then
  1675. for _apifile in $(ls "$LE_WORKING_DIR/dnsapi/"*.sh) ; do
  1676. _setShebang "$_apifile" "$_shebang"
  1677. done
  1678. fi
  1679. fi
  1680. fi
  1681. _info OK
  1682. }
  1683. uninstall() {
  1684. uninstallcronjob
  1685. _initpath
  1686. _profile="$(_detect_profile)"
  1687. if [ "$_profile" ] ; then
  1688. text="$(cat $_profile)"
  1689. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" > "$_profile"
  1690. fi
  1691. _csh_profile="$HOME/.cshrc"
  1692. if [ -f "$_csh_profile" ] ; then
  1693. text="$(cat $_csh_profile)"
  1694. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_csh_profile"
  1695. fi
  1696. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  1697. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1698. }
  1699. cron() {
  1700. IN_CRON=1
  1701. renewAll
  1702. IN_CRON=""
  1703. }
  1704. version() {
  1705. echo "$PROJECT"
  1706. echo "v$VER"
  1707. }
  1708. showhelp() {
  1709. version
  1710. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  1711. Commands:
  1712. --help, -h Show this help message.
  1713. --version, -v Show version info.
  1714. --install Install $PROJECT_NAME to your system.
  1715. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  1716. --issue Issue a cert.
  1717. --installcert Install the issued cert to apache/nginx or any other server.
  1718. --renew, -r Renew a cert.
  1719. --renewAll Renew all the certs
  1720. --revoke Revoke a cert.
  1721. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1722. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  1723. --cron Run cron job to renew all the certs.
  1724. --toPkcs Export the certificate and key to a pfx file.
  1725. --createAccountKey, -cak Create an account private key, professional use.
  1726. --createDomainKey, -cdk Create an domain private key, professional use.
  1727. --createCSR, -ccsr Create CSR , professional use.
  1728. Parameters:
  1729. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  1730. --force, -f Used to force to install or force to renew a cert immediately.
  1731. --staging, --test Use staging server, just for test.
  1732. --debug Output debug info.
  1733. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  1734. --standalone Use standalone mode.
  1735. --apache Use apache mode.
  1736. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  1737. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  1738. --accountkeylength, -ak [2048] Specifies the account key length.
  1739. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  1740. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  1741. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  1742. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  1743. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  1744. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  1745. --accountconf Specifies a customized account config file.
  1746. --home Specifies the home dir for $PROJECT_NAME .
  1747. --certhome Specifies the home dir to save all the certs.
  1748. --useragent Specifies the user agent string. it will be saved for future use too.
  1749. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  1750. --accountkey Specifies the account key path, Only valid for the '--install' command.
  1751. --days Specifies the days to renew the cert when using '--issue' command. The max value is 80 days.
  1752. "
  1753. }
  1754. _installOnline() {
  1755. _info "Installing from online archive."
  1756. if [ ! "$BRANCH" ] ; then
  1757. BRANCH="master"
  1758. fi
  1759. _initpath
  1760. target="$PROJECT/archive/$BRANCH.tar.gz"
  1761. _info "Downloading $target"
  1762. localname="$BRANCH.tar.gz"
  1763. if ! _get "$target" > $localname ; then
  1764. _debug "Download error."
  1765. return 1
  1766. fi
  1767. _info "Extracting $localname"
  1768. tar xzf $localname
  1769. cd "$PROJECT_NAME-$BRANCH"
  1770. chmod +x $PROJECT_ENTRY
  1771. if ./$PROJECT_ENTRY install ; then
  1772. _info "Install success!"
  1773. fi
  1774. cd ..
  1775. rm -rf "$PROJECT_NAME-$BRANCH"
  1776. rm -f "$localname"
  1777. }
  1778. _process() {
  1779. _CMD=""
  1780. _domain=""
  1781. _altdomains="no"
  1782. _webroot=""
  1783. _keylength="no"
  1784. _accountkeylength="no"
  1785. _certpath="no"
  1786. _keypath="no"
  1787. _capath="no"
  1788. _fullchainpath="no"
  1789. _reloadcmd=""
  1790. _password=""
  1791. _accountconf=""
  1792. _useragent=""
  1793. _accountemail=""
  1794. _accountkey=""
  1795. _certhome=""
  1796. while [ ${#} -gt 0 ] ; do
  1797. case "${1}" in
  1798. --help|-h)
  1799. showhelp
  1800. return
  1801. ;;
  1802. --version|-v)
  1803. version
  1804. return
  1805. ;;
  1806. --install)
  1807. _CMD="install"
  1808. ;;
  1809. --uninstall)
  1810. _CMD="uninstall"
  1811. ;;
  1812. --issue)
  1813. _CMD="issue"
  1814. ;;
  1815. --installcert|-i)
  1816. _CMD="installcert"
  1817. ;;
  1818. --renew|-r)
  1819. _CMD="renew"
  1820. ;;
  1821. --renewAll|--renewall)
  1822. _CMD="renewAll"
  1823. ;;
  1824. --revoke)
  1825. _CMD="revoke"
  1826. ;;
  1827. --installcronjob)
  1828. _CMD="installcronjob"
  1829. ;;
  1830. --uninstallcronjob)
  1831. _CMD="uninstallcronjob"
  1832. ;;
  1833. --cron)
  1834. _CMD="cron"
  1835. ;;
  1836. --toPkcs)
  1837. _CMD="toPkcs"
  1838. ;;
  1839. --createAccountKey|--createaccountkey|-cak)
  1840. _CMD="createAccountKey"
  1841. ;;
  1842. --createDomainKey|--createdomainkey|-cdk)
  1843. _CMD="createDomainKey"
  1844. ;;
  1845. --createCSR|--createcsr|-ccr)
  1846. _CMD="createCSR"
  1847. ;;
  1848. --domain|-d)
  1849. _dvalue="$2"
  1850. if [ -z "$_dvalue" ] || _startswith "$_dvalue" "-" ; then
  1851. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  1852. return 1
  1853. fi
  1854. if [ -z "$_domain" ] ; then
  1855. _domain="$_dvalue"
  1856. else
  1857. if [ "$_altdomains" = "no" ] ; then
  1858. _altdomains="$_dvalue"
  1859. else
  1860. _altdomains="$_altdomains,$_dvalue"
  1861. fi
  1862. fi
  1863. shift
  1864. ;;
  1865. --force|-f)
  1866. FORCE="1"
  1867. ;;
  1868. --staging|--test)
  1869. STAGE="1"
  1870. ;;
  1871. --debug)
  1872. if [ -z "$2" ] || _startswith "$2" "-" ; then
  1873. DEBUG="1"
  1874. else
  1875. DEBUG="$2"
  1876. shift
  1877. fi
  1878. ;;
  1879. --webroot|-w)
  1880. wvalue="$2"
  1881. if [ -z "$_webroot" ] ; then
  1882. _webroot="$wvalue"
  1883. else
  1884. _webroot="$_webroot,$wvalue"
  1885. fi
  1886. shift
  1887. ;;
  1888. --standalone)
  1889. wvalue="no"
  1890. if [ -z "$_webroot" ] ; then
  1891. _webroot="$wvalue"
  1892. else
  1893. _webroot="$_webroot,$wvalue"
  1894. fi
  1895. ;;
  1896. --apache)
  1897. wvalue="apache"
  1898. if [ -z "$_webroot" ] ; then
  1899. _webroot="$wvalue"
  1900. else
  1901. _webroot="$_webroot,$wvalue"
  1902. fi
  1903. ;;
  1904. --dns)
  1905. wvalue="dns"
  1906. if ! _startswith "$2" "-" ; then
  1907. wvalue="$2"
  1908. shift
  1909. fi
  1910. if [ -z "$_webroot" ] ; then
  1911. _webroot="$wvalue"
  1912. else
  1913. _webroot="$_webroot,$wvalue"
  1914. fi
  1915. ;;
  1916. --keylength|-k)
  1917. _keylength="$2"
  1918. accountkeylength="$2"
  1919. shift
  1920. ;;
  1921. --accountkeylength|-ak)
  1922. accountkeylength="$2"
  1923. shift
  1924. ;;
  1925. --certpath)
  1926. _certpath="$2"
  1927. shift
  1928. ;;
  1929. --keypath)
  1930. _keypath="$2"
  1931. shift
  1932. ;;
  1933. --capath)
  1934. _capath="$2"
  1935. shift
  1936. ;;
  1937. --fullchainpath)
  1938. _fullchainpath="$2"
  1939. shift
  1940. ;;
  1941. --reloadcmd|--reloadCmd)
  1942. _reloadcmd="$2"
  1943. shift
  1944. ;;
  1945. --password)
  1946. _password="$2"
  1947. shift
  1948. ;;
  1949. --accountconf)
  1950. _accountconf="$2"
  1951. ACCOUNT_CONF_PATH="$_accountconf"
  1952. shift
  1953. ;;
  1954. --home)
  1955. LE_WORKING_DIR="$2"
  1956. shift
  1957. ;;
  1958. --certhome)
  1959. _certhome="$2"
  1960. CERT_HOME="$_certhome"
  1961. shift
  1962. ;;
  1963. --useragent)
  1964. _useragent="$2"
  1965. USER_AGENT="$_useragent"
  1966. shift
  1967. ;;
  1968. --accountemail )
  1969. _accountemail="$2"
  1970. ACCOUNT_EMAIL="$_accountemail"
  1971. shift
  1972. ;;
  1973. --accountkey )
  1974. _accountkey="$2"
  1975. ACCOUNT_KEY_PATH="$_accountkey"
  1976. shift
  1977. ;;
  1978. --days )
  1979. _days="$2"
  1980. Le_RenewalDays="$_days"
  1981. shift
  1982. ;;
  1983. *)
  1984. _err "Unknown parameter : $1"
  1985. return 1
  1986. ;;
  1987. esac
  1988. shift 1
  1989. done
  1990. case "${_CMD}" in
  1991. install) install ;;
  1992. uninstall) uninstall ;;
  1993. issue)
  1994. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1995. ;;
  1996. installcert)
  1997. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  1998. ;;
  1999. renew)
  2000. renew "$_domain"
  2001. ;;
  2002. renewAll)
  2003. renewAll
  2004. ;;
  2005. revoke)
  2006. revoke "$_domain"
  2007. ;;
  2008. installcronjob) installcronjob ;;
  2009. uninstallcronjob) uninstallcronjob ;;
  2010. cron) cron ;;
  2011. toPkcs)
  2012. toPkcs "$_domain" "$_password"
  2013. ;;
  2014. createAccountKey)
  2015. createAccountKey "$_domain" "$_accountkeylength"
  2016. ;;
  2017. createDomainKey)
  2018. createDomainKey "$_domain" "$_keylength"
  2019. ;;
  2020. createCSR)
  2021. createCSR "$_domain" "$_altdomains"
  2022. ;;
  2023. *)
  2024. _err "Invalid command: $_CMD"
  2025. showhelp;
  2026. return 1
  2027. ;;
  2028. esac
  2029. if [ "$_useragent" ] ; then
  2030. _saveaccountconf "USER_AGENT" "$_useragent"
  2031. fi
  2032. if [ "$_accountemail" ] ; then
  2033. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  2034. fi
  2035. }
  2036. if [ "$INSTALLONLINE" ] ; then
  2037. INSTALLONLINE=""
  2038. _installOnline $BRANCH
  2039. exit
  2040. fi
  2041. if [ -z "$1" ] ; then
  2042. showhelp
  2043. else
  2044. if echo "$1" | grep "^-" >/dev/null 2>&1 ; then
  2045. _process "$@"
  2046. else
  2047. "$@"
  2048. fi
  2049. fi