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.

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