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.

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