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.

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