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.

1719 lines
42 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
  1. #!/usr/bin/env bash
  2. VER=1.2.2
  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. #domain [2048]
  177. createAccountKey() {
  178. _info "Creating account key"
  179. if [ -z "$1" ] ; then
  180. echo Usage: createAccountKey account-domain [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. #domain length
  202. createDomainKey() {
  203. _info "Creating domain key"
  204. if [ -z "$1" ] ; then
  205. echo Usage: createDomainKey domain [2048]
  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. # domain domainlist
  256. createCSR() {
  257. _info "Creating csr"
  258. if [ -z "$1" ] ; then
  259. echo Usage: $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. #keyfile
  307. _calcjwk() {
  308. keyfile="$1"
  309. if [ -z "$keyfile" ] ; then
  310. _err "Usage: _calcjwk 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. # 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. # 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. # 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. #setopt "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. echo usage: _setopt '"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. #_savedomainconf key value
  477. #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. #_saveaccountconf 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. _startserver() {
  498. content="$1"
  499. nchelp="$(nc -h 2>&1)"
  500. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  501. _NC="nc -q 1 -l"
  502. else
  503. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  504. _NC="nc -c -l"
  505. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  506. _NC="nc -N -l"
  507. else
  508. _NC="nc -l"
  509. fi
  510. fi
  511. _debug "_NC" "$_NC"
  512. # while true ; do
  513. if [ "$DEBUG" ] ; then
  514. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort -vv ; then
  515. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort -vv ;
  516. fi
  517. else
  518. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  519. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  520. fi
  521. fi
  522. if [ "$?" != "0" ] ; then
  523. _err "nc listen error."
  524. return 1
  525. fi
  526. # done
  527. }
  528. _stopserver() {
  529. pid="$1"
  530. }
  531. _initpath() {
  532. if [ -z "$LE_WORKING_DIR" ]; then
  533. LE_WORKING_DIR=$HOME/.le
  534. fi
  535. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  536. ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  537. fi
  538. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  539. source "$ACCOUNT_CONF_PATH"
  540. fi
  541. if [[ "$IN_CRON" ]] ; then
  542. if [[ ! "$_USER_PATH_EXPORTED" ]] ; then
  543. _USER_PATH_EXPORTED=1
  544. export PATH="$USER_PATH:$PATH"
  545. fi
  546. fi
  547. if [ -z "$API" ] ; then
  548. if [ -z "$STAGE" ] ; then
  549. API="$DEFAULT_CA"
  550. else
  551. API="$STAGE_CA"
  552. _info "Using stage api:$API"
  553. fi
  554. fi
  555. if [ -z "$ACME_DIR" ] ; then
  556. ACME_DIR="/home/.acme"
  557. fi
  558. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  559. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  560. fi
  561. if [ -z "$USER_AGENT" ] ; then
  562. USER_AGENT="$DEFAULT_USER_AGENT"
  563. fi
  564. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  565. WGET="wget -q"
  566. if [ "$DEBUG" ] ; then
  567. WGET="$WGET -d "
  568. fi
  569. dp="$LE_WORKING_DIR/curl.dump"
  570. CURL="curl -L --silent"
  571. if [ "$DEBUG" ] ; then
  572. CURL="$CURL -L --trace-ascii $dp "
  573. fi
  574. domain="$1"
  575. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  576. ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  577. fi
  578. if [ -z "$domain" ] ; then
  579. return 0
  580. fi
  581. domainhome="$LE_WORKING_DIR/$domain"
  582. mkdir -p "$domainhome"
  583. if [ -z "$DOMAIN_PATH" ] ; then
  584. DOMAIN_PATH="$domainhome"
  585. fi
  586. if [ -z "$DOMAIN_CONF" ] ; then
  587. DOMAIN_CONF="$domainhome/$domain.conf"
  588. fi
  589. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  590. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  591. fi
  592. if [ -z "$CSR_PATH" ] ; then
  593. CSR_PATH="$domainhome/$domain.csr"
  594. fi
  595. if [ -z "$CERT_KEY_PATH" ] ; then
  596. CERT_KEY_PATH="$domainhome/$domain.key"
  597. fi
  598. if [ -z "$CERT_PATH" ] ; then
  599. CERT_PATH="$domainhome/$domain.cer"
  600. fi
  601. if [ -z "$CA_CERT_PATH" ] ; then
  602. CA_CERT_PATH="$domainhome/ca.cer"
  603. fi
  604. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  605. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  606. fi
  607. }
  608. _apachePath() {
  609. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  610. if [[ "$httpdconfname" == '/'* ]] ; then
  611. httpdconf="$httpdconfname"
  612. httpdconfname="$(basename $httpdconfname)"
  613. else
  614. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  615. httpdconf="$httpdroot/$httpdconfname"
  616. fi
  617. if [ ! -f $httpdconf ] ; then
  618. _err "Apache Config file not found" $httpdconf
  619. return 1
  620. fi
  621. return 0
  622. }
  623. _restoreApache() {
  624. if [ -z "$usingApache" ] ; then
  625. return 0
  626. fi
  627. _initpath
  628. if ! _apachePath ; then
  629. return 1
  630. fi
  631. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  632. _debug "No config file to restore."
  633. return 0
  634. fi
  635. cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
  636. if ! apachectl -t ; then
  637. _err "Sorry, restore apache config error, please contact me."
  638. return 1;
  639. fi
  640. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  641. return 0
  642. }
  643. _setApache() {
  644. _initpath
  645. if ! _apachePath ; then
  646. return 1
  647. fi
  648. #backup the conf
  649. _debug "Backup apache config file" $httpdconf
  650. cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
  651. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  652. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  653. _info "The backup file will be deleted on sucess, just forget it."
  654. #add alias
  655. apacheVer="$(apachectl -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  656. _debug "apacheVer" "$apacheVer"
  657. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  658. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  659. if [[ "$apacheVer" ]] && [[ "$apacheMajer" -ge "2" ]] && [[ "$apacheMinor" -ge "4" ]] ; then
  660. echo "
  661. Alias /.well-known/acme-challenge $ACME_DIR
  662. <Directory $ACME_DIR >
  663. Require all granted
  664. </Directory>
  665. " >> $httpdconf
  666. else
  667. echo "
  668. Alias /.well-known/acme-challenge $ACME_DIR
  669. <Directory $ACME_DIR >
  670. Order allow,deny
  671. Allow from all
  672. </Directory>
  673. " >> $httpdconf
  674. fi
  675. if ! apachectl -t ; then
  676. _err "Sorry, apache config error, please contact me."
  677. _restoreApache
  678. return 1;
  679. fi
  680. if [ ! -d "$ACME_DIR" ] ; then
  681. mkdir -p "$ACME_DIR"
  682. chmod 755 "$ACME_DIR"
  683. fi
  684. if ! apachectl graceful ; then
  685. _err "Sorry, apachectl graceful error, please contact me."
  686. _restoreApache
  687. return 1;
  688. fi
  689. usingApache="1"
  690. return 0
  691. }
  692. _clearup () {
  693. _stopserver $serverproc
  694. serverproc=""
  695. _restoreApache
  696. }
  697. # webroot removelevel tokenfile
  698. _clearupwebbroot() {
  699. __webroot="$1"
  700. if [ -z "$__webroot" ] ; then
  701. _debug "no webroot specified, skip"
  702. return 0
  703. fi
  704. if [ "$2" == '1' ] ; then
  705. _debug "remove $__webroot/.well-known"
  706. rm -rf "$__webroot/.well-known"
  707. elif [ "$2" == '2' ] ; then
  708. _debug "remove $__webroot/.well-known/acme-challenge"
  709. rm -rf "$__webroot/.well-known/acme-challenge"
  710. elif [ "$2" == '3' ] ; then
  711. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  712. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  713. else
  714. _info "Skip for removelevel:$2"
  715. fi
  716. return 0
  717. }
  718. issue() {
  719. if [ -z "$2" ] ; then
  720. _err "Usage: le issue webroot|no|apache|dns a.com [www.a.com,b.com,c.com]|no [key-length]|no"
  721. return 1
  722. fi
  723. Le_Webroot="$1"
  724. Le_Domain="$2"
  725. Le_Alt="$3"
  726. Le_Keylength="$4"
  727. Le_RealCertPath="$5"
  728. Le_RealKeyPath="$6"
  729. Le_RealCACertPath="$7"
  730. Le_ReloadCmd="$8"
  731. _initpath $Le_Domain
  732. if [ -f "$DOMAIN_CONF" ] ; then
  733. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  734. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  735. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  736. return 2
  737. fi
  738. fi
  739. _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
  740. _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
  741. _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
  742. _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
  743. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  744. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  745. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  746. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  747. if [ "$Le_Alt" == "no" ] ; then
  748. Le_Alt=""
  749. fi
  750. if [ "$Le_Keylength" == "no" ] ; then
  751. Le_Keylength=""
  752. fi
  753. if [ "$Le_RealCertPath" == "no" ] ; then
  754. Le_RealCertPath=""
  755. fi
  756. if [ "$Le_RealKeyPath" == "no" ] ; then
  757. Le_RealKeyPath=""
  758. fi
  759. if [ "$Le_RealCACertPath" == "no" ] ; then
  760. Le_RealCACertPath=""
  761. fi
  762. if [ "$Le_ReloadCmd" == "no" ] ; then
  763. Le_ReloadCmd=""
  764. fi
  765. if [ "$Le_Webroot" == "no" ] ; then
  766. _info "Standalone mode."
  767. if ! command -v "nc" > /dev/null ; then
  768. _err "Please install netcat(nc) tools first."
  769. return 1
  770. fi
  771. if [ -z "$Le_HTTPPort" ] ; then
  772. Le_HTTPPort=80
  773. fi
  774. _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
  775. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  776. if [ "$netprc" ] ; then
  777. _err "$netprc"
  778. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  779. _err "Please stop it first"
  780. return 1
  781. fi
  782. fi
  783. if [ "$Le_Webroot" == "apache" ] ; then
  784. if ! _setApache ; then
  785. _err "set up apache error. Report error to me."
  786. return 1
  787. fi
  788. wellknown_path="$ACME_DIR"
  789. else
  790. usingApache=""
  791. fi
  792. createAccountKey $Le_Domain $Le_Keylength
  793. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  794. return 1
  795. fi
  796. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  797. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  798. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  799. if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
  800. _info "Registering account"
  801. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  802. if [ "$ACCOUNT_EMAIL" ] ; then
  803. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  804. fi
  805. _send_signed_request "$API/acme/new-reg" "$regjson"
  806. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  807. _info "Registered"
  808. echo $response > $LE_WORKING_DIR/account.json
  809. elif [ "$code" == '409' ] ; then
  810. _info "Already registered"
  811. else
  812. _err "Register account Error: $response"
  813. _clearup
  814. return 1
  815. fi
  816. ACCOUNT_KEY_HASH="$accountkeyhash"
  817. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  818. else
  819. _info "Skip register account key"
  820. fi
  821. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  822. _err "Create domain key error."
  823. return 1
  824. fi
  825. if ! createCSR $Le_Domain $Le_Alt ; then
  826. _err "Create CSR error."
  827. return 1
  828. fi
  829. vtype="$VTYPE_HTTP"
  830. if [[ "$Le_Webroot" == "dns"* ]] ; then
  831. vtype="$VTYPE_DNS"
  832. fi
  833. vlist="$Le_Vlist"
  834. # verify each domain
  835. _info "Verify each domain"
  836. sep='#'
  837. if [ -z "$vlist" ] ; then
  838. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  839. for d in $alldomains
  840. do
  841. _info "Getting token for domain" $d
  842. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  843. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  844. _err "new-authz error: $response"
  845. _clearup
  846. return 1
  847. fi
  848. entry="$(printf $response | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  849. _debug entry "$entry"
  850. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  851. _debug token $token
  852. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  853. _debug uri $uri
  854. keyauthorization="$token.$thumbprint"
  855. _debug keyauthorization "$keyauthorization"
  856. dvlist="$d$sep$keyauthorization$sep$uri"
  857. _debug dvlist "$dvlist"
  858. vlist="$vlist$dvlist,"
  859. done
  860. #add entry
  861. dnsadded=""
  862. ventries=$(echo "$vlist" | tr ',' ' ' )
  863. for ventry in $ventries
  864. do
  865. d=$(echo $ventry | cut -d $sep -f 1)
  866. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  867. if [ "$vtype" == "$VTYPE_DNS" ] ; then
  868. dnsadded='0'
  869. txtdomain="_acme-challenge.$d"
  870. _debug txtdomain "$txtdomain"
  871. txt="$(echo -e -n $keyauthorization | _digest "sha256" | _urlencode)"
  872. _debug txt "$txt"
  873. #dns
  874. #1. check use api
  875. d_api=""
  876. if [ -f "$LE_WORKING_DIR/$d/$Le_Webroot" ] ; then
  877. d_api="$LE_WORKING_DIR/$d/$Le_Webroot"
  878. elif [ -f "$LE_WORKING_DIR/$d/$Le_Webroot.sh" ] ; then
  879. d_api="$LE_WORKING_DIR/$d/$Le_Webroot.sh"
  880. elif [ -f "$LE_WORKING_DIR/$Le_Webroot" ] ; then
  881. d_api="$LE_WORKING_DIR/$Le_Webroot"
  882. elif [ -f "$LE_WORKING_DIR/$Le_Webroot.sh" ] ; then
  883. d_api="$LE_WORKING_DIR/$Le_Webroot.sh"
  884. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot" ] ; then
  885. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot"
  886. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh" ] ; then
  887. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh"
  888. fi
  889. _debug d_api "$d_api"
  890. if [ "$d_api" ]; then
  891. _info "Found domain api file: $d_api"
  892. else
  893. _err "Add the following TXT record:"
  894. _err "Domain: $txtdomain"
  895. _err "TXT value: $txt"
  896. _err "Please be aware that you prepend _acme-challenge. before your domain"
  897. _err "so the resulting subdomain will be: $txtdomain"
  898. continue
  899. fi
  900. (
  901. if ! source $d_api ; then
  902. _err "Load file $d_api error. Please check your api file and try again."
  903. return 1
  904. fi
  905. addcommand="$Le_Webroot-add"
  906. if ! command -v $addcommand ; then
  907. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  908. return 1
  909. fi
  910. if ! $addcommand $txtdomain $txt ; then
  911. _err "Error add txt for domain:$txtdomain"
  912. return 1
  913. fi
  914. )
  915. if [[ "$?" != "0" ]] ; then
  916. return 1
  917. fi
  918. dnsadded='1'
  919. fi
  920. done
  921. if [ "$dnsadded" == '0' ] ; then
  922. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  923. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  924. _err "Please add the TXT records to the domains, and retry again."
  925. return 1
  926. fi
  927. fi
  928. if [ "$dnsadded" == '1' ] ; then
  929. _info "Sleep 60 seconds for the txt records to take effect"
  930. sleep 60
  931. fi
  932. _debug "ok, let's start to verify"
  933. ventries=$(echo "$vlist" | tr ',' ' ' )
  934. for ventry in $ventries
  935. do
  936. d=$(echo $ventry | cut -d $sep -f 1)
  937. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  938. uri=$(echo $ventry | cut -d $sep -f 3)
  939. _info "Verifying:$d"
  940. _debug "d" "$d"
  941. _debug "keyauthorization" "$keyauthorization"
  942. _debug "uri" "$uri"
  943. removelevel=""
  944. token=""
  945. if [ "$vtype" == "$VTYPE_HTTP" ] ; then
  946. if [ "$Le_Webroot" == "no" ] ; then
  947. _info "Standalone mode server"
  948. _startserver "$keyauthorization" &
  949. serverproc="$!"
  950. sleep 2
  951. _debug serverproc $serverproc
  952. else
  953. if [ -z "$wellknown_path" ] ; then
  954. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  955. fi
  956. _debug wellknown_path "$wellknown_path"
  957. if [ ! -d "$Le_Webroot/.well-known" ] ; then
  958. removelevel='1'
  959. elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
  960. removelevel='2'
  961. else
  962. removelevel='3'
  963. fi
  964. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  965. _debug "writing token:$token to $wellknown_path/$token"
  966. mkdir -p "$wellknown_path"
  967. echo -n "$keyauthorization" > "$wellknown_path/$token"
  968. if [[ ! "$usingApache" ]] ; then
  969. webroot_owner=$(_stat $Le_Webroot)
  970. _debug "Changing owner/group of .well-known to $webroot_owner"
  971. chown -R $webroot_owner "$Le_Webroot/.well-known"
  972. fi
  973. fi
  974. fi
  975. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  976. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  977. _err "$d:Challenge error: $response"
  978. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  979. _clearup
  980. return 1
  981. fi
  982. while [ "1" ] ; do
  983. _debug "sleep 5 secs to verify"
  984. sleep 5
  985. _debug "checking"
  986. response="$(_get $uri)"
  987. if [ "$?" != "0" ] ; then
  988. _err "$d:Verify error:$response"
  989. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  990. _clearup
  991. return 1
  992. fi
  993. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  994. if [ "$status" == "valid" ] ; then
  995. _info "Success"
  996. _stopserver $serverproc
  997. serverproc=""
  998. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  999. break;
  1000. fi
  1001. if [ "$status" == "invalid" ] ; then
  1002. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  1003. _err "$d:Verify error:$error"
  1004. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  1005. _clearup
  1006. return 1;
  1007. fi
  1008. if [ "$status" == "pending" ] ; then
  1009. _info "Pending"
  1010. else
  1011. _err "$d:Verify error:$response"
  1012. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  1013. _clearup
  1014. return 1
  1015. fi
  1016. done
  1017. done
  1018. _clearup
  1019. _info "Verify finished, start to sign."
  1020. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1021. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  1022. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1023. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  1024. if [ "$Le_LinkCert" ] ; then
  1025. echo "$BEGIN_CERT" > "$CERT_PATH"
  1026. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1027. echo "$END_CERT" >> "$CERT_PATH"
  1028. _info "Cert success."
  1029. cat "$CERT_PATH"
  1030. _info "Your cert is in $CERT_PATH"
  1031. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1032. if [[ ! "$USER_PATH" ]] || [[ ! "$IN_CRON" ]] ; then
  1033. USER_PATH="$PATH"
  1034. _saveaccountconf "USER_PATH" "$USER_PATH"
  1035. fi
  1036. fi
  1037. if [ -z "$Le_LinkCert" ] ; then
  1038. response="$(echo $response | _dbase64 "multiline" )"
  1039. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1040. return 1
  1041. fi
  1042. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  1043. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1044. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  1045. if [ "$Le_LinkIssuer" ] ; then
  1046. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1047. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1048. echo "$END_CERT" >> "$CA_CERT_PATH"
  1049. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1050. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1051. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1052. fi
  1053. Le_CertCreateTime=$(date -u "+%s")
  1054. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  1055. Le_CertCreateTimeStr=$(date -u )
  1056. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  1057. if [ ! "$Le_RenewalDays" ] ; then
  1058. Le_RenewalDays=80
  1059. fi
  1060. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  1061. let "Le_NextRenewTime=Le_CertCreateTime+Le_RenewalDays*24*60*60"
  1062. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  1063. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1064. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  1065. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  1066. }
  1067. renew() {
  1068. Le_Domain="$1"
  1069. if [ -z "$Le_Domain" ] ; then
  1070. _err "Usage: $0 domain.com"
  1071. return 1
  1072. fi
  1073. _initpath $Le_Domain
  1074. if [ ! -f "$DOMAIN_CONF" ] ; then
  1075. _info "$Le_Domain is not a issued domain, skip."
  1076. return 0;
  1077. fi
  1078. source "$DOMAIN_CONF"
  1079. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  1080. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1081. return 2
  1082. fi
  1083. IS_RENEW="1"
  1084. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  1085. local res=$?
  1086. IS_RENEW=""
  1087. return $res
  1088. }
  1089. renewAll() {
  1090. _initpath
  1091. _info "renewAll"
  1092. for d in $(ls -F ${LE_WORKING_DIR}/ | grep [^.].*[.].*/$ ) ; do
  1093. d=$(echo $d | cut -d '/' -f 1)
  1094. _info "renew $d"
  1095. Le_LinkCert=""
  1096. Le_Domain=""
  1097. Le_Alt="no"
  1098. Le_Webroot=""
  1099. Le_Keylength=""
  1100. Le_LinkIssuer=""
  1101. Le_CertCreateTime=""
  1102. Le_CertCreateTimeStr=""
  1103. Le_RenewalDays=""
  1104. Le_NextRenewTime=""
  1105. Le_NextRenewTimeStr=""
  1106. Le_RealCertPath=""
  1107. Le_RealKeyPath=""
  1108. Le_RealCACertPath=""
  1109. Le_ReloadCmd=""
  1110. DOMAIN_PATH=""
  1111. DOMAIN_CONF=""
  1112. DOMAIN_SSL_CONF=""
  1113. CSR_PATH=""
  1114. CERT_KEY_PATH=""
  1115. CERT_PATH=""
  1116. CA_CERT_PATH=""
  1117. CERT_FULLCHAIN_PATH=""
  1118. ACCOUNT_KEY_PATH=""
  1119. wellknown_path=""
  1120. renew "$d"
  1121. done
  1122. }
  1123. installcert() {
  1124. Le_Domain="$1"
  1125. if [ -z "$Le_Domain" ] ; then
  1126. _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
  1127. return 1
  1128. fi
  1129. Le_RealCertPath="$2"
  1130. Le_RealKeyPath="$3"
  1131. Le_RealCACertPath="$4"
  1132. Le_ReloadCmd="$5"
  1133. _initpath $Le_Domain
  1134. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  1135. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  1136. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  1137. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  1138. if [ "$Le_RealCertPath" ] ; then
  1139. if [ -f "$Le_RealCertPath" ] ; then
  1140. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  1141. fi
  1142. cat "$CERT_PATH" > "$Le_RealCertPath"
  1143. fi
  1144. if [ "$Le_RealCACertPath" ] ; then
  1145. if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
  1146. echo "" >> "$Le_RealCACertPath"
  1147. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1148. else
  1149. if [ -f "$Le_RealCACertPath" ] ; then
  1150. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1151. fi
  1152. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1153. fi
  1154. fi
  1155. if [ "$Le_RealKeyPath" ] ; then
  1156. if [ -f "$Le_RealKeyPath" ] ; then
  1157. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1158. fi
  1159. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1160. fi
  1161. if [ "$Le_ReloadCmd" ] ; then
  1162. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1163. (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
  1164. fi
  1165. }
  1166. installcronjob() {
  1167. _initpath
  1168. if ! _exists "crontab" ; then
  1169. _err "crontab doesn't exist, so, we can not install cron jobs."
  1170. _err "All your certs will not be renewed automatically."
  1171. _err "You must add your own cron job to call 'le.sh cron' everyday."
  1172. return 1
  1173. fi
  1174. _info "Installing cron job"
  1175. if ! crontab -l | grep 'le.sh cron' ; then
  1176. if [ -f "$LE_WORKING_DIR/le.sh" ] ; then
  1177. lesh="\"$LE_WORKING_DIR\"/le.sh"
  1178. else
  1179. _err "Can not install cronjob, le.sh not found."
  1180. return 1
  1181. fi
  1182. crontab -l | { cat; echo "0 0 * * * LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  1183. fi
  1184. if [ "$?" != "0" ] ; then
  1185. _err "Install cron job failed. You need to manually renew your certs."
  1186. _err "Or you can add cronjob by yourself:"
  1187. _err "LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"
  1188. return 1
  1189. fi
  1190. }
  1191. uninstallcronjob() {
  1192. if ! _exists "crontab" ; then
  1193. return
  1194. fi
  1195. _info "Removing cron job"
  1196. cr="$(crontab -l | grep 'le.sh cron')"
  1197. if [ "$cr" ] ; then
  1198. crontab -l | sed "/le.sh cron/d" | crontab -
  1199. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 6 | cut -d '=' -f 2 | tr -d '"')"
  1200. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1201. fi
  1202. _initpath
  1203. }
  1204. # Detect profile file if not specified as environment variable
  1205. _detect_profile() {
  1206. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  1207. echo "$PROFILE"
  1208. return
  1209. fi
  1210. local DETECTED_PROFILE
  1211. DETECTED_PROFILE=''
  1212. local SHELLTYPE
  1213. SHELLTYPE="$(basename "/$SHELL")"
  1214. if [ "$SHELLTYPE" = "bash" ]; then
  1215. if [ -f "$HOME/.bashrc" ]; then
  1216. DETECTED_PROFILE="$HOME/.bashrc"
  1217. elif [ -f "$HOME/.bash_profile" ]; then
  1218. DETECTED_PROFILE="$HOME/.bash_profile"
  1219. fi
  1220. elif [ "$SHELLTYPE" = "zsh" ]; then
  1221. DETECTED_PROFILE="$HOME/.zshrc"
  1222. fi
  1223. if [ -z "$DETECTED_PROFILE" ]; then
  1224. if [ -f "$HOME/.profile" ]; then
  1225. DETECTED_PROFILE="$HOME/.profile"
  1226. elif [ -f "$HOME/.bashrc" ]; then
  1227. DETECTED_PROFILE="$HOME/.bashrc"
  1228. elif [ -f "$HOME/.bash_profile" ]; then
  1229. DETECTED_PROFILE="$HOME/.bash_profile"
  1230. elif [ -f "$HOME/.zshrc" ]; then
  1231. DETECTED_PROFILE="$HOME/.zshrc"
  1232. fi
  1233. fi
  1234. if [ ! -z "$DETECTED_PROFILE" ]; then
  1235. echo "$DETECTED_PROFILE"
  1236. fi
  1237. }
  1238. _initconf() {
  1239. _initpath
  1240. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1241. echo "#Account configurations:
  1242. #Here are the supported macros, uncomment them to make them take effect.
  1243. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1244. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1245. #STAGE=1 # Use the staging api
  1246. #FORCE=1 # Force to issue cert
  1247. #DEBUG=1 # Debug mode
  1248. #ACCOUNT_KEY_HASH=account key hash
  1249. USER_AGENT=\"le.sh client: $PROJECT\"
  1250. #USER_PATH=""
  1251. #dns api
  1252. #######################
  1253. #Cloudflare:
  1254. #api key
  1255. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1256. #account email
  1257. #CF_Email=\"xxxx@sss.com\"
  1258. #######################
  1259. #Dnspod.cn:
  1260. #api key id
  1261. #DP_Id=\"1234\"
  1262. #api key
  1263. #DP_Key=\"sADDsdasdgdsf\"
  1264. #######################
  1265. #Cloudxns.com:
  1266. #CX_Key=\"1234\"
  1267. #
  1268. #CX_Secret=\"sADDsdasdgdsf\"
  1269. " > $ACCOUNT_CONF_PATH
  1270. fi
  1271. }
  1272. _precheck() {
  1273. if ! _exists "curl" && ! _exists "wget"; then
  1274. _err "Please install curl or wget first, we need to access http resources."
  1275. return 1
  1276. fi
  1277. if ! _exists "crontab" ; then
  1278. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1279. _err "We need to set cron job to renew the certs automatically."
  1280. _err "Otherwise, your certs will not be able to be renewed automatically."
  1281. if [ -z "$FORCE" ] ; then
  1282. _err "Please define 'FORCE=1' and try install again to go without crontab."
  1283. _err "FORCE=1 ./le.sh install"
  1284. return 1
  1285. fi
  1286. fi
  1287. if ! _exists "openssl" ; then
  1288. _err "Please install openssl first."
  1289. _err "We need openssl to generate keys."
  1290. return 1
  1291. fi
  1292. if ! _exists "nc" ; then
  1293. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1294. _err "We use nc for standalone server if you use standalone mode."
  1295. _err "If you don't use standalone mode, just ignore this warning."
  1296. fi
  1297. return 0
  1298. }
  1299. install() {
  1300. if ! _initpath ; then
  1301. _err "Install failed."
  1302. return 1
  1303. fi
  1304. if ! _precheck ; then
  1305. _err "Pre-check failed, can not install."
  1306. return 1
  1307. fi
  1308. _info "Installing to $LE_WORKING_DIR"
  1309. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1310. _err "Can not craete working dir: $LE_WORKING_DIR"
  1311. return 1
  1312. fi
  1313. cp le.sh "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/le.sh"
  1314. if [ "$?" != "0" ] ; then
  1315. _err "Install failed, can not copy le.sh"
  1316. return 1
  1317. fi
  1318. _info "Installed to $LE_WORKING_DIR/le.sh"
  1319. _profile="$(_detect_profile)"
  1320. if [ "$_profile" ] ; then
  1321. _debug "Found profile: $_profile"
  1322. echo "LE_WORKING_DIR=$LE_WORKING_DIR
  1323. alias le=\"$LE_WORKING_DIR/le.sh\"
  1324. alias le.sh=\"$LE_WORKING_DIR/le.sh\"
  1325. " > "$LE_WORKING_DIR/le.env"
  1326. echo "" >> "$_profile"
  1327. _setopt "$_profile" "source \"$LE_WORKING_DIR/le.env\""
  1328. _info "OK, Close and reopen your terminal to start using le"
  1329. else
  1330. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use le.sh"
  1331. fi
  1332. mkdir -p $LE_WORKING_DIR/dnsapi
  1333. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1334. #to keep compatible mv the .acc file to .key file
  1335. if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
  1336. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  1337. fi
  1338. installcronjob
  1339. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1340. _initconf
  1341. fi
  1342. _info OK
  1343. }
  1344. uninstall() {
  1345. uninstallcronjob
  1346. _initpath
  1347. _profile="$(_detect_profile)"
  1348. if [ "$_profile" ] ; then
  1349. text="$(cat $_profile)"
  1350. echo "$text" | sed "s|^source.*le.env.*$||" > "$_profile"
  1351. fi
  1352. rm -f $LE_WORKING_DIR/le.sh
  1353. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1354. }
  1355. cron() {
  1356. IN_CRON=1
  1357. renewAll
  1358. IN_CRON=""
  1359. }
  1360. version() {
  1361. _info "$PROJECT"
  1362. _info "v$VER"
  1363. }
  1364. showhelp() {
  1365. version
  1366. echo "Usage: le.sh [command] ...[args]....
  1367. Avalible commands:
  1368. install:
  1369. Install le.sh to your system.
  1370. issue:
  1371. Issue a cert.
  1372. installcert:
  1373. Install the issued cert to apache/nginx or any other server.
  1374. renew:
  1375. Renew a cert.
  1376. renewAll:
  1377. Renew all the certs.
  1378. uninstall:
  1379. Uninstall le.sh, and uninstall the cron job.
  1380. version:
  1381. Show version info.
  1382. installcronjob:
  1383. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1384. uninstallcronjob:
  1385. Uninstall the cron job. The 'uninstall' command can do this automatically.
  1386. createAccountKey:
  1387. Create an account private key, professional use.
  1388. createDomainKey:
  1389. Create an domain private key, professional use.
  1390. createCSR:
  1391. Create CSR , professional use.
  1392. "
  1393. }
  1394. _installOnline() {
  1395. _info "Installing from online archive."
  1396. if [ ! "$BRANCH" ] ; then
  1397. BRANCH="master"
  1398. fi
  1399. _initpath
  1400. target="$PROJECT/archive/$BRANCH.tar.gz"
  1401. _info "Downloading $target"
  1402. localname="$BRANCH.tar.gz"
  1403. if ! _get "$target" > $localname ; then
  1404. _debug "Download error."
  1405. return 1
  1406. fi
  1407. _info "Extracting $localname"
  1408. tar xzf $localname
  1409. cd "le-$BRANCH"
  1410. chmod +x le.sh
  1411. if ./le.sh install ; then
  1412. _info "Install success!"
  1413. fi
  1414. cd ..
  1415. rm -rf "le-$BRANCH"
  1416. rm -f "$localname"
  1417. }
  1418. if [ "$INSTALLONLINE" ] ; then
  1419. INSTALLONLINE=""
  1420. _installOnline $BRANCH
  1421. exit
  1422. fi
  1423. if [ -z "$1" ] ; then
  1424. showhelp
  1425. else
  1426. "$@"
  1427. fi