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.

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