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.

1809 lines
44 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
  1. #!/usr/bin/env bash
  2. VER=1.2.3
  3. PROJECT="https://github.com/Neilpang/le"
  4. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  5. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  6. DEFAULT_USER_AGENT="le.sh client: $PROJECT"
  7. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  8. VTYPE_HTTP="http-01"
  9. VTYPE_DNS="dns-01"
  10. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  11. END_CSR="-----END CERTIFICATE REQUEST-----"
  12. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  13. END_CERT="-----END CERTIFICATE-----"
  14. if [ -z "$AGREEMENT" ] ; then
  15. AGREEMENT="$DEFAULT_AGREEMENT"
  16. fi
  17. _info() {
  18. if [ -z "$2" ] ; then
  19. echo "$1"
  20. else
  21. echo "$1"="$2"
  22. fi
  23. }
  24. _err() {
  25. if [ -z "$2" ] ; then
  26. echo "$1" >&2
  27. else
  28. echo "$1"="'$2'" >&2
  29. fi
  30. return 1
  31. }
  32. _debug() {
  33. if [ -z "$DEBUG" ] ; then
  34. return
  35. fi
  36. _err "$1" "$2"
  37. return 0
  38. }
  39. _exists() {
  40. cmd="$1"
  41. if [ -z "$cmd" ] ; then
  42. _err "Usage: _exists cmd"
  43. return 1
  44. fi
  45. command -v $cmd >/dev/null 2>&1
  46. ret="$?"
  47. _debug "$cmd exists=$ret"
  48. return $ret
  49. }
  50. _h2b() {
  51. hex=$(cat)
  52. i=1
  53. j=2
  54. while [ '1' ] ; do
  55. h=$(printf $hex | cut -c $i-$j)
  56. if [ -z "$h" ] ; then
  57. break;
  58. fi
  59. printf "\x$h"
  60. let "i+=2"
  61. let "j+=2"
  62. done
  63. }
  64. #options file
  65. _sed_i() {
  66. options="$1"
  67. filename="$2"
  68. if [ -z "$filename" ] ; then
  69. _err "Usage:_sed_i options filename"
  70. return 1
  71. fi
  72. if sed -h 2>&1 | grep "\-i[SUFFIX]" ; then
  73. _debug "Using sed -i"
  74. sed -i ""
  75. else
  76. _debug "No -i support in sed"
  77. text="$(cat $filename)"
  78. echo "$text" | sed "$options" > "$filename"
  79. fi
  80. }
  81. #Usage: file startline endline
  82. _getfile() {
  83. filename="$1"
  84. startline="$2"
  85. endline="$3"
  86. if [ -z "$endline" ] ; then
  87. _err "Usage: file startline endline"
  88. return 1
  89. fi
  90. i="$(grep -n -- "$startline" $filename | cut -d : -f 1)"
  91. if [ -z "$i" ] ; then
  92. _err "Can not find start line: $startline"
  93. return 1
  94. fi
  95. let "i+=1"
  96. _debug i $i
  97. j="$(grep -n -- "$endline" $filename | cut -d : -f 1)"
  98. if [ -z "$j" ] ; then
  99. _err "Can not find end line: $endline"
  100. return 1
  101. fi
  102. let "j-=1"
  103. _debug j $j
  104. sed -n $i,${j}p "$filename"
  105. }
  106. #Usage: multiline
  107. _base64() {
  108. if [ "$1" ] ; then
  109. openssl base64 -e
  110. else
  111. openssl base64 -e | tr -d '\r\n'
  112. fi
  113. }
  114. #Usage: multiline
  115. _dbase64() {
  116. if [ "$1" ] ; then
  117. openssl base64 -d -A
  118. else
  119. openssl base64 -d
  120. fi
  121. }
  122. #Usage: hashalg
  123. #Output Base64-encoded digest
  124. _digest() {
  125. alg="$1"
  126. if [ -z "$alg" ] ; then
  127. _err "Usage: _digest hashalg"
  128. return 1
  129. fi
  130. if [ "$alg" == "sha256" ] ; then
  131. openssl dgst -sha256 -binary | _base64
  132. else
  133. _err "$alg is not supported yet"
  134. return 1
  135. fi
  136. }
  137. #Usage: keyfile hashalg
  138. #Output: Base64-encoded signature value
  139. _sign() {
  140. keyfile="$1"
  141. alg="$2"
  142. if [ -z "$alg" ] ; then
  143. _err "Usage: _sign keyfile hashalg"
  144. return 1
  145. fi
  146. if [ "$alg" == "sha256" ] ; then
  147. openssl dgst -sha256 -sign "$keyfile" | _base64
  148. else
  149. _err "$alg is not supported yet"
  150. return 1
  151. fi
  152. }
  153. _ss() {
  154. _port="$1"
  155. if _exists "ss" ; then
  156. _debug "Using: ss"
  157. ss -ntpl | grep :$_port" "
  158. return 0
  159. fi
  160. if _exists "netstat" ; then
  161. _debug "Using: netstat"
  162. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  163. #for windows version netstat tool
  164. netstat -anb -p tcp | grep "LISTENING" | grep :$_port" "
  165. else
  166. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  167. netstat -an -p tcp | grep LISTEN | grep :$_port" "
  168. else
  169. netstat -ntpl | grep :$_port" "
  170. fi
  171. fi
  172. return 0
  173. fi
  174. return 1
  175. }
  176. toPkcs() {
  177. domain="$1"
  178. pfxPassword="$2"
  179. if [[ -z "$domain" ]] ; then
  180. _err "Usage: toPkcs domain [pfx-password]"
  181. return 1
  182. fi
  183. _initpath "$domain"
  184. if [[ "$pfxPassword" ]] ; then
  185. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  186. else
  187. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  188. fi
  189. if [[ "$?" == "0" ]] ; then
  190. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  191. fi
  192. }
  193. #domain [2048]
  194. createAccountKey() {
  195. _info "Creating account key"
  196. if [ -z "$1" ] ; then
  197. echo Usage: createAccountKey account-domain [2048]
  198. return
  199. fi
  200. account=$1
  201. length=$2
  202. if [[ "$length" == "ec-"* ]] ; then
  203. length=2048
  204. fi
  205. if [ -z "$2" ] ; then
  206. _info "Use default length 2048"
  207. length=2048
  208. fi
  209. _initpath
  210. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  211. _info "Account key exists, skip"
  212. return
  213. else
  214. #generate account key
  215. openssl genrsa $length 2>/dev/null > "$ACCOUNT_KEY_PATH"
  216. fi
  217. }
  218. #domain length
  219. createDomainKey() {
  220. _info "Creating domain key"
  221. if [ -z "$1" ] ; then
  222. echo Usage: createDomainKey domain [2048]
  223. return
  224. fi
  225. domain=$1
  226. length=$2
  227. isec=""
  228. if [[ "$length" == "ec-"* ]] ; then
  229. isec="1"
  230. length=$(printf $length | cut -d '-' -f 2-100)
  231. eccname="$length"
  232. fi
  233. if [ -z "$length" ] ; then
  234. if [ "$isec" ] ; then
  235. length=256
  236. else
  237. length=2048
  238. fi
  239. fi
  240. _info "Use length $length"
  241. if [ "$isec" ] ; then
  242. if [ "$length" == "256" ] ; then
  243. eccname="prime256v1"
  244. fi
  245. if [ "$length" == "384" ] ; then
  246. eccname="secp384r1"
  247. fi
  248. if [ "$length" == "521" ] ; then
  249. eccname="secp521r1"
  250. fi
  251. _info "Using ec name: $eccname"
  252. fi
  253. _initpath $domain
  254. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  255. #generate account key
  256. if [ "$isec" ] ; then
  257. openssl ecparam -name $eccname -genkey 2>/dev/null > "$CERT_KEY_PATH"
  258. else
  259. openssl genrsa $length 2>/dev/null > "$CERT_KEY_PATH"
  260. fi
  261. else
  262. if [ "$IS_RENEW" ] ; then
  263. _info "Domain key exists, skip"
  264. return 0
  265. else
  266. _err "Domain key exists, do you want to overwrite the key?"
  267. _err "Set FORCE=1, and try again."
  268. return 1
  269. fi
  270. fi
  271. }
  272. # domain domainlist
  273. createCSR() {
  274. _info "Creating csr"
  275. if [ -z "$1" ] ; then
  276. echo Usage: $0 domain [domainlist]
  277. return
  278. fi
  279. domain=$1
  280. _initpath $domain
  281. domainlist=$2
  282. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && ! [ "$FORCE" ]; then
  283. _info "CSR exists, skip"
  284. return
  285. fi
  286. if [ -z "$domainlist" ] ; then
  287. #single domain
  288. _info "Single domain" $domain
  289. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$DOMAIN_SSL_CONF"
  290. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  291. else
  292. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  293. #multi
  294. _info "Multi domain" "$alt"
  295. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n[SAN]\nsubjectAltName=$alt" > "$DOMAIN_SSL_CONF"
  296. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -reqexts SAN -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  297. fi
  298. }
  299. _urlencode() {
  300. __n=$(cat)
  301. echo $__n | tr '/+' '_-' | tr -d '= '
  302. }
  303. _time2str() {
  304. #BSD
  305. if date -u -d@$1 2>/dev/null ; then
  306. return
  307. fi
  308. #Linux
  309. if date -u -r $1 2>/dev/null ; then
  310. return
  311. fi
  312. }
  313. _stat() {
  314. #Linux
  315. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  316. return
  317. fi
  318. #BSD
  319. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  320. return
  321. fi
  322. }
  323. #keyfile
  324. _calcjwk() {
  325. keyfile="$1"
  326. if [ -z "$keyfile" ] ; then
  327. _err "Usage: _calcjwk keyfile"
  328. return 1
  329. fi
  330. EC_SIGN=""
  331. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  332. _debug "RSA key"
  333. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  334. if [ "${#pub_exp}" == "5" ] ; then
  335. pub_exp=0$pub_exp
  336. fi
  337. _debug pub_exp "$pub_exp"
  338. e=$(echo $pub_exp | _h2b | _base64)
  339. _debug e "$e"
  340. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  341. n=$(echo $modulus| _h2b | _base64 | _urlencode )
  342. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  343. _debug jwk "$jwk"
  344. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  345. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  346. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  347. _debug "EC key"
  348. EC_SIGN="1"
  349. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  350. _debug crv $crv
  351. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  352. _debug pubi $pubi
  353. let "pubi=pubi+1"
  354. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  355. _debug pubj $pubj
  356. let "pubj=pubj-1"
  357. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  358. _debug pubtext "$pubtext"
  359. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  360. let "xlen=xlen/4"
  361. _debug xlen $xlen
  362. let "xend=xlen+1"
  363. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  364. _debug x $x
  365. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  366. _debug x64 $x64
  367. let "xend+=1"
  368. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  369. _debug y $y
  370. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  371. _debug y64 $y64
  372. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  373. _debug jwk "$jwk"
  374. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  375. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  376. else
  377. _err "Only RSA or EC key is supported."
  378. return 1
  379. fi
  380. _debug HEADER "$HEADER"
  381. }
  382. # body url [needbase64]
  383. _post() {
  384. body="$1"
  385. url="$2"
  386. needbase64="$3"
  387. if _exists "curl" ; then
  388. CURL="$CURL --dump-header $HTTP_HEADER "
  389. if [ "$needbase64" ] ; then
  390. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url | _base64)"
  391. else
  392. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url)"
  393. fi
  394. else
  395. if [ "$needbase64" ] ; then
  396. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER" | _base64)"
  397. else
  398. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER")"
  399. fi
  400. _sed_i "s/^ *//g" "$HTTP_HEADER"
  401. fi
  402. echo -n "$response"
  403. }
  404. # url getheader
  405. _get() {
  406. url="$1"
  407. onlyheader="$2"
  408. _debug url $url
  409. if _exists "curl" ; then
  410. if [ "$onlyheader" ] ; then
  411. $CURL -I -A "User-Agent: $USER_AGENT" $url
  412. else
  413. $CURL -A "User-Agent: $USER_AGENT" $url
  414. fi
  415. else
  416. _debug "WGET" "$WGET"
  417. if [ "$onlyheader" ] ; then
  418. eval $WGET --user-agent=\"$USER_AGENT\" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  419. else
  420. eval $WGET --user-agent=\"$USER_AGENT\" -O - $url
  421. fi
  422. fi
  423. ret=$?
  424. return $ret
  425. }
  426. # url payload needbase64 keyfile
  427. _send_signed_request() {
  428. url=$1
  429. payload=$2
  430. needbase64=$3
  431. keyfile=$4
  432. if [ -z "$keyfile" ] ; then
  433. keyfile="$ACCOUNT_KEY_PATH"
  434. fi
  435. _debug url $url
  436. _debug payload "$payload"
  437. if ! _calcjwk "$keyfile" ; then
  438. return 1
  439. fi
  440. payload64=$(echo -n $payload | _base64 | _urlencode)
  441. _debug payload64 $payload64
  442. nonceurl="$API/directory"
  443. nonce="$(_get $nonceurl "onlyheader" | grep -o "Replay-Nonce:.*$" | head -1 | tr -d "\r\n" | cut -d ' ' -f 2)"
  444. _debug nonce "$nonce"
  445. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  446. _debug protected "$protected"
  447. protected64="$(printf "$protected" | _base64 | _urlencode)"
  448. _debug protected64 "$protected64"
  449. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  450. _debug sig "$sig"
  451. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  452. _debug body "$body"
  453. response="$(_post "$body" $url "$needbase64" )"
  454. responseHeaders="$(cat $HTTP_HEADER)"
  455. _debug responseHeaders "$responseHeaders"
  456. _debug response "$response"
  457. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  458. _debug code $code
  459. }
  460. #setopt "file" "opt" "=" "value" [";"]
  461. _setopt() {
  462. __conf="$1"
  463. __opt="$2"
  464. __sep="$3"
  465. __val="$4"
  466. __end="$5"
  467. if [ -z "$__opt" ] ; then
  468. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  469. return
  470. fi
  471. if [ ! -f "$__conf" ] ; then
  472. touch "$__conf"
  473. fi
  474. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  475. _debug OK
  476. if [[ "$__val" == *"&"* ]] ; then
  477. __val="$(echo $__val | sed 's/&/\\&/g')"
  478. fi
  479. text="$(cat $__conf)"
  480. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  481. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  482. if [[ "$__val" == *"&"* ]] ; then
  483. __val="$(echo $__val | sed 's/&/\\&/g')"
  484. fi
  485. text="$(cat $__conf)"
  486. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  487. else
  488. _debug APP
  489. echo "$__opt$__sep$__val$__end" >> "$__conf"
  490. fi
  491. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  492. }
  493. #_savedomainconf key value
  494. #save to domain.conf
  495. _savedomainconf() {
  496. key="$1"
  497. value="$2"
  498. if [ "$DOMAIN_CONF" ] ; then
  499. _setopt $DOMAIN_CONF "$key" "=" "$value"
  500. else
  501. _err "DOMAIN_CONF is empty, can not save $key=$value"
  502. fi
  503. }
  504. #_saveaccountconf key value
  505. _saveaccountconf() {
  506. key="$1"
  507. value="$2"
  508. if [ "$ACCOUNT_CONF_PATH" ] ; then
  509. _setopt $ACCOUNT_CONF_PATH "$key" "=" "\"$value\""
  510. else
  511. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  512. fi
  513. }
  514. _startserver() {
  515. content="$1"
  516. nchelp="$(nc -h 2>&1)"
  517. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  518. _NC="nc -q 1 -l"
  519. else
  520. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  521. _NC="nc -c -l"
  522. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  523. _NC="nc -N -l"
  524. else
  525. _NC="nc -l"
  526. fi
  527. fi
  528. _debug "_NC" "$_NC"
  529. # while true ; do
  530. if [ "$DEBUG" ] ; then
  531. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort -vv ; then
  532. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort -vv ;
  533. fi
  534. else
  535. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  536. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  537. fi
  538. fi
  539. if [ "$?" != "0" ] ; then
  540. _err "nc listen error."
  541. return 1
  542. fi
  543. # done
  544. }
  545. _stopserver() {
  546. pid="$1"
  547. }
  548. _initpath() {
  549. if [ -z "$LE_WORKING_DIR" ]; then
  550. LE_WORKING_DIR=$HOME/.le
  551. fi
  552. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  553. ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  554. fi
  555. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  556. source "$ACCOUNT_CONF_PATH"
  557. fi
  558. if [[ "$IN_CRON" ]] ; then
  559. if [[ ! "$_USER_PATH_EXPORTED" ]] ; then
  560. _USER_PATH_EXPORTED=1
  561. export PATH="$USER_PATH:$PATH"
  562. fi
  563. fi
  564. if [ -z "$API" ] ; then
  565. if [ -z "$STAGE" ] ; then
  566. API="$DEFAULT_CA"
  567. else
  568. API="$STAGE_CA"
  569. _info "Using stage api:$API"
  570. fi
  571. fi
  572. if [ -z "$ACME_DIR" ] ; then
  573. ACME_DIR="/home/.acme"
  574. fi
  575. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  576. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  577. fi
  578. if [ -z "$USER_AGENT" ] ; then
  579. USER_AGENT="$DEFAULT_USER_AGENT"
  580. fi
  581. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  582. WGET="wget -q"
  583. if [ "$DEBUG" ] ; then
  584. WGET="$WGET -d "
  585. fi
  586. dp="$LE_WORKING_DIR/curl.dump"
  587. CURL="curl -L --silent"
  588. if [ "$DEBUG" ] ; then
  589. CURL="$CURL -L --trace-ascii $dp "
  590. fi
  591. domain="$1"
  592. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  593. ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  594. fi
  595. if [ -z "$domain" ] ; then
  596. return 0
  597. fi
  598. domainhome="$LE_WORKING_DIR/$domain"
  599. mkdir -p "$domainhome"
  600. if [ -z "$DOMAIN_PATH" ] ; then
  601. DOMAIN_PATH="$domainhome"
  602. fi
  603. if [ -z "$DOMAIN_CONF" ] ; then
  604. DOMAIN_CONF="$domainhome/$domain.conf"
  605. fi
  606. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  607. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  608. fi
  609. if [ -z "$CSR_PATH" ] ; then
  610. CSR_PATH="$domainhome/$domain.csr"
  611. fi
  612. if [ -z "$CERT_KEY_PATH" ] ; then
  613. CERT_KEY_PATH="$domainhome/$domain.key"
  614. fi
  615. if [ -z "$CERT_PATH" ] ; then
  616. CERT_PATH="$domainhome/$domain.cer"
  617. fi
  618. if [ -z "$CA_CERT_PATH" ] ; then
  619. CA_CERT_PATH="$domainhome/ca.cer"
  620. fi
  621. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  622. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  623. fi
  624. if [ -z "$CERT_PFX_PATH" ] ; then
  625. CERT_PFX_PATH="$domainhome/$domain.pfx"
  626. fi
  627. }
  628. _apachePath() {
  629. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  630. if [[ "$httpdconfname" == '/'* ]] ; then
  631. httpdconf="$httpdconfname"
  632. httpdconfname="$(basename $httpdconfname)"
  633. else
  634. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  635. httpdconf="$httpdroot/$httpdconfname"
  636. fi
  637. if [ ! -f $httpdconf ] ; then
  638. _err "Apache Config file not found" $httpdconf
  639. return 1
  640. fi
  641. return 0
  642. }
  643. _restoreApache() {
  644. if [ -z "$usingApache" ] ; then
  645. return 0
  646. fi
  647. _initpath
  648. if ! _apachePath ; then
  649. return 1
  650. fi
  651. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  652. _debug "No config file to restore."
  653. return 0
  654. fi
  655. cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
  656. if ! apachectl -t ; then
  657. _err "Sorry, restore apache config error, please contact me."
  658. return 1;
  659. fi
  660. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  661. return 0
  662. }
  663. _setApache() {
  664. _initpath
  665. if ! _apachePath ; then
  666. return 1
  667. fi
  668. #backup the conf
  669. _debug "Backup apache config file" $httpdconf
  670. cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
  671. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  672. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  673. _info "The backup file will be deleted on sucess, just forget it."
  674. #add alias
  675. apacheVer="$(apachectl -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  676. _debug "apacheVer" "$apacheVer"
  677. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  678. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  679. if [[ "$apacheVer" ]] && [[ "$apacheMajer" -ge "2" ]] && [[ "$apacheMinor" -ge "4" ]] ; then
  680. echo "
  681. Alias /.well-known/acme-challenge $ACME_DIR
  682. <Directory $ACME_DIR >
  683. Require all granted
  684. </Directory>
  685. " >> $httpdconf
  686. else
  687. echo "
  688. Alias /.well-known/acme-challenge $ACME_DIR
  689. <Directory $ACME_DIR >
  690. Order allow,deny
  691. Allow from all
  692. </Directory>
  693. " >> $httpdconf
  694. fi
  695. if ! apachectl -t ; then
  696. _err "Sorry, apache config error, please contact me."
  697. _restoreApache
  698. return 1;
  699. fi
  700. if [ ! -d "$ACME_DIR" ] ; then
  701. mkdir -p "$ACME_DIR"
  702. chmod 755 "$ACME_DIR"
  703. fi
  704. if ! apachectl graceful ; then
  705. _err "Sorry, apachectl graceful error, please contact me."
  706. _restoreApache
  707. return 1;
  708. fi
  709. usingApache="1"
  710. return 0
  711. }
  712. _clearup () {
  713. _stopserver $serverproc
  714. serverproc=""
  715. _restoreApache
  716. }
  717. # webroot removelevel tokenfile
  718. _clearupwebbroot() {
  719. __webroot="$1"
  720. if [ -z "$__webroot" ] ; then
  721. _debug "no webroot specified, skip"
  722. return 0
  723. fi
  724. if [ "$2" == '1' ] ; then
  725. _debug "remove $__webroot/.well-known"
  726. rm -rf "$__webroot/.well-known"
  727. elif [ "$2" == '2' ] ; then
  728. _debug "remove $__webroot/.well-known/acme-challenge"
  729. rm -rf "$__webroot/.well-known/acme-challenge"
  730. elif [ "$2" == '3' ] ; then
  731. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  732. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  733. else
  734. _info "Skip for removelevel:$2"
  735. fi
  736. return 0
  737. }
  738. issue() {
  739. if [ -z "$2" ] ; then
  740. _err "Usage: le issue webroot|no|apache|dns a.com [www.a.com,b.com,c.com]|no [key-length]|no"
  741. return 1
  742. fi
  743. Le_Webroot="$1"
  744. Le_Domain="$2"
  745. Le_Alt="$3"
  746. Le_Keylength="$4"
  747. Le_RealCertPath="$5"
  748. Le_RealKeyPath="$6"
  749. Le_RealCACertPath="$7"
  750. Le_ReloadCmd="$8"
  751. _initpath $Le_Domain
  752. if [ -f "$DOMAIN_CONF" ] ; then
  753. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  754. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  755. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  756. return 2
  757. fi
  758. fi
  759. _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
  760. _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
  761. _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
  762. _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
  763. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  764. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  765. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  766. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  767. if [ "$Le_Alt" == "no" ] ; then
  768. Le_Alt=""
  769. fi
  770. if [ "$Le_Keylength" == "no" ] ; then
  771. Le_Keylength=""
  772. fi
  773. if [ "$Le_RealCertPath" == "no" ] ; then
  774. Le_RealCertPath=""
  775. fi
  776. if [ "$Le_RealKeyPath" == "no" ] ; then
  777. Le_RealKeyPath=""
  778. fi
  779. if [ "$Le_RealCACertPath" == "no" ] ; then
  780. Le_RealCACertPath=""
  781. fi
  782. if [ "$Le_ReloadCmd" == "no" ] ; then
  783. Le_ReloadCmd=""
  784. fi
  785. if [ "$Le_Webroot" == "no" ] ; then
  786. _info "Standalone mode."
  787. if ! command -v "nc" > /dev/null ; then
  788. _err "Please install netcat(nc) tools first."
  789. return 1
  790. fi
  791. if [ -z "$Le_HTTPPort" ] ; then
  792. Le_HTTPPort=80
  793. fi
  794. _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
  795. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  796. if [ "$netprc" ] ; then
  797. _err "$netprc"
  798. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  799. _err "Please stop it first"
  800. return 1
  801. fi
  802. fi
  803. if [ "$Le_Webroot" == "apache" ] ; then
  804. if ! _setApache ; then
  805. _err "set up apache error. Report error to me."
  806. return 1
  807. fi
  808. wellknown_path="$ACME_DIR"
  809. else
  810. usingApache=""
  811. fi
  812. createAccountKey $Le_Domain $Le_Keylength
  813. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  814. return 1
  815. fi
  816. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  817. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  818. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  819. if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
  820. _info "Registering account"
  821. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  822. if [ "$ACCOUNT_EMAIL" ] ; then
  823. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  824. fi
  825. _send_signed_request "$API/acme/new-reg" "$regjson"
  826. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  827. _info "Registered"
  828. echo $response > $LE_WORKING_DIR/account.json
  829. elif [ "$code" == '409' ] ; then
  830. _info "Already registered"
  831. else
  832. _err "Register account Error: $response"
  833. _clearup
  834. return 1
  835. fi
  836. ACCOUNT_KEY_HASH="$accountkeyhash"
  837. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  838. else
  839. _info "Skip register account key"
  840. fi
  841. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  842. _err "Create domain key error."
  843. return 1
  844. fi
  845. if ! createCSR $Le_Domain $Le_Alt ; then
  846. _err "Create CSR error."
  847. return 1
  848. fi
  849. vtype="$VTYPE_HTTP"
  850. if [[ "$Le_Webroot" == "dns"* ]] ; then
  851. vtype="$VTYPE_DNS"
  852. fi
  853. vlist="$Le_Vlist"
  854. # verify each domain
  855. _info "Verify each domain"
  856. sep='#'
  857. if [ -z "$vlist" ] ; then
  858. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  859. for d in $alldomains
  860. do
  861. _info "Getting token for domain" $d
  862. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  863. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  864. _err "new-authz error: $response"
  865. _clearup
  866. return 1
  867. fi
  868. entry="$(printf $response | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  869. _debug entry "$entry"
  870. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  871. _debug token $token
  872. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  873. _debug uri $uri
  874. keyauthorization="$token.$thumbprint"
  875. _debug keyauthorization "$keyauthorization"
  876. dvlist="$d$sep$keyauthorization$sep$uri"
  877. _debug dvlist "$dvlist"
  878. vlist="$vlist$dvlist,"
  879. done
  880. #add entry
  881. dnsadded=""
  882. ventries=$(echo "$vlist" | tr ',' ' ' )
  883. for ventry in $ventries
  884. do
  885. d=$(echo $ventry | cut -d $sep -f 1)
  886. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  887. if [ "$vtype" == "$VTYPE_DNS" ] ; then
  888. dnsadded='0'
  889. txtdomain="_acme-challenge.$d"
  890. _debug txtdomain "$txtdomain"
  891. txt="$(echo -e -n $keyauthorization | _digest "sha256" | _urlencode)"
  892. _debug txt "$txt"
  893. #dns
  894. #1. check use api
  895. d_api=""
  896. if [ -f "$LE_WORKING_DIR/$d/$Le_Webroot" ] ; then
  897. d_api="$LE_WORKING_DIR/$d/$Le_Webroot"
  898. elif [ -f "$LE_WORKING_DIR/$d/$Le_Webroot.sh" ] ; then
  899. d_api="$LE_WORKING_DIR/$d/$Le_Webroot.sh"
  900. elif [ -f "$LE_WORKING_DIR/$Le_Webroot" ] ; then
  901. d_api="$LE_WORKING_DIR/$Le_Webroot"
  902. elif [ -f "$LE_WORKING_DIR/$Le_Webroot.sh" ] ; then
  903. d_api="$LE_WORKING_DIR/$Le_Webroot.sh"
  904. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot" ] ; then
  905. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot"
  906. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh" ] ; then
  907. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh"
  908. fi
  909. _debug d_api "$d_api"
  910. if [ "$d_api" ]; then
  911. _info "Found domain api file: $d_api"
  912. else
  913. _err "Add the following TXT record:"
  914. _err "Domain: $txtdomain"
  915. _err "TXT value: $txt"
  916. _err "Please be aware that you prepend _acme-challenge. before your domain"
  917. _err "so the resulting subdomain will be: $txtdomain"
  918. continue
  919. fi
  920. (
  921. if ! source $d_api ; then
  922. _err "Load file $d_api error. Please check your api file and try again."
  923. return 1
  924. fi
  925. addcommand="$Le_Webroot-add"
  926. if ! command -v $addcommand ; then
  927. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  928. return 1
  929. fi
  930. if ! $addcommand $txtdomain $txt ; then
  931. _err "Error add txt for domain:$txtdomain"
  932. return 1
  933. fi
  934. )
  935. if [[ "$?" != "0" ]] ; then
  936. return 1
  937. fi
  938. dnsadded='1'
  939. fi
  940. done
  941. if [ "$dnsadded" == '0' ] ; then
  942. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  943. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  944. _err "Please add the TXT records to the domains, and retry again."
  945. return 1
  946. fi
  947. fi
  948. if [ "$dnsadded" == '1' ] ; then
  949. _info "Sleep 60 seconds for the txt records to take effect"
  950. sleep 60
  951. fi
  952. _debug "ok, let's start to verify"
  953. ventries=$(echo "$vlist" | tr ',' ' ' )
  954. for ventry in $ventries
  955. do
  956. d=$(echo $ventry | cut -d $sep -f 1)
  957. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  958. uri=$(echo $ventry | cut -d $sep -f 3)
  959. _info "Verifying:$d"
  960. _debug "d" "$d"
  961. _debug "keyauthorization" "$keyauthorization"
  962. _debug "uri" "$uri"
  963. removelevel=""
  964. token=""
  965. if [ "$vtype" == "$VTYPE_HTTP" ] ; then
  966. if [ "$Le_Webroot" == "no" ] ; then
  967. _info "Standalone mode server"
  968. _startserver "$keyauthorization" &
  969. serverproc="$!"
  970. sleep 2
  971. _debug serverproc $serverproc
  972. else
  973. if [ -z "$wellknown_path" ] ; then
  974. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  975. fi
  976. _debug wellknown_path "$wellknown_path"
  977. if [ ! -d "$Le_Webroot/.well-known" ] ; then
  978. removelevel='1'
  979. elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
  980. removelevel='2'
  981. else
  982. removelevel='3'
  983. fi
  984. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  985. _debug "writing token:$token to $wellknown_path/$token"
  986. mkdir -p "$wellknown_path"
  987. echo -n "$keyauthorization" > "$wellknown_path/$token"
  988. if [[ ! "$usingApache" ]] ; then
  989. webroot_owner=$(_stat $Le_Webroot)
  990. _debug "Changing owner/group of .well-known to $webroot_owner"
  991. chown -R $webroot_owner "$Le_Webroot/.well-known"
  992. fi
  993. fi
  994. fi
  995. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  996. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  997. _err "$d:Challenge error: $response"
  998. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  999. _clearup
  1000. return 1
  1001. fi
  1002. while [ "1" ] ; do
  1003. _debug "sleep 5 secs to verify"
  1004. sleep 5
  1005. _debug "checking"
  1006. response="$(_get $uri)"
  1007. if [ "$?" != "0" ] ; then
  1008. _err "$d:Verify error:$response"
  1009. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  1010. _clearup
  1011. return 1
  1012. fi
  1013. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  1014. if [ "$status" == "valid" ] ; then
  1015. _info "Success"
  1016. _stopserver $serverproc
  1017. serverproc=""
  1018. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  1019. break;
  1020. fi
  1021. if [ "$status" == "invalid" ] ; then
  1022. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  1023. _err "$d:Verify error:$error"
  1024. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  1025. _clearup
  1026. return 1;
  1027. fi
  1028. if [ "$status" == "pending" ] ; then
  1029. _info "Pending"
  1030. else
  1031. _err "$d:Verify error:$response"
  1032. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  1033. _clearup
  1034. return 1
  1035. fi
  1036. done
  1037. done
  1038. _clearup
  1039. _info "Verify finished, start to sign."
  1040. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1041. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  1042. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1043. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  1044. if [ "$Le_LinkCert" ] ; then
  1045. echo "$BEGIN_CERT" > "$CERT_PATH"
  1046. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1047. echo "$END_CERT" >> "$CERT_PATH"
  1048. _info "Cert success."
  1049. cat "$CERT_PATH"
  1050. _info "Your cert is in $CERT_PATH"
  1051. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1052. if [[ ! "$USER_PATH" ]] || [[ ! "$IN_CRON" ]] ; then
  1053. USER_PATH="$PATH"
  1054. _saveaccountconf "USER_PATH" "$USER_PATH"
  1055. fi
  1056. fi
  1057. if [ -z "$Le_LinkCert" ] ; then
  1058. response="$(echo $response | _dbase64 "multiline" )"
  1059. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1060. return 1
  1061. fi
  1062. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  1063. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1064. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  1065. if [ "$Le_LinkIssuer" ] ; then
  1066. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1067. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1068. echo "$END_CERT" >> "$CA_CERT_PATH"
  1069. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1070. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1071. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1072. fi
  1073. Le_CertCreateTime=$(date -u "+%s")
  1074. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  1075. Le_CertCreateTimeStr=$(date -u )
  1076. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  1077. if [ ! "$Le_RenewalDays" ] ; then
  1078. Le_RenewalDays=80
  1079. fi
  1080. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  1081. let "Le_NextRenewTime=Le_CertCreateTime+Le_RenewalDays*24*60*60"
  1082. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  1083. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1084. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  1085. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  1086. }
  1087. renew() {
  1088. Le_Domain="$1"
  1089. if [ -z "$Le_Domain" ] ; then
  1090. _err "Usage: $0 domain.com"
  1091. return 1
  1092. fi
  1093. _initpath $Le_Domain
  1094. if [ ! -f "$DOMAIN_CONF" ] ; then
  1095. _info "$Le_Domain is not a issued domain, skip."
  1096. return 0;
  1097. fi
  1098. source "$DOMAIN_CONF"
  1099. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  1100. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1101. return 2
  1102. fi
  1103. IS_RENEW="1"
  1104. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  1105. local res=$?
  1106. IS_RENEW=""
  1107. return $res
  1108. }
  1109. renewAll() {
  1110. _initpath
  1111. _info "renewAll"
  1112. for d in $(ls -F ${LE_WORKING_DIR}/ | grep [^.].*[.].*/$ ) ; do
  1113. d=$(echo $d | cut -d '/' -f 1)
  1114. _info "renew $d"
  1115. Le_LinkCert=""
  1116. Le_Domain=""
  1117. Le_Alt="no"
  1118. Le_Webroot=""
  1119. Le_Keylength=""
  1120. Le_LinkIssuer=""
  1121. Le_CertCreateTime=""
  1122. Le_CertCreateTimeStr=""
  1123. Le_RenewalDays=""
  1124. Le_NextRenewTime=""
  1125. Le_NextRenewTimeStr=""
  1126. Le_RealCertPath=""
  1127. Le_RealKeyPath=""
  1128. Le_RealCACertPath=""
  1129. Le_ReloadCmd=""
  1130. DOMAIN_PATH=""
  1131. DOMAIN_CONF=""
  1132. DOMAIN_SSL_CONF=""
  1133. CSR_PATH=""
  1134. CERT_KEY_PATH=""
  1135. CERT_PATH=""
  1136. CA_CERT_PATH=""
  1137. CERT_PFX_PATH=""
  1138. CERT_FULLCHAIN_PATH=""
  1139. ACCOUNT_KEY_PATH=""
  1140. wellknown_path=""
  1141. renew "$d"
  1142. done
  1143. }
  1144. installcert() {
  1145. Le_Domain="$1"
  1146. if [ -z "$Le_Domain" ] ; then
  1147. _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
  1148. return 1
  1149. fi
  1150. Le_RealCertPath="$2"
  1151. Le_RealKeyPath="$3"
  1152. Le_RealCACertPath="$4"
  1153. Le_ReloadCmd="$5"
  1154. _initpath $Le_Domain
  1155. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  1156. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  1157. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  1158. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  1159. if [ "$Le_RealCertPath" ] ; then
  1160. if [ -f "$Le_RealCertPath" ] ; then
  1161. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  1162. fi
  1163. cat "$CERT_PATH" > "$Le_RealCertPath"
  1164. fi
  1165. if [ "$Le_RealCACertPath" ] ; then
  1166. if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
  1167. echo "" >> "$Le_RealCACertPath"
  1168. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1169. else
  1170. if [ -f "$Le_RealCACertPath" ] ; then
  1171. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1172. fi
  1173. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1174. fi
  1175. fi
  1176. if [ "$Le_RealKeyPath" ] ; then
  1177. if [ -f "$Le_RealKeyPath" ] ; then
  1178. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1179. fi
  1180. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1181. fi
  1182. if [ "$Le_ReloadCmd" ] ; then
  1183. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1184. (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
  1185. fi
  1186. }
  1187. installcronjob() {
  1188. _initpath
  1189. if ! _exists "crontab" ; then
  1190. _err "crontab doesn't exist, so, we can not install cron jobs."
  1191. _err "All your certs will not be renewed automatically."
  1192. _err "You must add your own cron job to call 'le.sh cron' everyday."
  1193. return 1
  1194. fi
  1195. _info "Installing cron job"
  1196. if ! crontab -l | grep 'le.sh cron' ; then
  1197. if [ -f "$LE_WORKING_DIR/le.sh" ] ; then
  1198. lesh="\"$LE_WORKING_DIR\"/le.sh"
  1199. else
  1200. _err "Can not install cronjob, le.sh not found."
  1201. return 1
  1202. fi
  1203. crontab -l | { cat; echo "0 0 * * * LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  1204. fi
  1205. if [ "$?" != "0" ] ; then
  1206. _err "Install cron job failed. You need to manually renew your certs."
  1207. _err "Or you can add cronjob by yourself:"
  1208. _err "LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"
  1209. return 1
  1210. fi
  1211. }
  1212. uninstallcronjob() {
  1213. if ! _exists "crontab" ; then
  1214. return
  1215. fi
  1216. _info "Removing cron job"
  1217. cr="$(crontab -l | grep 'le.sh cron')"
  1218. if [ "$cr" ] ; then
  1219. crontab -l | sed "/le.sh cron/d" | crontab -
  1220. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 6 | cut -d '=' -f 2 | tr -d '"')"
  1221. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1222. fi
  1223. _initpath
  1224. }
  1225. revoke() {
  1226. Le_Domain="$1"
  1227. if [ -z "$Le_Domain" ] ; then
  1228. _err "Usage: revoke domain.com"
  1229. return 1
  1230. fi
  1231. _initpath $Le_Domain
  1232. if [ ! -f "$DOMAIN_CONF" ] ; then
  1233. _err "$Le_Domain is not a issued domain, skip."
  1234. return 1;
  1235. fi
  1236. if [ ! -f "$CERT_PATH" ] ; then
  1237. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  1238. return 1
  1239. fi
  1240. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  1241. if [ -z "$cert" ] ; then
  1242. _err "Cert for $Le_Domain is empty found, skip."
  1243. return 1
  1244. fi
  1245. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  1246. uri="$API/acme/revoke-cert"
  1247. _info "Try domain key first."
  1248. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  1249. if [ -z "$response" ] ; then
  1250. _info "Revoke success."
  1251. rm -f $CERT_PATH
  1252. return 0
  1253. else
  1254. _err "Revoke error by domain key."
  1255. _err "$resource"
  1256. fi
  1257. fi
  1258. _info "Then try account key."
  1259. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  1260. if [ -z "$response" ] ; then
  1261. _info "Revoke success."
  1262. rm -f $CERT_PATH
  1263. return 0
  1264. else
  1265. _err "Revoke error."
  1266. _debug "$resource"
  1267. fi
  1268. fi
  1269. return 1
  1270. }
  1271. # Detect profile file if not specified as environment variable
  1272. _detect_profile() {
  1273. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  1274. echo "$PROFILE"
  1275. return
  1276. fi
  1277. local DETECTED_PROFILE
  1278. DETECTED_PROFILE=''
  1279. local SHELLTYPE
  1280. SHELLTYPE="$(basename "/$SHELL")"
  1281. if [ "$SHELLTYPE" = "bash" ]; then
  1282. if [ -f "$HOME/.bashrc" ]; then
  1283. DETECTED_PROFILE="$HOME/.bashrc"
  1284. elif [ -f "$HOME/.bash_profile" ]; then
  1285. DETECTED_PROFILE="$HOME/.bash_profile"
  1286. fi
  1287. elif [ "$SHELLTYPE" = "zsh" ]; then
  1288. DETECTED_PROFILE="$HOME/.zshrc"
  1289. fi
  1290. if [ -z "$DETECTED_PROFILE" ]; then
  1291. if [ -f "$HOME/.profile" ]; then
  1292. DETECTED_PROFILE="$HOME/.profile"
  1293. elif [ -f "$HOME/.bashrc" ]; then
  1294. DETECTED_PROFILE="$HOME/.bashrc"
  1295. elif [ -f "$HOME/.bash_profile" ]; then
  1296. DETECTED_PROFILE="$HOME/.bash_profile"
  1297. elif [ -f "$HOME/.zshrc" ]; then
  1298. DETECTED_PROFILE="$HOME/.zshrc"
  1299. fi
  1300. fi
  1301. if [ ! -z "$DETECTED_PROFILE" ]; then
  1302. echo "$DETECTED_PROFILE"
  1303. fi
  1304. }
  1305. _initconf() {
  1306. _initpath
  1307. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1308. echo "#Account configurations:
  1309. #Here are the supported macros, uncomment them to make them take effect.
  1310. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1311. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1312. #STAGE=1 # Use the staging api
  1313. #FORCE=1 # Force to issue cert
  1314. #DEBUG=1 # Debug mode
  1315. #ACCOUNT_KEY_HASH=account key hash
  1316. USER_AGENT=\"le.sh client: $PROJECT\"
  1317. #USER_PATH=""
  1318. #dns api
  1319. #######################
  1320. #Cloudflare:
  1321. #api key
  1322. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1323. #account email
  1324. #CF_Email=\"xxxx@sss.com\"
  1325. #######################
  1326. #Dnspod.cn:
  1327. #api key id
  1328. #DP_Id=\"1234\"
  1329. #api key
  1330. #DP_Key=\"sADDsdasdgdsf\"
  1331. #######################
  1332. #Cloudxns.com:
  1333. #CX_Key=\"1234\"
  1334. #
  1335. #CX_Secret=\"sADDsdasdgdsf\"
  1336. " > $ACCOUNT_CONF_PATH
  1337. fi
  1338. if [ -n "$ACCOUNT_KEY_PATH" ]; then
  1339. _sed_i "s/^#ACCOUNT_KEY_PATH=.*$/ACCOUNT_KEY_PATH=\"${ACCOUNT_KEY_PATH//\//\\\/}\"/g" "$ACCOUNT_CONF_PATH"
  1340. fi
  1341. if [ -n "$ACCOUNT_EMAIL" ]; then
  1342. _sed_i "s/^#ACCOUNT_EMAIL=.*$/ACCOUNT_EMAIL=\"${ACCOUNT_EMAIL//\//\\\/}\"/g" "$ACCOUNT_CONF_PATH"
  1343. fi
  1344. }
  1345. _precheck() {
  1346. if ! _exists "curl" && ! _exists "wget"; then
  1347. _err "Please install curl or wget first, we need to access http resources."
  1348. return 1
  1349. fi
  1350. if ! _exists "crontab" ; then
  1351. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1352. _err "We need to set cron job to renew the certs automatically."
  1353. _err "Otherwise, your certs will not be able to be renewed automatically."
  1354. if [ -z "$FORCE" ] ; then
  1355. _err "Please define 'FORCE=1' and try install again to go without crontab."
  1356. _err "FORCE=1 ./le.sh install"
  1357. return 1
  1358. fi
  1359. fi
  1360. if ! _exists "openssl" ; then
  1361. _err "Please install openssl first."
  1362. _err "We need openssl to generate keys."
  1363. return 1
  1364. fi
  1365. if ! _exists "nc" ; then
  1366. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1367. _err "We use nc for standalone server if you use standalone mode."
  1368. _err "If you don't use standalone mode, just ignore this warning."
  1369. fi
  1370. return 0
  1371. }
  1372. install() {
  1373. if ! _initpath ; then
  1374. _err "Install failed."
  1375. return 1
  1376. fi
  1377. if ! _precheck ; then
  1378. _err "Pre-check failed, can not install."
  1379. return 1
  1380. fi
  1381. _info "Installing to $LE_WORKING_DIR"
  1382. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1383. _err "Can not craete working dir: $LE_WORKING_DIR"
  1384. return 1
  1385. fi
  1386. cp le.sh "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/le.sh"
  1387. if [ "$?" != "0" ] ; then
  1388. _err "Install failed, can not copy le.sh"
  1389. return 1
  1390. fi
  1391. _info "Installed to $LE_WORKING_DIR/le.sh"
  1392. _profile="$(_detect_profile)"
  1393. if [ "$_profile" ] ; then
  1394. _debug "Found profile: $_profile"
  1395. echo "LE_WORKING_DIR=$LE_WORKING_DIR
  1396. alias le=\"$LE_WORKING_DIR/le.sh\"
  1397. alias le.sh=\"$LE_WORKING_DIR/le.sh\"
  1398. " > "$LE_WORKING_DIR/le.env"
  1399. echo "" >> "$_profile"
  1400. _setopt "$_profile" "source \"$LE_WORKING_DIR/le.env\""
  1401. _info "OK, Close and reopen your terminal to start using le"
  1402. else
  1403. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use le.sh"
  1404. fi
  1405. mkdir -p $LE_WORKING_DIR/dnsapi
  1406. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1407. #to keep compatible mv the .acc file to .key file
  1408. if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
  1409. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  1410. fi
  1411. installcronjob
  1412. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1413. _initconf
  1414. fi
  1415. _info OK
  1416. }
  1417. uninstall() {
  1418. uninstallcronjob
  1419. _initpath
  1420. _profile="$(_detect_profile)"
  1421. if [ "$_profile" ] ; then
  1422. text="$(cat $_profile)"
  1423. echo "$text" | sed "s|^source.*le.env.*$||" > "$_profile"
  1424. fi
  1425. rm -f $LE_WORKING_DIR/le.sh
  1426. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1427. }
  1428. cron() {
  1429. IN_CRON=1
  1430. renewAll
  1431. IN_CRON=""
  1432. }
  1433. version() {
  1434. _info "$PROJECT"
  1435. _info "v$VER"
  1436. }
  1437. showhelp() {
  1438. version
  1439. echo "Usage: le.sh [command] ...[args]....
  1440. Available commands:
  1441. install:
  1442. Install le.sh to your system.
  1443. issue:
  1444. Issue a cert.
  1445. installcert:
  1446. Install the issued cert to apache/nginx or any other server.
  1447. renew:
  1448. Renew a cert.
  1449. renewAll:
  1450. Renew all the certs.
  1451. uninstall:
  1452. Uninstall le.sh, and uninstall the cron job.
  1453. revoke:
  1454. Revoke a cert.
  1455. version:
  1456. Show version info.
  1457. installcronjob:
  1458. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1459. uninstallcronjob:
  1460. Uninstall the cron job. The 'uninstall' command can do this automatically.
  1461. toPkcs:
  1462. Export the certificate and key to a pfx file.
  1463. createAccountKey:
  1464. Create an account private key, professional use.
  1465. createDomainKey:
  1466. Create an domain private key, professional use.
  1467. createCSR:
  1468. Create CSR , professional use.
  1469. "
  1470. }
  1471. _installOnline() {
  1472. _info "Installing from online archive."
  1473. if [ ! "$BRANCH" ] ; then
  1474. BRANCH="master"
  1475. fi
  1476. _initpath
  1477. target="$PROJECT/archive/$BRANCH.tar.gz"
  1478. _info "Downloading $target"
  1479. localname="$BRANCH.tar.gz"
  1480. if ! _get "$target" > $localname ; then
  1481. _debug "Download error."
  1482. return 1
  1483. fi
  1484. _info "Extracting $localname"
  1485. tar xzf $localname
  1486. cd "le-$BRANCH"
  1487. chmod +x le.sh
  1488. if ./le.sh install ; then
  1489. _info "Install success!"
  1490. fi
  1491. cd ..
  1492. rm -rf "le-$BRANCH"
  1493. rm -f "$localname"
  1494. }
  1495. if [ "$INSTALLONLINE" ] ; then
  1496. INSTALLONLINE=""
  1497. _installOnline $BRANCH
  1498. exit
  1499. fi
  1500. if [ -z "$1" ] ; then
  1501. showhelp
  1502. else
  1503. "$@"
  1504. fi