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.

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