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.

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