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.

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