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.

1026 lines
25 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. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  706. fi
  707. if [ "$Le_RealKeyPath" ] ; then
  708. if [ -f "$Le_RealKeyPath" ] ; then
  709. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  710. fi
  711. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  712. fi
  713. if [ "$Le_ReloadCmd" ] ; then
  714. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  715. $Le_ReloadCmd
  716. fi
  717. }
  718. installcronjob() {
  719. _initpath
  720. _info "Installing cron job"
  721. if ! crontab -l | grep 'le.sh cron' ; then
  722. if command -v "le.sh" > /dev/null ; then
  723. lesh="$(which le.sh)"
  724. elif [ -f "$WORKING_DIR/le.sh" ] ; then
  725. lesh="\"$WORKING_DIR\"/le.sh"
  726. else
  727. _err "Can not install cronjob, le.sh not found."
  728. return 1
  729. fi
  730. crontab -l | { cat; echo "0 0 * * * $SUDO WORKING_DIR=\"$WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  731. fi
  732. return 0
  733. }
  734. uninstallcronjob() {
  735. _info "Removing cron job"
  736. cr="$(crontab -l | grep 'le.sh cron')"
  737. if [ "$cr" ] ; then
  738. crontab -l | sed "/le.sh cron/d" | crontab -
  739. WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 7 | cut -d '=' -f 2 | tr -d '"')"
  740. _info WORKING_DIR "$WORKING_DIR"
  741. fi
  742. _initpath
  743. }
  744. install() {
  745. _initpath
  746. if ! command -v "curl" > /dev/null ; then
  747. _err "Please install curl first."
  748. _err "Ubuntu: sudo apt-get install curl"
  749. _err "CentOS: yum install curl"
  750. return 1
  751. fi
  752. if ! command -v "crontab" > /dev/null ; then
  753. _err "Please install crontab first."
  754. _err "CentOs: yum -y install crontabs"
  755. return 1
  756. fi
  757. if ! command -v "openssl" > /dev/null ; then
  758. _err "Please install openssl first."
  759. _err "CentOs: yum -y install openssl"
  760. return 1
  761. fi
  762. if ! command -v "xxd" > /dev/null ; then
  763. _err "Please install xxd first."
  764. _err "CentOs: yum install vim-common"
  765. return 1
  766. fi
  767. _info "Installing to $WORKING_DIR"
  768. #try install to /bin if is root
  769. if [ ! -f /usr/local/bin/le.sh ] ; then
  770. #if root
  771. if $SUDO cp le.sh /usr/local/bin/le.sh 2>&1 > /dev/null; then
  772. $SUDO chmod 755 /usr/local/bin/le.sh
  773. $SUDO ln -s "/usr/local/bin/le.sh" /usr/local/bin/le
  774. rm -f $WORKING_DIR/le.sh
  775. $SUDO ln -s /usr/local/bin/le.sh $WORKING_DIR/le.sh
  776. _info "Installed to /usr/local/bin/le"
  777. else
  778. #install to home, for non root user
  779. cp le.sh $WORKING_DIR/
  780. chmod +x $WORKING_DIR/le.sh
  781. _info "Installed to $WORKING_DIR/le.sh"
  782. fi
  783. fi
  784. rm -f $WORKING_DIR/le
  785. ln -s $WORKING_DIR/le.sh $WORKING_DIR/le
  786. installcronjob
  787. _info OK
  788. }
  789. uninstall() {
  790. uninstallcronjob
  791. _initpath
  792. if [ -f "/usr/local/bin/le.sh" ] ; then
  793. _info "Removing /usr/local/bin/le.sh"
  794. if $SUDO rm -f /usr/local/bin/le.sh ; then
  795. $SUDO rm -f /usr/local/bin/le
  796. fi
  797. fi
  798. _info "The keys and certs are in $WORKING_DIR, you can remove them by yourself."
  799. }
  800. cron() {
  801. renewAll
  802. }
  803. version() {
  804. _info "$PROJECT"
  805. _info "v$VER"
  806. }
  807. showhelp() {
  808. version
  809. echo "Usage: le.sh [command] ...[args]....
  810. Avalible commands:
  811. install:
  812. Install le.sh to your system.
  813. issue:
  814. Issue a cert.
  815. installcert:
  816. Install the issued cert to apache/nginx or any other server.
  817. renew:
  818. Renew a cert.
  819. renewAll:
  820. Renew all the certs.
  821. uninstall:
  822. Uninstall le.sh, and uninstall the cron job.
  823. version:
  824. Show version info.
  825. installcronjob:
  826. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  827. uninstallcronjob:
  828. Uninstall the cron job. The 'uninstall' command can do this automatically.
  829. createAccountKey:
  830. Create an account private key, professional use.
  831. createDomainKey:
  832. Create an domain private key, professional use.
  833. createCSR:
  834. Create CSR , professional use.
  835. "
  836. }
  837. if [ -z "$1" ] ; then
  838. showhelp
  839. else
  840. "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9"
  841. fi