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.

657 lines
16 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
  1. #!/bin/bash
  2. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  3. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  4. API="$DEFAULT_CA"
  5. AGREEMENT="$DEFAULT_AGREEMENT"
  6. _debug() {
  7. if [ -z "$DEBUG" ] ; then
  8. return
  9. fi
  10. if [ -z "$2" ] ; then
  11. echo $1
  12. else
  13. echo $1:$2
  14. fi
  15. }
  16. _info() {
  17. if [ -z "$2" ] ; then
  18. echo $1
  19. else
  20. echo $1:$2
  21. fi
  22. }
  23. _err() {
  24. if [ -z "$2" ] ; then
  25. echo "$1" >&2
  26. else
  27. echo "$1:$2" >&2
  28. fi
  29. }
  30. #domain [2048]
  31. createAccountKey() {
  32. if [ -z "$1" ] ; then
  33. echo Usage: $0 account-domain [2048]
  34. return
  35. fi
  36. account=$1
  37. length=$2
  38. if [ -z "$2" ] ; then
  39. echo Use default length 2048
  40. length=2048
  41. fi
  42. _initpath
  43. mkdir -p $WORKING_DIR
  44. ACCOUNT_KEY_PATH=$WORKING_DIR/account.acc
  45. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  46. echo account key exists, skip
  47. return
  48. else
  49. #generate account key
  50. openssl genrsa $length > $ACCOUNT_KEY_PATH
  51. fi
  52. }
  53. #domain length
  54. createDomainKey() {
  55. if [ -z "$1" ] ; then
  56. echo Usage: $0 domain [2048]
  57. return
  58. fi
  59. domain=$1
  60. length=$2
  61. if [ -z "$2" ] ; then
  62. echo Use default length 2048
  63. length=2048
  64. fi
  65. _initpath $domain
  66. mkdir -p $WORKING_DIR/$domain
  67. CERT_KEY_PATH=$WORKING_DIR/$domain/$domain.key
  68. if [ -f "$CERT_KEY_PATH" ] ; then
  69. echo domain key exists, skip
  70. else
  71. #generate account key
  72. openssl genrsa $length > $CERT_KEY_PATH
  73. fi
  74. }
  75. # domain domainlist
  76. createCSR() {
  77. if [ -z "$1" ] ; then
  78. echo Usage: $0 domain [domainlist]
  79. return
  80. fi
  81. domain=$1
  82. _initpath $domain
  83. domainlist=$2
  84. if [ -f $CSR_PATH ] ; then
  85. echo CSR exists, skip
  86. return
  87. fi
  88. if [ -z "$domainlist" ] ; then
  89. #single domain
  90. echo single domain
  91. openssl req -new -sha256 -key $CERT_KEY_PATH -subj "/CN=$domain" > $CSR_PATH
  92. else
  93. alt=DNS:$(echo $domainlist | sed "s/,/,DNS:/g")
  94. #multi
  95. echo multi domain $alt
  96. 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
  97. fi
  98. }
  99. _b64() {
  100. __n=$(cat)
  101. echo $__n | tr '/+' '_-' | tr -d '= '
  102. }
  103. _send_signed_request() {
  104. url=$1
  105. payload=$2
  106. needbase64=$3
  107. _debug url $url
  108. _debug payload "$payload"
  109. CURL_HEADER="$WORKING_DIR/curl.header"
  110. dp="$WORKING_DIR/curl.dump"
  111. CURL="curl --silent --dump-header $CURL_HEADER "
  112. if [ "$DEBUG" ] ; then
  113. CURL="$CURL --trace-ascii $dp "
  114. fi
  115. payload64=$(echo -n $payload | base64 -w 0 | _b64)
  116. _debug payload64 $payload64
  117. nonceurl="$API/directory"
  118. nonce=$($CURL -I $nonceurl | grep "^Replay-Nonce:" | sed s/\\r//|sed s/\\n//| cut -d ' ' -f 2)
  119. _debug nonce $nonce
  120. protected=$(echo -n "$HEADERPLACE" | sed "s/NONCE/$nonce/" )
  121. _debug protected "$protected"
  122. protected64=$( echo -n $protected | base64 -w 0 | _b64)
  123. _debug protected64 "$protected64"
  124. sig=$(echo -n "$protected64.$payload64" | openssl dgst -sha256 -sign $ACCOUNT_KEY_PATH | base64 -w 0 | _b64)
  125. _debug sig "$sig"
  126. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  127. _debug body "$body"
  128. if [ "$needbase64" ] ; then
  129. response="$($CURL -X POST --data "$body" $url | base64 -w 0)"
  130. else
  131. response="$($CURL -X POST --data "$body" $url)"
  132. fi
  133. responseHeaders="$(sed 's/\r//g' $CURL_HEADER)"
  134. _debug responseHeaders "$responseHeaders"
  135. _debug response "$response"
  136. code="$(grep ^HTTP $CURL_HEADER | tail -1 | cut -d " " -f 2)"
  137. _debug code $code
  138. }
  139. _get() {
  140. url="$1"
  141. _debug url $url
  142. response="$(curl --silent $url)"
  143. ret=$?
  144. _debug response "$response"
  145. code="$(echo $response | grep -o '"status":[0-9]\+' | cut -d : -f 2)"
  146. _debug code $code
  147. return $ret
  148. }
  149. #setopt "file" "opt" "=" "value" [";"]
  150. _setopt() {
  151. __conf="$1"
  152. __opt="$2"
  153. __sep="$3"
  154. __val="$4"
  155. __end="$5"
  156. if [ -z "$__opt" ] ; then
  157. echo usage: $0 '"file" "opt" "=" "value" [";"]'
  158. return
  159. fi
  160. if [ ! -f $__conf ] ; then
  161. touch $__conf
  162. fi
  163. if grep -H -n "^$__opt$__sep" $__conf > /dev/null ; then
  164. _debug OK
  165. sed -i "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" $__conf
  166. else
  167. _debug APP
  168. echo "$__opt$__sep$__val$__end" >> $__conf
  169. fi
  170. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  171. }
  172. _startserver() {
  173. content="$1"
  174. while true ; do
  175. if [ -z "$DEBUG" ] ; then
  176. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | nc -q 1 -l -p 80 > /dev/null
  177. else
  178. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | nc -q 1 -l -p 80
  179. fi
  180. done
  181. }
  182. _stopserver() {
  183. pid="$1"
  184. if [ "$pid" ] ; then
  185. if [ -z "$DEBUG" ] ; then
  186. kill -s 9 $pid 2>&1
  187. killall -s 9 nc 2>&1
  188. else
  189. kill -s 9 $pid 2>&1 > /dev/null
  190. killall -s 9 nc 2>&1 > /dev/null
  191. fi
  192. fi
  193. }
  194. _initpath() {
  195. if [ -z "$WORKING_DIR" ]; then
  196. WORKING_DIR=~/.le
  197. fi
  198. domain=$1
  199. mkdir -p $WORKING_DIR
  200. ACCOUNT_KEY_PATH=$WORKING_DIR/account.acc
  201. if [ -z "$domain" ] ; then
  202. return 0
  203. fi
  204. mkdir -p $WORKING_DIR/$domain
  205. CSR_PATH=$WORKING_DIR/$domain/$domain.csr
  206. CERT_KEY_PATH=$WORKING_DIR/$domain/$domain.key
  207. CERT_PATH=$WORKING_DIR/$domain/$domain.cer
  208. CA_CERT_PATH=$WORKING_DIR/$domain/ca.cer
  209. }
  210. #issue webroot a.com [www.a.com,b.com,c.com] [key-length] [cert-file-path] [key-file-path] [reloadCmd]
  211. issue() {
  212. if [ -z "$1" ] ; then
  213. echo "Usage: $0 webroot a.com [www.a.com,b.com,c.com] [key-length] [cert-file-path] [key-file-path] [reloadCmd]"
  214. return 1
  215. fi
  216. Le_Webroot=$1
  217. Le_Domain=$2
  218. Le_Alt=$3
  219. Le_Keylength=$4
  220. if [ -z "$Le_Domain" ] ; then
  221. Le_Domain="$1"
  222. fi
  223. _initpath $Le_Domain
  224. DOMAIN_CONF=$WORKING_DIR/$Le_Domain/$Le_Domain.conf
  225. if [ -f "$DOMAIN_CONF" ] ; then
  226. source "$DOMAIN_CONF"
  227. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  228. _info "Skip, Next renwal time is: $Le_NextRenewTimeStr"
  229. return 2
  230. fi
  231. fi
  232. if [ "$Le_Alt" == "no" ] ; then
  233. Le_Alt=""
  234. fi
  235. if [ "$Le_Webroot" == "no" ] ; then
  236. _info "Standalone mode."
  237. if ! command -v "nc" > /dev/null ; then
  238. _err "Please install netcat(nc) tools first."
  239. return 1
  240. fi
  241. if ! command -v "netstat" > /dev/null ; then
  242. _err "Please install netstat first."
  243. return 1
  244. fi
  245. netprc="$(netstat -antpl | grep ':80 ')"
  246. if [ "$netprc" ] ; then
  247. _err "$netprc"
  248. _err "tcp port 80 is already used by $(echo "$netprc" | cut -d '/' -f 2)"
  249. _err "Please stop it first"
  250. return 1
  251. fi
  252. fi
  253. createAccountKey $Le_Domain $Le_Keylength
  254. createDomainKey $Le_Domain $Le_Keylength
  255. createCSR $Le_Domain $Le_Alt
  256. 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)
  257. if [ "${#pub_exp}" == "5" ] ; then
  258. pub_exp=0$pub_exp
  259. fi
  260. _debug pub_exp "$pub_exp"
  261. e=$(echo $pub_exp | xxd -r -p | base64)
  262. _debug e "$e"
  263. modulus=$(openssl rsa -in $ACCOUNT_KEY_PATH -modulus -noout | cut -d '=' -f 2 )
  264. n=$(echo $modulus| xxd -r -p | base64 -w 0 | _b64 )
  265. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  266. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  267. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  268. _debug HEADER "$HEADER"
  269. accountkey_json=$(echo -n "$jwk" | sed "s/ //g")
  270. thumbprint=$(echo -n "$accountkey_json" | sha256sum | xxd -r -p | base64 -w 0 | _b64)
  271. _info "Registering account"
  272. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  273. if [ "$ACCOUNT_EMAIL" ] ; then
  274. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  275. fi
  276. _send_signed_request "$API/acme/new-reg" "$regjson"
  277. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  278. _info "Registered"
  279. echo $response > $WORKING_DIR/account.json
  280. elif [ "$code" == '409' ] ; then
  281. _info "Already registered"
  282. else
  283. _err "Register account Error."
  284. return 1
  285. fi
  286. # verify each domain
  287. _info "Verify each domain"
  288. alldomains=$(echo "$Le_Domain,$Le_Alt" | sed "s/,/ /g")
  289. for d in $alldomains
  290. do
  291. _info "Verifing domain $d"
  292. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  293. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  294. _err "new-authz error: $response"
  295. return 1
  296. fi
  297. http01=$(echo $response | egrep -o '{[^{]*"type":"http-01"[^}]*')
  298. _debug http01 "$http01"
  299. token=$(echo "$http01" | sed 's/,/\n'/g| grep '"token":'| cut -d : -f 2|sed 's/"//g')
  300. _debug token $token
  301. uri=$(echo "$http01" | sed 's/,/\n'/g| grep '"uri":'| cut -d : -f 2,3|sed 's/"//g')
  302. _debug uri $uri
  303. keyauthorization="$token.$thumbprint"
  304. _debug keyauthorization "$keyauthorization"
  305. if [ "$Le_Webroot" == "no" ] ; then
  306. _info "Standalone mode server"
  307. _startserver "$keyauthorization" & 2>&1 >/dev/null
  308. serverproc="$!"
  309. sleep 2
  310. _debug serverproc $serverproc
  311. else
  312. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  313. _debug wellknown_path "$wellknown_path"
  314. mkdir -p "$wellknown_path"
  315. wellknown_path="$wellknown_path/$token"
  316. echo -n "$keyauthorization" > $wellknown_path
  317. fi
  318. wellknown_url="http://$d/.well-known/acme-challenge/$token"
  319. _debug wellknown_url "$wellknown_url"
  320. _debug challenge "$challenge"
  321. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  322. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  323. _err "challenge error: $d"
  324. _stopserver $serverproc
  325. return 1
  326. fi
  327. while [ "1" ] ; do
  328. _debug "sleep 5 secs to verify"
  329. sleep 5
  330. _debug "checking"
  331. if ! _get $uri ; then
  332. _err "Verify error:$resource"
  333. _stopserver $serverproc
  334. return 1
  335. fi
  336. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | sed 's/"//g')
  337. if [ "$status" == "valid" ] ; then
  338. _info "Verify success:$d"
  339. break;
  340. fi
  341. if [ "$status" == "invalid" ] ; then
  342. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  343. _err "Verify error:$error"
  344. _stopserver $serverproc
  345. return 1;
  346. fi
  347. if [ "$status" == "pending" ] ; then
  348. _info "Verify pending:$d"
  349. else
  350. _err "Verify error:$response"
  351. _stopserver $serverproc
  352. return 1
  353. fi
  354. done
  355. _stopserver $serverproc
  356. done
  357. _info "Verify finished, start to sign."
  358. der="$(openssl req -in $CSR_PATH -outform DER | base64 -w 0 | _b64)"
  359. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  360. Le_LinkCert="$(grep -i -o '^Location.*' $CURL_HEADER |sed 's/\r//g'| cut -d " " -f 2)"
  361. _setopt $DOMAIN_CONF "Le_LinkCert" "=" "$Le_LinkCert"
  362. if [ "$Le_LinkCert" ] ; then
  363. echo -----BEGIN CERTIFICATE----- > $CERT_PATH
  364. curl --silent $Le_LinkCert | base64 >> $CERT_PATH
  365. echo -----END CERTIFICATE----- >> $CERT_PATH
  366. _info "Cert success."
  367. cat $CERT_PATH
  368. _info "Your cert is in $CERT_PATH"
  369. fi
  370. _setopt $DOMAIN_CONF "Le_Domain" "=" "$Le_Domain"
  371. _setopt $DOMAIN_CONF "Le_Alt" "=" "$Le_Alt"
  372. _setopt $DOMAIN_CONF "Le_Webroot" "=" "$Le_Webroot"
  373. _setopt $DOMAIN_CONF "Le_Keylength" "=" "$Le_Keylength"
  374. if [ -z "$Le_LinkCert" ] ; then
  375. response="$(echo $response | base64 -d)"
  376. _info "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  377. return 1
  378. fi
  379. Le_LinkIssuer=$(grep -i '^Link' $CURL_HEADER | cut -d " " -f 2| cut -d ';' -f 1 | sed 's/<//g' | sed 's/>//g')
  380. _setopt $DOMAIN_CONF "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  381. if [ "$Le_LinkIssuer" ] ; then
  382. echo -----BEGIN CERTIFICATE----- > $CA_CERT_PATH
  383. curl --silent $Le_LinkIssuer | base64 >> $CA_CERT_PATH
  384. echo -----END CERTIFICATE----- >> $CA_CERT_PATH
  385. _info "The intermediate CA cert is in $CA_CERT_PATH"
  386. fi
  387. Le_CertCreateTime=$(date -u "+%s")
  388. _setopt $DOMAIN_CONF "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  389. Le_CertCreateTimeStr=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
  390. _setopt $DOMAIN_CONF "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  391. if [ ! "$Le_RenewalDays" ] ; then
  392. Le_RenewalDays=50
  393. fi
  394. _setopt $DOMAIN_CONF "Le_RenewalDays" "=" "$Le_RenewalDays"
  395. Le_NextRenewTime=$(date -u -d "+$Le_RenewalDays day" "+%s")
  396. _setopt $DOMAIN_CONF "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  397. Le_NextRenewTimeStr=$(date -u -d "+$Le_RenewalDays day" "+%Y-%m-%d %H:%M:%S UTC")
  398. _setopt $DOMAIN_CONF "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  399. _setopt $DOMAIN_CONF "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  400. if [ "$Le_RealCertPath" ] ; then
  401. if [ -f "$Le_RealCertPath" ] ; then
  402. rm -f $Le_RealCertPath
  403. fi
  404. ln -s $CERT_PATH $Le_RealCertPath
  405. fi
  406. _setopt $DOMAIN_CONF "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  407. if [ "$Le_RealKeyPath" ] ; then
  408. if [ -f "$Le_RealKeyPath" ] ; then
  409. rm -f $Le_RealKeyPath
  410. fi
  411. ln -s $CERT_KEY_PATH $Le_RealKeyPath
  412. fi
  413. _setopt $DOMAIN_CONF "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  414. if [ "$Le_ReloadCmd" ] ; then
  415. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  416. $Le_ReloadCmd
  417. fi
  418. }
  419. renew() {
  420. Le_Domain="$1"
  421. if [ -z "$Le_Domain" ] ; then
  422. echo Usage: $0 domain.com
  423. return 1
  424. fi
  425. issue $Le_Domain
  426. }
  427. renewAll() {
  428. _info "renewAll"
  429. for d in $(ls -F $WORKING_DIR | grep '/$') ; do
  430. d=$(echo $d | cut -d '/' -f 1)
  431. _info "renew $d"
  432. Le_LinkCert=""
  433. Le_Domain=""
  434. Le_Alt=""
  435. Le_Webroot=""
  436. Le_Keylength=""
  437. Le_LinkIssuer=""
  438. Le_CertCreateTime=""
  439. Le_CertCreateTimeStr=""
  440. Le_RenewalDays=""
  441. Le_NextRenewTime=""
  442. Le_NextRenewTimeStr=""
  443. Le_RealCertPath=""
  444. Le_RealKeyPath=""
  445. Le_ReloadCmd=""
  446. renew "$d"
  447. done
  448. }
  449. install() {
  450. _initpath
  451. if ! command -v "curl" > /dev/null ; then
  452. _err "Please install curl first."
  453. _err "Ubuntu: sudo apt-get install curl"
  454. _err "CentOS: yum install curl"
  455. return 1
  456. fi
  457. if ! command -v "crontab" > /dev/null ; then
  458. _err "Please install crontab first."
  459. _err "CentOs: yum -y install crontabs"
  460. return 1
  461. fi
  462. if ! command -v "openssl" > /dev/null ; then
  463. _err "Please install openssl first."
  464. _err "CentOs: yum -y install openssl"
  465. return 1
  466. fi
  467. if ! command -v "xxd" > /dev/null ; then
  468. _err "Please install xxd first."
  469. _err "CentOs: yum install vim-common"
  470. return 1
  471. fi
  472. _info "Installing to $WORKING_DIR"
  473. mkdir -p $WORKING_DIR/
  474. cp le.sh $WORKING_DIR/
  475. chmod +x $WORKING_DIR/le.sh
  476. if [ ! -f /bin/le.sh ] ; then
  477. ln -s $WORKING_DIR/le.sh /bin/le.sh
  478. ln -s $WORKING_DIR/le.sh /bin/le
  479. fi
  480. _info "Installing cron job"
  481. if ! crontab -l | grep 'le.sh renewAll' ; then
  482. crontab -l | { cat; echo "0 0 * * * le.sh renewAll"; } | crontab -
  483. if command -v crond > /dev/null ; then
  484. service crond reload 2>/dev/null
  485. else
  486. service cron reload 2>/dev/null
  487. fi
  488. fi
  489. _info OK
  490. }
  491. uninstall() {
  492. _initpath
  493. _info "Removing cron job"
  494. if crontab -l | grep 'le.sh renewAll' ; then
  495. crontab -l | sed "/le.sh renewAll/d" | crontab -
  496. if command -v crond > /dev/null ; then
  497. service crond reload 2>/dev/null
  498. else
  499. service cron reload 2>/dev/null
  500. fi
  501. fi
  502. _info "Removing /bin/le.sh"
  503. rm -f /bin/le
  504. rm -f /bin/le.sh
  505. _info "The keys and certs are in $WORKING_DIR, you can remove them by yourself."
  506. }
  507. showhelp() {
  508. echo "Usage: issue|renew|renewAll|createAccountKey|createDomainKey|createCSR|install|uninstall"
  509. }
  510. if [ -z "$1" ] ; then
  511. showhelp
  512. fi
  513. $1 $2 $3 $4 $5 $6 $7 $8