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.

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