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.

566 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
  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 grep -H -n "^$__opt$__sep" $__conf ; 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. if [ -z "$CSR_PATH" ] ; then
  185. CSR_PATH=$WORKING_DIR/$domain/$domain.csr
  186. fi
  187. if [ -z "$CERT_KEY_PATH" ] ; then
  188. CERT_KEY_PATH=$WORKING_DIR/$domain/$domain.key
  189. fi
  190. if [ -z "$CERT_PATH" ] ; then
  191. CERT_PATH=$WORKING_DIR/$domain/$domain.cer
  192. fi
  193. }
  194. #issue webroot a.com [www.a.com,b.com,c.com] [key-length] [cert-file-path] [key-file-path] [reloadCmd]
  195. issue() {
  196. if [ -z "$1" ] ; then
  197. echo "Usage: $0 webroot a.com [www.a.com,b.com,c.com] [key-length] [cert-file-path] [key-file-path] [reloadCmd]"
  198. return 1
  199. fi
  200. Le_Webroot=$1
  201. Le_Domain=$2
  202. Le_Alt=$3
  203. Le_Keylength=$4
  204. if [ -z "$Le_Domain" ] ; then
  205. Le_Domain="$1"
  206. fi
  207. _initpath $Le_Domain
  208. DOMAIN_CONF=$WORKING_DIR/$Le_Domain/$Le_Domain.conf
  209. if [ -f "$DOMAIN_CONF" ] ; then
  210. source "$DOMAIN_CONF"
  211. if [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  212. _info "Skip, Next renwal time is: $Le_NextRenewTimeStr"
  213. return 2
  214. fi
  215. fi
  216. if [ -z "$Le_Webroot" ] ; then
  217. echo Usage: $0 webroot a.com [b.com,c.com] [key-length]
  218. return 1
  219. fi
  220. createAccountKey $Le_Domain $Le_Keylength
  221. createDomainKey $Le_Domain $Le_Keylength
  222. createCSR $Le_Domain $Le_Alt
  223. 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)
  224. if [ "${#pub_exp}" == "5" ] ; then
  225. pub_exp=0$pub_exp
  226. fi
  227. _debug pub_exp "$pub_exp"
  228. e=$(echo $pub_exp | xxd -r -p | base64)
  229. _debug e "$e"
  230. modulus=$(openssl rsa -in $ACCOUNT_KEY_PATH -modulus -noout | cut -d '=' -f 2 )
  231. n=$(echo $modulus| xxd -r -p | base64 | _b64 )
  232. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  233. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  234. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  235. _debug HEADER "$HEADER"
  236. accountkey_json=$(echo -n "$jwk" | sed "s/ //g")
  237. thumbprint=$(echo -n "$accountkey_json" | sha256sum | xxd -r -p | base64 | _b64)
  238. _info "Registering account"
  239. regjson='{"resource": "new-reg", "agreement": "https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"}'
  240. if [ "$ACCOUNT_EMAIL" ] ; then
  241. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"}'
  242. fi
  243. _send_signed_request "$API/acme/new-reg" "$regjson"
  244. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  245. _info "Registered"
  246. echo $response > $WORKING_DIR/account.json
  247. elif [ "$code" == '409' ] ; then
  248. _info "Already registered"
  249. else
  250. _info "Register account Error."
  251. return 1
  252. fi
  253. # verify each domain
  254. _info "verify each domain"
  255. alldomains=$(echo "$Le_Domain,$Le_Alt" | sed "s/,/ /g")
  256. for d in $alldomains
  257. do
  258. _info "Verifing domain $d"
  259. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  260. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  261. _info "new-authz error: $d"
  262. return 1
  263. fi
  264. http01=$(echo $response | egrep -o '{[^{]*"type":"http-01"[^}]*')
  265. _debug http01 "$http01"
  266. token=$(echo "$http01" | sed 's/,/\n'/g| grep '"token":'| cut -d : -f 2|sed 's/"//g')
  267. _debug token $token
  268. uri=$(echo "$http01" | sed 's/,/\n'/g| grep '"uri":'| cut -d : -f 2,3|sed 's/"//g')
  269. _debug uri $uri
  270. keyauthorization="$token.$thumbprint"
  271. _debug keyauthorization "$keyauthorization"
  272. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  273. _debug wellknown_path "$wellknown_path"
  274. mkdir -p "$wellknown_path"
  275. wellknown_path="$wellknown_path/$token"
  276. echo -n "$keyauthorization" > $wellknown_path
  277. wellknown_url="http://$d/.well-known/acme-challenge/$token"
  278. _debug wellknown_url "$wellknown_url"
  279. _debug challenge "$challenge"
  280. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  281. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  282. _info "challenge error: $d"
  283. return 1
  284. fi
  285. while [ "1" ] ; do
  286. _debug "sleep 5 secs to verify"
  287. sleep 5
  288. _debug "checking"
  289. if ! _get $uri ; then
  290. _info "verify error:$d"
  291. return 1
  292. fi
  293. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | sed 's/"//g')
  294. if [ "$status" == "valid" ] ; then
  295. _info "verify success:$d"
  296. break;
  297. fi
  298. if [ "$status" == "invalid" ] ; then
  299. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  300. _info "verify error:$d"
  301. _debug $error
  302. return 1;
  303. fi
  304. if [ "$status" == "pending" ] ; then
  305. _info "verify pending:$d"
  306. else
  307. _info "verify error:$d"
  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\"}" "needbas64"
  315. echo -----BEGIN CERTIFICATE----- > $CERT_PATH
  316. echo $response | sed "s/ /\n/g" >> $CERT_PATH
  317. echo -----END CERTIFICATE----- >> $CERT_PATH
  318. _info "Cert success."
  319. cat $CERT_PATH
  320. _setopt $DOMAIN_CONF "Le_Domain" "=" "$Le_Domain"
  321. _setopt $DOMAIN_CONF "Le_Alt" "=" "$Le_Alt"
  322. _setopt $DOMAIN_CONF "Le_Webroot" "=" "$Le_Webroot"
  323. _setopt $DOMAIN_CONF "Le_Keylength" "=" "$Le_Keylength"
  324. Le_LinkIssuer=$(grep -i '^Link' $CURL_HEADER | cut -d " " -f 2| cut -d ';' -f 1 | sed 's/<//g' | sed 's/>//g')
  325. _setopt $DOMAIN_CONF "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  326. Le_LinkCert=$(grep -i '^Location' $CURL_HEADER | cut -d " " -f 2)
  327. _setopt $DOMAIN_CONF "Le_LinkCert" "=" "$Le_LinkCert"
  328. Le_CertCreateTime=$(date -u "+%s")
  329. _setopt $DOMAIN_CONF "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  330. Le_CertCreateTimeStr=$(date -u "+%Y-%m-%d %H:%M:%S UTC")
  331. _setopt $DOMAIN_CONF "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  332. if [ ! "$Le_RenewalDays" ] ; then
  333. Le_RenewalDays=50
  334. fi
  335. _setopt $DOMAIN_CONF "Le_RenewalDays" "=" "$Le_RenewalDays"
  336. Le_NextRenewTime=$(date -u -d "+$Le_RenewalDays day" "+%s")
  337. _setopt $DOMAIN_CONF "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  338. Le_NextRenewTimeStr=$(date -u -d "+$Le_RenewalDays day" "+%Y-%m-%d %H:%M:%S UTC")
  339. _setopt $DOMAIN_CONF "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  340. _setopt $DOMAIN_CONF "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  341. if [ "$Le_RealCertPath" ] ; then
  342. if [ -f "$Le_RealCertPath" ] ; then
  343. rm -f $Le_RealCertPath
  344. fi
  345. ln -s $CERT_PATH $Le_RealCertPath
  346. fi
  347. _setopt $DOMAIN_CONF "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  348. if [ "$Le_RealKeyPath" ] ; then
  349. if [ -f "$Le_RealKeyPath" ] ; then
  350. rm -f $Le_RealKeyPath
  351. fi
  352. ln -s $CERT_KEY_PATH $Le_RealKeyPath
  353. fi
  354. _setopt $DOMAIN_CONF "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  355. if [ "Le_ReloadCmd" ] ; then
  356. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  357. $Le_ReloadCmd
  358. fi
  359. }
  360. renew() {
  361. Le_Domain="$1"
  362. if [ -z "$Le_Domain" ] ; then
  363. echo Usage: $0 domain.com
  364. return 1
  365. fi
  366. DOMAIN_CONF=$WORKING_DIR/$Le_Domain/$Le_Domain.conf
  367. if [ -f "$DOMAIN_CONF" ] ; then
  368. source "$DOMAIN_CONF"
  369. if [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  370. _info "Skip, Next renwal time is: $Le_NextRenewTimeStr"
  371. return 2
  372. fi
  373. fi
  374. if [ -z "$Le_Webroot" ] ; then
  375. echo Le_Webroot can not found, please remove the conf file and issue a new cert
  376. return 1
  377. fi
  378. issue $Le_Domain
  379. }
  380. renewAll() {
  381. _info "renewAll"
  382. for d in $(ls -F $WORKING_DIR | grep '/$') ; do
  383. d=$(echo $d | cut -d '/' -f 1)
  384. _info "renew $d"
  385. renew "$d"
  386. done
  387. }
  388. install() {
  389. _initpath
  390. if ! command -v "curl" ; then
  391. _info "Please install curl first."
  392. _info "sudo apt-get install curl"
  393. return 1
  394. fi
  395. _info "Installing to $WORKING_DIR"
  396. mkdir -p $WORKING_DIR/
  397. cp le.sh $WORKING_DIR/
  398. chmod +x $WORKING_DIR/le.sh
  399. if [ ! -f /bin/le.sh ] ; then
  400. ln -s $WORKING_DIR/le.sh /bin/le.sh
  401. ln -s $WORKING_DIR/le.sh /bin/le
  402. fi
  403. _info "Installing cron job"
  404. if ! crontab -l | grep 'le.sh renewAll' ; then
  405. crontab -l | { cat; echo "0 0 * * * le.sh renewAll"; } | crontab -
  406. service cron restart
  407. fi
  408. _info OK
  409. }
  410. uninstall() {
  411. _initpath
  412. _info "Removing cron job"
  413. crontab -l | sed "/le.sh renewAll/d" | crontab -
  414. _info "Removing /bin/le.sh"
  415. rm -f /bin/le
  416. rm -f /bin/le.sh
  417. _info "The keys and certs are in $WORKING_DIR, you can remove them by yourself."
  418. }
  419. showhelp() {
  420. echo "Usage: issue|renew|renewAll|createAccountKey|createDomainKey|createCSR|install|uninstall"
  421. }
  422. if [ -z "$1" ] ; then
  423. showhelp
  424. fi
  425. $1 $2 $3 $4 $5 $6 $7 $8