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.

599 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)"
  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 | 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. _get "$Le_LinkIssuer"
  338. echo -----BEGIN CERTIFICATE----- > $CA_CERT_PATH
  339. curl --silent $Le_LinkIssuer | base64 >> $CA_CERT_PATH
  340. echo -----END CERTIFICATE----- >> $CA_CERT_PATH
  341. _info "The intermediate CA cert is in $CA_CERT_PATH"
  342. fi
  343. Le_CertCreateTime=$(date -u "+%s")
  344. _setopt $DOMAIN_CONF "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  345. Le_CertCreateTimeStr=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
  346. _setopt $DOMAIN_CONF "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  347. if [ ! "$Le_RenewalDays" ] ; then
  348. Le_RenewalDays=50
  349. fi
  350. _setopt $DOMAIN_CONF "Le_RenewalDays" "=" "$Le_RenewalDays"
  351. Le_NextRenewTime=$(date -u -d "+$Le_RenewalDays day" "+%s")
  352. _setopt $DOMAIN_CONF "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  353. Le_NextRenewTimeStr=$(date -u -d "+$Le_RenewalDays day" "+%Y-%m-%d %H:%M:%S UTC")
  354. _setopt $DOMAIN_CONF "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  355. _setopt $DOMAIN_CONF "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  356. if [ "$Le_RealCertPath" ] ; then
  357. if [ -f "$Le_RealCertPath" ] ; then
  358. rm -f $Le_RealCertPath
  359. fi
  360. ln -s $CERT_PATH $Le_RealCertPath
  361. fi
  362. _setopt $DOMAIN_CONF "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  363. if [ "$Le_RealKeyPath" ] ; then
  364. if [ -f "$Le_RealKeyPath" ] ; then
  365. rm -f $Le_RealKeyPath
  366. fi
  367. ln -s $CERT_KEY_PATH $Le_RealKeyPath
  368. fi
  369. _setopt $DOMAIN_CONF "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  370. if [ "$Le_ReloadCmd" ] ; then
  371. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  372. $Le_ReloadCmd
  373. fi
  374. }
  375. renew() {
  376. Le_Domain="$1"
  377. if [ -z "$Le_Domain" ] ; then
  378. echo Usage: $0 domain.com
  379. return 1
  380. fi
  381. DOMAIN_CONF=$WORKING_DIR/$Le_Domain/$Le_Domain.conf
  382. if [ -f "$DOMAIN_CONF" ] ; then
  383. source "$DOMAIN_CONF"
  384. if [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  385. _info "Skip, Next renwal time is: $Le_NextRenewTimeStr"
  386. return 2
  387. fi
  388. fi
  389. if [ -z "$Le_Webroot" ] ; then
  390. echo Le_Webroot can not found, please remove the conf file and issue a new cert
  391. return 1
  392. fi
  393. issue $Le_Domain
  394. }
  395. renewAll() {
  396. _info "renewAll"
  397. for d in $(ls -F $WORKING_DIR | grep '/$') ; do
  398. d=$(echo $d | cut -d '/' -f 1)
  399. _info "renew $d"
  400. renew "$d"
  401. done
  402. }
  403. install() {
  404. _initpath
  405. if ! command -v "curl" ; then
  406. _info "Please install curl first."
  407. _info "Ubuntu: sudo apt-get install curl"
  408. _info "CentOS: yum install curl"
  409. return 1
  410. fi
  411. if ! command -v "crontab" ; then
  412. _info "Please install crontab first."
  413. _info "CentOs: yum -y install crontabs"
  414. return 1
  415. fi
  416. if ! command -v "openssl" ; then
  417. _info "Please install openssl first."
  418. _info "CentOs: yum -y install openssl"
  419. return 1
  420. fi
  421. if ! command -v "xxd" ; then
  422. _info "Please install xxd first."
  423. _info "CentOs: yum install vim-common"
  424. return 1
  425. fi
  426. _info "Installing to $WORKING_DIR"
  427. mkdir -p $WORKING_DIR/
  428. cp le.sh $WORKING_DIR/
  429. chmod +x $WORKING_DIR/le.sh
  430. if [ ! -f /bin/le.sh ] ; then
  431. ln -s $WORKING_DIR/le.sh /bin/le.sh
  432. ln -s $WORKING_DIR/le.sh /bin/le
  433. fi
  434. _info "Installing cron job"
  435. if ! crontab -l | grep 'le.sh renewAll' ; then
  436. crontab -l | { cat; echo "0 0 * * * le.sh renewAll"; } | crontab -
  437. if command -v crond ; then
  438. service cron reload
  439. else
  440. service cron restart
  441. fi
  442. fi
  443. _info OK
  444. }
  445. uninstall() {
  446. _initpath
  447. _info "Removing cron job"
  448. crontab -l | sed "/le.sh renewAll/d" | crontab -
  449. _info "Removing /bin/le.sh"
  450. rm -f /bin/le
  451. rm -f /bin/le.sh
  452. _info "The keys and certs are in $WORKING_DIR, you can remove them by yourself."
  453. }
  454. showhelp() {
  455. echo "Usage: issue|renew|renewAll|createAccountKey|createDomainKey|createCSR|install|uninstall"
  456. }
  457. if [ -z "$1" ] ; then
  458. showhelp
  459. fi
  460. $1 $2 $3 $4 $5 $6 $7 $8