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.

1263 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 80 -vv
  264. else
  265. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -l -p 80 > /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. netprc="$(ss -ntpl | grep ':80 ')"
  473. if [ "$netprc" ] ; then
  474. _err "$netprc"
  475. _err "tcp port 80 is already used by $(echo "$netprc" | cut -d : -f 4)"
  476. _err "Please stop it first"
  477. return 1
  478. fi
  479. fi
  480. if [ "$Le_Webroot" == "apache" ] ; then
  481. if ! _setApache ; then
  482. _err "set up apache error. Report error to me."
  483. return 1
  484. fi
  485. wellknown_path="$ACME_DIR"
  486. else
  487. usingApache=""
  488. fi
  489. createAccountKey $Le_Domain $Le_Keylength
  490. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  491. _err "Create domain key error."
  492. return 1
  493. fi
  494. if ! createCSR $Le_Domain $Le_Alt ; then
  495. _err "Create CSR error."
  496. return 1
  497. fi
  498. 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)
  499. if [ "${#pub_exp}" == "5" ] ; then
  500. pub_exp=0$pub_exp
  501. fi
  502. _debug pub_exp "$pub_exp"
  503. e=$(echo $pub_exp | _h2b | _base64)
  504. _debug e "$e"
  505. modulus=$(openssl rsa -in $ACCOUNT_KEY_PATH -modulus -noout | cut -d '=' -f 2 )
  506. n=$(echo $modulus| _h2b | _base64 | _b64 )
  507. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  508. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  509. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  510. _debug HEADER "$HEADER"
  511. accountkey_json=$(echo -n "$jwk" | sed "s/ //g")
  512. thumbprint=$(echo -n "$accountkey_json" | openssl dgst -sha256 -binary | _base64 | _b64)
  513. _info "Registering account"
  514. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  515. if [ "$ACCOUNT_EMAIL" ] ; then
  516. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  517. fi
  518. _send_signed_request "$API/acme/new-reg" "$regjson"
  519. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  520. _info "Registered"
  521. echo $response > $LE_WORKING_DIR/account.json
  522. elif [ "$code" == '409' ] ; then
  523. _info "Already registered"
  524. else
  525. _err "Register account Error."
  526. _clearup
  527. return 1
  528. fi
  529. vtype="$VTYPE_HTTP"
  530. if [[ "$Le_Webroot" == "dns"* ]] ; then
  531. vtype="$VTYPE_DNS"
  532. fi
  533. vlist="$Le_Vlist"
  534. # verify each domain
  535. _info "Verify each domain"
  536. sep='#'
  537. if [ -z "$vlist" ] ; then
  538. alldomains=$(echo "$Le_Domain,$Le_Alt" | sed "s/,/ /g")
  539. for d in $alldomains
  540. do
  541. _info "Geting token for domain" $d
  542. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  543. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  544. _err "new-authz error: $response"
  545. _clearup
  546. return 1
  547. fi
  548. entry=$(echo $response | egrep -o '{[^{]*"type":"'$vtype'"[^}]*')
  549. _debug entry "$entry"
  550. token=$(echo "$entry" | sed 's/,/\n'/g| grep '"token":'| cut -d : -f 2|sed 's/"//g')
  551. _debug token $token
  552. uri=$(echo "$entry" | sed 's/,/\n'/g| grep '"uri":'| cut -d : -f 2,3|sed 's/"//g')
  553. _debug uri $uri
  554. keyauthorization="$token.$thumbprint"
  555. _debug keyauthorization "$keyauthorization"
  556. dvlist="$d$sep$keyauthorization$sep$uri"
  557. _debug dvlist "$dvlist"
  558. vlist="$vlist$dvlist,"
  559. done
  560. #add entry
  561. dnsadded=""
  562. ventries=$(echo "$vlist" | sed "s/,/ /g")
  563. for ventry in $ventries
  564. do
  565. d=$(echo $ventry | cut -d $sep -f 1)
  566. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  567. if [ "$vtype" == "$VTYPE_DNS" ] ; then
  568. dnsadded='0'
  569. txtdomain="_acme-challenge.$d"
  570. _debug txtdomain "$txtdomain"
  571. txt="$(echo -e -n $keyauthorization | openssl sha -sha256 -binary | _base64 | _b64)"
  572. _debug txt "$txt"
  573. #dns
  574. #1. check use api
  575. d_api=""
  576. if [ -f "$LE_WORKING_DIR/$d/$Le_Webroot" ] ; then
  577. d_api="$LE_WORKING_DIR/$d/$Le_Webroot"
  578. elif [ -f "$LE_WORKING_DIR/$d/$Le_Webroot.sh" ] ; then
  579. d_api="$LE_WORKING_DIR/$d/$Le_Webroot.sh"
  580. elif [ -f "$LE_WORKING_DIR/$Le_Webroot" ] ; then
  581. d_api="$LE_WORKING_DIR/$Le_Webroot"
  582. elif [ -f "$LE_WORKING_DIR/$Le_Webroot.sh" ] ; then
  583. d_api="$LE_WORKING_DIR/$Le_Webroot.sh"
  584. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot" ] ; then
  585. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot"
  586. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh" ] ; then
  587. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh"
  588. fi
  589. _debug d_api "$d_api"
  590. if [ "$d_api" ]; then
  591. _info "Found domain api file: $d_api"
  592. else
  593. _err "Add the following TXT record:"
  594. _err "Domain: $txtdomain"
  595. _err "TXT value: $txt"
  596. _err "Please be aware that you prepend _acme-challenge. before your domain"
  597. _err "so the resulting subdomain will be: $txtdomain"
  598. continue
  599. fi
  600. if ! source $d_api ; then
  601. _err "Load file $d_api error. Please check your api file and try again."
  602. return 1
  603. fi
  604. addcommand="$Le_Webroot-add"
  605. if ! command -v $addcommand ; then
  606. _err "It seems that your api file is not correct, it must have a function named: $Le_Webroot"
  607. return 1
  608. fi
  609. if ! $addcommand $txtdomain $txt ; then
  610. _err "Error add txt for domain:$txtdomain"
  611. return 1
  612. fi
  613. dnsadded='1'
  614. fi
  615. done
  616. if [ "$dnsadded" == '0' ] ; then
  617. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  618. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  619. _err "Please add the TXT records to the domains, and retry again."
  620. return 1
  621. fi
  622. fi
  623. if [ "$dnsadded" == '1' ] ; then
  624. _info "Sleep 60 seconds for the txt records to take effect"
  625. sleep 60
  626. fi
  627. _debug "ok, let's start to verify"
  628. ventries=$(echo "$vlist" | sed "s/,/ /g")
  629. for ventry in $ventries
  630. do
  631. d=$(echo $ventry | cut -d $sep -f 1)
  632. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  633. uri=$(echo $ventry | cut -d $sep -f 3)
  634. _info "Verifying:$d"
  635. _debug "d" "$d"
  636. _debug "keyauthorization" "$keyauthorization"
  637. _debug "uri" "$uri"
  638. removelevel=""
  639. token=""
  640. if [ "$vtype" == "$VTYPE_HTTP" ] ; then
  641. if [ "$Le_Webroot" == "no" ] ; then
  642. _info "Standalone mode server"
  643. _startserver "$keyauthorization" &
  644. serverproc="$!"
  645. sleep 2
  646. _debug serverproc $serverproc
  647. else
  648. if [ -z "$wellknown_path" ] ; then
  649. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  650. fi
  651. _debug wellknown_path "$wellknown_path"
  652. if [ ! -d "$Le_Webroot/.well-known" ] ; then
  653. removelevel='1'
  654. elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
  655. removelevel='2'
  656. else
  657. removelevel='3'
  658. fi
  659. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  660. _debug "writing token:$token to $wellknown_path/$token"
  661. mkdir -p "$wellknown_path"
  662. echo -n "$keyauthorization" > "$wellknown_path/$token"
  663. webroot_owner=$(stat -c '%U:%G' $Le_Webroot)
  664. _debug "Changing owner/group of .well-known to $webroot_owner"
  665. chown -R $webroot_owner "$Le_Webroot/.well-known"
  666. fi
  667. fi
  668. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  669. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  670. _err "$d:Challenge error: $resource"
  671. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  672. _clearup
  673. return 1
  674. fi
  675. while [ "1" ] ; do
  676. _debug "sleep 5 secs to verify"
  677. sleep 5
  678. _debug "checking"
  679. if ! _get $uri ; then
  680. _err "$d:Verify error:$resource"
  681. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  682. _clearup
  683. return 1
  684. fi
  685. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | sed 's/"//g')
  686. if [ "$status" == "valid" ] ; then
  687. _info "Success"
  688. _stopserver $serverproc
  689. serverproc=""
  690. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  691. break;
  692. fi
  693. if [ "$status" == "invalid" ] ; then
  694. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  695. _err "$d:Verify error:$error"
  696. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  697. _clearup
  698. return 1;
  699. fi
  700. if [ "$status" == "pending" ] ; then
  701. _info "Pending"
  702. else
  703. _err "$d:Verify error:$response"
  704. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  705. _clearup
  706. return 1
  707. fi
  708. done
  709. done
  710. _clearup
  711. _info "Verify finished, start to sign."
  712. der="$(openssl req -in $CSR_PATH -outform DER | _base64 | _b64)"
  713. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  714. Le_LinkCert="$(grep -i -o '^Location.*' $CURL_HEADER |sed 's/\r//g'| cut -d " " -f 2)"
  715. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  716. if [ "$Le_LinkCert" ] ; then
  717. echo -----BEGIN CERTIFICATE----- > "$CERT_PATH"
  718. curl --silent "$Le_LinkCert" | openssl base64 -e >> "$CERT_PATH"
  719. echo -----END CERTIFICATE----- >> "$CERT_PATH"
  720. _info "Cert success."
  721. cat "$CERT_PATH"
  722. _info "Your cert is in $CERT_PATH"
  723. fi
  724. if [ -z "$Le_LinkCert" ] ; then
  725. response="$(echo $response | openssl base64 -d -A)"
  726. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  727. return 1
  728. fi
  729. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  730. Le_LinkIssuer=$(grep -i '^Link' $CURL_HEADER | cut -d " " -f 2| cut -d ';' -f 1 | sed 's/<//g' | sed 's/>//g')
  731. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  732. if [ "$Le_LinkIssuer" ] ; then
  733. echo -----BEGIN CERTIFICATE----- > "$CA_CERT_PATH"
  734. curl --silent "$Le_LinkIssuer" | openssl base64 -e >> "$CA_CERT_PATH"
  735. echo -----END CERTIFICATE----- >> "$CA_CERT_PATH"
  736. _info "The intermediate CA cert is in $CA_CERT_PATH"
  737. fi
  738. Le_CertCreateTime=$(date -u "+%s")
  739. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  740. Le_CertCreateTimeStr=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
  741. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  742. if [ ! "$Le_RenewalDays" ] ; then
  743. Le_RenewalDays=80
  744. fi
  745. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  746. Le_NextRenewTime=$(date -u -d "+$Le_RenewalDays day" "+%s")
  747. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  748. Le_NextRenewTimeStr=$(date -u -d "+$Le_RenewalDays day" "+%Y-%m-%d %H:%M:%S UTC")
  749. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  750. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  751. }
  752. renew() {
  753. Le_Domain="$1"
  754. if [ -z "$Le_Domain" ] ; then
  755. _err "Usage: $0 domain.com"
  756. return 1
  757. fi
  758. _initpath $Le_Domain
  759. if [ ! -f "$DOMAIN_CONF" ] ; then
  760. _info "$Le_Domain is not a issued domain, skip."
  761. return 0;
  762. fi
  763. source "$DOMAIN_CONF"
  764. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  765. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  766. return 2
  767. fi
  768. IS_RENEW="1"
  769. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  770. local res=$?
  771. IS_RENEW=""
  772. return $res
  773. }
  774. renewAll() {
  775. _initpath
  776. _info "renewAll"
  777. for d in $(ls -F $LE_WORKING_DIR | grep [^.].*[.].*/$ ) ; do
  778. d=$(echo $d | cut -d '/' -f 1)
  779. _info "renew $d"
  780. Le_LinkCert=""
  781. Le_Domain=""
  782. Le_Alt=""
  783. Le_Webroot=""
  784. Le_Keylength=""
  785. Le_LinkIssuer=""
  786. Le_CertCreateTime=""
  787. Le_CertCreateTimeStr=""
  788. Le_RenewalDays=""
  789. Le_NextRenewTime=""
  790. Le_NextRenewTimeStr=""
  791. Le_RealCertPath=""
  792. Le_RealKeyPath=""
  793. Le_RealCACertPath=""
  794. Le_ReloadCmd=""
  795. DOMAIN_CONF=""
  796. CSR_PATH=""
  797. CERT_KEY_PATH=""
  798. CERT_PATH=""
  799. CA_CERT_PATH=""
  800. ACCOUNT_KEY_PATH=""
  801. wellknown_path=""
  802. renew "$d"
  803. done
  804. }
  805. installcert() {
  806. Le_Domain="$1"
  807. if [ -z "$Le_Domain" ] ; then
  808. _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
  809. return 1
  810. fi
  811. Le_RealCertPath="$2"
  812. Le_RealKeyPath="$3"
  813. Le_RealCACertPath="$4"
  814. Le_ReloadCmd="$5"
  815. _initpath $Le_Domain
  816. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  817. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  818. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  819. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  820. if [ "$Le_RealCertPath" ] ; then
  821. if [ -f "$Le_RealCertPath" ] ; then
  822. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  823. fi
  824. cat "$CERT_PATH" > "$Le_RealCertPath"
  825. fi
  826. if [ "$Le_RealCACertPath" ] ; then
  827. if [ -f "$Le_RealCACertPath" ] ; then
  828. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  829. fi
  830. if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
  831. echo "" >> "$Le_RealCACertPath"
  832. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  833. else
  834. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  835. fi
  836. fi
  837. if [ "$Le_RealKeyPath" ] ; then
  838. if [ -f "$Le_RealKeyPath" ] ; then
  839. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  840. fi
  841. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  842. fi
  843. if [ "$Le_ReloadCmd" ] ; then
  844. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  845. $Le_ReloadCmd
  846. fi
  847. }
  848. installcronjob() {
  849. _initpath
  850. _info "Installing cron job"
  851. if ! crontab -l | grep 'le.sh cron' ; then
  852. if [ -f "$LE_WORKING_DIR/le.sh" ] ; then
  853. lesh="\"$LE_WORKING_DIR\"/le.sh"
  854. else
  855. _err "Can not install cronjob, le.sh not found."
  856. return 1
  857. fi
  858. crontab -l | { cat; echo "0 0 * * * $SUDO LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  859. fi
  860. return 0
  861. }
  862. uninstallcronjob() {
  863. _info "Removing cron job"
  864. cr="$(crontab -l | grep 'le.sh cron')"
  865. if [ "$cr" ] ; then
  866. crontab -l | sed "/le.sh cron/d" | crontab -
  867. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 7 | cut -d '=' -f 2 | tr -d '"')"
  868. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  869. fi
  870. _initpath
  871. }
  872. # Detect profile file if not specified as environment variable
  873. _detect_profile() {
  874. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  875. echo "$PROFILE"
  876. return
  877. fi
  878. local DETECTED_PROFILE
  879. DETECTED_PROFILE=''
  880. local SHELLTYPE
  881. SHELLTYPE="$(basename "/$SHELL")"
  882. if [ "$SHELLTYPE" = "bash" ]; then
  883. if [ -f "$HOME/.bashrc" ]; then
  884. DETECTED_PROFILE="$HOME/.bashrc"
  885. elif [ -f "$HOME/.bash_profile" ]; then
  886. DETECTED_PROFILE="$HOME/.bash_profile"
  887. fi
  888. elif [ "$SHELLTYPE" = "zsh" ]; then
  889. DETECTED_PROFILE="$HOME/.zshrc"
  890. fi
  891. if [ -z "$DETECTED_PROFILE" ]; then
  892. if [ -f "$HOME/.profile" ]; then
  893. DETECTED_PROFILE="$HOME/.profile"
  894. elif [ -f "$HOME/.bashrc" ]; then
  895. DETECTED_PROFILE="$HOME/.bashrc"
  896. elif [ -f "$HOME/.bash_profile" ]; then
  897. DETECTED_PROFILE="$HOME/.bash_profile"
  898. elif [ -f "$HOME/.zshrc" ]; then
  899. DETECTED_PROFILE="$HOME/.zshrc"
  900. fi
  901. fi
  902. if [ ! -z "$DETECTED_PROFILE" ]; then
  903. echo "$DETECTED_PROFILE"
  904. fi
  905. }
  906. _initconf() {
  907. _initpath
  908. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  909. echo "#Account configurations:
  910. #Here are the supported macros, uncomment them to make them take effect.
  911. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  912. #STAGE=1 # Use the staging api
  913. #FORCE=1 # Force to issue cert
  914. #DEBUG=1 # Debug mode
  915. #dns api
  916. #######################
  917. #Cloudflare:
  918. #api key
  919. #CF_Key="sdfsdfsdfljlbjkljlkjsdfoiwje"
  920. #account email
  921. #CF_Email="xxxx@sss.com"
  922. #######################
  923. #Dnspod.cn:
  924. #api key id
  925. #DP_Id="1234"
  926. #api key
  927. #DP_Key="sADDsdasdgdsf"
  928. #######################
  929. #Cloudxns.com:
  930. #CX_Key="1234"
  931. #
  932. #CX_Secret="sADDsdasdgdsf"
  933. " > $ACCOUNT_CONF_PATH
  934. fi
  935. }
  936. install() {
  937. _initpath
  938. if command -v yum > /dev/null ; then
  939. YUM="1"
  940. INSTALL="$SUDO yum install -y "
  941. elif command -v apt-get > /dev/null ; then
  942. INSTALL="$SUDO apt-get install -y "
  943. fi
  944. if ! command -v "curl" > /dev/null ; then
  945. _err "Please install curl first."
  946. _err "$INSTALL curl"
  947. return 1
  948. fi
  949. if ! command -v "crontab" > /dev/null ; then
  950. _err "Please install crontab first."
  951. if [ "$YUM" ] ; then
  952. _err "$INSTALL crontabs"
  953. else
  954. _err "$INSTALL crontab"
  955. fi
  956. return 1
  957. fi
  958. if ! command -v "openssl" > /dev/null ; then
  959. _err "Please install openssl first."
  960. _err "$INSTALL openssl"
  961. return 1
  962. fi
  963. _info "Installing to $LE_WORKING_DIR"
  964. _info "Installed to $LE_WORKING_DIR/le.sh"
  965. cp le.sh $LE_WORKING_DIR/
  966. chmod +x $LE_WORKING_DIR/le.sh
  967. _profile="$(_detect_profile)"
  968. if [ "$_profile" ] ; then
  969. _debug "Found profile: $_profile"
  970. echo "LE_WORKING_DIR=$LE_WORKING_DIR
  971. alias le=\"$LE_WORKING_DIR/le.sh\"
  972. alias le.sh=\"$LE_WORKING_DIR/le.sh\"
  973. " > "$LE_WORKING_DIR/le.env"
  974. _setopt "$_profile" "source \"$LE_WORKING_DIR/le.env\""
  975. _info "OK, Close and reopen your terminal to start using le"
  976. else
  977. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use le.sh"
  978. fi
  979. mkdir -p $LE_WORKING_DIR/dnsapi
  980. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  981. #to keep compatible mv the .acc file to .key file
  982. if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
  983. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  984. fi
  985. installcronjob
  986. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  987. _initconf
  988. fi
  989. _info OK
  990. }
  991. uninstall() {
  992. uninstallcronjob
  993. _initpath
  994. _profile="$(_detect_profile)"
  995. if [ "$_profile" ] ; then
  996. sed -i /le.env/d "$_profile"
  997. fi
  998. rm -f $LE_WORKING_DIR/le.sh
  999. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1000. }
  1001. cron() {
  1002. renewAll
  1003. }
  1004. version() {
  1005. _info "$PROJECT"
  1006. _info "v$VER"
  1007. }
  1008. showhelp() {
  1009. version
  1010. echo "Usage: le.sh [command] ...[args]....
  1011. Avalible commands:
  1012. install:
  1013. Install le.sh to your system.
  1014. issue:
  1015. Issue a cert.
  1016. installcert:
  1017. Install the issued cert to apache/nginx or any other server.
  1018. renew:
  1019. Renew a cert.
  1020. renewAll:
  1021. Renew all the certs.
  1022. uninstall:
  1023. Uninstall le.sh, and uninstall the cron job.
  1024. version:
  1025. Show version info.
  1026. installcronjob:
  1027. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1028. uninstallcronjob:
  1029. Uninstall the cron job. The 'uninstall' command can do this automatically.
  1030. createAccountKey:
  1031. Create an account private key, professional use.
  1032. createDomainKey:
  1033. Create an domain private key, professional use.
  1034. createCSR:
  1035. Create CSR , professional use.
  1036. "
  1037. }
  1038. if [ -z "$1" ] ; then
  1039. showhelp
  1040. else
  1041. "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9"
  1042. fi