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.

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