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