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.

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