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
34 KiB

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. printf "$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. printf "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  246. else
  247. _debug APP
  248. echo "" >> "$__conf"
  249. echo "$__opt$__sep$__val$__end" >> "$__conf"
  250. fi
  251. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  252. }
  253. #_savedomainconf key value
  254. #save to domain.conf
  255. _savedomainconf() {
  256. key="$1"
  257. value="$2"
  258. if [ "$DOMAIN_CONF" ] ; then
  259. _setopt $DOMAIN_CONF "$key" "=" "$value"
  260. else
  261. _err "DOMAIN_CONF is empty, can not save $key=$value"
  262. fi
  263. }
  264. #_saveaccountconf key value
  265. _saveaccountconf() {
  266. key="$1"
  267. value="$2"
  268. if [ "$ACCOUNT_CONF_PATH" ] ; then
  269. _setopt $ACCOUNT_CONF_PATH "$key" "=" "$value"
  270. else
  271. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  272. fi
  273. }
  274. _startserver() {
  275. content="$1"
  276. _NC="nc -q 1"
  277. if nc -h 2>&1 | grep "nmap.org/ncat" >/dev/null ; then
  278. _NC="nc"
  279. fi
  280. # while true ; do
  281. if [ "$DEBUG" ] ; then
  282. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -l -p $Le_HTTPPort -vv
  283. else
  284. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -l -p $Le_HTTPPort > /dev/null
  285. fi
  286. # done
  287. }
  288. _stopserver() {
  289. pid="$1"
  290. }
  291. _initpath() {
  292. if [ -z "$LE_WORKING_DIR" ]; then
  293. LE_WORKING_DIR=$HOME/.le
  294. fi
  295. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  296. ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  297. fi
  298. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  299. source "$ACCOUNT_CONF_PATH"
  300. fi
  301. if [ -z "$API" ] ; then
  302. if [ -z "$STAGE" ] ; then
  303. API="$DEFAULT_CA"
  304. else
  305. API="$STAGE_CA"
  306. _info "Using stage api:$API"
  307. fi
  308. fi
  309. if [ -z "$ACME_DIR" ] ; then
  310. ACME_DIR="/home/.acme"
  311. fi
  312. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  313. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR/"
  314. fi
  315. domain="$1"
  316. if ! mkdir -p "$LE_WORKING_DIR" ; then
  317. _err "Can not craete working dir: $LE_WORKING_DIR"
  318. return 1
  319. fi
  320. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  321. ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  322. fi
  323. if [ -z "$domain" ] ; then
  324. return 0
  325. fi
  326. domainhome="$LE_WORKING_DIR/$domain"
  327. mkdir -p "$domainhome"
  328. if [ -z "$DOMAIN_PATH" ] ; then
  329. DOMAIN_PATH="$domainhome"
  330. fi
  331. if [ -z "$DOMAIN_CONF" ] ; then
  332. DOMAIN_CONF="$domainhome/$Le_Domain.conf"
  333. fi
  334. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  335. DOMAIN_SSL_CONF="$domainhome/$Le_Domain.ssl.conf"
  336. fi
  337. if [ -z "$CSR_PATH" ] ; then
  338. CSR_PATH="$domainhome/$domain.csr"
  339. fi
  340. if [ -z "$CERT_KEY_PATH" ] ; then
  341. CERT_KEY_PATH="$domainhome/$domain.key"
  342. fi
  343. if [ -z "$CERT_PATH" ] ; then
  344. CERT_PATH="$domainhome/$domain.cer"
  345. fi
  346. if [ -z "$CA_CERT_PATH" ] ; then
  347. CA_CERT_PATH="$domainhome/ca.cer"
  348. fi
  349. }
  350. _apachePath() {
  351. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  352. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  353. httpdconf="$httpdroot/$httpdconfname"
  354. if [ ! -f $httpdconf ] ; then
  355. _err "Apache Config file not found" $httpdconf
  356. return 1
  357. fi
  358. return 0
  359. }
  360. _restoreApache() {
  361. if [ -z "$usingApache" ] ; then
  362. return 0
  363. fi
  364. _initpath
  365. if ! _apachePath ; then
  366. return 1
  367. fi
  368. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  369. _debug "No config file to restore."
  370. return 0
  371. fi
  372. cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
  373. if ! apachectl -t ; then
  374. _err "Sorry, restore apache config error, please contact me."
  375. return 1;
  376. fi
  377. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  378. return 0
  379. }
  380. _setApache() {
  381. _initpath
  382. if ! _apachePath ; then
  383. return 1
  384. fi
  385. #backup the conf
  386. _debug "Backup apache config file" $httpdconf
  387. cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
  388. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  389. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  390. _info "The backup file will be deleted on sucess, just forget it."
  391. #add alias
  392. echo "
  393. Alias /.well-known/acme-challenge $ACME_DIR
  394. <Directory $ACME_DIR >
  395. Require all granted
  396. </Directory>
  397. " >> $httpdconf
  398. if ! apachectl -t ; then
  399. _err "Sorry, apache config error, please contact me."
  400. _restoreApache
  401. return 1;
  402. fi
  403. if [ ! -d "$ACME_DIR" ] ; then
  404. mkdir -p "$ACME_DIR"
  405. chmod 755 "$ACME_DIR"
  406. fi
  407. if ! apachectl graceful ; then
  408. _err "Sorry, apachectl graceful error, please contact me."
  409. _restoreApache
  410. return 1;
  411. fi
  412. usingApache="1"
  413. return 0
  414. }
  415. _clearup () {
  416. _stopserver $serverproc
  417. serverproc=""
  418. _restoreApache
  419. }
  420. # webroot removelevel tokenfile
  421. _clearupwebbroot() {
  422. __webroot="$1"
  423. if [ -z "$__webroot" ] ; then
  424. _debug "no webroot specified, skip"
  425. return 0
  426. fi
  427. if [ "$2" == '1' ] ; then
  428. _debug "remove $__webroot/.well-known"
  429. rm -rf "$__webroot/.well-known"
  430. elif [ "$2" == '2' ] ; then
  431. _debug "remove $__webroot/.well-known/acme-challenge"
  432. rm -rf "$__webroot/.well-known/acme-challenge"
  433. elif [ "$2" == '3' ] ; then
  434. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  435. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  436. else
  437. _info "Skip for removelevel:$2"
  438. fi
  439. return 0
  440. }
  441. issue() {
  442. if [ -z "$2" ] ; then
  443. _err "Usage: le issue webroot|no|apache|dns a.com [www.a.com,b.com,c.com]|no [key-length]|no"
  444. return 1
  445. fi
  446. Le_Webroot="$1"
  447. Le_Domain="$2"
  448. Le_Alt="$3"
  449. Le_Keylength="$4"
  450. Le_RealCertPath="$5"
  451. Le_RealKeyPath="$6"
  452. Le_RealCACertPath="$7"
  453. Le_ReloadCmd="$8"
  454. _initpath $Le_Domain
  455. if [ -f "$DOMAIN_CONF" ] ; then
  456. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  457. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  458. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  459. return 2
  460. fi
  461. fi
  462. if [ "$Le_Alt" == "no" ] ; then
  463. Le_Alt=""
  464. fi
  465. if [ "$Le_Keylength" == "no" ] ; then
  466. Le_Keylength=""
  467. fi
  468. if [ "$Le_RealCertPath" == "no" ] ; then
  469. Le_RealCertPath=""
  470. fi
  471. if [ "$Le_RealKeyPath" == "no" ] ; then
  472. Le_RealKeyPath=""
  473. fi
  474. if [ "$Le_RealCACertPath" == "no" ] ; then
  475. Le_RealCACertPath=""
  476. fi
  477. if [ "$Le_ReloadCmd" == "no" ] ; then
  478. Le_ReloadCmd=""
  479. fi
  480. _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
  481. _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
  482. _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
  483. _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
  484. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  485. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  486. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  487. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  488. if [ "$Le_Webroot" == "no" ] ; then
  489. _info "Standalone mode."
  490. if ! command -v "nc" > /dev/null ; then
  491. _err "Please install netcat(nc) tools first."
  492. return 1
  493. fi
  494. if [ -z "$Le_HTTPPort" ] ; then
  495. Le_HTTPPort=80
  496. fi
  497. _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
  498. netprc="$(ss -ntpl | grep :$Le_HTTPPort" ")"
  499. if [ "$netprc" ] ; then
  500. _err "$netprc"
  501. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  502. _err "Please stop it first"
  503. return 1
  504. fi
  505. fi
  506. if [ "$Le_Webroot" == "apache" ] ; then
  507. if ! _setApache ; then
  508. _err "set up apache error. Report error to me."
  509. return 1
  510. fi
  511. wellknown_path="$ACME_DIR"
  512. else
  513. usingApache=""
  514. fi
  515. createAccountKey $Le_Domain $Le_Keylength
  516. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  517. _err "Create domain key error."
  518. return 1
  519. fi
  520. if ! createCSR $Le_Domain $Le_Alt ; then
  521. _err "Create CSR error."
  522. return 1
  523. fi
  524. 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)
  525. if [ "${#pub_exp}" == "5" ] ; then
  526. pub_exp=0$pub_exp
  527. fi
  528. _debug pub_exp "$pub_exp"
  529. e=$(echo $pub_exp | _h2b | _base64)
  530. _debug e "$e"
  531. modulus=$(openssl rsa -in $ACCOUNT_KEY_PATH -modulus -noout | cut -d '=' -f 2 )
  532. n=$(echo $modulus| _h2b | _base64 | _b64 )
  533. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  534. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  535. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  536. _debug HEADER "$HEADER"
  537. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  538. thumbprint=$(echo -n "$accountkey_json" | openssl dgst -sha256 -binary | _base64 | _b64)
  539. _info "Registering account"
  540. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  541. if [ "$ACCOUNT_EMAIL" ] ; then
  542. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  543. fi
  544. _send_signed_request "$API/acme/new-reg" "$regjson"
  545. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  546. _info "Registered"
  547. echo $response > $LE_WORKING_DIR/account.json
  548. elif [ "$code" == '409' ] ; then
  549. _info "Already registered"
  550. else
  551. _err "Register account Error."
  552. _clearup
  553. return 1
  554. fi
  555. vtype="$VTYPE_HTTP"
  556. if [[ "$Le_Webroot" == "dns"* ]] ; then
  557. vtype="$VTYPE_DNS"
  558. fi
  559. vlist="$Le_Vlist"
  560. # verify each domain
  561. _info "Verify each domain"
  562. sep='#'
  563. if [ -z "$vlist" ] ; then
  564. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  565. for d in $alldomains
  566. do
  567. _info "Getting token for domain" $d
  568. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  569. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  570. _err "new-authz error: $response"
  571. _clearup
  572. return 1
  573. fi
  574. entry="$(printf $response | egrep -o '{[^{]*"type":"'$vtype'"[^}]*')"
  575. _debug entry "$entry"
  576. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  577. _debug token $token
  578. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  579. _debug uri $uri
  580. keyauthorization="$token.$thumbprint"
  581. _debug keyauthorization "$keyauthorization"
  582. dvlist="$d$sep$keyauthorization$sep$uri"
  583. _debug dvlist "$dvlist"
  584. vlist="$vlist$dvlist,"
  585. done
  586. #add entry
  587. dnsadded=""
  588. ventries=$(echo "$vlist" | tr ',' ' ' )
  589. for ventry in $ventries
  590. do
  591. d=$(echo $ventry | cut -d $sep -f 1)
  592. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  593. if [ "$vtype" == "$VTYPE_DNS" ] ; then
  594. dnsadded='0'
  595. txtdomain="_acme-challenge.$d"
  596. _debug txtdomain "$txtdomain"
  597. txt="$(echo -e -n $keyauthorization | openssl dgst -sha256 -binary | _base64 | _b64)"
  598. _debug txt "$txt"
  599. #dns
  600. #1. check use api
  601. d_api=""
  602. if [ -f "$LE_WORKING_DIR/$d/$Le_Webroot" ] ; then
  603. d_api="$LE_WORKING_DIR/$d/$Le_Webroot"
  604. elif [ -f "$LE_WORKING_DIR/$d/$Le_Webroot.sh" ] ; then
  605. d_api="$LE_WORKING_DIR/$d/$Le_Webroot.sh"
  606. elif [ -f "$LE_WORKING_DIR/$Le_Webroot" ] ; then
  607. d_api="$LE_WORKING_DIR/$Le_Webroot"
  608. elif [ -f "$LE_WORKING_DIR/$Le_Webroot.sh" ] ; then
  609. d_api="$LE_WORKING_DIR/$Le_Webroot.sh"
  610. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot" ] ; then
  611. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot"
  612. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh" ] ; then
  613. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh"
  614. fi
  615. _debug d_api "$d_api"
  616. if [ "$d_api" ]; then
  617. _info "Found domain api file: $d_api"
  618. else
  619. _err "Add the following TXT record:"
  620. _err "Domain: $txtdomain"
  621. _err "TXT value: $txt"
  622. _err "Please be aware that you prepend _acme-challenge. before your domain"
  623. _err "so the resulting subdomain will be: $txtdomain"
  624. continue
  625. fi
  626. if ! source $d_api ; then
  627. _err "Load file $d_api error. Please check your api file and try again."
  628. return 1
  629. fi
  630. addcommand="$Le_Webroot-add"
  631. if ! command -v $addcommand ; then
  632. _err "It seems that your api file is not correct, it must have a function named: $Le_Webroot"
  633. return 1
  634. fi
  635. if ! $addcommand $txtdomain $txt ; then
  636. _err "Error add txt for domain:$txtdomain"
  637. return 1
  638. fi
  639. dnsadded='1'
  640. fi
  641. done
  642. if [ "$dnsadded" == '0' ] ; then
  643. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  644. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  645. _err "Please add the TXT records to the domains, and retry again."
  646. return 1
  647. fi
  648. fi
  649. if [ "$dnsadded" == '1' ] ; then
  650. _info "Sleep 60 seconds for the txt records to take effect"
  651. sleep 60
  652. fi
  653. _debug "ok, let's start to verify"
  654. ventries=$(echo "$vlist" | tr ',' ' ' )
  655. for ventry in $ventries
  656. do
  657. d=$(echo $ventry | cut -d $sep -f 1)
  658. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  659. uri=$(echo $ventry | cut -d $sep -f 3)
  660. _info "Verifying:$d"
  661. _debug "d" "$d"
  662. _debug "keyauthorization" "$keyauthorization"
  663. _debug "uri" "$uri"
  664. removelevel=""
  665. token=""
  666. if [ "$vtype" == "$VTYPE_HTTP" ] ; then
  667. if [ "$Le_Webroot" == "no" ] ; then
  668. _info "Standalone mode server"
  669. _startserver "$keyauthorization" &
  670. serverproc="$!"
  671. sleep 2
  672. _debug serverproc $serverproc
  673. else
  674. if [ -z "$wellknown_path" ] ; then
  675. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  676. fi
  677. _debug wellknown_path "$wellknown_path"
  678. if [ ! -d "$Le_Webroot/.well-known" ] ; then
  679. removelevel='1'
  680. elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
  681. removelevel='2'
  682. else
  683. removelevel='3'
  684. fi
  685. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  686. _debug "writing token:$token to $wellknown_path/$token"
  687. mkdir -p "$wellknown_path"
  688. echo -n "$keyauthorization" > "$wellknown_path/$token"
  689. webroot_owner=$(stat -c '%U:%G' $Le_Webroot)
  690. _debug "Changing owner/group of .well-known to $webroot_owner"
  691. chown -R $webroot_owner "$Le_Webroot/.well-known"
  692. fi
  693. fi
  694. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  695. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  696. _err "$d:Challenge error: $resource"
  697. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  698. _clearup
  699. return 1
  700. fi
  701. while [ "1" ] ; do
  702. _debug "sleep 5 secs to verify"
  703. sleep 5
  704. _debug "checking"
  705. if ! _get $uri ; then
  706. _err "$d:Verify error:$resource"
  707. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  708. _clearup
  709. return 1
  710. fi
  711. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | tr -d '"')
  712. if [ "$status" == "valid" ] ; then
  713. _info "Success"
  714. _stopserver $serverproc
  715. serverproc=""
  716. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  717. break;
  718. fi
  719. if [ "$status" == "invalid" ] ; then
  720. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  721. _err "$d:Verify error:$error"
  722. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  723. _clearup
  724. return 1;
  725. fi
  726. if [ "$status" == "pending" ] ; then
  727. _info "Pending"
  728. else
  729. _err "$d:Verify error:$response"
  730. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  731. _clearup
  732. return 1
  733. fi
  734. done
  735. done
  736. _clearup
  737. _info "Verify finished, start to sign."
  738. der="$(openssl req -in $CSR_PATH -outform DER | _base64 | _b64)"
  739. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  740. Le_LinkCert="$(grep -i -o '^Location.*$' $CURL_HEADER | tr -d "\r\n" | cut -d " " -f 2)"
  741. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  742. if [ "$Le_LinkCert" ] ; then
  743. echo -----BEGIN CERTIFICATE----- > "$CERT_PATH"
  744. curl --silent "$Le_LinkCert" | openssl base64 -e >> "$CERT_PATH"
  745. echo -----END CERTIFICATE----- >> "$CERT_PATH"
  746. _info "Cert success."
  747. cat "$CERT_PATH"
  748. _info "Your cert is in $CERT_PATH"
  749. fi
  750. if [ -z "$Le_LinkCert" ] ; then
  751. response="$(echo $response | openssl base64 -d -A)"
  752. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  753. return 1
  754. fi
  755. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  756. Le_LinkIssuer=$(grep -i '^Link' $CURL_HEADER | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  757. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  758. if [ "$Le_LinkIssuer" ] ; then
  759. echo -----BEGIN CERTIFICATE----- > "$CA_CERT_PATH"
  760. curl --silent "$Le_LinkIssuer" | openssl base64 -e >> "$CA_CERT_PATH"
  761. echo -----END CERTIFICATE----- >> "$CA_CERT_PATH"
  762. _info "The intermediate CA cert is in $CA_CERT_PATH"
  763. fi
  764. Le_CertCreateTime=$(date -u "+%s")
  765. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  766. Le_CertCreateTimeStr=$(date -u )
  767. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  768. if [ ! "$Le_RenewalDays" ] ; then
  769. Le_RenewalDays=80
  770. fi
  771. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  772. let "Le_NextRenewTime=Le_CertCreateTime+Le_RenewalDays*24*60*60"
  773. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  774. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  775. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  776. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  777. }
  778. renew() {
  779. Le_Domain="$1"
  780. if [ -z "$Le_Domain" ] ; then
  781. _err "Usage: $0 domain.com"
  782. return 1
  783. fi
  784. _initpath $Le_Domain
  785. if [ ! -f "$DOMAIN_CONF" ] ; then
  786. _info "$Le_Domain is not a issued domain, skip."
  787. return 0;
  788. fi
  789. source "$DOMAIN_CONF"
  790. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  791. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  792. return 2
  793. fi
  794. IS_RENEW="1"
  795. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  796. local res=$?
  797. IS_RENEW=""
  798. return $res
  799. }
  800. renewAll() {
  801. _initpath
  802. _info "renewAll"
  803. for d in $(ls -F $LE_WORKING_DIR | grep [^.].*[.].*/$ ) ; do
  804. d=$(echo $d | cut -d '/' -f 1)
  805. _info "renew $d"
  806. Le_LinkCert=""
  807. Le_Domain=""
  808. Le_Alt=""
  809. Le_Webroot=""
  810. Le_Keylength=""
  811. Le_LinkIssuer=""
  812. Le_CertCreateTime=""
  813. Le_CertCreateTimeStr=""
  814. Le_RenewalDays=""
  815. Le_NextRenewTime=""
  816. Le_NextRenewTimeStr=""
  817. Le_RealCertPath=""
  818. Le_RealKeyPath=""
  819. Le_RealCACertPath=""
  820. Le_ReloadCmd=""
  821. DOMAIN_PATH=""
  822. DOMAIN_CONF=""
  823. DOMAIN_SSL_CONF=""
  824. CSR_PATH=""
  825. CERT_KEY_PATH=""
  826. CERT_PATH=""
  827. CA_CERT_PATH=""
  828. ACCOUNT_KEY_PATH=""
  829. wellknown_path=""
  830. renew "$d"
  831. done
  832. }
  833. installcert() {
  834. Le_Domain="$1"
  835. if [ -z "$Le_Domain" ] ; then
  836. _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
  837. return 1
  838. fi
  839. Le_RealCertPath="$2"
  840. Le_RealKeyPath="$3"
  841. Le_RealCACertPath="$4"
  842. Le_ReloadCmd="$5"
  843. _initpath $Le_Domain
  844. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  845. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  846. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  847. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  848. if [ "$Le_RealCertPath" ] ; then
  849. if [ -f "$Le_RealCertPath" ] ; then
  850. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  851. fi
  852. cat "$CERT_PATH" > "$Le_RealCertPath"
  853. fi
  854. if [ "$Le_RealCACertPath" ] ; then
  855. if [ -f "$Le_RealCACertPath" ] ; then
  856. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  857. fi
  858. if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
  859. echo "" >> "$Le_RealCACertPath"
  860. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  861. else
  862. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  863. fi
  864. fi
  865. if [ "$Le_RealKeyPath" ] ; then
  866. if [ -f "$Le_RealKeyPath" ] ; then
  867. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  868. fi
  869. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  870. fi
  871. if [ "$Le_ReloadCmd" ] ; then
  872. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  873. (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
  874. fi
  875. }
  876. installcronjob() {
  877. _initpath
  878. _info "Installing cron job"
  879. if ! crontab -l | grep 'le.sh cron' ; then
  880. if [ -f "$LE_WORKING_DIR/le.sh" ] ; then
  881. lesh="\"$LE_WORKING_DIR\"/le.sh"
  882. else
  883. _err "Can not install cronjob, le.sh not found."
  884. return 1
  885. fi
  886. crontab -l | { cat; echo "0 0 * * * LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  887. fi
  888. if [ "$?" != "0" ] ; then
  889. _err "Install cron job failed. You need to manually renew your certs."
  890. _err "Or you can add cronjob by yourself:"
  891. _err "LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"
  892. return 1
  893. fi
  894. }
  895. uninstallcronjob() {
  896. _info "Removing cron job"
  897. cr="$(crontab -l | grep 'le.sh cron')"
  898. if [ "$cr" ] ; then
  899. crontab -l | sed "/le.sh cron/d" | crontab -
  900. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 6 | cut -d '=' -f 2 | tr -d '"')"
  901. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  902. fi
  903. _initpath
  904. }
  905. # Detect profile file if not specified as environment variable
  906. _detect_profile() {
  907. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  908. echo "$PROFILE"
  909. return
  910. fi
  911. local DETECTED_PROFILE
  912. DETECTED_PROFILE=''
  913. local SHELLTYPE
  914. SHELLTYPE="$(basename "/$SHELL")"
  915. if [ "$SHELLTYPE" = "bash" ]; then
  916. if [ -f "$HOME/.bashrc" ]; then
  917. DETECTED_PROFILE="$HOME/.bashrc"
  918. elif [ -f "$HOME/.bash_profile" ]; then
  919. DETECTED_PROFILE="$HOME/.bash_profile"
  920. fi
  921. elif [ "$SHELLTYPE" = "zsh" ]; then
  922. DETECTED_PROFILE="$HOME/.zshrc"
  923. fi
  924. if [ -z "$DETECTED_PROFILE" ]; then
  925. if [ -f "$HOME/.profile" ]; then
  926. DETECTED_PROFILE="$HOME/.profile"
  927. elif [ -f "$HOME/.bashrc" ]; then
  928. DETECTED_PROFILE="$HOME/.bashrc"
  929. elif [ -f "$HOME/.bash_profile" ]; then
  930. DETECTED_PROFILE="$HOME/.bash_profile"
  931. elif [ -f "$HOME/.zshrc" ]; then
  932. DETECTED_PROFILE="$HOME/.zshrc"
  933. fi
  934. fi
  935. if [ ! -z "$DETECTED_PROFILE" ]; then
  936. echo "$DETECTED_PROFILE"
  937. fi
  938. }
  939. _initconf() {
  940. _initpath
  941. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  942. echo "#Account configurations:
  943. #Here are the supported macros, uncomment them to make them take effect.
  944. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  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. _setopt "$_profile" "source \"$LE_WORKING_DIR/le.env\""
  1020. _info "OK, Close and reopen your terminal to start using le"
  1021. else
  1022. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use le.sh"
  1023. fi
  1024. mkdir -p $LE_WORKING_DIR/dnsapi
  1025. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1026. #to keep compatible mv the .acc file to .key file
  1027. if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
  1028. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  1029. fi
  1030. installcronjob
  1031. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1032. _initconf
  1033. fi
  1034. _info OK
  1035. }
  1036. uninstall() {
  1037. uninstallcronjob
  1038. _initpath
  1039. _profile="$(_detect_profile)"
  1040. if [ "$_profile" ] ; then
  1041. sed -i /le.env/d "$_profile"
  1042. fi
  1043. rm -f $LE_WORKING_DIR/le.sh
  1044. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1045. }
  1046. cron() {
  1047. renewAll
  1048. }
  1049. version() {
  1050. _info "$PROJECT"
  1051. _info "v$VER"
  1052. }
  1053. showhelp() {
  1054. version
  1055. echo "Usage: le.sh [command] ...[args]....
  1056. Avalible commands:
  1057. install:
  1058. Install le.sh to your system.
  1059. issue:
  1060. Issue a cert.
  1061. installcert:
  1062. Install the issued cert to apache/nginx or any other server.
  1063. renew:
  1064. Renew a cert.
  1065. renewAll:
  1066. Renew all the certs.
  1067. uninstall:
  1068. Uninstall le.sh, and uninstall the cron job.
  1069. version:
  1070. Show version info.
  1071. installcronjob:
  1072. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1073. uninstallcronjob:
  1074. Uninstall the cron job. The 'uninstall' command can do this automatically.
  1075. createAccountKey:
  1076. Create an account private key, professional use.
  1077. createDomainKey:
  1078. Create an domain private key, professional use.
  1079. createCSR:
  1080. Create CSR , professional use.
  1081. "
  1082. }
  1083. if [ -z "$1" ] ; then
  1084. showhelp
  1085. else
  1086. "$@"
  1087. fi