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.

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