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.

1033 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. _info "Geting token for domain" $d
  463. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  464. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  465. _err "new-authz error: $response"
  466. _clearup
  467. return 1
  468. fi
  469. entry=$(echo $response | egrep -o '{[^{]*"type":"'$vtype'"[^}]*')
  470. _debug entry "$entry"
  471. token=$(echo "$entry" | sed 's/,/\n'/g| grep '"token":'| cut -d : -f 2|sed 's/"//g')
  472. _debug token $token
  473. uri=$(echo "$entry" | sed 's/,/\n'/g| grep '"uri":'| cut -d : -f 2,3|sed 's/"//g')
  474. _debug uri $uri
  475. keyauthorization="$token.$thumbprint"
  476. _debug keyauthorization "$keyauthorization"
  477. dvlist="$d$sep$keyauthorization$sep$uri"
  478. _debug dvlist "$dvlist"
  479. vlist="$vlist$dvlist,"
  480. done
  481. #add entry
  482. dnsadded=""
  483. ventries=$(echo "$vlist" | sed "s/,/ /g")
  484. for ventry in $ventries
  485. do
  486. d=$(echo $ventry | cut -d $sep -f 1)
  487. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  488. if [ "$vtype" == "$VTYPE_DNS" ] ; then
  489. dnsadded='0'
  490. txtdomain="_acme-challenge.$d"
  491. _debug txtdomain "$txtdomain"
  492. txt="$(echo -e -n $keyauthorization | sha256sum | xxd -r -p | base64 -w 0 | _b64)"
  493. _debug txt "$txt"
  494. #dns
  495. #1. check use api
  496. _err "Add the following txt record:"
  497. _err "Domain:$txtdomain"
  498. _err "Txt value:$txt"
  499. #dnsadded='1'
  500. fi
  501. done
  502. if [ "$dnsadded" == '0' ] ; then
  503. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  504. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  505. _err "Please add the txt records to the domains, and retry again."
  506. return 1
  507. fi
  508. fi
  509. _debug "ok, let's start to verify"
  510. ventries=$(echo "$vlist" | sed "s/,/ /g")
  511. for ventry in $ventries
  512. do
  513. d=$(echo $ventry | cut -d $sep -f 1)
  514. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  515. uri=$(echo $ventry | cut -d $sep -f 3)
  516. _info "Verifying:$d"
  517. _debug "d" "$d"
  518. _debug "keyauthorization" "$keyauthorization"
  519. _debug "uri" "$uri"
  520. removelevel=""
  521. token=""
  522. if [ "$vtype" == "$VTYPE_HTTP" ] ; then
  523. if [ "$Le_Webroot" == "no" ] ; then
  524. _info "Standalone mode server"
  525. _startserver "$keyauthorization" &
  526. serverproc="$!"
  527. sleep 2
  528. _debug serverproc $serverproc
  529. else
  530. if [ -z "$wellknown_path" ] ; then
  531. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  532. fi
  533. _debug wellknown_path "$wellknown_path"
  534. if [ ! -d "$Le_Webroot/.well-known" ] ; then
  535. removelevel='1'
  536. elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
  537. removelevel='2'
  538. else
  539. removelevel='3'
  540. fi
  541. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  542. _debug "writing token:$token to $wellknown_path/$token"
  543. mkdir -p "$wellknown_path"
  544. echo -n "$keyauthorization" > "$wellknown_path/$token"
  545. webroot_owner=$(stat -c '%U:%G' $Le_Webroot)
  546. _debug "Changing owner/group of .well-known to $webroot_owner"
  547. chown -R $webroot_owner "$Le_Webroot/.well-known"
  548. fi
  549. fi
  550. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  551. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  552. _err "$d:Challenge error: $resource"
  553. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  554. _clearup
  555. return 1
  556. fi
  557. while [ "1" ] ; do
  558. _debug "sleep 5 secs to verify"
  559. sleep 5
  560. _debug "checking"
  561. if ! _get $uri ; then
  562. _err "$d:Verify error:$resource"
  563. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  564. _clearup
  565. return 1
  566. fi
  567. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | sed 's/"//g')
  568. if [ "$status" == "valid" ] ; then
  569. _info "Success"
  570. _stopserver $serverproc
  571. serverproc=""
  572. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  573. break;
  574. fi
  575. if [ "$status" == "invalid" ] ; then
  576. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  577. _err "$d:Verify error:$error"
  578. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  579. _clearup
  580. return 1;
  581. fi
  582. if [ "$status" == "pending" ] ; then
  583. _info "Pending"
  584. else
  585. _err "$d:Verify error:$response"
  586. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  587. _clearup
  588. return 1
  589. fi
  590. done
  591. done
  592. _clearup
  593. _info "Verify finished, start to sign."
  594. der="$(openssl req -in $CSR_PATH -outform DER | base64 -w 0 | _b64)"
  595. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  596. Le_LinkCert="$(grep -i -o '^Location.*' $CURL_HEADER |sed 's/\r//g'| cut -d " " -f 2)"
  597. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  598. if [ "$Le_LinkCert" ] ; then
  599. echo -----BEGIN CERTIFICATE----- > "$CERT_PATH"
  600. curl --silent "$Le_LinkCert" | base64 >> "$CERT_PATH"
  601. echo -----END CERTIFICATE----- >> "$CERT_PATH"
  602. _info "Cert success."
  603. cat "$CERT_PATH"
  604. _info "Your cert is in $CERT_PATH"
  605. fi
  606. if [ -z "$Le_LinkCert" ] ; then
  607. response="$(echo $response | base64 -d)"
  608. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  609. return 1
  610. fi
  611. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  612. Le_LinkIssuer=$(grep -i '^Link' $CURL_HEADER | cut -d " " -f 2| cut -d ';' -f 1 | sed 's/<//g' | sed 's/>//g')
  613. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  614. if [ "$Le_LinkIssuer" ] ; then
  615. echo -----BEGIN CERTIFICATE----- > "$CA_CERT_PATH"
  616. curl --silent "$Le_LinkIssuer" | base64 >> "$CA_CERT_PATH"
  617. echo -----END CERTIFICATE----- >> "$CA_CERT_PATH"
  618. _info "The intermediate CA cert is in $CA_CERT_PATH"
  619. fi
  620. Le_CertCreateTime=$(date -u "+%s")
  621. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  622. Le_CertCreateTimeStr=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
  623. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  624. if [ ! "$Le_RenewalDays" ] ; then
  625. Le_RenewalDays=80
  626. fi
  627. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  628. Le_NextRenewTime=$(date -u -d "+$Le_RenewalDays day" "+%s")
  629. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  630. Le_NextRenewTimeStr=$(date -u -d "+$Le_RenewalDays day" "+%Y-%m-%d %H:%M:%S UTC")
  631. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  632. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  633. }
  634. renew() {
  635. Le_Domain="$1"
  636. if [ -z "$Le_Domain" ] ; then
  637. _err "Usage: $0 domain.com"
  638. return 1
  639. fi
  640. _initpath $Le_Domain
  641. if [ -f "$DOMAIN_CONF" ] ; then
  642. source "$DOMAIN_CONF"
  643. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  644. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  645. return 2
  646. fi
  647. fi
  648. IS_RENEW="1"
  649. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  650. IS_RENEW=""
  651. }
  652. renewAll() {
  653. _initpath
  654. _info "renewAll"
  655. for d in $(ls -F $WORKING_DIR | grep '/$') ; do
  656. d=$(echo $d | cut -d '/' -f 1)
  657. _info "renew $d"
  658. Le_LinkCert=""
  659. Le_Domain=""
  660. Le_Alt=""
  661. Le_Webroot=""
  662. Le_Keylength=""
  663. Le_LinkIssuer=""
  664. Le_CertCreateTime=""
  665. Le_CertCreateTimeStr=""
  666. Le_RenewalDays=""
  667. Le_NextRenewTime=""
  668. Le_NextRenewTimeStr=""
  669. Le_RealCertPath=""
  670. Le_RealKeyPath=""
  671. Le_RealCACertPath=""
  672. Le_ReloadCmd=""
  673. DOMAIN_CONF=""
  674. CSR_PATH=""
  675. CERT_KEY_PATH=""
  676. CERT_PATH=""
  677. CA_CERT_PATH=""
  678. ACCOUNT_KEY_PATH=""
  679. wellknown_path=""
  680. renew "$d"
  681. done
  682. }
  683. installcert() {
  684. Le_Domain="$1"
  685. if [ -z "$Le_Domain" ] ; then
  686. _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
  687. return 1
  688. fi
  689. Le_RealCertPath="$2"
  690. Le_RealKeyPath="$3"
  691. Le_RealCACertPath="$4"
  692. Le_ReloadCmd="$5"
  693. _initpath $Le_Domain
  694. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  695. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  696. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  697. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  698. if [ "$Le_RealCertPath" ] ; then
  699. if [ -f "$Le_RealCertPath" ] ; then
  700. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  701. fi
  702. cat "$CERT_PATH" > "$Le_RealCertPath"
  703. fi
  704. if [ "$Le_RealCACertPath" ] ; then
  705. if [ -f "$Le_RealCACertPath" ] ; then
  706. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  707. fi
  708. if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
  709. echo "" >> "$Le_RealCACertPath"
  710. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  711. else
  712. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  713. fi
  714. fi
  715. if [ "$Le_RealKeyPath" ] ; then
  716. if [ -f "$Le_RealKeyPath" ] ; then
  717. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  718. fi
  719. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  720. fi
  721. if [ "$Le_ReloadCmd" ] ; then
  722. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  723. $Le_ReloadCmd
  724. fi
  725. }
  726. installcronjob() {
  727. _initpath
  728. _info "Installing cron job"
  729. if ! crontab -l | grep 'le.sh cron' ; then
  730. if [ -f "$WORKING_DIR/le.sh" ] ; then
  731. lesh="\"$WORKING_DIR\"/le.sh"
  732. else
  733. _err "Can not install cronjob, le.sh not found."
  734. return 1
  735. fi
  736. crontab -l | { cat; echo "0 0 * * * $SUDO WORKING_DIR=\"$WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  737. fi
  738. return 0
  739. }
  740. uninstallcronjob() {
  741. _info "Removing cron job"
  742. cr="$(crontab -l | grep 'le.sh cron')"
  743. if [ "$cr" ] ; then
  744. crontab -l | sed "/le.sh cron/d" | crontab -
  745. WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 7 | cut -d '=' -f 2 | tr -d '"')"
  746. _info WORKING_DIR "$WORKING_DIR"
  747. fi
  748. _initpath
  749. }
  750. install() {
  751. _initpath
  752. if ! command -v "curl" > /dev/null ; then
  753. _err "Please install curl first."
  754. _err "Ubuntu: sudo apt-get install curl"
  755. _err "CentOS: yum install curl"
  756. return 1
  757. fi
  758. if ! command -v "crontab" > /dev/null ; then
  759. _err "Please install crontab first."
  760. _err "CentOs: yum -y install crontabs"
  761. return 1
  762. fi
  763. if ! command -v "openssl" > /dev/null ; then
  764. _err "Please install openssl first."
  765. _err "CentOs: yum -y install openssl"
  766. return 1
  767. fi
  768. if ! command -v "xxd" > /dev/null ; then
  769. _err "Please install xxd first."
  770. _err "CentOs: yum install vim-common"
  771. return 1
  772. fi
  773. _info "Installing to $WORKING_DIR"
  774. #try install to /bin if is root
  775. if [ ! -f /usr/local/bin/le.sh ] ; then
  776. #if root
  777. if $SUDO cp le.sh /usr/local/bin/le.sh 2>&1 > /dev/null; then
  778. $SUDO chmod 755 /usr/local/bin/le.sh
  779. $SUDO ln -s "/usr/local/bin/le.sh" /usr/local/bin/le
  780. rm -f $WORKING_DIR/le.sh
  781. $SUDO ln -s /usr/local/bin/le.sh $WORKING_DIR/le.sh
  782. _info "Installed to /usr/local/bin/le"
  783. else
  784. #install to home, for non root user
  785. cp le.sh $WORKING_DIR/
  786. chmod +x $WORKING_DIR/le.sh
  787. _info "Installed to $WORKING_DIR/le.sh"
  788. fi
  789. fi
  790. rm -f $WORKING_DIR/le
  791. ln -s $WORKING_DIR/le.sh $WORKING_DIR/le
  792. installcronjob
  793. _info OK
  794. }
  795. uninstall() {
  796. uninstallcronjob
  797. _initpath
  798. if [ -f "/usr/local/bin/le.sh" ] ; then
  799. _info "Removing /usr/local/bin/le.sh"
  800. if $SUDO rm -f /usr/local/bin/le.sh ; then
  801. $SUDO rm -f /usr/local/bin/le
  802. fi
  803. fi
  804. rm -f $WORKING_DIR/le
  805. rm -f $WORKING_DIR/le.sh
  806. _info "The keys and certs are in $WORKING_DIR, you can remove them by yourself."
  807. }
  808. cron() {
  809. renewAll
  810. }
  811. version() {
  812. _info "$PROJECT"
  813. _info "v$VER"
  814. }
  815. showhelp() {
  816. version
  817. echo "Usage: le.sh [command] ...[args]....
  818. Avalible commands:
  819. install:
  820. Install le.sh to your system.
  821. issue:
  822. Issue a cert.
  823. installcert:
  824. Install the issued cert to apache/nginx or any other server.
  825. renew:
  826. Renew a cert.
  827. renewAll:
  828. Renew all the certs.
  829. uninstall:
  830. Uninstall le.sh, and uninstall the cron job.
  831. version:
  832. Show version info.
  833. installcronjob:
  834. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  835. uninstallcronjob:
  836. Uninstall the cron job. The 'uninstall' command can do this automatically.
  837. createAccountKey:
  838. Create an account private key, professional use.
  839. createDomainKey:
  840. Create an domain private key, professional use.
  841. createCSR:
  842. Create CSR , professional use.
  843. "
  844. }
  845. if [ -z "$1" ] ; then
  846. showhelp
  847. else
  848. "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9"
  849. fi