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.

653 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_Webroot" == "no" ] ; then
  233. _info "Standalone mode."
  234. if ! command -v "nc" > /dev/null ; then
  235. _err "Please install netcat(nc) tools first."
  236. return 1
  237. fi
  238. if ! command -v "netstat" > /dev/null ; then
  239. _err "Please install netstat first."
  240. return 1
  241. fi
  242. netprc="$(netstat -antpl | grep ':80 ')"
  243. if [ "$netprc" ] ; then
  244. _err "$netprc"
  245. _err "tcp port 80 is already used by $(echo "$netprc" | cut -d '/' -f 2)"
  246. _err "Please stop it first"
  247. return 1
  248. fi
  249. fi
  250. createAccountKey $Le_Domain $Le_Keylength
  251. createDomainKey $Le_Domain $Le_Keylength
  252. createCSR $Le_Domain $Le_Alt
  253. 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)
  254. if [ "${#pub_exp}" == "5" ] ; then
  255. pub_exp=0$pub_exp
  256. fi
  257. _debug pub_exp "$pub_exp"
  258. e=$(echo $pub_exp | xxd -r -p | base64)
  259. _debug e "$e"
  260. modulus=$(openssl rsa -in $ACCOUNT_KEY_PATH -modulus -noout | cut -d '=' -f 2 )
  261. n=$(echo $modulus| xxd -r -p | base64 -w 0 | _b64 )
  262. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  263. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  264. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  265. _debug HEADER "$HEADER"
  266. accountkey_json=$(echo -n "$jwk" | sed "s/ //g")
  267. thumbprint=$(echo -n "$accountkey_json" | sha256sum | xxd -r -p | base64 -w 0 | _b64)
  268. _info "Registering account"
  269. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  270. if [ "$ACCOUNT_EMAIL" ] ; then
  271. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  272. fi
  273. _send_signed_request "$API/acme/new-reg" "$regjson"
  274. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  275. _info "Registered"
  276. echo $response > $WORKING_DIR/account.json
  277. elif [ "$code" == '409' ] ; then
  278. _info "Already registered"
  279. else
  280. _err "Register account Error."
  281. return 1
  282. fi
  283. # verify each domain
  284. _info "Verify each domain"
  285. alldomains=$(echo "$Le_Domain,$Le_Alt" | sed "s/,/ /g")
  286. for d in $alldomains
  287. do
  288. _info "Verifing domain $d"
  289. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  290. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  291. _err "new-authz error: $response"
  292. return 1
  293. fi
  294. http01=$(echo $response | egrep -o '{[^{]*"type":"http-01"[^}]*')
  295. _debug http01 "$http01"
  296. token=$(echo "$http01" | sed 's/,/\n'/g| grep '"token":'| cut -d : -f 2|sed 's/"//g')
  297. _debug token $token
  298. uri=$(echo "$http01" | sed 's/,/\n'/g| grep '"uri":'| cut -d : -f 2,3|sed 's/"//g')
  299. _debug uri $uri
  300. keyauthorization="$token.$thumbprint"
  301. _debug keyauthorization "$keyauthorization"
  302. if [ "$Le_Webroot" == "no" ] ; then
  303. _info "Standalone mode server"
  304. _startserver "$keyauthorization" & 2>&1 >/dev/null
  305. serverproc="$!"
  306. sleep 2
  307. _debug serverproc $serverproc
  308. else
  309. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  310. _debug wellknown_path "$wellknown_path"
  311. mkdir -p "$wellknown_path"
  312. wellknown_path="$wellknown_path/$token"
  313. echo -n "$keyauthorization" > $wellknown_path
  314. fi
  315. wellknown_url="http://$d/.well-known/acme-challenge/$token"
  316. _debug wellknown_url "$wellknown_url"
  317. _debug challenge "$challenge"
  318. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  319. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  320. _err "challenge error: $d"
  321. _stopserver $serverproc
  322. return 1
  323. fi
  324. while [ "1" ] ; do
  325. _debug "sleep 5 secs to verify"
  326. sleep 5
  327. _debug "checking"
  328. if ! _get $uri ; then
  329. _err "Verify error:$resource"
  330. _stopserver $serverproc
  331. return 1
  332. fi
  333. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | sed 's/"//g')
  334. if [ "$status" == "valid" ] ; then
  335. _info "Verify success:$d"
  336. break;
  337. fi
  338. if [ "$status" == "invalid" ] ; then
  339. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  340. _err "Verify error:$error"
  341. _stopserver $serverproc
  342. return 1;
  343. fi
  344. if [ "$status" == "pending" ] ; then
  345. _info "Verify pending:$d"
  346. else
  347. _err "Verify error:$response"
  348. _stopserver $serverproc
  349. return 1
  350. fi
  351. done
  352. _stopserver $serverproc
  353. done
  354. _info "Verify finished, start to sign."
  355. der="$(openssl req -in $CSR_PATH -outform DER | base64 -w 0 | _b64)"
  356. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  357. Le_LinkCert="$(grep -i -o '^Location.*' $CURL_HEADER |sed 's/\r//g'| cut -d " " -f 2)"
  358. _setopt $DOMAIN_CONF "Le_LinkCert" "=" "$Le_LinkCert"
  359. if [ "$Le_LinkCert" ] ; then
  360. echo -----BEGIN CERTIFICATE----- > $CERT_PATH
  361. curl --silent $Le_LinkCert | base64 >> $CERT_PATH
  362. echo -----END CERTIFICATE----- >> $CERT_PATH
  363. _info "Cert success."
  364. cat $CERT_PATH
  365. _info "Your cert is in $CERT_PATH"
  366. fi
  367. _setopt $DOMAIN_CONF "Le_Domain" "=" "$Le_Domain"
  368. _setopt $DOMAIN_CONF "Le_Alt" "=" "$Le_Alt"
  369. _setopt $DOMAIN_CONF "Le_Webroot" "=" "$Le_Webroot"
  370. _setopt $DOMAIN_CONF "Le_Keylength" "=" "$Le_Keylength"
  371. if [ -z "$Le_LinkCert" ] ; then
  372. response="$(echo $response | base64 -d)"
  373. _info "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  374. return 1
  375. fi
  376. Le_LinkIssuer=$(grep -i '^Link' $CURL_HEADER | cut -d " " -f 2| cut -d ';' -f 1 | sed 's/<//g' | sed 's/>//g')
  377. _setopt $DOMAIN_CONF "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  378. if [ "$Le_LinkIssuer" ] ; then
  379. echo -----BEGIN CERTIFICATE----- > $CA_CERT_PATH
  380. curl --silent $Le_LinkIssuer | base64 >> $CA_CERT_PATH
  381. echo -----END CERTIFICATE----- >> $CA_CERT_PATH
  382. _info "The intermediate CA cert is in $CA_CERT_PATH"
  383. fi
  384. Le_CertCreateTime=$(date -u "+%s")
  385. _setopt $DOMAIN_CONF "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  386. Le_CertCreateTimeStr=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
  387. _setopt $DOMAIN_CONF "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  388. if [ ! "$Le_RenewalDays" ] ; then
  389. Le_RenewalDays=50
  390. fi
  391. _setopt $DOMAIN_CONF "Le_RenewalDays" "=" "$Le_RenewalDays"
  392. Le_NextRenewTime=$(date -u -d "+$Le_RenewalDays day" "+%s")
  393. _setopt $DOMAIN_CONF "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  394. Le_NextRenewTimeStr=$(date -u -d "+$Le_RenewalDays day" "+%Y-%m-%d %H:%M:%S UTC")
  395. _setopt $DOMAIN_CONF "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  396. _setopt $DOMAIN_CONF "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  397. if [ "$Le_RealCertPath" ] ; then
  398. if [ -f "$Le_RealCertPath" ] ; then
  399. rm -f $Le_RealCertPath
  400. fi
  401. ln -s $CERT_PATH $Le_RealCertPath
  402. fi
  403. _setopt $DOMAIN_CONF "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  404. if [ "$Le_RealKeyPath" ] ; then
  405. if [ -f "$Le_RealKeyPath" ] ; then
  406. rm -f $Le_RealKeyPath
  407. fi
  408. ln -s $CERT_KEY_PATH $Le_RealKeyPath
  409. fi
  410. _setopt $DOMAIN_CONF "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  411. if [ "$Le_ReloadCmd" ] ; then
  412. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  413. $Le_ReloadCmd
  414. fi
  415. }
  416. renew() {
  417. Le_Domain="$1"
  418. if [ -z "$Le_Domain" ] ; then
  419. echo Usage: $0 domain.com
  420. return 1
  421. fi
  422. issue $Le_Domain
  423. }
  424. renewAll() {
  425. _info "renewAll"
  426. for d in $(ls -F $WORKING_DIR | grep '/$') ; do
  427. d=$(echo $d | cut -d '/' -f 1)
  428. _info "renew $d"
  429. Le_LinkCert=""
  430. Le_Domain=""
  431. Le_Alt=""
  432. Le_Webroot=""
  433. Le_Keylength=""
  434. Le_LinkIssuer=""
  435. Le_CertCreateTime=""
  436. Le_CertCreateTimeStr=""
  437. Le_RenewalDays=""
  438. Le_NextRenewTime=""
  439. Le_NextRenewTimeStr=""
  440. Le_RealCertPath=""
  441. Le_RealKeyPath=""
  442. Le_ReloadCmd=""
  443. renew "$d"
  444. done
  445. }
  446. install() {
  447. _initpath
  448. if ! command -v "curl" > /dev/null ; then
  449. _err "Please install curl first."
  450. _err "Ubuntu: sudo apt-get install curl"
  451. _err "CentOS: yum install curl"
  452. return 1
  453. fi
  454. if ! command -v "crontab" > /dev/null ; then
  455. _err "Please install crontab first."
  456. _err "CentOs: yum -y install crontabs"
  457. return 1
  458. fi
  459. if ! command -v "openssl" > /dev/null ; then
  460. _err "Please install openssl first."
  461. _err "CentOs: yum -y install openssl"
  462. return 1
  463. fi
  464. if ! command -v "xxd" > /dev/null ; then
  465. _err "Please install xxd first."
  466. _err "CentOs: yum install vim-common"
  467. return 1
  468. fi
  469. _info "Installing to $WORKING_DIR"
  470. mkdir -p $WORKING_DIR/
  471. cp le.sh $WORKING_DIR/
  472. chmod +x $WORKING_DIR/le.sh
  473. if [ ! -f /bin/le.sh ] ; then
  474. ln -s $WORKING_DIR/le.sh /bin/le.sh
  475. ln -s $WORKING_DIR/le.sh /bin/le
  476. fi
  477. _info "Installing cron job"
  478. if ! crontab -l | grep 'le.sh renewAll' ; then
  479. crontab -l | { cat; echo "0 0 * * * le.sh renewAll"; } | crontab -
  480. if command -v crond > /dev/null ; then
  481. service crond reload 2>/dev/null
  482. else
  483. service cron reload 2>/dev/null
  484. fi
  485. fi
  486. _info OK
  487. }
  488. uninstall() {
  489. _initpath
  490. _info "Removing cron job"
  491. if crontab -l | grep 'le.sh renewAll' ; then
  492. crontab -l | sed "/le.sh renewAll/d" | crontab -
  493. if command -v crond > /dev/null ; then
  494. service crond reload 2>/dev/null
  495. else
  496. service cron reload 2>/dev/null
  497. fi
  498. fi
  499. _info "Removing /bin/le.sh"
  500. rm -f /bin/le
  501. rm -f /bin/le.sh
  502. _info "The keys and certs are in $WORKING_DIR, you can remove them by yourself."
  503. }
  504. showhelp() {
  505. echo "Usage: issue|renew|renewAll|createAccountKey|createDomainKey|createCSR|install|uninstall"
  506. }
  507. if [ -z "$1" ] ; then
  508. showhelp
  509. fi
  510. $1 $2 $3 $4 $5 $6 $7 $8