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.

1098 lines
27 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
9 years ago
9 years ago
  1. #!/bin/bash
  2. VER=1.1.2
  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. _h2b() {
  37. hex=$(cat)
  38. i=1
  39. j=2
  40. while [ '1' ] ; do
  41. h=$(printf $hex | cut -c $i-$j)
  42. if [ -z "$h" ] ; then
  43. break;
  44. fi
  45. printf "\x$h"
  46. let "i+=2"
  47. let "j+=2"
  48. done
  49. }
  50. _base64() {
  51. openssl base64 -e | tr -d '\n'
  52. }
  53. #domain [2048]
  54. createAccountKey() {
  55. _info "Creating account key"
  56. if [ -z "$1" ] ; then
  57. echo Usage: $0 account-domain [2048]
  58. return
  59. fi
  60. account=$1
  61. length=$2
  62. if [ -z "$2" ] ; then
  63. _info "Use default length 2048"
  64. length=2048
  65. fi
  66. _initpath
  67. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  68. _info "Account key exists, skip"
  69. return
  70. else
  71. #generate account key
  72. openssl genrsa $length > "$ACCOUNT_KEY_PATH"
  73. fi
  74. }
  75. #domain length
  76. createDomainKey() {
  77. _info "Creating domain key"
  78. if [ -z "$1" ] ; then
  79. echo Usage: $0 domain [2048]
  80. return
  81. fi
  82. domain=$1
  83. length=$2
  84. if [ -z "$2" ] ; then
  85. _info "Use default length 2048"
  86. length=2048
  87. fi
  88. _initpath $domain
  89. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  90. #generate account key
  91. openssl genrsa $length > "$CERT_KEY_PATH"
  92. else
  93. if [ "$IS_RENEW" ] ; then
  94. _info "Domain key exists, skip"
  95. return 0
  96. else
  97. _err "Domain key exists, do you want to overwrite the key?"
  98. _err "Set FORCE=1, and try again."
  99. return 1
  100. fi
  101. fi
  102. }
  103. # domain domainlist
  104. createCSR() {
  105. _info "Creating csr"
  106. if [ -z "$1" ] ; then
  107. echo Usage: $0 domain [domainlist]
  108. return
  109. fi
  110. domain=$1
  111. _initpath $domain
  112. domainlist=$2
  113. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && ! [ "$FORCE" ]; then
  114. _info "CSR exists, skip"
  115. return
  116. fi
  117. if [ -z "$domainlist" ] ; then
  118. #single domain
  119. _info "Single domain" $domain
  120. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" > "$CSR_PATH"
  121. else
  122. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  123. #multi
  124. _info "Multi domain" "$alt"
  125. 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"
  126. fi
  127. }
  128. _b64() {
  129. __n=$(cat)
  130. echo $__n | tr '/+' '_-' | tr -d '= '
  131. }
  132. _send_signed_request() {
  133. url=$1
  134. payload=$2
  135. needbase64=$3
  136. _debug url $url
  137. _debug payload "$payload"
  138. CURL_HEADER="$WORKING_DIR/curl.header"
  139. dp="$WORKING_DIR/curl.dump"
  140. CURL="curl --silent --dump-header $CURL_HEADER "
  141. if [ "$DEBUG" ] ; then
  142. CURL="$CURL --trace-ascii $dp "
  143. fi
  144. payload64=$(echo -n $payload | _base64 | _b64)
  145. _debug payload64 $payload64
  146. nonceurl="$API/directory"
  147. nonce=$($CURL -I $nonceurl | grep "^Replay-Nonce:" | sed s/\\r//|sed s/\\n//| cut -d ' ' -f 2)
  148. _debug nonce $nonce
  149. protected=$(echo -n "$HEADERPLACE" | sed "s/NONCE/$nonce/" )
  150. _debug protected "$protected"
  151. protected64=$( echo -n $protected | _base64 | _b64)
  152. _debug protected64 "$protected64"
  153. sig=$(echo -n "$protected64.$payload64" | openssl dgst -sha256 -sign $ACCOUNT_KEY_PATH | _base64 | _b64)
  154. _debug sig "$sig"
  155. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  156. _debug body "$body"
  157. if [ "$needbase64" ] ; then
  158. response="$($CURL -X POST --data "$body" $url | _base64)"
  159. else
  160. response="$($CURL -X POST --data "$body" $url)"
  161. fi
  162. responseHeaders="$(sed 's/\r//g' $CURL_HEADER)"
  163. _debug responseHeaders "$responseHeaders"
  164. _debug response "$response"
  165. code="$(grep ^HTTP $CURL_HEADER | tail -1 | cut -d " " -f 2)"
  166. _debug code $code
  167. }
  168. _get() {
  169. url="$1"
  170. _debug url $url
  171. response="$(curl --silent $url)"
  172. ret=$?
  173. _debug response "$response"
  174. code="$(echo $response | grep -o '"status":[0-9]\+' | cut -d : -f 2)"
  175. _debug code $code
  176. return $ret
  177. }
  178. #setopt "file" "opt" "=" "value" [";"]
  179. _setopt() {
  180. __conf="$1"
  181. __opt="$2"
  182. __sep="$3"
  183. __val="$4"
  184. __end="$5"
  185. if [ -z "$__opt" ] ; then
  186. echo usage: $0 '"file" "opt" "=" "value" [";"]'
  187. return
  188. fi
  189. if [ ! -f "$__conf" ] ; then
  190. touch "$__conf"
  191. fi
  192. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  193. _debug OK
  194. if [[ "$__val" == *"&"* ]] ; then
  195. __val="$(echo $__val | sed 's/&/\\&/g')"
  196. fi
  197. sed -i "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" "$__conf"
  198. else
  199. _debug APP
  200. echo "$__opt$__sep$__val$__end" >> "$__conf"
  201. fi
  202. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  203. }
  204. _startserver() {
  205. content="$1"
  206. _NC="nc -q 1"
  207. if nc -h 2>&1 | grep "nmap.org/ncat" >/dev/null ; then
  208. _NC="nc"
  209. fi
  210. # while true ; do
  211. if [ "$DEBUG" ] ; then
  212. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -l -p 80 -vv
  213. else
  214. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -l -p 80 > /dev/null
  215. fi
  216. # done
  217. }
  218. _stopserver() {
  219. pid="$1"
  220. }
  221. _initpath() {
  222. #check if there is sudo installed, AND if the current user is a sudoer.
  223. if command -v sudo > /dev/null ; then
  224. if [ "$(sudo -n uptime 2>&1|grep "load"|wc -l)" != "0" ] ; then
  225. SUDO=sudo
  226. fi
  227. fi
  228. if [ -z "$API" ] ; then
  229. if [ -z "$STAGE" ] ; then
  230. API="$DEFAULT_CA"
  231. else
  232. API="$STAGE_CA"
  233. _info "Using stage api:$API"
  234. fi
  235. fi
  236. if [ -z "$WORKING_DIR" ]; then
  237. WORKING_DIR=$HOME/.le
  238. fi
  239. if [ -z "$ACME_DIR" ] ; then
  240. ACME_DIR="/home/.acme"
  241. fi
  242. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  243. APACHE_CONF_BACKUP_DIR="$WORKING_DIR/"
  244. fi
  245. domain="$1"
  246. mkdir -p "$WORKING_DIR"
  247. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  248. ACCOUNT_KEY_PATH="$WORKING_DIR/account.acc"
  249. fi
  250. if [ -z "$domain" ] ; then
  251. return 0
  252. fi
  253. mkdir -p "$WORKING_DIR/$domain"
  254. if [ -z "$DOMAIN_CONF" ] ; then
  255. DOMAIN_CONF="$WORKING_DIR/$domain/$Le_Domain.conf"
  256. fi
  257. if [ -z "$CSR_PATH" ] ; then
  258. CSR_PATH="$WORKING_DIR/$domain/$domain.csr"
  259. fi
  260. if [ -z "$CERT_KEY_PATH" ] ; then
  261. CERT_KEY_PATH="$WORKING_DIR/$domain/$domain.key"
  262. fi
  263. if [ -z "$CERT_PATH" ] ; then
  264. CERT_PATH="$WORKING_DIR/$domain/$domain.cer"
  265. fi
  266. if [ -z "$CA_CERT_PATH" ] ; then
  267. CA_CERT_PATH="$WORKING_DIR/$domain/ca.cer"
  268. fi
  269. }
  270. _apachePath() {
  271. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | sed s/\"//g)"
  272. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | sed s/\"//g)"
  273. httpdconf="$httpdroot/$httpdconfname"
  274. if [ ! -f $httpdconf ] ; then
  275. _err "Apache Config file not found" $httpdconf
  276. return 1
  277. fi
  278. return 0
  279. }
  280. _restoreApache() {
  281. if [ -z "$usingApache" ] ; then
  282. return 0
  283. fi
  284. _initpath
  285. if ! _apachePath ; then
  286. return 1
  287. fi
  288. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  289. _debug "No config file to restore."
  290. return 0
  291. fi
  292. cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
  293. if ! apachectl -t ; then
  294. _err "Sorry, restore apache config error, please contact me."
  295. return 1;
  296. fi
  297. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  298. return 0
  299. }
  300. _setApache() {
  301. _initpath
  302. if ! _apachePath ; then
  303. return 1
  304. fi
  305. #backup the conf
  306. _debug "Backup apache config file" $httpdconf
  307. cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
  308. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  309. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  310. _info "The backup file will be deleted on sucess, just forget it."
  311. #add alias
  312. echo "
  313. Alias /.well-known/acme-challenge $ACME_DIR
  314. <Directory $ACME_DIR >
  315. Require all granted
  316. </Directory>
  317. " >> $httpdconf
  318. if ! apachectl -t ; then
  319. _err "Sorry, apache config error, please contact me."
  320. _restoreApache
  321. return 1;
  322. fi
  323. if [ ! -d "$ACME_DIR" ] ; then
  324. mkdir -p "$ACME_DIR"
  325. chmod 755 "$ACME_DIR"
  326. fi
  327. if ! apachectl graceful ; then
  328. _err "Sorry, apachectl graceful error, please contact me."
  329. _restoreApache
  330. return 1;
  331. fi
  332. usingApache="1"
  333. return 0
  334. }
  335. _clearup () {
  336. _stopserver $serverproc
  337. serverproc=""
  338. _restoreApache
  339. }
  340. # webroot removelevel tokenfile
  341. _clearupwebbroot() {
  342. __webroot="$1"
  343. if [ -z "$__webroot" ] ; then
  344. _debug "no webroot specified, skip"
  345. return 0
  346. fi
  347. if [ "$2" == '1' ] ; then
  348. _debug "remove $__webroot/.well-known"
  349. rm -rf "$__webroot/.well-known"
  350. elif [ "$2" == '2' ] ; then
  351. _debug "remove $__webroot/.well-known/acme-challenge"
  352. rm -rf "$__webroot/.well-known/acme-challenge"
  353. elif [ "$2" == '3' ] ; then
  354. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  355. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  356. else
  357. _info "skip for removelevel:$2"
  358. fi
  359. return 0
  360. }
  361. issue() {
  362. if [ -z "$2" ] ; then
  363. _err "Usage: le issue webroot|no|apache|dns a.com [www.a.com,b.com,c.com]|no [key-length]|no"
  364. return 1
  365. fi
  366. Le_Webroot="$1"
  367. Le_Domain="$2"
  368. Le_Alt="$3"
  369. Le_Keylength="$4"
  370. Le_RealCertPath="$5"
  371. Le_RealKeyPath="$6"
  372. Le_RealCACertPath="$7"
  373. Le_ReloadCmd="$8"
  374. _initpath $Le_Domain
  375. if [ -f "$DOMAIN_CONF" ] ; then
  376. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  377. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  378. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  379. return 2
  380. fi
  381. fi
  382. if [ "$Le_Alt" == "no" ] ; then
  383. Le_Alt=""
  384. fi
  385. if [ "$Le_Keylength" == "no" ] ; then
  386. Le_Keylength=""
  387. fi
  388. if [ "$Le_RealCertPath" == "no" ] ; then
  389. Le_RealCertPath=""
  390. fi
  391. if [ "$Le_RealKeyPath" == "no" ] ; then
  392. Le_RealKeyPath=""
  393. fi
  394. if [ "$Le_RealCACertPath" == "no" ] ; then
  395. Le_RealCACertPath=""
  396. fi
  397. if [ "$Le_ReloadCmd" == "no" ] ; then
  398. Le_ReloadCmd=""
  399. fi
  400. _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
  401. _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
  402. _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
  403. _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
  404. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  405. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  406. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  407. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  408. if [ "$Le_Webroot" == "no" ] ; then
  409. _info "Standalone mode."
  410. if ! command -v "nc" > /dev/null ; then
  411. _err "Please install netcat(nc) tools first."
  412. return 1
  413. fi
  414. netprc="$(ss -ntpl | grep ':80 ')"
  415. if [ "$netprc" ] ; then
  416. _err "$netprc"
  417. _err "tcp port 80 is already used by $(echo "$netprc" | cut -d : -f 4)"
  418. _err "Please stop it first"
  419. return 1
  420. fi
  421. fi
  422. if [ "$Le_Webroot" == "apache" ] ; then
  423. if ! _setApache ; then
  424. _err "set up apache error. Report error to me."
  425. return 1
  426. fi
  427. wellknown_path="$ACME_DIR"
  428. else
  429. usingApache=""
  430. fi
  431. createAccountKey $Le_Domain $Le_Keylength
  432. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  433. _err "Create domain key error."
  434. return 1
  435. fi
  436. if ! createCSR $Le_Domain $Le_Alt ; then
  437. _err "Create CSR error."
  438. return 1
  439. fi
  440. 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)
  441. if [ "${#pub_exp}" == "5" ] ; then
  442. pub_exp=0$pub_exp
  443. fi
  444. _debug pub_exp "$pub_exp"
  445. e=$(echo $pub_exp | _h2b | _base64)
  446. _debug e "$e"
  447. modulus=$(openssl rsa -in $ACCOUNT_KEY_PATH -modulus -noout | cut -d '=' -f 2 )
  448. n=$(echo $modulus| _h2b | _base64 | _b64 )
  449. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  450. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  451. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  452. _debug HEADER "$HEADER"
  453. accountkey_json=$(echo -n "$jwk" | sed "s/ //g")
  454. thumbprint=$(echo -n "$accountkey_json" | openssl sha -sha256 -binary | _base64 | _b64)
  455. _info "Registering account"
  456. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  457. if [ "$ACCOUNT_EMAIL" ] ; then
  458. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  459. fi
  460. _send_signed_request "$API/acme/new-reg" "$regjson"
  461. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  462. _info "Registered"
  463. echo $response > $WORKING_DIR/account.json
  464. elif [ "$code" == '409' ] ; then
  465. _info "Already registered"
  466. else
  467. _err "Register account Error."
  468. _clearup
  469. return 1
  470. fi
  471. vtype="$VTYPE_HTTP"
  472. if [[ "$Le_Webroot" == "dns"* ]] ; then
  473. vtype="$VTYPE_DNS"
  474. fi
  475. vlist="$Le_Vlist"
  476. # verify each domain
  477. _info "Verify each domain"
  478. sep='#'
  479. if [ -z "$vlist" ] ; then
  480. alldomains=$(echo "$Le_Domain,$Le_Alt" | sed "s/,/ /g")
  481. for d in $alldomains
  482. do
  483. _info "Geting token for domain" $d
  484. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  485. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  486. _err "new-authz error: $response"
  487. _clearup
  488. return 1
  489. fi
  490. entry=$(echo $response | egrep -o '{[^{]*"type":"'$vtype'"[^}]*')
  491. _debug entry "$entry"
  492. token=$(echo "$entry" | sed 's/,/\n'/g| grep '"token":'| cut -d : -f 2|sed 's/"//g')
  493. _debug token $token
  494. uri=$(echo "$entry" | sed 's/,/\n'/g| grep '"uri":'| cut -d : -f 2,3|sed 's/"//g')
  495. _debug uri $uri
  496. keyauthorization="$token.$thumbprint"
  497. _debug keyauthorization "$keyauthorization"
  498. dvlist="$d$sep$keyauthorization$sep$uri"
  499. _debug dvlist "$dvlist"
  500. vlist="$vlist$dvlist,"
  501. done
  502. #add entry
  503. dnsadded=""
  504. ventries=$(echo "$vlist" | sed "s/,/ /g")
  505. for ventry in $ventries
  506. do
  507. d=$(echo $ventry | cut -d $sep -f 1)
  508. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  509. if [ "$vtype" == "$VTYPE_DNS" ] ; then
  510. dnsadded='0'
  511. txtdomain="_acme-challenge.$d"
  512. _debug txtdomain "$txtdomain"
  513. txt="$(echo -e -n $keyauthorization | openssl sha -sha256 -binary | _base64 | _b64)"
  514. _debug txt "$txt"
  515. #dns
  516. #1. check use api
  517. d_api=""
  518. if [ -f "$WORKING_DIR/$d/$Le_Webroot" ] ; then
  519. d_api="$WORKING_DIR/$d/$Le_Webroot"
  520. elif [ -f "$WORKING_DIR/$d/$Le_Webroot.sh" ] ; then
  521. d_api="$WORKING_DIR/$d/$Le_Webroot.sh"
  522. elif [ -f "$WORKING_DIR/$Le_Webroot" ] ; then
  523. d_api="$WORKING_DIR/$Le_Webroot"
  524. elif [ -f "$WORKING_DIR/$Le_Webroot.sh" ] ; then
  525. d_api="$WORKING_DIR/$Le_Webroot.sh"
  526. fi
  527. if [ "$d_api" ]; then
  528. _info "Found domain api file: $d_api"
  529. else
  530. _err "Add the following TXT record:"
  531. _err "Domain: $txtdomain"
  532. _err "TXT value: $txt"
  533. _err "Please be aware that you prepend _acme-challenge. before your domain"
  534. _err "so the resulting subdomain will be: $txtdomain"
  535. continue
  536. fi
  537. if ! source $d_api ; then
  538. _err "Load file $d_api error. Please check your api file and try again."
  539. return 1
  540. fi
  541. addcommand="$Le_Webroot-add"
  542. if ! command -v $addcommand ; then
  543. _err "It seems that your api file is not correct, it must have a function named: $Le_Webroot"
  544. return 1
  545. fi
  546. if ! $addcommand $txtdomain $txt ; then
  547. _err "Error add txt for domain:$txtdomain"
  548. return 1
  549. fi
  550. dnsadded='1'
  551. fi
  552. done
  553. if [ "$dnsadded" == '0' ] ; then
  554. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  555. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  556. _err "Please add the TXT records to the domains, and retry again."
  557. return 1
  558. fi
  559. fi
  560. _debug "ok, let's start to verify"
  561. ventries=$(echo "$vlist" | sed "s/,/ /g")
  562. for ventry in $ventries
  563. do
  564. d=$(echo $ventry | cut -d $sep -f 1)
  565. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  566. uri=$(echo $ventry | cut -d $sep -f 3)
  567. _info "Verifying:$d"
  568. _debug "d" "$d"
  569. _debug "keyauthorization" "$keyauthorization"
  570. _debug "uri" "$uri"
  571. removelevel=""
  572. token=""
  573. if [ "$vtype" == "$VTYPE_HTTP" ] ; then
  574. if [ "$Le_Webroot" == "no" ] ; then
  575. _info "Standalone mode server"
  576. _startserver "$keyauthorization" &
  577. serverproc="$!"
  578. sleep 2
  579. _debug serverproc $serverproc
  580. else
  581. if [ -z "$wellknown_path" ] ; then
  582. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  583. fi
  584. _debug wellknown_path "$wellknown_path"
  585. if [ ! -d "$Le_Webroot/.well-known" ] ; then
  586. removelevel='1'
  587. elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
  588. removelevel='2'
  589. else
  590. removelevel='3'
  591. fi
  592. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  593. _debug "writing token:$token to $wellknown_path/$token"
  594. mkdir -p "$wellknown_path"
  595. echo -n "$keyauthorization" > "$wellknown_path/$token"
  596. webroot_owner=$(stat -c '%U:%G' $Le_Webroot)
  597. _debug "Changing owner/group of .well-known to $webroot_owner"
  598. chown -R $webroot_owner "$Le_Webroot/.well-known"
  599. fi
  600. fi
  601. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  602. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  603. _err "$d:Challenge error: $resource"
  604. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  605. _clearup
  606. return 1
  607. fi
  608. while [ "1" ] ; do
  609. _debug "sleep 5 secs to verify"
  610. sleep 5
  611. _debug "checking"
  612. if ! _get $uri ; then
  613. _err "$d:Verify error:$resource"
  614. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  615. _clearup
  616. return 1
  617. fi
  618. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | sed 's/"//g')
  619. if [ "$status" == "valid" ] ; then
  620. _info "Success"
  621. _stopserver $serverproc
  622. serverproc=""
  623. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  624. break;
  625. fi
  626. if [ "$status" == "invalid" ] ; then
  627. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  628. _err "$d:Verify error:$error"
  629. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  630. _clearup
  631. return 1;
  632. fi
  633. if [ "$status" == "pending" ] ; then
  634. _info "Pending"
  635. else
  636. _err "$d:Verify error:$response"
  637. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  638. _clearup
  639. return 1
  640. fi
  641. done
  642. done
  643. _clearup
  644. _info "Verify finished, start to sign."
  645. der="$(openssl req -in $CSR_PATH -outform DER | _base64 | _b64)"
  646. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  647. Le_LinkCert="$(grep -i -o '^Location.*' $CURL_HEADER |sed 's/\r//g'| cut -d " " -f 2)"
  648. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  649. if [ "$Le_LinkCert" ] ; then
  650. echo -----BEGIN CERTIFICATE----- > "$CERT_PATH"
  651. curl --silent "$Le_LinkCert" | openssl base64 -e >> "$CERT_PATH"
  652. echo -----END CERTIFICATE----- >> "$CERT_PATH"
  653. _info "Cert success."
  654. cat "$CERT_PATH"
  655. _info "Your cert is in $CERT_PATH"
  656. fi
  657. if [ -z "$Le_LinkCert" ] ; then
  658. response="$(echo $response | openssl base64 -d)"
  659. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  660. return 1
  661. fi
  662. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  663. Le_LinkIssuer=$(grep -i '^Link' $CURL_HEADER | cut -d " " -f 2| cut -d ';' -f 1 | sed 's/<//g' | sed 's/>//g')
  664. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  665. if [ "$Le_LinkIssuer" ] ; then
  666. echo -----BEGIN CERTIFICATE----- > "$CA_CERT_PATH"
  667. curl --silent "$Le_LinkIssuer" | openssl base64 -e >> "$CA_CERT_PATH"
  668. echo -----END CERTIFICATE----- >> "$CA_CERT_PATH"
  669. _info "The intermediate CA cert is in $CA_CERT_PATH"
  670. fi
  671. Le_CertCreateTime=$(date -u "+%s")
  672. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  673. Le_CertCreateTimeStr=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
  674. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  675. if [ ! "$Le_RenewalDays" ] ; then
  676. Le_RenewalDays=80
  677. fi
  678. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  679. Le_NextRenewTime=$(date -u -d "+$Le_RenewalDays day" "+%s")
  680. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  681. Le_NextRenewTimeStr=$(date -u -d "+$Le_RenewalDays day" "+%Y-%m-%d %H:%M:%S UTC")
  682. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  683. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  684. }
  685. renew() {
  686. Le_Domain="$1"
  687. if [ -z "$Le_Domain" ] ; then
  688. _err "Usage: $0 domain.com"
  689. return 1
  690. fi
  691. _initpath $Le_Domain
  692. if [ ! -f "$DOMAIN_CONF" ] ; then
  693. _err "$Le_Domain is not a issued domain, skip."
  694. return 1;
  695. fi
  696. source "$DOMAIN_CONF"
  697. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  698. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  699. return 2
  700. fi
  701. IS_RENEW="1"
  702. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  703. IS_RENEW=""
  704. }
  705. renewAll() {
  706. _initpath
  707. _info "renewAll"
  708. for d in $(ls -F $WORKING_DIR | grep '/$') ; do
  709. d=$(echo $d | cut -d '/' -f 1)
  710. _info "renew $d"
  711. Le_LinkCert=""
  712. Le_Domain=""
  713. Le_Alt=""
  714. Le_Webroot=""
  715. Le_Keylength=""
  716. Le_LinkIssuer=""
  717. Le_CertCreateTime=""
  718. Le_CertCreateTimeStr=""
  719. Le_RenewalDays=""
  720. Le_NextRenewTime=""
  721. Le_NextRenewTimeStr=""
  722. Le_RealCertPath=""
  723. Le_RealKeyPath=""
  724. Le_RealCACertPath=""
  725. Le_ReloadCmd=""
  726. DOMAIN_CONF=""
  727. CSR_PATH=""
  728. CERT_KEY_PATH=""
  729. CERT_PATH=""
  730. CA_CERT_PATH=""
  731. ACCOUNT_KEY_PATH=""
  732. wellknown_path=""
  733. renew "$d"
  734. done
  735. }
  736. installcert() {
  737. Le_Domain="$1"
  738. if [ -z "$Le_Domain" ] ; then
  739. _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
  740. return 1
  741. fi
  742. Le_RealCertPath="$2"
  743. Le_RealKeyPath="$3"
  744. Le_RealCACertPath="$4"
  745. Le_ReloadCmd="$5"
  746. _initpath $Le_Domain
  747. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  748. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  749. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  750. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  751. if [ "$Le_RealCertPath" ] ; then
  752. if [ -f "$Le_RealCertPath" ] ; then
  753. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  754. fi
  755. cat "$CERT_PATH" > "$Le_RealCertPath"
  756. fi
  757. if [ "$Le_RealCACertPath" ] ; then
  758. if [ -f "$Le_RealCACertPath" ] ; then
  759. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  760. fi
  761. if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
  762. echo "" >> "$Le_RealCACertPath"
  763. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  764. else
  765. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  766. fi
  767. fi
  768. if [ "$Le_RealKeyPath" ] ; then
  769. if [ -f "$Le_RealKeyPath" ] ; then
  770. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  771. fi
  772. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  773. fi
  774. if [ "$Le_ReloadCmd" ] ; then
  775. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  776. $Le_ReloadCmd
  777. fi
  778. }
  779. installcronjob() {
  780. _initpath
  781. _info "Installing cron job"
  782. if ! crontab -l | grep 'le.sh cron' ; then
  783. if [ -f "$WORKING_DIR/le.sh" ] ; then
  784. lesh="\"$WORKING_DIR\"/le.sh"
  785. else
  786. _err "Can not install cronjob, le.sh not found."
  787. return 1
  788. fi
  789. crontab -l | { cat; echo "0 0 * * * $SUDO WORKING_DIR=\"$WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  790. fi
  791. return 0
  792. }
  793. uninstallcronjob() {
  794. _info "Removing cron job"
  795. cr="$(crontab -l | grep 'le.sh cron')"
  796. if [ "$cr" ] ; then
  797. crontab -l | sed "/le.sh cron/d" | crontab -
  798. WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 7 | cut -d '=' -f 2 | tr -d '"')"
  799. _info WORKING_DIR "$WORKING_DIR"
  800. fi
  801. _initpath
  802. }
  803. install() {
  804. _initpath
  805. if command -v yum > /dev/null ; then
  806. YUM="1"
  807. INSTALL="$SUDO yum install -y "
  808. elif command -v apt-get > /dev/null ; then
  809. INSTALL="$SUDO apt-get install -y "
  810. fi
  811. if ! command -v "curl" > /dev/null ; then
  812. _err "Please install curl first."
  813. _err "$INSTALL curl"
  814. return 1
  815. fi
  816. if ! command -v "crontab" > /dev/null ; then
  817. _err "Please install crontab first."
  818. if [ "$YUM" ] ; then
  819. _err "$INSTALL crontabs"
  820. else
  821. _err "$INSTALL crontab"
  822. fi
  823. return 1
  824. fi
  825. if ! command -v "openssl" > /dev/null ; then
  826. _err "Please install openssl first."
  827. _err "$INSTALL openssl"
  828. return 1
  829. fi
  830. _info "Installing to $WORKING_DIR"
  831. #try install to /bin if is root
  832. if [ ! -f /usr/local/bin/le.sh ] ; then
  833. #if root
  834. if $SUDO cp le.sh /usr/local/bin/le.sh > /dev/null 2>&1; then
  835. $SUDO chmod 755 /usr/local/bin/le.sh
  836. $SUDO ln -s "/usr/local/bin/le.sh" /usr/local/bin/le
  837. rm -f $WORKING_DIR/le.sh
  838. $SUDO ln -s /usr/local/bin/le.sh $WORKING_DIR/le.sh
  839. _info "Installed to /usr/local/bin/le"
  840. else
  841. #install to home, for non root user
  842. cp le.sh $WORKING_DIR/
  843. chmod +x $WORKING_DIR/le.sh
  844. _info "Installed to $WORKING_DIR/le.sh"
  845. fi
  846. fi
  847. rm -f $WORKING_DIR/le
  848. ln -s $WORKING_DIR/le.sh $WORKING_DIR/le
  849. installcronjob
  850. _info OK
  851. }
  852. uninstall() {
  853. uninstallcronjob
  854. _initpath
  855. if [ -f "/usr/local/bin/le.sh" ] ; then
  856. _info "Removing /usr/local/bin/le.sh"
  857. if $SUDO rm -f /usr/local/bin/le.sh ; then
  858. $SUDO rm -f /usr/local/bin/le
  859. fi
  860. fi
  861. rm -f $WORKING_DIR/le
  862. rm -f $WORKING_DIR/le.sh
  863. _info "The keys and certs are in $WORKING_DIR, you can remove them by yourself."
  864. }
  865. cron() {
  866. renewAll
  867. }
  868. version() {
  869. _info "$PROJECT"
  870. _info "v$VER"
  871. }
  872. showhelp() {
  873. version
  874. echo "Usage: le.sh [command] ...[args]....
  875. Avalible commands:
  876. install:
  877. Install le.sh to your system.
  878. issue:
  879. Issue a cert.
  880. installcert:
  881. Install the issued cert to apache/nginx or any other server.
  882. renew:
  883. Renew a cert.
  884. renewAll:
  885. Renew all the certs.
  886. uninstall:
  887. Uninstall le.sh, and uninstall the cron job.
  888. version:
  889. Show version info.
  890. installcronjob:
  891. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  892. uninstallcronjob:
  893. Uninstall the cron job. The 'uninstall' command can do this automatically.
  894. createAccountKey:
  895. Create an account private key, professional use.
  896. createDomainKey:
  897. Create an domain private key, professional use.
  898. createCSR:
  899. Create CSR , professional use.
  900. "
  901. }
  902. if [ -z "$1" ] ; then
  903. showhelp
  904. else
  905. "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9"
  906. fi