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.

1288 lines
31 KiB

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