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.

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