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.

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