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.

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