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.

1110 lines
28 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
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. elif [ -f "$WORKING_DIR/dnsapi/$Le_Webroot" ] ; then
  527. d_api="$WORKING_DIR/dnsapi/$Le_Webroot"
  528. elif [ -f "$WORKING_DIR/dnsapi/$Le_Webroot.sh" ] ; then
  529. d_api="$WORKING_DIR/dnsapi/$Le_Webroot.sh"
  530. fi
  531. _debug d_api "$d_api"
  532. if [ "$d_api" ]; then
  533. _info "Found domain api file: $d_api"
  534. else
  535. _err "Add the following TXT record:"
  536. _err "Domain: $txtdomain"
  537. _err "TXT value: $txt"
  538. _err "Please be aware that you prepend _acme-challenge. before your domain"
  539. _err "so the resulting subdomain will be: $txtdomain"
  540. continue
  541. fi
  542. if ! source $d_api ; then
  543. _err "Load file $d_api error. Please check your api file and try again."
  544. return 1
  545. fi
  546. addcommand="$Le_Webroot-add"
  547. if ! command -v $addcommand ; then
  548. _err "It seems that your api file is not correct, it must have a function named: $Le_Webroot"
  549. return 1
  550. fi
  551. if ! $addcommand $txtdomain $txt ; then
  552. _err "Error add txt for domain:$txtdomain"
  553. return 1
  554. fi
  555. dnsadded='1'
  556. fi
  557. done
  558. if [ "$dnsadded" == '0' ] ; then
  559. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  560. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  561. _err "Please add the TXT records to the domains, and retry again."
  562. return 1
  563. fi
  564. fi
  565. if [ "$dnsadded" == '1' ] ; then
  566. _info "Sleep 60 seconds for the txt records to take effect"
  567. sleep 60
  568. fi
  569. _debug "ok, let's start to verify"
  570. ventries=$(echo "$vlist" | sed "s/,/ /g")
  571. for ventry in $ventries
  572. do
  573. d=$(echo $ventry | cut -d $sep -f 1)
  574. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  575. uri=$(echo $ventry | cut -d $sep -f 3)
  576. _info "Verifying:$d"
  577. _debug "d" "$d"
  578. _debug "keyauthorization" "$keyauthorization"
  579. _debug "uri" "$uri"
  580. removelevel=""
  581. token=""
  582. if [ "$vtype" == "$VTYPE_HTTP" ] ; then
  583. if [ "$Le_Webroot" == "no" ] ; then
  584. _info "Standalone mode server"
  585. _startserver "$keyauthorization" &
  586. serverproc="$!"
  587. sleep 2
  588. _debug serverproc $serverproc
  589. else
  590. if [ -z "$wellknown_path" ] ; then
  591. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  592. fi
  593. _debug wellknown_path "$wellknown_path"
  594. if [ ! -d "$Le_Webroot/.well-known" ] ; then
  595. removelevel='1'
  596. elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
  597. removelevel='2'
  598. else
  599. removelevel='3'
  600. fi
  601. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  602. _debug "writing token:$token to $wellknown_path/$token"
  603. mkdir -p "$wellknown_path"
  604. echo -n "$keyauthorization" > "$wellknown_path/$token"
  605. webroot_owner=$(stat -c '%U:%G' $Le_Webroot)
  606. _debug "Changing owner/group of .well-known to $webroot_owner"
  607. chown -R $webroot_owner "$Le_Webroot/.well-known"
  608. fi
  609. fi
  610. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  611. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  612. _err "$d:Challenge error: $resource"
  613. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  614. _clearup
  615. return 1
  616. fi
  617. while [ "1" ] ; do
  618. _debug "sleep 5 secs to verify"
  619. sleep 5
  620. _debug "checking"
  621. if ! _get $uri ; then
  622. _err "$d:Verify error:$resource"
  623. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  624. _clearup
  625. return 1
  626. fi
  627. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | sed 's/"//g')
  628. if [ "$status" == "valid" ] ; then
  629. _info "Success"
  630. _stopserver $serverproc
  631. serverproc=""
  632. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  633. break;
  634. fi
  635. if [ "$status" == "invalid" ] ; then
  636. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  637. _err "$d:Verify error:$error"
  638. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  639. _clearup
  640. return 1;
  641. fi
  642. if [ "$status" == "pending" ] ; then
  643. _info "Pending"
  644. else
  645. _err "$d:Verify error:$response"
  646. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  647. _clearup
  648. return 1
  649. fi
  650. done
  651. done
  652. _clearup
  653. _info "Verify finished, start to sign."
  654. der="$(openssl req -in $CSR_PATH -outform DER | _base64 | _b64)"
  655. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  656. Le_LinkCert="$(grep -i -o '^Location.*' $CURL_HEADER |sed 's/\r//g'| cut -d " " -f 2)"
  657. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  658. if [ "$Le_LinkCert" ] ; then
  659. echo -----BEGIN CERTIFICATE----- > "$CERT_PATH"
  660. curl --silent "$Le_LinkCert" | openssl base64 -e >> "$CERT_PATH"
  661. echo -----END CERTIFICATE----- >> "$CERT_PATH"
  662. _info "Cert success."
  663. cat "$CERT_PATH"
  664. _info "Your cert is in $CERT_PATH"
  665. fi
  666. if [ -z "$Le_LinkCert" ] ; then
  667. response="$(echo $response | openssl base64 -d)"
  668. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  669. return 1
  670. fi
  671. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  672. Le_LinkIssuer=$(grep -i '^Link' $CURL_HEADER | cut -d " " -f 2| cut -d ';' -f 1 | sed 's/<//g' | sed 's/>//g')
  673. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  674. if [ "$Le_LinkIssuer" ] ; then
  675. echo -----BEGIN CERTIFICATE----- > "$CA_CERT_PATH"
  676. curl --silent "$Le_LinkIssuer" | openssl base64 -e >> "$CA_CERT_PATH"
  677. echo -----END CERTIFICATE----- >> "$CA_CERT_PATH"
  678. _info "The intermediate CA cert is in $CA_CERT_PATH"
  679. fi
  680. Le_CertCreateTime=$(date -u "+%s")
  681. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  682. Le_CertCreateTimeStr=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
  683. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  684. if [ ! "$Le_RenewalDays" ] ; then
  685. Le_RenewalDays=80
  686. fi
  687. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  688. Le_NextRenewTime=$(date -u -d "+$Le_RenewalDays day" "+%s")
  689. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  690. Le_NextRenewTimeStr=$(date -u -d "+$Le_RenewalDays day" "+%Y-%m-%d %H:%M:%S UTC")
  691. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  692. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  693. }
  694. renew() {
  695. Le_Domain="$1"
  696. if [ -z "$Le_Domain" ] ; then
  697. _err "Usage: $0 domain.com"
  698. return 1
  699. fi
  700. _initpath $Le_Domain
  701. if [ ! -f "$DOMAIN_CONF" ] ; then
  702. _err "$Le_Domain is not a issued domain, skip."
  703. return 1;
  704. fi
  705. source "$DOMAIN_CONF"
  706. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  707. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  708. return 2
  709. fi
  710. IS_RENEW="1"
  711. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  712. IS_RENEW=""
  713. }
  714. renewAll() {
  715. _initpath
  716. _info "renewAll"
  717. for d in $(ls -F $WORKING_DIR | grep '/$') ; do
  718. d=$(echo $d | cut -d '/' -f 1)
  719. _info "renew $d"
  720. Le_LinkCert=""
  721. Le_Domain=""
  722. Le_Alt=""
  723. Le_Webroot=""
  724. Le_Keylength=""
  725. Le_LinkIssuer=""
  726. Le_CertCreateTime=""
  727. Le_CertCreateTimeStr=""
  728. Le_RenewalDays=""
  729. Le_NextRenewTime=""
  730. Le_NextRenewTimeStr=""
  731. Le_RealCertPath=""
  732. Le_RealKeyPath=""
  733. Le_RealCACertPath=""
  734. Le_ReloadCmd=""
  735. DOMAIN_CONF=""
  736. CSR_PATH=""
  737. CERT_KEY_PATH=""
  738. CERT_PATH=""
  739. CA_CERT_PATH=""
  740. ACCOUNT_KEY_PATH=""
  741. wellknown_path=""
  742. renew "$d"
  743. done
  744. }
  745. installcert() {
  746. Le_Domain="$1"
  747. if [ -z "$Le_Domain" ] ; then
  748. _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
  749. return 1
  750. fi
  751. Le_RealCertPath="$2"
  752. Le_RealKeyPath="$3"
  753. Le_RealCACertPath="$4"
  754. Le_ReloadCmd="$5"
  755. _initpath $Le_Domain
  756. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  757. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  758. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  759. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  760. if [ "$Le_RealCertPath" ] ; then
  761. if [ -f "$Le_RealCertPath" ] ; then
  762. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  763. fi
  764. cat "$CERT_PATH" > "$Le_RealCertPath"
  765. fi
  766. if [ "$Le_RealCACertPath" ] ; then
  767. if [ -f "$Le_RealCACertPath" ] ; then
  768. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  769. fi
  770. if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
  771. echo "" >> "$Le_RealCACertPath"
  772. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  773. else
  774. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  775. fi
  776. fi
  777. if [ "$Le_RealKeyPath" ] ; then
  778. if [ -f "$Le_RealKeyPath" ] ; then
  779. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  780. fi
  781. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  782. fi
  783. if [ "$Le_ReloadCmd" ] ; then
  784. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  785. $Le_ReloadCmd
  786. fi
  787. }
  788. installcronjob() {
  789. _initpath
  790. _info "Installing cron job"
  791. if ! crontab -l | grep 'le.sh cron' ; then
  792. if [ -f "$WORKING_DIR/le.sh" ] ; then
  793. lesh="\"$WORKING_DIR\"/le.sh"
  794. else
  795. _err "Can not install cronjob, le.sh not found."
  796. return 1
  797. fi
  798. crontab -l | { cat; echo "0 0 * * * $SUDO WORKING_DIR=\"$WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  799. fi
  800. return 0
  801. }
  802. uninstallcronjob() {
  803. _info "Removing cron job"
  804. cr="$(crontab -l | grep 'le.sh cron')"
  805. if [ "$cr" ] ; then
  806. crontab -l | sed "/le.sh cron/d" | crontab -
  807. WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 7 | cut -d '=' -f 2 | tr -d '"')"
  808. _info WORKING_DIR "$WORKING_DIR"
  809. fi
  810. _initpath
  811. }
  812. install() {
  813. _initpath
  814. if command -v yum > /dev/null ; then
  815. YUM="1"
  816. INSTALL="$SUDO yum install -y "
  817. elif command -v apt-get > /dev/null ; then
  818. INSTALL="$SUDO apt-get install -y "
  819. fi
  820. if ! command -v "curl" > /dev/null ; then
  821. _err "Please install curl first."
  822. _err "$INSTALL curl"
  823. return 1
  824. fi
  825. if ! command -v "crontab" > /dev/null ; then
  826. _err "Please install crontab first."
  827. if [ "$YUM" ] ; then
  828. _err "$INSTALL crontabs"
  829. else
  830. _err "$INSTALL crontab"
  831. fi
  832. return 1
  833. fi
  834. if ! command -v "openssl" > /dev/null ; then
  835. _err "Please install openssl first."
  836. _err "$INSTALL openssl"
  837. return 1
  838. fi
  839. _info "Installing to $WORKING_DIR"
  840. #try install to /bin if is root
  841. if [ ! -f /usr/local/bin/le.sh ] ; then
  842. #if root
  843. if $SUDO cp le.sh /usr/local/bin/le.sh > /dev/null 2>&1; then
  844. $SUDO chmod 755 /usr/local/bin/le.sh
  845. $SUDO ln -s "/usr/local/bin/le.sh" /usr/local/bin/le
  846. rm -f $WORKING_DIR/le.sh
  847. $SUDO ln -s /usr/local/bin/le.sh $WORKING_DIR/le.sh
  848. _info "Installed to /usr/local/bin/le"
  849. else
  850. #install to home, for non root user
  851. cp le.sh $WORKING_DIR/
  852. chmod +x $WORKING_DIR/le.sh
  853. _info "Installed to $WORKING_DIR/le.sh"
  854. fi
  855. fi
  856. rm -f $WORKING_DIR/le
  857. ln -s $WORKING_DIR/le.sh $WORKING_DIR/le
  858. mkdir -p $WORKING_DIR/dnsapi
  859. cp dnsapi/* $WORKING_DIR/dnsapi/
  860. installcronjob
  861. _info OK
  862. }
  863. uninstall() {
  864. uninstallcronjob
  865. _initpath
  866. if [ -f "/usr/local/bin/le.sh" ] ; then
  867. _info "Removing /usr/local/bin/le.sh"
  868. if $SUDO rm -f /usr/local/bin/le.sh ; then
  869. $SUDO rm -f /usr/local/bin/le
  870. fi
  871. fi
  872. rm -f $WORKING_DIR/le
  873. rm -f $WORKING_DIR/le.sh
  874. _info "The keys and certs are in $WORKING_DIR, you can remove them by yourself."
  875. }
  876. cron() {
  877. renewAll
  878. }
  879. version() {
  880. _info "$PROJECT"
  881. _info "v$VER"
  882. }
  883. showhelp() {
  884. version
  885. echo "Usage: le.sh [command] ...[args]....
  886. Avalible commands:
  887. install:
  888. Install le.sh to your system.
  889. issue:
  890. Issue a cert.
  891. installcert:
  892. Install the issued cert to apache/nginx or any other server.
  893. renew:
  894. Renew a cert.
  895. renewAll:
  896. Renew all the certs.
  897. uninstall:
  898. Uninstall le.sh, and uninstall the cron job.
  899. version:
  900. Show version info.
  901. installcronjob:
  902. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  903. uninstallcronjob:
  904. Uninstall the cron job. The 'uninstall' command can do this automatically.
  905. createAccountKey:
  906. Create an account private key, professional use.
  907. createDomainKey:
  908. Create an domain private key, professional use.
  909. createCSR:
  910. Create CSR , professional use.
  911. "
  912. }
  913. if [ -z "$1" ] ; then
  914. showhelp
  915. else
  916. "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9"
  917. fi