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.

1058 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 record:"
  515. _err "Domain:$txtdomain"
  516. _err "Txt value:$txt"
  517. #dnsadded='1'
  518. fi
  519. done
  520. if [ "$dnsadded" == '0' ] ; then
  521. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  522. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  523. _err "Please add the txt records to the domains, and retry again."
  524. return 1
  525. fi
  526. fi
  527. _debug "ok, let's start to verify"
  528. ventries=$(echo "$vlist" | sed "s/,/ /g")
  529. for ventry in $ventries
  530. do
  531. d=$(echo $ventry | cut -d $sep -f 1)
  532. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  533. uri=$(echo $ventry | cut -d $sep -f 3)
  534. _info "Verifying:$d"
  535. _debug "d" "$d"
  536. _debug "keyauthorization" "$keyauthorization"
  537. _debug "uri" "$uri"
  538. removelevel=""
  539. token=""
  540. if [ "$vtype" == "$VTYPE_HTTP" ] ; then
  541. if [ "$Le_Webroot" == "no" ] ; then
  542. _info "Standalone mode server"
  543. _startserver "$keyauthorization" &
  544. serverproc="$!"
  545. sleep 2
  546. _debug serverproc $serverproc
  547. else
  548. if [ -z "$wellknown_path" ] ; then
  549. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  550. fi
  551. _debug wellknown_path "$wellknown_path"
  552. if [ ! -d "$Le_Webroot/.well-known" ] ; then
  553. removelevel='1'
  554. elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
  555. removelevel='2'
  556. else
  557. removelevel='3'
  558. fi
  559. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  560. _debug "writing token:$token to $wellknown_path/$token"
  561. mkdir -p "$wellknown_path"
  562. echo -n "$keyauthorization" > "$wellknown_path/$token"
  563. webroot_owner=$(stat -c '%U:%G' $Le_Webroot)
  564. _debug "Changing owner/group of .well-known to $webroot_owner"
  565. chown -R $webroot_owner "$Le_Webroot/.well-known"
  566. fi
  567. fi
  568. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  569. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  570. _err "$d:Challenge error: $resource"
  571. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  572. _clearup
  573. return 1
  574. fi
  575. while [ "1" ] ; do
  576. _debug "sleep 5 secs to verify"
  577. sleep 5
  578. _debug "checking"
  579. if ! _get $uri ; then
  580. _err "$d:Verify error:$resource"
  581. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  582. _clearup
  583. return 1
  584. fi
  585. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | sed 's/"//g')
  586. if [ "$status" == "valid" ] ; then
  587. _info "Success"
  588. _stopserver $serverproc
  589. serverproc=""
  590. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  591. break;
  592. fi
  593. if [ "$status" == "invalid" ] ; then
  594. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  595. _err "$d:Verify error:$error"
  596. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  597. _clearup
  598. return 1;
  599. fi
  600. if [ "$status" == "pending" ] ; then
  601. _info "Pending"
  602. else
  603. _err "$d:Verify error:$response"
  604. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  605. _clearup
  606. return 1
  607. fi
  608. done
  609. done
  610. _clearup
  611. _info "Verify finished, start to sign."
  612. der="$(openssl req -in $CSR_PATH -outform DER | _base64 | _b64)"
  613. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  614. Le_LinkCert="$(grep -i -o '^Location.*' $CURL_HEADER |sed 's/\r//g'| cut -d " " -f 2)"
  615. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  616. if [ "$Le_LinkCert" ] ; then
  617. echo -----BEGIN CERTIFICATE----- > "$CERT_PATH"
  618. curl --silent "$Le_LinkCert" | openssl base64 -e >> "$CERT_PATH"
  619. echo -----END CERTIFICATE----- >> "$CERT_PATH"
  620. _info "Cert success."
  621. cat "$CERT_PATH"
  622. _info "Your cert is in $CERT_PATH"
  623. fi
  624. if [ -z "$Le_LinkCert" ] ; then
  625. response="$(echo $response | openssl base64 -d)"
  626. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  627. return 1
  628. fi
  629. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  630. Le_LinkIssuer=$(grep -i '^Link' $CURL_HEADER | cut -d " " -f 2| cut -d ';' -f 1 | sed 's/<//g' | sed 's/>//g')
  631. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  632. if [ "$Le_LinkIssuer" ] ; then
  633. echo -----BEGIN CERTIFICATE----- > "$CA_CERT_PATH"
  634. curl --silent "$Le_LinkIssuer" | openssl base64 -e >> "$CA_CERT_PATH"
  635. echo -----END CERTIFICATE----- >> "$CA_CERT_PATH"
  636. _info "The intermediate CA cert is in $CA_CERT_PATH"
  637. fi
  638. Le_CertCreateTime=$(date -u "+%s")
  639. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  640. Le_CertCreateTimeStr=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
  641. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  642. if [ ! "$Le_RenewalDays" ] ; then
  643. Le_RenewalDays=80
  644. fi
  645. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  646. Le_NextRenewTime=$(date -u -d "+$Le_RenewalDays day" "+%s")
  647. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  648. Le_NextRenewTimeStr=$(date -u -d "+$Le_RenewalDays day" "+%Y-%m-%d %H:%M:%S UTC")
  649. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  650. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  651. }
  652. renew() {
  653. Le_Domain="$1"
  654. if [ -z "$Le_Domain" ] ; then
  655. _err "Usage: $0 domain.com"
  656. return 1
  657. fi
  658. _initpath $Le_Domain
  659. if [ -f "$DOMAIN_CONF" ] ; then
  660. source "$DOMAIN_CONF"
  661. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  662. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  663. return 2
  664. fi
  665. fi
  666. IS_RENEW="1"
  667. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  668. IS_RENEW=""
  669. }
  670. renewAll() {
  671. _initpath
  672. _info "renewAll"
  673. for d in $(ls -F $WORKING_DIR | grep '/$') ; do
  674. d=$(echo $d | cut -d '/' -f 1)
  675. _info "renew $d"
  676. Le_LinkCert=""
  677. Le_Domain=""
  678. Le_Alt=""
  679. Le_Webroot=""
  680. Le_Keylength=""
  681. Le_LinkIssuer=""
  682. Le_CertCreateTime=""
  683. Le_CertCreateTimeStr=""
  684. Le_RenewalDays=""
  685. Le_NextRenewTime=""
  686. Le_NextRenewTimeStr=""
  687. Le_RealCertPath=""
  688. Le_RealKeyPath=""
  689. Le_RealCACertPath=""
  690. Le_ReloadCmd=""
  691. DOMAIN_CONF=""
  692. CSR_PATH=""
  693. CERT_KEY_PATH=""
  694. CERT_PATH=""
  695. CA_CERT_PATH=""
  696. ACCOUNT_KEY_PATH=""
  697. wellknown_path=""
  698. renew "$d"
  699. done
  700. }
  701. installcert() {
  702. Le_Domain="$1"
  703. if [ -z "$Le_Domain" ] ; then
  704. _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
  705. return 1
  706. fi
  707. Le_RealCertPath="$2"
  708. Le_RealKeyPath="$3"
  709. Le_RealCACertPath="$4"
  710. Le_ReloadCmd="$5"
  711. _initpath $Le_Domain
  712. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  713. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  714. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  715. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  716. if [ "$Le_RealCertPath" ] ; then
  717. if [ -f "$Le_RealCertPath" ] ; then
  718. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  719. fi
  720. cat "$CERT_PATH" > "$Le_RealCertPath"
  721. fi
  722. if [ "$Le_RealCACertPath" ] ; then
  723. if [ -f "$Le_RealCACertPath" ] ; then
  724. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  725. fi
  726. if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
  727. echo "" >> "$Le_RealCACertPath"
  728. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  729. else
  730. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  731. fi
  732. fi
  733. if [ "$Le_RealKeyPath" ] ; then
  734. if [ -f "$Le_RealKeyPath" ] ; then
  735. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  736. fi
  737. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  738. fi
  739. if [ "$Le_ReloadCmd" ] ; then
  740. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  741. $Le_ReloadCmd
  742. fi
  743. }
  744. installcronjob() {
  745. _initpath
  746. _info "Installing cron job"
  747. if ! crontab -l | grep 'le.sh cron' ; then
  748. if [ -f "$WORKING_DIR/le.sh" ] ; then
  749. lesh="\"$WORKING_DIR\"/le.sh"
  750. else
  751. _err "Can not install cronjob, le.sh not found."
  752. return 1
  753. fi
  754. crontab -l | { cat; echo "0 0 * * * $SUDO WORKING_DIR=\"$WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  755. fi
  756. return 0
  757. }
  758. uninstallcronjob() {
  759. _info "Removing cron job"
  760. cr="$(crontab -l | grep 'le.sh cron')"
  761. if [ "$cr" ] ; then
  762. crontab -l | sed "/le.sh cron/d" | crontab -
  763. WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 7 | cut -d '=' -f 2 | tr -d '"')"
  764. _info WORKING_DIR "$WORKING_DIR"
  765. fi
  766. _initpath
  767. }
  768. install() {
  769. _initpath
  770. if command -v yum > /dev/null ; then
  771. YUM="1"
  772. INSTALL="$SUDO yum install -y "
  773. elif command -v apt-get > /dev/null ; then
  774. INSTALL="$SUDO apt-get install -y "
  775. fi
  776. if ! command -v "curl" > /dev/null ; then
  777. _err "Please install curl first."
  778. _err "$INSTALL curl"
  779. return 1
  780. fi
  781. if ! command -v "crontab" > /dev/null ; then
  782. _err "Please install crontab first."
  783. if [ "$YUM" ] ; then
  784. _err "$INSTALL crontabs"
  785. else
  786. _err "$INSTALL crontab"
  787. fi
  788. return 1
  789. fi
  790. if ! command -v "openssl" > /dev/null ; then
  791. _err "Please install openssl first."
  792. _err "$INSTALL openssl"
  793. return 1
  794. fi
  795. _info "Installing to $WORKING_DIR"
  796. #try install to /bin if is root
  797. if [ ! -f /usr/local/bin/le.sh ] ; then
  798. #if root
  799. if $SUDO cp le.sh /usr/local/bin/le.sh > /dev/null 2>&1; then
  800. $SUDO chmod 755 /usr/local/bin/le.sh
  801. $SUDO ln -s "/usr/local/bin/le.sh" /usr/local/bin/le
  802. rm -f $WORKING_DIR/le.sh
  803. $SUDO ln -s /usr/local/bin/le.sh $WORKING_DIR/le.sh
  804. _info "Installed to /usr/local/bin/le"
  805. else
  806. #install to home, for non root user
  807. cp le.sh $WORKING_DIR/
  808. chmod +x $WORKING_DIR/le.sh
  809. _info "Installed to $WORKING_DIR/le.sh"
  810. fi
  811. fi
  812. rm -f $WORKING_DIR/le
  813. ln -s $WORKING_DIR/le.sh $WORKING_DIR/le
  814. installcronjob
  815. _info OK
  816. }
  817. uninstall() {
  818. uninstallcronjob
  819. _initpath
  820. if [ -f "/usr/local/bin/le.sh" ] ; then
  821. _info "Removing /usr/local/bin/le.sh"
  822. if $SUDO rm -f /usr/local/bin/le.sh ; then
  823. $SUDO rm -f /usr/local/bin/le
  824. fi
  825. fi
  826. rm -f $WORKING_DIR/le
  827. rm -f $WORKING_DIR/le.sh
  828. _info "The keys and certs are in $WORKING_DIR, you can remove them by yourself."
  829. }
  830. cron() {
  831. renewAll
  832. }
  833. version() {
  834. _info "$PROJECT"
  835. _info "v$VER"
  836. }
  837. showhelp() {
  838. version
  839. echo "Usage: le.sh [command] ...[args]....
  840. Avalible commands:
  841. install:
  842. Install le.sh to your system.
  843. issue:
  844. Issue a cert.
  845. installcert:
  846. Install the issued cert to apache/nginx or any other server.
  847. renew:
  848. Renew a cert.
  849. renewAll:
  850. Renew all the certs.
  851. uninstall:
  852. Uninstall le.sh, and uninstall the cron job.
  853. version:
  854. Show version info.
  855. installcronjob:
  856. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  857. uninstallcronjob:
  858. Uninstall the cron job. The 'uninstall' command can do this automatically.
  859. createAccountKey:
  860. Create an account private key, professional use.
  861. createDomainKey:
  862. Create an domain private key, professional use.
  863. createCSR:
  864. Create CSR , professional use.
  865. "
  866. }
  867. if [ -z "$1" ] ; then
  868. showhelp
  869. else
  870. "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9"
  871. fi