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.

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