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.

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