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.

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