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.

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