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.

1297 lines
32 KiB

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