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.

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