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.

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