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.

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