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
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. if [ -z "$DEBUG" ] ; then
  16. return
  17. fi
  18. if [ -z "$2" ] ; then
  19. echo $1
  20. else
  21. echo $1:$2
  22. fi
  23. }
  24. _info() {
  25. if [ -z "$2" ] ; then
  26. echo $1
  27. else
  28. echo $1:$2
  29. fi
  30. }
  31. #domain [2048]
  32. createAccountKey() {
  33. if [ -z "$1" ] ; then
  34. echo Usage: $0 account-domain [2048]
  35. return
  36. fi
  37. account=$1
  38. length=$2
  39. if [ -z "$2" ] ; then
  40. echo Use default length 2048
  41. length=2048
  42. fi
  43. mkdir -p $WORKING_DIR
  44. ACCOUNT_KEY_PATH=$WORKING_DIR/account.acc
  45. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  46. echo account key exists, skip
  47. return
  48. else
  49. #generate account key
  50. openssl genrsa $length > $ACCOUNT_KEY_PATH
  51. fi
  52. }
  53. #domain length
  54. createDomainKey() {
  55. if [ -z "$1" ] ; then
  56. echo Usage: $0 domain [2048]
  57. return
  58. fi
  59. domain=$1
  60. length=$2
  61. if [ -z "$2" ] ; then
  62. echo Use default length 2048
  63. length=2048
  64. fi
  65. mkdir -p $WORKING_DIR/$domain
  66. CERT_KEY_PATH=$WORKING_DIR/$domain/$domain.key
  67. if [ -f "$CERT_KEY_PATH" ] ; then
  68. echo domain key exists, skip
  69. else
  70. #generate account key
  71. openssl genrsa $length > $CERT_KEY_PATH
  72. fi
  73. }
  74. # domain domainlist
  75. createCSR() {
  76. if [ -z "$1" ] ; then
  77. echo Usage: $0 domain [domainlist]
  78. return
  79. fi
  80. domain=$1
  81. _initpath $domain
  82. domainlist=$2
  83. if [ -f $CSR_PATH ] ; then
  84. echo CSR exists, skip
  85. return
  86. fi
  87. if [ -z "$domainlist" ] ; then
  88. #single domain
  89. echo single domain
  90. openssl req -new -sha256 -key $CERT_KEY_PATH -subj "/CN=$domain" > $CSR_PATH
  91. else
  92. alt=DNS:$(echo $domainlist | sed "s/,/,DNS:/g")
  93. #multi
  94. echo multi domain $alt
  95. 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
  96. fi
  97. }
  98. _b64() {
  99. while read __line; do
  100. __n=$__n$__line
  101. done;
  102. __n=$(echo $__n | sed "s|/|_|g")
  103. __n=$(echo $__n | sed "s| ||g")
  104. __n=$(echo $__n | sed "s|+|-|g")
  105. __n=$(echo $__n | sed "s|=||g")
  106. echo $__n
  107. }
  108. _send_signed_request() {
  109. url=$1
  110. payload=$2
  111. _debug url $url
  112. _debug payload "$payload"
  113. CURL_HEADER="$WORKING_DIR/curl.header"
  114. dp="$WORKING_DIR/curl.dump"
  115. CURL="curl --silent --dump-header $CURL_HEADER "
  116. if [ "$DEBUG" ] ; then
  117. CURL="$CURL --trace-ascii $dp "
  118. fi
  119. payload64=$(echo -n $payload | base64 | _b64)
  120. _debug payload64 $payload64
  121. nonceurl="$API/directory"
  122. nonce=$($CURL -I $nonceurl | grep "^Replay-Nonce:" | sed s/\\r//|sed s/\\n//| cut -d ' ' -f 2)
  123. _debug nonce $nonce
  124. protected=$(echo -n "$HEADERPLACE" | sed "s/NONCE/$nonce/" )
  125. _debug protected "$protected"
  126. protected64=$( echo -n $protected | base64 | _b64)
  127. _debug protected64 "$protected64"
  128. sig=$(echo -n "$protected64.$payload64" | openssl dgst -sha256 -sign $ACCOUNT_KEY_PATH | base64| _b64)
  129. _debug sig "$sig"
  130. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  131. _debug body "$body"
  132. response="$($CURL -X POST --data "$body" $url)"
  133. responseHeaders="$(cat $CURL_HEADER)"
  134. _debug responseHeaders "$responseHeaders"
  135. _debug response "$response"
  136. code="$(grep ^HTTP $CURL_HEADER | tail -1 | cut -d " " -f 2)"
  137. _debug code $code
  138. }
  139. _get() {
  140. url="$1"
  141. _debug url $url
  142. response=$(curl --silent $url)
  143. ret=$?
  144. _debug response "$response"
  145. code=$(echo $response | grep -o '"status":[0-9]\+' | cut -d : -f 2)
  146. _debug code $code
  147. return $ret
  148. }
  149. #setopt "file" "opt" "=" "value" [";"]
  150. _setopt() {
  151. __conf="$1"
  152. __opt="$2"
  153. __sep="$3"
  154. __val="$4"
  155. __end="$5"
  156. if [ -z "$__opt" ] ; then
  157. echo usage: $0 '"file" "opt" "=" "value" [";"]'
  158. return
  159. fi
  160. if [ ! -f $__conf ] ; then
  161. touch $__conf
  162. fi
  163. if grep -H -n "^$__opt$__sep" $__conf > /dev/null ; then
  164. _debug OK
  165. sed -i "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" $__conf
  166. else
  167. _debug APP
  168. echo "$__opt$__sep$__val$__end" >> $__conf
  169. fi
  170. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  171. }
  172. _initpath() {
  173. WORKING_DIR=~/.le
  174. domain=$1
  175. mkdir -p $WORKING_DIR
  176. ACCOUNT_KEY_PATH=$WORKING_DIR/account.acc
  177. if [ -z "$domain" ] ; then
  178. return 0
  179. fi
  180. mkdir -p $WORKING_DIR/$domain
  181. CSR_PATH=$WORKING_DIR/$domain/$domain.csr
  182. CERT_KEY_PATH=$WORKING_DIR/$domain/$domain.key
  183. CERT_PATH=$WORKING_DIR/$domain/$domain.cer
  184. }
  185. #issue webroot a.com [www.a.com,b.com,c.com] [key-length] [cert-file-path] [key-file-path] [reloadCmd]
  186. issue() {
  187. if [ -z "$1" ] ; then
  188. echo "Usage: $0 webroot a.com [www.a.com,b.com,c.com] [key-length] [cert-file-path] [key-file-path] [reloadCmd]"
  189. return 1
  190. fi
  191. Le_Webroot=$1
  192. Le_Domain=$2
  193. Le_Alt=$3
  194. Le_Keylength=$4
  195. if [ -z "$Le_Domain" ] ; then
  196. Le_Domain="$1"
  197. fi
  198. _initpath $Le_Domain
  199. DOMAIN_CONF=$WORKING_DIR/$Le_Domain/$Le_Domain.conf
  200. if [ -f "$DOMAIN_CONF" ] ; then
  201. source "$DOMAIN_CONF"
  202. if [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  203. _info "Skip, Next renwal time is: $Le_NextRenewTimeStr"
  204. return 2
  205. fi
  206. fi
  207. if [ -z "$Le_Webroot" ] ; then
  208. echo Usage: $0 webroot a.com [b.com,c.com] [key-length]
  209. return 1
  210. fi
  211. createAccountKey $Le_Domain $Le_Keylength
  212. createDomainKey $Le_Domain $Le_Keylength
  213. createCSR $Le_Domain $Le_Alt
  214. 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)
  215. if [ "${#pub_exp}" == "5" ] ; then
  216. pub_exp=0$pub_exp
  217. fi
  218. _debug pub_exp "$pub_exp"
  219. e=$(echo $pub_exp | xxd -r -p | base64)
  220. _debug e "$e"
  221. modulus=$(openssl rsa -in $ACCOUNT_KEY_PATH -modulus -noout | cut -d '=' -f 2 )
  222. n=$(echo $modulus| xxd -r -p | base64 | _b64 )
  223. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  224. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  225. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  226. _debug HEADER "$HEADER"
  227. accountkey_json=$(echo -n "$jwk" | sed "s/ //g")
  228. thumbprint=$(echo -n "$accountkey_json" | sha256sum | xxd -r -p | base64 | _b64)
  229. _info "Registering account"
  230. regjson='{"resource": "new-reg", "agreement": "https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"}'
  231. if [ "$ACCOUNT_EMAIL" ] ; then
  232. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"}'
  233. fi
  234. _send_signed_request "$API/acme/new-reg" "$regjson"
  235. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  236. _info "Registered"
  237. echo $response > $WORKING_DIR/account.json
  238. elif [ "$code" == '409' ] ; then
  239. _info "Already registered"
  240. else
  241. _info "Register account Error."
  242. return 1
  243. fi
  244. # verify each domain
  245. _info "Verify each domain"
  246. alldomains=$(echo "$Le_Domain,$Le_Alt" | sed "s/,/ /g")
  247. for d in $alldomains
  248. do
  249. _info "Verifing domain $d"
  250. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  251. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  252. _info "new-authz error: $d"
  253. return 1
  254. fi
  255. http01=$(echo $response | egrep -o '{[^{]*"type":"http-01"[^}]*')
  256. _debug http01 "$http01"
  257. token=$(echo "$http01" | sed 's/,/\n'/g| grep '"token":'| cut -d : -f 2|sed 's/"//g')
  258. _debug token $token
  259. uri=$(echo "$http01" | sed 's/,/\n'/g| grep '"uri":'| cut -d : -f 2,3|sed 's/"//g')
  260. _debug uri $uri
  261. keyauthorization="$token.$thumbprint"
  262. _debug keyauthorization "$keyauthorization"
  263. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  264. _debug wellknown_path "$wellknown_path"
  265. mkdir -p "$wellknown_path"
  266. wellknown_path="$wellknown_path/$token"
  267. echo -n "$keyauthorization" > $wellknown_path
  268. wellknown_url="http://$d/.well-known/acme-challenge/$token"
  269. _debug wellknown_url "$wellknown_url"
  270. _debug challenge "$challenge"
  271. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  272. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  273. _info "challenge error: $d"
  274. return 1
  275. fi
  276. while [ "1" ] ; do
  277. _debug "sleep 5 secs to verify"
  278. sleep 5
  279. _debug "checking"
  280. if ! _get $uri ; then
  281. _info "Verify error:$d"
  282. return 1
  283. fi
  284. status=$(echo $response | egrep -o '"status":"[^"]+"' | cut -d : -f 2 | sed 's/"//g')
  285. if [ "$status" == "valid" ] ; then
  286. _info "Verify success:$d"
  287. break;
  288. fi
  289. if [ "$status" == "invalid" ] ; then
  290. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  291. _info "Verify error:$d"
  292. _debug $error
  293. return 1;
  294. fi
  295. if [ "$status" == "pending" ] ; then
  296. _info "Verify pending:$d"
  297. else
  298. _info "Verify error:$d"
  299. return 1
  300. fi
  301. done
  302. done
  303. _info "Verify finished, start to sign."
  304. der=$(openssl req -in $CSR_PATH -outform DER | base64 | _b64)
  305. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}"
  306. Le_LinkCert=$(grep -i '^Location' $CURL_HEADER | cut -d " " -f 2)
  307. _setopt $DOMAIN_CONF "Le_LinkCert" "=" "$Le_LinkCert"
  308. if [ "$Le_LinkCert" ] ; then
  309. echo -----BEGIN CERTIFICATE----- > $CERT_PATH
  310. echo $response | base64 | sed "s/ /\n/g" >> $CERT_PATH
  311. echo -----END CERTIFICATE----- >> $CERT_PATH
  312. _info "Cert success."
  313. cat $CERT_PATH
  314. _info "Your cert is in $CERT_PATH"
  315. fi
  316. _setopt $DOMAIN_CONF "Le_Domain" "=" "$Le_Domain"
  317. _setopt $DOMAIN_CONF "Le_Alt" "=" "$Le_Alt"
  318. _setopt $DOMAIN_CONF "Le_Webroot" "=" "$Le_Webroot"
  319. _setopt $DOMAIN_CONF "Le_Keylength" "=" "$Le_Keylength"
  320. if [ -z "$Le_LinkCert" ] ; then
  321. _info "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  322. return 1
  323. fi
  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_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