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.

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