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.

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