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.

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