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.

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