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.

2932 lines
73 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
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
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
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
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
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
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
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
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
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
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
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. #!/usr/bin/env sh
  2. VER=2.3.4
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  7. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
  8. DEFAULT_USER_AGENT="$PROJECT_ENTRY client: $PROJECT"
  9. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  10. VTYPE_HTTP="http-01"
  11. VTYPE_DNS="dns-01"
  12. VTYPE_TLS="tls-sni-01"
  13. VTYPE_TLS2="tls-sni-02"
  14. MAX_RENEW=80
  15. DEFAULT_DNS_SLEEP=120
  16. W_TLS="tls"
  17. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  18. END_CSR="-----END CERTIFICATE REQUEST-----"
  19. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  20. END_CERT="-----END CERTIFICATE-----"
  21. RENEW_SKIP=2
  22. if [ -z "$AGREEMENT" ] ; then
  23. AGREEMENT="$DEFAULT_AGREEMENT"
  24. fi
  25. _URGLY_PRINTF=""
  26. if [ "$(printf '\x41')" != 'A' ] ; then
  27. _URGLY_PRINTF=1
  28. fi
  29. _info() {
  30. if [ -z "$2" ] ; then
  31. echo "[$(date)] $1"
  32. else
  33. echo "[$(date)] $1='$2'"
  34. fi
  35. }
  36. _err() {
  37. _info "$@" >&2
  38. return 1
  39. }
  40. _debug() {
  41. if [ -z "$DEBUG" ] ; then
  42. return
  43. fi
  44. _err "$@"
  45. return 0
  46. }
  47. _debug2() {
  48. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  49. _debug "$@"
  50. fi
  51. return
  52. }
  53. _startswith(){
  54. _str="$1"
  55. _sub="$2"
  56. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  57. }
  58. _contains(){
  59. _str="$1"
  60. _sub="$2"
  61. echo "$_str" | grep "$_sub" >/dev/null 2>&1
  62. }
  63. _hasfield() {
  64. _str="$1"
  65. _field="$2"
  66. _sep="$3"
  67. if [ -z "$_field" ] ; then
  68. _err "Usage: str field [sep]"
  69. return 1
  70. fi
  71. if [ -z "$_sep" ] ; then
  72. _sep=","
  73. fi
  74. for f in $(echo "$_str" | tr ',' ' ') ; do
  75. if [ "$f" = "$_field" ] ; then
  76. _debug "'$_str' contains '$_field'"
  77. return 0 #contains ok
  78. fi
  79. done
  80. _debug "'$_str' does not contain '$_field'"
  81. return 1 #not contains
  82. }
  83. _exists(){
  84. cmd="$1"
  85. if [ -z "$cmd" ] ; then
  86. _err "Usage: _exists cmd"
  87. return 1
  88. fi
  89. if type command >/dev/null 2>&1 ; then
  90. command -v "$cmd" >/dev/null 2>&1
  91. else
  92. type "$cmd" >/dev/null 2>&1
  93. fi
  94. ret="$?"
  95. _debug2 "$cmd exists=$ret"
  96. return $ret
  97. }
  98. #a + b
  99. _math(){
  100. expr "$@"
  101. }
  102. _h_char_2_dec() {
  103. _ch=$1
  104. case "${_ch}" in
  105. a|A)
  106. printf "10"
  107. ;;
  108. b|B)
  109. printf "11"
  110. ;;
  111. c|C)
  112. printf "12"
  113. ;;
  114. d|D)
  115. printf "13"
  116. ;;
  117. e|E)
  118. printf "14"
  119. ;;
  120. f|F)
  121. printf "15"
  122. ;;
  123. *)
  124. printf "%s" "$_ch"
  125. ;;
  126. esac
  127. }
  128. _h2b() {
  129. hex=$(cat)
  130. i=1
  131. j=2
  132. if _exists let ; then
  133. uselet="1"
  134. fi
  135. _debug2 uselet "$uselet"
  136. _debug2 _URGLY_PRINTF "$_URGLY_PRINTF"
  137. while true ; do
  138. if [ -z "$_URGLY_PRINTF" ] ; then
  139. h="$(printf $hex | cut -c $i-$j)"
  140. if [ -z "$h" ] ; then
  141. break;
  142. fi
  143. printf "\x$h"
  144. else
  145. ic="$(printf $hex | cut -c $i)"
  146. jc="$(printf $hex | cut -c $j)"
  147. if [ -z "$ic$jc" ] ; then
  148. break;
  149. fi
  150. ic="$(_h_char_2_dec "$ic")"
  151. jc="$(_h_char_2_dec "$jc")"
  152. printf '\'"$(printf %o "$(_math $ic \* 16 + $jc)")"
  153. fi
  154. if [ "$uselet" ] ; then
  155. let "i+=2" >/dev/null
  156. let "j+=2" >/dev/null
  157. else
  158. i="$(_math $i + 2)"
  159. j="$(_math $j + 2)"
  160. fi
  161. done
  162. }
  163. #options file
  164. _sed_i() {
  165. options="$1"
  166. filename="$2"
  167. if [ -z "$filename" ] ; then
  168. _err "Usage:_sed_i options filename"
  169. return 1
  170. fi
  171. _debug2 options "$options"
  172. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  173. _debug "Using sed -i"
  174. sed -i "$options" "$filename"
  175. else
  176. _debug "No -i support in sed"
  177. text="$(cat "$filename")"
  178. echo "$text" | sed "$options" > "$filename"
  179. fi
  180. }
  181. #Usage: file startline endline
  182. _getfile() {
  183. filename="$1"
  184. startline="$2"
  185. endline="$3"
  186. if [ -z "$endline" ] ; then
  187. _err "Usage: file startline endline"
  188. return 1
  189. fi
  190. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  191. if [ -z "$i" ] ; then
  192. _err "Can not find start line: $startline"
  193. return 1
  194. fi
  195. i="$(_math "$i" + 1)"
  196. _debug i "$i"
  197. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  198. if [ -z "$j" ] ; then
  199. _err "Can not find end line: $endline"
  200. return 1
  201. fi
  202. j="$(_math "$j" - 1)"
  203. _debug j "$j"
  204. sed -n "$i,${j}p" "$filename"
  205. }
  206. #Usage: multiline
  207. _base64() {
  208. if [ "$1" ] ; then
  209. openssl base64 -e
  210. else
  211. openssl base64 -e | tr -d '\r\n'
  212. fi
  213. }
  214. #Usage: multiline
  215. _dbase64() {
  216. if [ "$1" ] ; then
  217. openssl base64 -d -A
  218. else
  219. openssl base64 -d
  220. fi
  221. }
  222. #Usage: hashalg [outputhex]
  223. #Output Base64-encoded digest
  224. _digest() {
  225. alg="$1"
  226. if [ -z "$alg" ] ; then
  227. _err "Usage: _digest hashalg"
  228. return 1
  229. fi
  230. outputhex="$2"
  231. if [ "$alg" = "sha256" ] ; then
  232. if [ "$outputhex" ] ; then
  233. echo $(openssl dgst -sha256 -hex | cut -d = -f 2)
  234. else
  235. openssl dgst -sha256 -binary | _base64
  236. fi
  237. else
  238. _err "$alg is not supported yet"
  239. return 1
  240. fi
  241. }
  242. #Usage: keyfile hashalg
  243. #Output: Base64-encoded signature value
  244. _sign() {
  245. keyfile="$1"
  246. alg="$2"
  247. if [ -z "$alg" ] ; then
  248. _err "Usage: _sign keyfile hashalg"
  249. return 1
  250. fi
  251. if [ "$alg" = "sha256" ] ; then
  252. openssl dgst -sha256 -sign "$keyfile" | _base64
  253. else
  254. _err "$alg is not supported yet"
  255. return 1
  256. fi
  257. }
  258. # _createkey 2048|ec-256 file
  259. _createkey() {
  260. length="$1"
  261. f="$2"
  262. isec=""
  263. if _startswith "$length" "ec-" ; then
  264. isec="1"
  265. length=$(printf $length | cut -d '-' -f 2-100)
  266. eccname="$length"
  267. fi
  268. if [ -z "$length" ] ; then
  269. if [ "$isec" ] ; then
  270. length=256
  271. else
  272. length=2048
  273. fi
  274. fi
  275. _info "Use length $length"
  276. if [ "$isec" ] ; then
  277. if [ "$length" = "256" ] ; then
  278. eccname="prime256v1"
  279. fi
  280. if [ "$length" = "384" ] ; then
  281. eccname="secp384r1"
  282. fi
  283. if [ "$length" = "521" ] ; then
  284. eccname="secp521r1"
  285. fi
  286. _info "Using ec name: $eccname"
  287. fi
  288. #generate account key
  289. if [ "$isec" ] ; then
  290. openssl ecparam -name $eccname -genkey 2>/dev/null > "$f"
  291. else
  292. openssl genrsa $length 2>/dev/null > "$f"
  293. fi
  294. }
  295. #_createcsr cn san_list keyfile csrfile conf
  296. _createcsr() {
  297. _debug _createcsr
  298. domain="$1"
  299. domainlist="$2"
  300. key="$3"
  301. csr="$4"
  302. csrconf="$5"
  303. _debug2 domain "$domain"
  304. _debug2 domainlist "$domainlist"
  305. if [ -z "$domainlist" ] || [ "$domainlist" = "no" ]; then
  306. #single domain
  307. _info "Single domain" "$domain"
  308. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$csrconf"
  309. openssl req -new -sha256 -key "$key" -subj "/CN=$domain" -config "$csrconf" -out "$csr"
  310. else
  311. if _contains "$domainlist" "," ; then
  312. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  313. else
  314. alt="DNS:$domainlist"
  315. fi
  316. #multi
  317. _info "Multi domain" "$alt"
  318. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment\nsubjectAltName=$alt" > "$csrconf"
  319. openssl req -new -sha256 -key "$key" -subj "/CN=$domain" -config "$csrconf" -out "$csr"
  320. fi
  321. }
  322. #_signcsr key csr conf cert
  323. _signcsr() {
  324. key="$1"
  325. csr="$2"
  326. conf="$3"
  327. cert="$4"
  328. _debug "_signcsr"
  329. _msg="$(openssl x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  330. _ret="$?"
  331. _debug "$_msg"
  332. return $_ret
  333. }
  334. _ss() {
  335. _port="$1"
  336. if _exists "ss" ; then
  337. _debug "Using: ss"
  338. ss -ntpl | grep ":$_port "
  339. return 0
  340. fi
  341. if _exists "netstat" ; then
  342. _debug "Using: netstat"
  343. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  344. #for windows version netstat tool
  345. netstat -anb -p tcp | grep "LISTENING" | grep ":$_port "
  346. else
  347. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  348. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  349. else
  350. netstat -ntpl | grep ":$_port "
  351. fi
  352. fi
  353. return 0
  354. fi
  355. return 1
  356. }
  357. toPkcs() {
  358. domain="$1"
  359. pfxPassword="$2"
  360. if [ -z "$domain" ] ; then
  361. echo "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  362. return 1
  363. fi
  364. _initpath "$domain"
  365. if [ "$pfxPassword" ] ; then
  366. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  367. else
  368. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  369. fi
  370. if [ "$?" = "0" ] ; then
  371. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  372. fi
  373. }
  374. #domain [2048]
  375. createAccountKey() {
  376. _info "Creating account key"
  377. if [ -z "$1" ] ; then
  378. echo Usage: $PROJECT_ENTRY --createAccountKey -d domain.com [--accountkeylength 2048]
  379. return
  380. fi
  381. account=$1
  382. length=$2
  383. _debug account "$account"
  384. _debug length "$length"
  385. if _startswith "$length" "ec-" ; then
  386. length=2048
  387. fi
  388. if [ -z "$2" ] || [ "$2" = "no" ] ; then
  389. _info "Use default length 2048"
  390. length=2048
  391. fi
  392. _initpath
  393. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  394. _info "Account key exists, skip"
  395. return
  396. else
  397. #generate account key
  398. _createkey $length "$ACCOUNT_KEY_PATH"
  399. fi
  400. }
  401. #domain length
  402. createDomainKey() {
  403. _info "Creating domain key"
  404. if [ -z "$1" ] ; then
  405. echo Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]
  406. return
  407. fi
  408. domain=$1
  409. _initpath $domain
  410. length=$2
  411. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  412. _createkey "$length" "$CERT_KEY_PATH"
  413. else
  414. if [ "$IS_RENEW" ] ; then
  415. _info "Domain key exists, skip"
  416. return 0
  417. else
  418. _err "Domain key exists, do you want to overwrite the key?"
  419. _err "Add '--force', and try again."
  420. return 1
  421. fi
  422. fi
  423. }
  424. # domain domainlist
  425. createCSR() {
  426. _info "Creating csr"
  427. if [ -z "$1" ] ; then
  428. echo "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  429. return
  430. fi
  431. domain=$1
  432. _initpath "$domain"
  433. domainlist=$2
  434. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  435. _info "CSR exists, skip"
  436. return
  437. fi
  438. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  439. }
  440. _urlencode() {
  441. __n=$(cat)
  442. echo $__n | tr '/+' '_-' | tr -d '= '
  443. }
  444. _time2str() {
  445. #BSD
  446. if date -u -d@$1 2>/dev/null ; then
  447. return
  448. fi
  449. #Linux
  450. if date -u -r $1 2>/dev/null ; then
  451. return
  452. fi
  453. }
  454. _normalizeJson() {
  455. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  456. }
  457. _stat() {
  458. #Linux
  459. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  460. return
  461. fi
  462. #BSD
  463. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  464. return
  465. fi
  466. return 1; #error, 'stat' not found
  467. }
  468. #keyfile
  469. _calcjwk() {
  470. keyfile="$1"
  471. if [ -z "$keyfile" ] ; then
  472. _err "Usage: _calcjwk keyfile"
  473. return 1
  474. fi
  475. EC_SIGN=""
  476. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  477. _debug "RSA key"
  478. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  479. if [ "${#pub_exp}" = "5" ] ; then
  480. pub_exp=0$pub_exp
  481. fi
  482. _debug2 pub_exp "$pub_exp"
  483. e=$(echo $pub_exp | _h2b | _base64)
  484. _debug2 e "$e"
  485. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  486. _debug2 modulus "$modulus"
  487. n="$(printf "%s" "$modulus"| _h2b | _base64 | _urlencode )"
  488. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  489. _debug2 jwk "$jwk"
  490. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  491. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  492. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  493. _debug "EC key"
  494. EC_SIGN="1"
  495. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  496. _debug2 crv "$crv"
  497. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  498. pubi=$(_math $pubi + 1)
  499. _debug2 pubi "$pubi"
  500. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  501. pubj=$(_math $pubj + 1)
  502. _debug2 pubj "$pubj"
  503. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  504. _debug2 pubtext "$pubtext"
  505. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  506. xlen=$(_math $xlen / 4)
  507. _debug2 xlen "$xlen"
  508. xend=$(_math "$xend" + 1)
  509. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  510. _debug2 x "$x"
  511. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  512. _debug2 x64 "$x64"
  513. xend=$(_math "$xend" + 1)
  514. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  515. _debug2 y "$y"
  516. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  517. _debug2 y64 "$y64"
  518. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  519. _debug2 jwk "$jwk"
  520. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  521. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  522. else
  523. _err "Only RSA or EC key is supported."
  524. return 1
  525. fi
  526. _debug2 HEADER "$HEADER"
  527. }
  528. # body url [needbase64] [POST|PUT]
  529. _post() {
  530. body="$1"
  531. url="$2"
  532. needbase64="$3"
  533. httpmethod="$4"
  534. if [ -z "$httpmethod" ] ; then
  535. httpmethod="POST"
  536. fi
  537. _debug $httpmethod
  538. _debug "url" "$url"
  539. _debug2 "body" "$body"
  540. if _exists "curl" ; then
  541. _CURL="$CURL --dump-header $HTTP_HEADER "
  542. _debug "_CURL" "$_CURL"
  543. if [ "$needbase64" ] ; then
  544. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" --data "$body" "$url" | _base64)"
  545. else
  546. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" --data "$body" "$url" )"
  547. fi
  548. _ret="$?"
  549. if [ "$_ret" != "0" ] ; then
  550. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  551. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  552. _err "Here is the curl dump log:"
  553. _err "$(cat "$_CURL_DUMP")"
  554. fi
  555. fi
  556. elif _exists "wget" ; then
  557. _debug "WGET" "$WGET"
  558. if [ "$needbase64" ] ; then
  559. if [ "$httpmethod"="POST" ] ; then
  560. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  561. else
  562. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  563. fi
  564. else
  565. if [ "$httpmethod"="POST" ] ; then
  566. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
  567. else
  568. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
  569. fi
  570. fi
  571. _ret="$?"
  572. if [ "$_ret" != "0" ] ; then
  573. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  574. fi
  575. _sed_i "s/^ *//g" "$HTTP_HEADER"
  576. else
  577. _ret="$?"
  578. _err "Neither curl nor wget is found, can not do $httpmethod."
  579. fi
  580. _debug "_ret" "$_ret"
  581. printf "%s" "$response"
  582. return $_ret
  583. }
  584. # url getheader
  585. _get() {
  586. _debug GET
  587. url="$1"
  588. onlyheader="$2"
  589. _debug url $url
  590. if _exists "curl" ; then
  591. _debug "CURL" "$CURL"
  592. if [ "$onlyheader" ] ; then
  593. $CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" $url
  594. else
  595. $CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" $url
  596. fi
  597. ret=$?
  598. elif _exists "wget" ; then
  599. _debug "WGET" "$WGET"
  600. if [ "$onlyheader" ] ; then
  601. $WGET --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  602. else
  603. $WGET --user-agent="$USER_AGENT" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - $url
  604. fi
  605. ret=$?
  606. else
  607. ret=$?
  608. _err "Neither curl nor wget is found, can not do GET."
  609. fi
  610. _debug "ret" "$ret"
  611. return $ret
  612. }
  613. # url payload needbase64 keyfile
  614. _send_signed_request() {
  615. url=$1
  616. payload=$2
  617. needbase64=$3
  618. keyfile=$4
  619. if [ -z "$keyfile" ] ; then
  620. keyfile="$ACCOUNT_KEY_PATH"
  621. fi
  622. _debug url $url
  623. _debug payload "$payload"
  624. if ! _calcjwk "$keyfile" ; then
  625. return 1
  626. fi
  627. payload64=$(echo -n $payload | _base64 | _urlencode)
  628. _debug2 payload64 $payload64
  629. nonceurl="$API/directory"
  630. _headers="$(_get $nonceurl "onlyheader")"
  631. if [ "$?" != "0" ] ; then
  632. _err "Can not connect to $nonceurl to get nonce."
  633. return 1
  634. fi
  635. _debug2 _headers "$_headers"
  636. nonce="$( echo "$_headers" | grep "Replay-Nonce:" | head -1 | tr -d "\r\n " | cut -d ':' -f 2)"
  637. _debug nonce "$nonce"
  638. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  639. _debug2 protected "$protected"
  640. protected64="$(printf "$protected" | _base64 | _urlencode)"
  641. _debug2 protected64 "$protected64"
  642. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  643. _debug2 sig "$sig"
  644. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  645. _debug2 body "$body"
  646. response="$(_post "$body" $url "$needbase64")"
  647. if [ "$?" != "0" ] ; then
  648. _err "Can not post to $url."
  649. return 1
  650. fi
  651. _debug2 original "$response"
  652. response="$( echo "$response" | _normalizeJson )"
  653. responseHeaders="$(cat $HTTP_HEADER)"
  654. _debug2 responseHeaders "$responseHeaders"
  655. _debug2 response "$response"
  656. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  657. _debug code $code
  658. }
  659. #setopt "file" "opt" "=" "value" [";"]
  660. _setopt() {
  661. __conf="$1"
  662. __opt="$2"
  663. __sep="$3"
  664. __val="$4"
  665. __end="$5"
  666. if [ -z "$__opt" ] ; then
  667. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  668. return
  669. fi
  670. if [ ! -f "$__conf" ] ; then
  671. touch "$__conf"
  672. fi
  673. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  674. _debug2 OK
  675. if _contains "$__val" "&" ; then
  676. __val="$(echo $__val | sed 's/&/\\&/g')"
  677. fi
  678. text="$(cat $__conf)"
  679. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  680. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  681. if _contains "$__val" "&" ; then
  682. __val="$(echo $__val | sed 's/&/\\&/g')"
  683. fi
  684. text="$(cat $__conf)"
  685. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  686. else
  687. _debug2 APP
  688. echo "$__opt$__sep$__val$__end" >> "$__conf"
  689. fi
  690. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  691. }
  692. #_savedomainconf key value
  693. #save to domain.conf
  694. _savedomainconf() {
  695. key="$1"
  696. value="$2"
  697. if [ "$DOMAIN_CONF" ] ; then
  698. _setopt "$DOMAIN_CONF" "$key" "=" "\"$value\""
  699. else
  700. _err "DOMAIN_CONF is empty, can not save $key=$value"
  701. fi
  702. }
  703. #_cleardomainconf key
  704. _cleardomainconf() {
  705. key="$1"
  706. if [ "$DOMAIN_CONF" ] ; then
  707. _sed_i "s/^$key.*$//" "$DOMAIN_CONF"
  708. else
  709. _err "DOMAIN_CONF is empty, can not save $key=$value"
  710. fi
  711. }
  712. #_readdomainconf key
  713. _readdomainconf() {
  714. key="$1"
  715. if [ "$DOMAIN_CONF" ] ; then
  716. (
  717. eval $(grep "^$key *=" "$DOMAIN_CONF")
  718. eval "printf \"%s\" \"\$$key\""
  719. )
  720. else
  721. _err "DOMAIN_CONF is empty, can not read $key"
  722. fi
  723. }
  724. #_saveaccountconf key value
  725. _saveaccountconf() {
  726. key="$1"
  727. value="$2"
  728. if [ "$ACCOUNT_CONF_PATH" ] ; then
  729. _setopt "$ACCOUNT_CONF_PATH" "$key" "=" "\"$value\""
  730. else
  731. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  732. fi
  733. }
  734. _startserver() {
  735. content="$1"
  736. _debug "startserver: $$"
  737. nchelp="$(nc -h 2>&1)"
  738. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  739. _NC="nc -q 1 -l"
  740. else
  741. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  742. _NC="nc -c -l"
  743. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  744. _NC="nc -N -l"
  745. else
  746. _NC="nc -l"
  747. fi
  748. fi
  749. _debug "_NC" "$_NC"
  750. _debug Le_HTTPPort "$Le_HTTPPort"
  751. # while true ; do
  752. if [ "$DEBUG" ] ; then
  753. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort ; then
  754. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort ;
  755. fi
  756. else
  757. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  758. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  759. fi
  760. fi
  761. if [ "$?" != "0" ] ; then
  762. _err "nc listen error."
  763. exit 1
  764. fi
  765. # done
  766. }
  767. _stopserver(){
  768. pid="$1"
  769. _debug "pid" "$pid"
  770. if [ -z "$pid" ] ; then
  771. return
  772. fi
  773. _debug2 "Le_HTTPPort" "$Le_HTTPPort"
  774. if [ "$Le_HTTPPort" ] ; then
  775. if [ "$DEBUG" ] ; then
  776. _get "http://localhost:$Le_HTTPPort"
  777. else
  778. _get "http://localhost:$Le_HTTPPort" >/dev/null 2>&1
  779. fi
  780. fi
  781. _debug2 "Le_TLSPort" "$Le_TLSPort"
  782. if [ "$Le_TLSPort" ] ; then
  783. if [ "$DEBUG" ] ; then
  784. _get "https://localhost:$Le_TLSPort"
  785. else
  786. _get "https://localhost:$Le_TLSPort" >/dev/null 2>&1
  787. fi
  788. fi
  789. }
  790. # _starttlsserver san_a san_b port content
  791. _starttlsserver() {
  792. _info "Starting tls server."
  793. san_a="$1"
  794. san_b="$2"
  795. port="$3"
  796. content="$4"
  797. _debug san_a "$san_a"
  798. _debug san_b "$san_b"
  799. _debug port "$port"
  800. #create key TLS_KEY
  801. if ! _createkey "2048" "$TLS_KEY" ; then
  802. _err "Create tls validation key error."
  803. return 1
  804. fi
  805. #create csr
  806. alt="$san_a"
  807. if [ "$san_b" ] ; then
  808. alt="$alt,$san_b"
  809. fi
  810. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" ; then
  811. _err "Create tls validation csr error."
  812. return 1
  813. fi
  814. #self signed
  815. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT" ; then
  816. _err "Create tls validation cert error."
  817. return 1
  818. fi
  819. #start openssl
  820. _debug "openssl s_server -cert \"$TLS_CERT\" -key \"$TLS_KEY\" -accept $port -naccept 1 -tlsextdebug"
  821. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  822. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | openssl s_server -cert "$TLS_CERT" -key "$TLS_KEY" -accept $port -naccept 1 -tlsextdebug ) &
  823. else
  824. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | openssl s_server -cert "$TLS_CERT" -key "$TLS_KEY" -accept $port -naccept 1 >/dev/null 2>&1) &
  825. fi
  826. serverproc="$!"
  827. sleep 2
  828. _debug serverproc $serverproc
  829. }
  830. _initpath() {
  831. if [ -z "$LE_WORKING_DIR" ] ; then
  832. LE_WORKING_DIR=$HOME/.$PROJECT_NAME
  833. fi
  834. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  835. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  836. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ] ; then
  837. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  838. fi
  839. fi
  840. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  841. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  842. fi
  843. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  844. . "$ACCOUNT_CONF_PATH"
  845. fi
  846. if [ "$IN_CRON" ] ; then
  847. if [ ! "$_USER_PATH_EXPORTED" ] ; then
  848. _USER_PATH_EXPORTED=1
  849. export PATH="$USER_PATH:$PATH"
  850. fi
  851. fi
  852. if [ -z "$API" ] ; then
  853. if [ -z "$STAGE" ] ; then
  854. API="$DEFAULT_CA"
  855. else
  856. API="$STAGE_CA"
  857. _info "Using stage api:$API"
  858. fi
  859. fi
  860. if [ -z "$ACME_DIR" ] ; then
  861. ACME_DIR="/home/.acme"
  862. fi
  863. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  864. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  865. fi
  866. if [ -z "$USER_AGENT" ] ; then
  867. USER_AGENT="$DEFAULT_USER_AGENT"
  868. fi
  869. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  870. WGET="wget -q"
  871. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  872. WGET="$WGET -d "
  873. fi
  874. _CURL_DUMP="$LE_WORKING_DIR/curl.dump"
  875. CURL="curl -L --silent"
  876. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  877. CURL="$CURL --trace-ascii $_CURL_DUMP "
  878. fi
  879. if [ "$Le_Insecure" ] ; then
  880. WGET="$WGET --no-check-certificate "
  881. CURL="$CURL --insecure "
  882. fi
  883. _DEFAULT_ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  884. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  885. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  886. fi
  887. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  888. if [ -z "$CERT_HOME" ] ; then
  889. CERT_HOME="$_DEFAULT_CERT_HOME"
  890. fi
  891. domain="$1"
  892. if [ -z "$domain" ] ; then
  893. return 0
  894. fi
  895. domainhome="$CERT_HOME/$domain"
  896. mkdir -p "$domainhome"
  897. if [ -z "$DOMAIN_PATH" ] ; then
  898. DOMAIN_PATH="$domainhome"
  899. fi
  900. if [ -z "$DOMAIN_CONF" ] ; then
  901. DOMAIN_CONF="$domainhome/$domain.conf"
  902. fi
  903. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  904. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  905. fi
  906. if [ -z "$CSR_PATH" ] ; then
  907. CSR_PATH="$domainhome/$domain.csr"
  908. fi
  909. if [ -z "$CERT_KEY_PATH" ] ; then
  910. CERT_KEY_PATH="$domainhome/$domain.key"
  911. fi
  912. if [ -z "$CERT_PATH" ] ; then
  913. CERT_PATH="$domainhome/$domain.cer"
  914. fi
  915. if [ -z "$CA_CERT_PATH" ] ; then
  916. CA_CERT_PATH="$domainhome/ca.cer"
  917. fi
  918. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  919. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  920. fi
  921. if [ -z "$CERT_PFX_PATH" ] ; then
  922. CERT_PFX_PATH="$domainhome/$domain.pfx"
  923. fi
  924. if [ -z "$TLS_CONF" ] ; then
  925. TLS_CONF="$domainhome/tls.valdation.conf"
  926. fi
  927. if [ -z "$TLS_CERT" ] ; then
  928. TLS_CERT="$domainhome/tls.valdation.cert"
  929. fi
  930. if [ -z "$TLS_KEY" ] ; then
  931. TLS_KEY="$domainhome/tls.valdation.key"
  932. fi
  933. if [ -z "$TLS_CSR" ] ; then
  934. TLS_CSR="$domainhome/tls.valdation.csr"
  935. fi
  936. }
  937. _apachePath() {
  938. _APACHECTL="apachectl"
  939. if ! _exists apachectl ; then
  940. if _exists apache2ctl ; then
  941. _APACHECTL="apache2ctl"
  942. else
  943. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  944. _err "Please use webroot mode to try again."
  945. return 1
  946. fi
  947. fi
  948. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  949. _debug httpdconfname "$httpdconfname"
  950. if _startswith "$httpdconfname" '/' ; then
  951. httpdconf="$httpdconfname"
  952. httpdconfname="$(basename $httpdconfname)"
  953. else
  954. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  955. _debug httpdroot "$httpdroot"
  956. httpdconf="$httpdroot/$httpdconfname"
  957. httpdconfname="$(basename $httpdconfname)"
  958. fi
  959. _debug httpdconf "$httpdconf"
  960. _debug httpdconfname "$httpdconfname"
  961. if [ ! -f "$httpdconf" ] ; then
  962. _err "Apache Config file not found" "$httpdconf"
  963. return 1
  964. fi
  965. return 0
  966. }
  967. _restoreApache() {
  968. if [ -z "$usingApache" ] ; then
  969. return 0
  970. fi
  971. _initpath
  972. if ! _apachePath ; then
  973. return 1
  974. fi
  975. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  976. _debug "No config file to restore."
  977. return 0
  978. fi
  979. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" > "$httpdconf"
  980. _debug "Restored: $httpdconf."
  981. if ! $_APACHECTL -t >/dev/null 2>&1 ; then
  982. _err "Sorry, restore apache config error, please contact me."
  983. return 1;
  984. fi
  985. _debug "Restored successfully."
  986. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  987. return 0
  988. }
  989. _setApache() {
  990. _initpath
  991. if ! _apachePath ; then
  992. return 1
  993. fi
  994. #test the conf first
  995. _info "Checking if there is an error in the apache config file before starting."
  996. _msg="$($_APACHECTL -t 2>&1 )"
  997. if [ "$?" != "0" ] ; then
  998. _err "Sorry, apache config file has error, please fix it first, then try again."
  999. _err "Don't worry, there is nothing changed to your system."
  1000. _err "$_msg"
  1001. return 1;
  1002. else
  1003. _info "OK"
  1004. fi
  1005. #backup the conf
  1006. _debug "Backup apache config file" "$httpdconf"
  1007. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/" ; then
  1008. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  1009. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  1010. return 1
  1011. fi
  1012. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1013. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  1014. _info "The backup file will be deleted on sucess, just forget it."
  1015. #add alias
  1016. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  1017. _debug "apacheVer" "$apacheVer"
  1018. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  1019. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  1020. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ] ; then
  1021. echo "
  1022. Alias /.well-known/acme-challenge $ACME_DIR
  1023. <Directory $ACME_DIR >
  1024. Require all granted
  1025. </Directory>
  1026. " >> "$httpdconf"
  1027. else
  1028. echo "
  1029. Alias /.well-known/acme-challenge $ACME_DIR
  1030. <Directory $ACME_DIR >
  1031. Order allow,deny
  1032. Allow from all
  1033. </Directory>
  1034. " >> "$httpdconf"
  1035. fi
  1036. _msg="$($_APACHECTL -t 2>&1 )"
  1037. if [ "$?" != "0" ] ; then
  1038. _err "Sorry, apache config error"
  1039. if _restoreApache ; then
  1040. _err "The apache config file is restored."
  1041. else
  1042. _err "Sorry, The apache config file can not be restored, please report bug."
  1043. fi
  1044. return 1;
  1045. fi
  1046. if [ ! -d "$ACME_DIR" ] ; then
  1047. mkdir -p "$ACME_DIR"
  1048. chmod 755 "$ACME_DIR"
  1049. fi
  1050. if ! $_APACHECTL graceful ; then
  1051. _err "Sorry, $_APACHECTL graceful error, please contact me."
  1052. _restoreApache
  1053. return 1;
  1054. fi
  1055. usingApache="1"
  1056. return 0
  1057. }
  1058. _clearup() {
  1059. _stopserver $serverproc
  1060. serverproc=""
  1061. _restoreApache
  1062. if [ -z "$DEBUG" ] ; then
  1063. rm -f "$TLS_CONF"
  1064. rm -f "$TLS_CERT"
  1065. rm -f "$TLS_KEY"
  1066. rm -f "$TLS_CSR"
  1067. fi
  1068. }
  1069. # webroot removelevel tokenfile
  1070. _clearupwebbroot() {
  1071. __webroot="$1"
  1072. if [ -z "$__webroot" ] ; then
  1073. _debug "no webroot specified, skip"
  1074. return 0
  1075. fi
  1076. _rmpath=""
  1077. if [ "$2" = '1' ] ; then
  1078. _rmpath="$__webroot/.well-known"
  1079. elif [ "$2" = '2' ] ; then
  1080. _rmpath="$__webroot/.well-known/acme-challenge"
  1081. elif [ "$2" = '3' ] ; then
  1082. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  1083. else
  1084. _debug "Skip for removelevel:$2"
  1085. fi
  1086. if [ "$_rmpath" ] ; then
  1087. if [ "$DEBUG" ] ; then
  1088. _debug "Debugging, skip removing: $_rmpath"
  1089. else
  1090. rm -rf "$_rmpath"
  1091. fi
  1092. fi
  1093. return 0
  1094. }
  1095. issue() {
  1096. if [ -z "$2" ] ; then
  1097. echo "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  1098. return 1
  1099. fi
  1100. Le_Webroot="$1"
  1101. Le_Domain="$2"
  1102. Le_Alt="$3"
  1103. Le_Keylength="$4"
  1104. Le_RealCertPath="$5"
  1105. Le_RealKeyPath="$6"
  1106. Le_RealCACertPath="$7"
  1107. Le_ReloadCmd="$8"
  1108. Le_RealFullChainPath="$9"
  1109. #remove these later.
  1110. if [ "$Le_Webroot" = "dns-cf" ] ; then
  1111. Le_Webroot="dns_cf"
  1112. fi
  1113. if [ "$Le_Webroot" = "dns-dp" ] ; then
  1114. Le_Webroot="dns_dp"
  1115. fi
  1116. if [ "$Le_Webroot" = "dns-cx" ] ; then
  1117. Le_Webroot="dns_cx"
  1118. fi
  1119. _initpath $Le_Domain
  1120. if [ -f "$DOMAIN_CONF" ] ; then
  1121. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  1122. _debug Le_NextRenewTime "$Le_NextRenewTime"
  1123. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ $(date -u "+%s" ) -lt $Le_NextRenewTime ] ; then
  1124. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  1125. return $RENEW_SKIP
  1126. fi
  1127. fi
  1128. _savedomainconf "Le_Domain" "$Le_Domain"
  1129. _savedomainconf "Le_Alt" "$Le_Alt"
  1130. _savedomainconf "Le_Webroot" "$Le_Webroot"
  1131. if [ "$Le_Alt" = "no" ] ; then
  1132. Le_Alt=""
  1133. fi
  1134. if _hasfield "$Le_Webroot" "no" ; then
  1135. _info "Standalone mode."
  1136. if ! _exists "nc" ; then
  1137. _err "Please install netcat(nc) tools first."
  1138. return 1
  1139. fi
  1140. if [ -z "$Le_HTTPPort" ] ; then
  1141. Le_HTTPPort=80
  1142. else
  1143. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  1144. fi
  1145. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  1146. if [ "$netprc" ] ; then
  1147. _err "$netprc"
  1148. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  1149. _err "Please stop it first"
  1150. return 1
  1151. fi
  1152. fi
  1153. if _hasfield "$Le_Webroot" "$W_TLS" ; then
  1154. _info "Standalone tls mode."
  1155. if [ -z "$Le_TLSPort" ] ; then
  1156. Le_TLSPort=443
  1157. else
  1158. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  1159. fi
  1160. netprc="$(_ss "$Le_TLSPort" | grep "$Le_TLSPort")"
  1161. if [ "$netprc" ] ; then
  1162. _err "$netprc"
  1163. _err "tcp port $Le_TLSPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  1164. _err "Please stop it first"
  1165. return 1
  1166. fi
  1167. fi
  1168. if _hasfield "$Le_Webroot" "apache" ; then
  1169. if ! _setApache ; then
  1170. _err "set up apache error. Report error to me."
  1171. return 1
  1172. fi
  1173. else
  1174. usingApache=""
  1175. fi
  1176. if [ ! -f "$ACCOUNT_KEY_PATH" ] ; then
  1177. if ! createAccountKey $Le_Domain $Le_Keylength ; then
  1178. _err "Create account key error."
  1179. if [ "$usingApache" ] ; then
  1180. _restoreApache
  1181. fi
  1182. return 1
  1183. fi
  1184. fi
  1185. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  1186. if [ "$usingApache" ] ; then
  1187. _restoreApache
  1188. fi
  1189. return 1
  1190. fi
  1191. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  1192. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  1193. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  1194. if [ "$ACCOUNT_EMAIL" ] ; then
  1195. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  1196. fi
  1197. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  1198. accountkeyhash="$(echo $accountkeyhash$API$regjson | _digest "sha256" )"
  1199. if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
  1200. _info "Registering account"
  1201. _send_signed_request "$API/acme/new-reg" "$regjson"
  1202. if [ "$code" = "" ] || [ "$code" = '201' ] ; then
  1203. _info "Registered"
  1204. echo "$response" > $LE_WORKING_DIR/account.json
  1205. elif [ "$code" = '409' ] ; then
  1206. _info "Already registered"
  1207. else
  1208. _err "Register account Error: $response"
  1209. _clearup
  1210. return 1
  1211. fi
  1212. ACCOUNT_KEY_HASH="$accountkeyhash"
  1213. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  1214. else
  1215. _info "Skip register account key"
  1216. fi
  1217. if [ "$Le_Keylength" = "no" ] ; then
  1218. Le_Keylength=""
  1219. fi
  1220. _key=$(_readdomainconf Le_Keylength)
  1221. _debug "Read key length:$_key"
  1222. if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ] ; then
  1223. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  1224. _err "Create domain key error."
  1225. _clearup
  1226. return 1
  1227. fi
  1228. fi
  1229. _savedomainconf "Le_Keylength" "$Le_Keylength"
  1230. if ! createCSR $Le_Domain $Le_Alt ; then
  1231. _err "Create CSR error."
  1232. _clearup
  1233. return 1
  1234. fi
  1235. vlist="$Le_Vlist"
  1236. # verify each domain
  1237. _info "Verify each domain"
  1238. sep='#'
  1239. if [ -z "$vlist" ] ; then
  1240. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  1241. _index=1
  1242. _currentRoot=""
  1243. for d in $alldomains
  1244. do
  1245. _info "Getting webroot for domain" $d
  1246. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  1247. _debug _w "$_w"
  1248. if [ "$_w" ] ; then
  1249. _currentRoot="$_w"
  1250. fi
  1251. _debug "_currentRoot" "$_currentRoot"
  1252. _index=$(_math $_index + 1)
  1253. vtype="$VTYPE_HTTP"
  1254. if _startswith "$_currentRoot" "dns" ; then
  1255. vtype="$VTYPE_DNS"
  1256. fi
  1257. if [ "$_currentRoot" = "$W_TLS" ] ; then
  1258. vtype="$VTYPE_TLS"
  1259. fi
  1260. _info "Getting token for domain" $d
  1261. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}" ; then
  1262. _err "Can not get domain token."
  1263. _clearup
  1264. return 1
  1265. fi
  1266. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  1267. _err "new-authz error: $response"
  1268. _clearup
  1269. return 1
  1270. fi
  1271. entry="$(printf "$response" | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  1272. _debug entry "$entry"
  1273. if [ -z "$entry" ] ; then
  1274. _err "Error, can not get domain token $d"
  1275. _clearup
  1276. return 1
  1277. fi
  1278. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  1279. _debug token $token
  1280. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  1281. _debug uri $uri
  1282. keyauthorization="$token.$thumbprint"
  1283. _debug keyauthorization "$keyauthorization"
  1284. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  1285. _debug dvlist "$dvlist"
  1286. vlist="$vlist$dvlist,"
  1287. done
  1288. #add entry
  1289. dnsadded=""
  1290. ventries=$(echo "$vlist" | tr ',' ' ' )
  1291. for ventry in $ventries
  1292. do
  1293. d=$(echo $ventry | cut -d $sep -f 1)
  1294. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1295. vtype=$(echo $ventry | cut -d $sep -f 4)
  1296. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1297. if [ "$vtype" = "$VTYPE_DNS" ] ; then
  1298. dnsadded='0'
  1299. txtdomain="_acme-challenge.$d"
  1300. _debug txtdomain "$txtdomain"
  1301. txt="$(echo -n $keyauthorization | _digest "sha256" | _urlencode)"
  1302. _debug txt "$txt"
  1303. #dns
  1304. #1. check use api
  1305. d_api=""
  1306. if [ -f "$LE_WORKING_DIR/$d/$_currentRoot" ] ; then
  1307. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  1308. elif [ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ] ; then
  1309. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  1310. elif [ -f "$LE_WORKING_DIR/$_currentRoot" ] ; then
  1311. d_api="$LE_WORKING_DIR/$_currentRoot"
  1312. elif [ -f "$LE_WORKING_DIR/$_currentRoot.sh" ] ; then
  1313. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  1314. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ] ; then
  1315. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  1316. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ] ; then
  1317. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  1318. fi
  1319. _debug d_api "$d_api"
  1320. if [ "$d_api" ] ; then
  1321. _info "Found domain api file: $d_api"
  1322. else
  1323. _err "Add the following TXT record:"
  1324. _err "Domain: $txtdomain"
  1325. _err "TXT value: $txt"
  1326. _err "Please be aware that you prepend _acme-challenge. before your domain"
  1327. _err "so the resulting subdomain will be: $txtdomain"
  1328. continue
  1329. fi
  1330. (
  1331. if ! . $d_api ; then
  1332. _err "Load file $d_api error. Please check your api file and try again."
  1333. return 1
  1334. fi
  1335. addcommand="${_currentRoot}_add"
  1336. if ! _exists $addcommand ; then
  1337. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1338. return 1
  1339. fi
  1340. if ! $addcommand $txtdomain $txt ; then
  1341. _err "Error add txt for domain:$txtdomain"
  1342. return 1
  1343. fi
  1344. )
  1345. if [ "$?" != "0" ] ; then
  1346. _clearup
  1347. return 1
  1348. fi
  1349. dnsadded='1'
  1350. fi
  1351. done
  1352. if [ "$dnsadded" = '0' ] ; then
  1353. _savedomainconf "Le_Vlist" "$vlist"
  1354. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1355. _err "Please add the TXT records to the domains, and retry again."
  1356. _clearup
  1357. return 1
  1358. fi
  1359. fi
  1360. if [ "$dnsadded" = '1' ] ; then
  1361. if [ -z "$Le_DNSSleep" ] ; then
  1362. Le_DNSSleep=$DEFAULT_DNS_SLEEP
  1363. else
  1364. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  1365. fi
  1366. _info "Sleep $Le_DNSSleep seconds for the txt records to take effect"
  1367. sleep $Le_DNSSleep
  1368. fi
  1369. _debug "ok, let's start to verify"
  1370. ventries=$(echo "$vlist" | tr ',' ' ' )
  1371. for ventry in $ventries
  1372. do
  1373. d=$(echo $ventry | cut -d $sep -f 1)
  1374. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1375. uri=$(echo $ventry | cut -d $sep -f 3)
  1376. vtype=$(echo $ventry | cut -d $sep -f 4)
  1377. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1378. _info "Verifying:$d"
  1379. _debug "d" "$d"
  1380. _debug "keyauthorization" "$keyauthorization"
  1381. _debug "uri" "$uri"
  1382. removelevel=""
  1383. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  1384. _debug "_currentRoot" "$_currentRoot"
  1385. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1386. if [ "$_currentRoot" = "no" ] ; then
  1387. _info "Standalone mode server"
  1388. _startserver "$keyauthorization" &
  1389. if [ "$?" != "0" ] ; then
  1390. _clearup
  1391. return 1
  1392. fi
  1393. serverproc="$!"
  1394. sleep 2
  1395. _debug serverproc $serverproc
  1396. else
  1397. if [ "$_currentRoot" = "apache" ] ; then
  1398. wellknown_path="$ACME_DIR"
  1399. else
  1400. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1401. if [ ! -d "$_currentRoot/.well-known" ] ; then
  1402. removelevel='1'
  1403. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ] ; then
  1404. removelevel='2'
  1405. else
  1406. removelevel='3'
  1407. fi
  1408. fi
  1409. _debug wellknown_path "$wellknown_path"
  1410. _debug "writing token:$token to $wellknown_path/$token"
  1411. mkdir -p "$wellknown_path"
  1412. printf "%s" "$keyauthorization" > "$wellknown_path/$token"
  1413. if [ ! "$usingApache" ] ; then
  1414. if webroot_owner=$(_stat $_currentRoot) ; then
  1415. _debug "Changing owner/group of .well-known to $webroot_owner"
  1416. chown -R $webroot_owner "$_currentRoot/.well-known"
  1417. else
  1418. _debug "not chaning owner/group of webroot";
  1419. fi
  1420. fi
  1421. fi
  1422. elif [ "$vtype" = "$VTYPE_TLS" ] ; then
  1423. #create A
  1424. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  1425. #_debug2 _hash_A "$_hash_A"
  1426. #_x="$(echo $_hash_A | cut -c 1-32)"
  1427. #_debug2 _x "$_x"
  1428. #_y="$(echo $_hash_A | cut -c 33-64)"
  1429. #_debug2 _y "$_y"
  1430. #_SAN_A="$_x.$_y.token.acme.invalid"
  1431. #_debug2 _SAN_A "$_SAN_A"
  1432. #create B
  1433. _hash_B="$(printf "%s" $keyauthorization | _digest "sha256" "hex" )"
  1434. _debug2 _hash_B "$_hash_B"
  1435. _x="$(echo $_hash_B | cut -c 1-32)"
  1436. _debug2 _x "$_x"
  1437. _y="$(echo $_hash_B | cut -c 33-64)"
  1438. _debug2 _y "$_y"
  1439. #_SAN_B="$_x.$_y.ka.acme.invalid"
  1440. _SAN_B="$_x.$_y.acme.invalid"
  1441. _debug2 _SAN_B "$_SAN_B"
  1442. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" ; then
  1443. _err "Start tls server error."
  1444. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1445. _clearup
  1446. return 1
  1447. fi
  1448. fi
  1449. if ! _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}" ; then
  1450. _err "$d:Can not get challenge: $response"
  1451. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1452. _clearup
  1453. return 1
  1454. fi
  1455. if [ ! -z "$code" ] && [ ! "$code" = '202' ] ; then
  1456. _err "$d:Challenge error: $response"
  1457. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1458. _clearup
  1459. return 1
  1460. fi
  1461. waittimes=0
  1462. if [ -z "$MAX_RETRY_TIMES" ] ; then
  1463. MAX_RETRY_TIMES=30
  1464. fi
  1465. while true ; do
  1466. waittimes=$(_math $waittimes + 1)
  1467. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ] ; then
  1468. _err "$d:Timeout"
  1469. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1470. _clearup
  1471. return 1
  1472. fi
  1473. _debug "sleep 5 secs to verify"
  1474. sleep 5
  1475. _debug "checking"
  1476. response="$(_get $uri)"
  1477. if [ "$?" != "0" ] ; then
  1478. _err "$d:Verify error:$response"
  1479. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1480. _clearup
  1481. return 1
  1482. fi
  1483. _debug2 original "$response"
  1484. response="$(echo "$response" | _normalizeJson )"
  1485. _debug2 response "$response"
  1486. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  1487. if [ "$status" = "valid" ] ; then
  1488. _info "Success"
  1489. _stopserver $serverproc
  1490. serverproc=""
  1491. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1492. break;
  1493. fi
  1494. if [ "$status" = "invalid" ] ; then
  1495. error="$(echo $response | tr -d "\r\n" | egrep -o '"error":\{[^}]*}')"
  1496. _debug2 error "$error"
  1497. errordetail="$(echo $error | grep -o '"detail": *"[^"]*"' | cut -d '"' -f 4)"
  1498. _debug2 errordetail "$errordetail"
  1499. if [ "$errordetail" ] ; then
  1500. _err "$d:Verify error:$errordetail"
  1501. else
  1502. _err "$d:Verify error:$error"
  1503. fi
  1504. if [ "$DEBUG" ] ; then
  1505. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1506. _get "http://$d/.well-known/acme-challenge/$token"
  1507. fi
  1508. fi
  1509. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1510. _clearup
  1511. return 1;
  1512. fi
  1513. if [ "$status" = "pending" ] ; then
  1514. _info "Pending"
  1515. else
  1516. _err "$d:Verify error:$response"
  1517. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  1518. _clearup
  1519. return 1
  1520. fi
  1521. done
  1522. done
  1523. _clearup
  1524. _info "Verify finished, start to sign."
  1525. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  1526. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64" ; then
  1527. _err "Sign failed."
  1528. return 1
  1529. fi
  1530. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1531. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  1532. if [ "$Le_LinkCert" ] ; then
  1533. echo "$BEGIN_CERT" > "$CERT_PATH"
  1534. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1535. echo "$END_CERT" >> "$CERT_PATH"
  1536. _info "Cert success."
  1537. cat "$CERT_PATH"
  1538. _info "Your cert is in $CERT_PATH"
  1539. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1540. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ] ; then
  1541. USER_PATH="$PATH"
  1542. _saveaccountconf "USER_PATH" "$USER_PATH"
  1543. fi
  1544. fi
  1545. if [ -z "$Le_LinkCert" ] ; then
  1546. response="$(echo $response | _dbase64 "multiline" | _normalizeJson )"
  1547. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1548. return 1
  1549. fi
  1550. _cleardomainconf "Le_Vlist"
  1551. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1552. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  1553. if [ "$Le_LinkIssuer" ] ; then
  1554. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1555. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1556. echo "$END_CERT" >> "$CA_CERT_PATH"
  1557. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1558. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1559. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1560. fi
  1561. Le_CertCreateTime=$(date -u "+%s")
  1562. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  1563. Le_CertCreateTimeStr=$(date -u )
  1564. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  1565. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ] ; then
  1566. Le_RenewalDays=$MAX_RENEW
  1567. else
  1568. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  1569. fi
  1570. if [ "$Le_Insecure" ] ; then
  1571. _savedomainconf "Le_Insecure" "$Le_Insecure"
  1572. fi
  1573. Le_NextRenewTime=$(_math $Le_CertCreateTime + $Le_RenewalDays \* 24 \* 60 \* 60)
  1574. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  1575. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1576. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  1577. if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ] ; then
  1578. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1579. fi
  1580. }
  1581. renew() {
  1582. Le_Domain="$1"
  1583. if [ -z "$Le_Domain" ] ; then
  1584. _err "Usage: $PROJECT_ENTRY --renew -d domain.com"
  1585. return 1
  1586. fi
  1587. _initpath $Le_Domain
  1588. _info "Renew: $Le_Domain"
  1589. if [ ! -f "$DOMAIN_CONF" ] ; then
  1590. _info "$Le_Domain is not a issued domain, skip."
  1591. return 0;
  1592. fi
  1593. if [ "$Le_RenewalDays" ] ; then
  1594. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  1595. fi
  1596. . "$DOMAIN_CONF"
  1597. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  1598. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1599. return $RENEW_SKIP
  1600. fi
  1601. IS_RENEW="1"
  1602. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath"
  1603. local res=$?
  1604. IS_RENEW=""
  1605. return $res
  1606. }
  1607. #renewAll [stopRenewOnError]
  1608. renewAll() {
  1609. _initpath
  1610. _stopRenewOnError="$1"
  1611. _debug "_stopRenewOnError" "$_stopRenewOnError"
  1612. _ret="0"
  1613. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1614. d=$(echo $d | cut -d '/' -f 1)
  1615. (
  1616. renew "$d"
  1617. )
  1618. rc="$?"
  1619. _debug "Return code: $rc"
  1620. if [ "$rc" != "0" ] ; then
  1621. if [ "$rc" = "$RENEW_SKIP" ] ; then
  1622. _info "Skipped $d"
  1623. elif [ "$_stopRenewOnError" ] ; then
  1624. _err "Error renew $d, stop now."
  1625. return $rc
  1626. else
  1627. _ret="$rc"
  1628. _err "Error renew $d, Go ahead to next one."
  1629. fi
  1630. fi
  1631. done
  1632. return $_ret
  1633. }
  1634. list() {
  1635. local _raw="$1"
  1636. _initpath
  1637. _sep="|"
  1638. if [ "$_raw" ] ; then
  1639. printf "Main_Domain${_sep}SAN_Domains${_sep}Created${_sep}Renew\n"
  1640. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  1641. d=$(echo $d | cut -d '/' -f 1)
  1642. (
  1643. _initpath $d
  1644. if [ -f "$DOMAIN_CONF" ] ; then
  1645. . "$DOMAIN_CONF"
  1646. printf "$Le_Domain${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr\n"
  1647. fi
  1648. )
  1649. done
  1650. else
  1651. list "raw" | column -t -s "$_sep"
  1652. fi
  1653. }
  1654. installcert() {
  1655. Le_Domain="$1"
  1656. if [ -z "$Le_Domain" ] ; then
  1657. echo "Usage: $PROJECT_ENTRY --installcert -d domain.com [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  1658. return 1
  1659. fi
  1660. Le_RealCertPath="$2"
  1661. Le_RealKeyPath="$3"
  1662. Le_RealCACertPath="$4"
  1663. Le_ReloadCmd="$5"
  1664. Le_RealFullChainPath="$6"
  1665. _initpath $Le_Domain
  1666. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  1667. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  1668. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  1669. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  1670. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  1671. if [ "$Le_RealCertPath" = "no" ] ; then
  1672. Le_RealCertPath=""
  1673. fi
  1674. if [ "$Le_RealKeyPath" = "no" ] ; then
  1675. Le_RealKeyPath=""
  1676. fi
  1677. if [ "$Le_RealCACertPath" = "no" ] ; then
  1678. Le_RealCACertPath=""
  1679. fi
  1680. if [ "$Le_ReloadCmd" = "no" ] ; then
  1681. Le_ReloadCmd=""
  1682. fi
  1683. if [ "$Le_RealFullChainPath" = "no" ] ; then
  1684. Le_RealFullChainPath=""
  1685. fi
  1686. _installed="0"
  1687. if [ "$Le_RealCertPath" ] ; then
  1688. _installed=1
  1689. _info "Installing cert to:$Le_RealCertPath"
  1690. if [ -f "$Le_RealCertPath" ] ; then
  1691. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  1692. fi
  1693. cat "$CERT_PATH" > "$Le_RealCertPath"
  1694. fi
  1695. if [ "$Le_RealCACertPath" ] ; then
  1696. _installed=1
  1697. _info "Installing CA to:$Le_RealCACertPath"
  1698. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ] ; then
  1699. echo "" >> "$Le_RealCACertPath"
  1700. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1701. else
  1702. if [ -f "$Le_RealCACertPath" ] ; then
  1703. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1704. fi
  1705. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1706. fi
  1707. fi
  1708. if [ "$Le_RealKeyPath" ] ; then
  1709. _installed=1
  1710. _info "Installing key to:$Le_RealKeyPath"
  1711. if [ -f "$Le_RealKeyPath" ] ; then
  1712. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1713. fi
  1714. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1715. fi
  1716. if [ "$Le_RealFullChainPath" ] ; then
  1717. _installed=1
  1718. _info "Installing full chain to:$Le_RealFullChainPath"
  1719. if [ -f "$Le_RealFullChainPath" ] ; then
  1720. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  1721. fi
  1722. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  1723. fi
  1724. if [ "$Le_ReloadCmd" ] ; then
  1725. _installed=1
  1726. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1727. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd") ; then
  1728. _info "Reload success."
  1729. else
  1730. _err "Reload error for :$Le_Domain"
  1731. fi
  1732. fi
  1733. }
  1734. installcronjob() {
  1735. _initpath
  1736. if ! _exists "crontab" ; then
  1737. _err "crontab doesn't exist, so, we can not install cron jobs."
  1738. _err "All your certs will not be renewed automatically."
  1739. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  1740. return 1
  1741. fi
  1742. _info "Installing cron job"
  1743. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  1744. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ] ; then
  1745. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  1746. else
  1747. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  1748. return 1
  1749. fi
  1750. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  1751. fi
  1752. if [ "$?" != "0" ] ; then
  1753. _err "Install cron job failed. You need to manually renew your certs."
  1754. _err "Or you can add cronjob by yourself:"
  1755. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  1756. return 1
  1757. fi
  1758. }
  1759. uninstallcronjob() {
  1760. if ! _exists "crontab" ; then
  1761. return
  1762. fi
  1763. _info "Removing cron job"
  1764. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  1765. if [ "$cr" ] ; then
  1766. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  1767. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  1768. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1769. fi
  1770. _initpath
  1771. }
  1772. revoke() {
  1773. Le_Domain="$1"
  1774. if [ -z "$Le_Domain" ] ; then
  1775. echo "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  1776. return 1
  1777. fi
  1778. _initpath $Le_Domain
  1779. if [ ! -f "$DOMAIN_CONF" ] ; then
  1780. _err "$Le_Domain is not a issued domain, skip."
  1781. return 1;
  1782. fi
  1783. if [ ! -f "$CERT_PATH" ] ; then
  1784. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  1785. return 1
  1786. fi
  1787. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  1788. if [ -z "$cert" ] ; then
  1789. _err "Cert for $Le_Domain is empty found, skip."
  1790. return 1
  1791. fi
  1792. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  1793. uri="$API/acme/revoke-cert"
  1794. _info "Try domain key first."
  1795. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  1796. if [ -z "$response" ] ; then
  1797. _info "Revoke success."
  1798. rm -f $CERT_PATH
  1799. return 0
  1800. else
  1801. _err "Revoke error by domain key."
  1802. _err "$response"
  1803. fi
  1804. fi
  1805. _info "Then try account key."
  1806. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  1807. if [ -z "$response" ] ; then
  1808. _info "Revoke success."
  1809. rm -f $CERT_PATH
  1810. return 0
  1811. else
  1812. _err "Revoke error."
  1813. _debug "$response"
  1814. fi
  1815. fi
  1816. return 1
  1817. }
  1818. # Detect profile file if not specified as environment variable
  1819. _detect_profile() {
  1820. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  1821. echo "$PROFILE"
  1822. return
  1823. fi
  1824. local DETECTED_PROFILE
  1825. DETECTED_PROFILE=''
  1826. local SHELLTYPE
  1827. SHELLTYPE="$(basename "/$SHELL")"
  1828. if [ "$SHELLTYPE" = "bash" ] ; then
  1829. if [ -f "$HOME/.bashrc" ] ; then
  1830. DETECTED_PROFILE="$HOME/.bashrc"
  1831. elif [ -f "$HOME/.bash_profile" ] ; then
  1832. DETECTED_PROFILE="$HOME/.bash_profile"
  1833. fi
  1834. elif [ "$SHELLTYPE" = "zsh" ] ; then
  1835. DETECTED_PROFILE="$HOME/.zshrc"
  1836. fi
  1837. if [ -z "$DETECTED_PROFILE" ] ; then
  1838. if [ -f "$HOME/.profile" ] ; then
  1839. DETECTED_PROFILE="$HOME/.profile"
  1840. elif [ -f "$HOME/.bashrc" ] ; then
  1841. DETECTED_PROFILE="$HOME/.bashrc"
  1842. elif [ -f "$HOME/.bash_profile" ] ; then
  1843. DETECTED_PROFILE="$HOME/.bash_profile"
  1844. elif [ -f "$HOME/.zshrc" ] ; then
  1845. DETECTED_PROFILE="$HOME/.zshrc"
  1846. fi
  1847. fi
  1848. if [ ! -z "$DETECTED_PROFILE" ] ; then
  1849. echo "$DETECTED_PROFILE"
  1850. fi
  1851. }
  1852. _initconf() {
  1853. _initpath
  1854. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1855. echo "#ACCOUNT_CONF_PATH=xxxx
  1856. #Account configurations:
  1857. #Here are the supported macros, uncomment them to make them take effect.
  1858. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1859. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1860. #CERT_HOME=\"/path/to/cert/home\"
  1861. #STAGE=1 # Use the staging api
  1862. #FORCE=1 # Force to issue cert
  1863. #DEBUG=1 # Debug mode
  1864. #ACCOUNT_KEY_HASH=account key hash
  1865. #USER_AGENT=\"$USER_AGENT\"
  1866. #USER_PATH=""
  1867. #dns api
  1868. #######################
  1869. #Cloudflare:
  1870. #api key
  1871. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1872. #account email
  1873. #CF_Email=\"xxxx@sss.com\"
  1874. #######################
  1875. #Dnspod.cn:
  1876. #api key id
  1877. #DP_Id=\"1234\"
  1878. #api key
  1879. #DP_Key=\"sADDsdasdgdsf\"
  1880. #######################
  1881. #Cloudxns.com:
  1882. #CX_Key=\"1234\"
  1883. #
  1884. #CX_Secret=\"sADDsdasdgdsf\"
  1885. #######################
  1886. #Godaddy.com:
  1887. #GD_Key=\"sdfdsgdgdfdasfds\"
  1888. #
  1889. #GD_Secret=\"sADDsdasdfsdfdssdgdsf\"
  1890. " > $ACCOUNT_CONF_PATH
  1891. fi
  1892. }
  1893. # nocron
  1894. _precheck() {
  1895. _nocron="$1"
  1896. if ! _exists "curl" && ! _exists "wget"; then
  1897. _err "Please install curl or wget first, we need to access http resources."
  1898. return 1
  1899. fi
  1900. if [ -z "$_nocron" ] ; then
  1901. if ! _exists "crontab" ; then
  1902. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1903. _err "We need to set cron job to renew the certs automatically."
  1904. _err "Otherwise, your certs will not be able to be renewed automatically."
  1905. if [ -z "$FORCE" ] ; then
  1906. _err "Please add '--force' and try install again to go without crontab."
  1907. _err "./$PROJECT_ENTRY --install --force"
  1908. return 1
  1909. fi
  1910. fi
  1911. fi
  1912. if ! _exists "openssl" ; then
  1913. _err "Please install openssl first."
  1914. _err "We need openssl to generate keys."
  1915. return 1
  1916. fi
  1917. if ! _exists "nc" ; then
  1918. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1919. _err "We use nc for standalone server if you use standalone mode."
  1920. _err "If you don't use standalone mode, just ignore this warning."
  1921. fi
  1922. return 0
  1923. }
  1924. _setShebang() {
  1925. _file="$1"
  1926. _shebang="$2"
  1927. if [ -z "$_shebang" ] ; then
  1928. _err "Usage: file shebang"
  1929. return 1
  1930. fi
  1931. cp "$_file" "$_file.tmp"
  1932. echo "$_shebang" > "$_file"
  1933. sed -n 2,99999p "$_file.tmp" >> "$_file"
  1934. rm -f "$_file.tmp"
  1935. }
  1936. _installalias() {
  1937. _initpath
  1938. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1939. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ] ; then
  1940. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  1941. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  1942. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  1943. fi
  1944. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  1945. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1946. _profile="$(_detect_profile)"
  1947. if [ "$_profile" ] ; then
  1948. _debug "Found profile: $_profile"
  1949. _setopt "$_profile" ". \"$_envfile\""
  1950. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  1951. else
  1952. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  1953. fi
  1954. #for csh
  1955. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  1956. _csh_profile="$HOME/.cshrc"
  1957. if [ -f "$_csh_profile" ] ; then
  1958. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  1959. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1960. _setopt "$_csh_profile" "source \"$_cshfile\""
  1961. fi
  1962. #for tcsh
  1963. _tcsh_profile="$HOME/.tcshrc"
  1964. if [ -f "$_tcsh_profile" ] ; then
  1965. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  1966. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  1967. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  1968. fi
  1969. }
  1970. # nocron
  1971. install() {
  1972. _nocron="$1"
  1973. if ! _initpath ; then
  1974. _err "Install failed."
  1975. return 1
  1976. fi
  1977. if [ "$_nocron" ] ; then
  1978. _debug "Skip install cron job"
  1979. fi
  1980. if ! _precheck "$_nocron" ; then
  1981. _err "Pre-check failed, can not install."
  1982. return 1
  1983. fi
  1984. #convert from le
  1985. if [ -d "$HOME/.le" ] ; then
  1986. for envfile in "le.env" "le.sh.env"
  1987. do
  1988. if [ -f "$HOME/.le/$envfile" ] ; then
  1989. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  1990. _upgrading="1"
  1991. _info "You are upgrading from le.sh"
  1992. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  1993. mv "$HOME/.le" "$LE_WORKING_DIR"
  1994. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  1995. break;
  1996. fi
  1997. fi
  1998. done
  1999. fi
  2000. _info "Installing to $LE_WORKING_DIR"
  2001. if ! mkdir -p "$LE_WORKING_DIR" ; then
  2002. _err "Can not create working dir: $LE_WORKING_DIR"
  2003. return 1
  2004. fi
  2005. chmod 700 "$LE_WORKING_DIR"
  2006. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  2007. if [ "$?" != "0" ] ; then
  2008. _err "Install failed, can not copy $PROJECT_ENTRY"
  2009. return 1
  2010. fi
  2011. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  2012. _installalias
  2013. if [ -d "dnsapi" ] ; then
  2014. mkdir -p $LE_WORKING_DIR/dnsapi
  2015. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  2016. fi
  2017. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  2018. _initconf
  2019. fi
  2020. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ] ; then
  2021. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  2022. fi
  2023. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ] ; then
  2024. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  2025. fi
  2026. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ] ; then
  2027. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  2028. fi
  2029. if [ -z "$_nocron" ] ; then
  2030. installcronjob
  2031. fi
  2032. if [ -z "$NO_DETECT_SH" ] ; then
  2033. #Modify shebang
  2034. if _exists bash ; then
  2035. _info "Good, bash is installed, change the shebang to use bash as prefered."
  2036. _shebang='#!/usr/bin/env bash'
  2037. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  2038. if [ -d "$LE_WORKING_DIR/dnsapi" ] ; then
  2039. for _apifile in $(ls "$LE_WORKING_DIR/dnsapi/"*.sh) ; do
  2040. _setShebang "$_apifile" "$_shebang"
  2041. done
  2042. fi
  2043. fi
  2044. fi
  2045. _info OK
  2046. }
  2047. # nocron
  2048. uninstall() {
  2049. _nocron="$1"
  2050. if [ -z "$_nocron" ] ; then
  2051. uninstallcronjob
  2052. fi
  2053. _initpath
  2054. _profile="$(_detect_profile)"
  2055. if [ "$_profile" ] ; then
  2056. text="$(cat $_profile)"
  2057. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" > "$_profile"
  2058. fi
  2059. _csh_profile="$HOME/.cshrc"
  2060. if [ -f "$_csh_profile" ] ; then
  2061. text="$(cat $_csh_profile)"
  2062. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_csh_profile"
  2063. fi
  2064. _tcsh_profile="$HOME/.tcshrc"
  2065. if [ -f "$_tcsh_profile" ] ; then
  2066. text="$(cat $_tcsh_profile)"
  2067. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_tcsh_profile"
  2068. fi
  2069. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  2070. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  2071. }
  2072. cron() {
  2073. IN_CRON=1
  2074. renewAll
  2075. _ret="$?"
  2076. IN_CRON=""
  2077. return $_ret
  2078. }
  2079. version() {
  2080. echo "$PROJECT"
  2081. echo "v$VER"
  2082. }
  2083. showhelp() {
  2084. version
  2085. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  2086. Commands:
  2087. --help, -h Show this help message.
  2088. --version, -v Show version info.
  2089. --install Install $PROJECT_NAME to your system.
  2090. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  2091. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT
  2092. --issue Issue a cert.
  2093. --installcert Install the issued cert to apache/nginx or any other server.
  2094. --renew, -r Renew a cert.
  2095. --renewAll Renew all the certs
  2096. --revoke Revoke a cert.
  2097. --list List all the certs
  2098. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  2099. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  2100. --cron Run cron job to renew all the certs.
  2101. --toPkcs Export the certificate and key to a pfx file.
  2102. --createAccountKey, -cak Create an account private key, professional use.
  2103. --createDomainKey, -cdk Create an domain private key, professional use.
  2104. --createCSR, -ccsr Create CSR , professional use.
  2105. Parameters:
  2106. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  2107. --force, -f Used to force to install or force to renew a cert immediately.
  2108. --staging, --test Use staging server, just for test.
  2109. --debug Output debug info.
  2110. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  2111. --standalone Use standalone mode.
  2112. --tls Use standalone tls mode.
  2113. --apache Use apache mode.
  2114. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  2115. --dnssleep [$DEFAULT_DNS_SLEEP] The time in seconds to wait for all the txt records to take effect in dns api mode. Default $DEFAULT_DNS_SLEEP seconds.
  2116. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  2117. --accountkeylength, -ak [2048] Specifies the account key length.
  2118. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  2119. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  2120. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  2121. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  2122. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  2123. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  2124. --accountconf Specifies a customized account config file.
  2125. --home Specifies the home dir for $PROJECT_NAME .
  2126. --certhome Specifies the home dir to save all the certs, only valid for '--install' command.
  2127. --useragent Specifies the user agent string. it will be saved for future use too.
  2128. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  2129. --accountkey Specifies the account key path, Only valid for the '--install' command.
  2130. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  2131. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  2132. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  2133. --listraw Only used for '--list' command, list the certs in raw format.
  2134. --stopRenewOnError, -se Only valid for '--renewall' command. Stop if one cert has error in renewal.
  2135. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  2136. --nocron Only valid for '--install' command, which means: do not install the default cron job. In this case, the certs will not be renewed automatically.
  2137. "
  2138. }
  2139. # nocron
  2140. _installOnline() {
  2141. _info "Installing from online archive."
  2142. _nocron="$1"
  2143. if [ ! "$BRANCH" ] ; then
  2144. BRANCH="master"
  2145. fi
  2146. _initpath
  2147. target="$PROJECT/archive/$BRANCH.tar.gz"
  2148. _info "Downloading $target"
  2149. localname="$BRANCH.tar.gz"
  2150. if ! _get "$target" > $localname ; then
  2151. _debug "Download error."
  2152. return 1
  2153. fi
  2154. (
  2155. _info "Extracting $localname"
  2156. tar xzf $localname
  2157. cd "$PROJECT_NAME-$BRANCH"
  2158. chmod +x $PROJECT_ENTRY
  2159. if ./$PROJECT_ENTRY install "$_nocron" ; then
  2160. _info "Install success!"
  2161. fi
  2162. cd ..
  2163. rm -rf "$PROJECT_NAME-$BRANCH"
  2164. rm -f "$localname"
  2165. )
  2166. }
  2167. upgrade() {
  2168. if (
  2169. cd "$LE_WORKING_DIR"
  2170. _installOnline "nocron"
  2171. ) ; then
  2172. _info "Upgrade success!"
  2173. exit 0
  2174. else
  2175. _err "Upgrade failed!"
  2176. exit 1
  2177. fi
  2178. }
  2179. _process() {
  2180. _CMD=""
  2181. _domain=""
  2182. _altdomains="no"
  2183. _webroot=""
  2184. _keylength=""
  2185. _accountkeylength=""
  2186. _certpath=""
  2187. _keypath=""
  2188. _capath=""
  2189. _fullchainpath=""
  2190. _reloadcmd=""
  2191. _password=""
  2192. _accountconf=""
  2193. _useragent=""
  2194. _accountemail=""
  2195. _accountkey=""
  2196. _certhome=""
  2197. _httpport=""
  2198. _tlsport=""
  2199. _dnssleep=""
  2200. _listraw=""
  2201. _stopRenewOnError=""
  2202. _insecure=""
  2203. _nocron=""
  2204. while [ ${#} -gt 0 ] ; do
  2205. case "${1}" in
  2206. --help|-h)
  2207. showhelp
  2208. return
  2209. ;;
  2210. --version|-v)
  2211. version
  2212. return
  2213. ;;
  2214. --install)
  2215. _CMD="install"
  2216. ;;
  2217. --uninstall)
  2218. _CMD="uninstall"
  2219. ;;
  2220. --upgrade)
  2221. _CMD="upgrade"
  2222. ;;
  2223. --issue)
  2224. _CMD="issue"
  2225. ;;
  2226. --installcert|-i)
  2227. _CMD="installcert"
  2228. ;;
  2229. --renew|-r)
  2230. _CMD="renew"
  2231. ;;
  2232. --renewAll|--renewall)
  2233. _CMD="renewAll"
  2234. ;;
  2235. --revoke)
  2236. _CMD="revoke"
  2237. ;;
  2238. --list)
  2239. _CMD="list"
  2240. ;;
  2241. --installcronjob)
  2242. _CMD="installcronjob"
  2243. ;;
  2244. --uninstallcronjob)
  2245. _CMD="uninstallcronjob"
  2246. ;;
  2247. --cron)
  2248. _CMD="cron"
  2249. ;;
  2250. --toPkcs)
  2251. _CMD="toPkcs"
  2252. ;;
  2253. --createAccountKey|--createaccountkey|-cak)
  2254. _CMD="createAccountKey"
  2255. ;;
  2256. --createDomainKey|--createdomainkey|-cdk)
  2257. _CMD="createDomainKey"
  2258. ;;
  2259. --createCSR|--createcsr|-ccr)
  2260. _CMD="createCSR"
  2261. ;;
  2262. --domain|-d)
  2263. _dvalue="$2"
  2264. if [ "$_dvalue" ] ; then
  2265. if _startswith "$_dvalue" "-" ; then
  2266. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  2267. return 1
  2268. fi
  2269. if [ -z "$_domain" ] ; then
  2270. _domain="$_dvalue"
  2271. else
  2272. if [ "$_altdomains" = "no" ] ; then
  2273. _altdomains="$_dvalue"
  2274. else
  2275. _altdomains="$_altdomains,$_dvalue"
  2276. fi
  2277. fi
  2278. fi
  2279. shift
  2280. ;;
  2281. --force|-f)
  2282. FORCE="1"
  2283. ;;
  2284. --staging|--test)
  2285. STAGE="1"
  2286. ;;
  2287. --debug)
  2288. if [ -z "$2" ] || _startswith "$2" "-" ; then
  2289. DEBUG="1"
  2290. else
  2291. DEBUG="$2"
  2292. shift
  2293. fi
  2294. ;;
  2295. --webroot|-w)
  2296. wvalue="$2"
  2297. if [ -z "$_webroot" ] ; then
  2298. _webroot="$wvalue"
  2299. else
  2300. _webroot="$_webroot,$wvalue"
  2301. fi
  2302. shift
  2303. ;;
  2304. --standalone)
  2305. wvalue="no"
  2306. if [ -z "$_webroot" ] ; then
  2307. _webroot="$wvalue"
  2308. else
  2309. _webroot="$_webroot,$wvalue"
  2310. fi
  2311. ;;
  2312. --apache)
  2313. wvalue="apache"
  2314. if [ -z "$_webroot" ] ; then
  2315. _webroot="$wvalue"
  2316. else
  2317. _webroot="$_webroot,$wvalue"
  2318. fi
  2319. ;;
  2320. --tls)
  2321. wvalue="$W_TLS"
  2322. if [ -z "$_webroot" ] ; then
  2323. _webroot="$wvalue"
  2324. else
  2325. _webroot="$_webroot,$wvalue"
  2326. fi
  2327. ;;
  2328. --dns)
  2329. wvalue="dns"
  2330. if ! _startswith "$2" "-" ; then
  2331. wvalue="$2"
  2332. shift
  2333. fi
  2334. if [ -z "$_webroot" ] ; then
  2335. _webroot="$wvalue"
  2336. else
  2337. _webroot="$_webroot,$wvalue"
  2338. fi
  2339. ;;
  2340. --dnssleep)
  2341. _dnssleep="$2"
  2342. Le_DNSSleep="$_dnssleep"
  2343. shift
  2344. ;;
  2345. --keylength|-k)
  2346. _keylength="$2"
  2347. if [ "$_accountkeylength" = "no" ] ; then
  2348. _accountkeylength="$2"
  2349. fi
  2350. shift
  2351. ;;
  2352. --accountkeylength|-ak)
  2353. _accountkeylength="$2"
  2354. shift
  2355. ;;
  2356. --certpath)
  2357. _certpath="$2"
  2358. shift
  2359. ;;
  2360. --keypath)
  2361. _keypath="$2"
  2362. shift
  2363. ;;
  2364. --capath)
  2365. _capath="$2"
  2366. shift
  2367. ;;
  2368. --fullchainpath)
  2369. _fullchainpath="$2"
  2370. shift
  2371. ;;
  2372. --reloadcmd|--reloadCmd)
  2373. _reloadcmd="$2"
  2374. shift
  2375. ;;
  2376. --password)
  2377. _password="$2"
  2378. shift
  2379. ;;
  2380. --accountconf)
  2381. _accountconf="$2"
  2382. ACCOUNT_CONF_PATH="$_accountconf"
  2383. shift
  2384. ;;
  2385. --home)
  2386. LE_WORKING_DIR="$2"
  2387. shift
  2388. ;;
  2389. --certhome)
  2390. _certhome="$2"
  2391. CERT_HOME="$_certhome"
  2392. shift
  2393. ;;
  2394. --useragent)
  2395. _useragent="$2"
  2396. USER_AGENT="$_useragent"
  2397. shift
  2398. ;;
  2399. --accountemail )
  2400. _accountemail="$2"
  2401. ACCOUNT_EMAIL="$_accountemail"
  2402. shift
  2403. ;;
  2404. --accountkey )
  2405. _accountkey="$2"
  2406. ACCOUNT_KEY_PATH="$_accountkey"
  2407. shift
  2408. ;;
  2409. --days )
  2410. _days="$2"
  2411. Le_RenewalDays="$_days"
  2412. shift
  2413. ;;
  2414. --httpport )
  2415. _httpport="$2"
  2416. Le_HTTPPort="$_httpport"
  2417. shift
  2418. ;;
  2419. --tlsport )
  2420. _tlsport="$2"
  2421. Le_TLSPort="$_tlsport"
  2422. shift
  2423. ;;
  2424. --listraw )
  2425. _listraw="raw"
  2426. ;;
  2427. --stopRenewOnError|--stoprenewonerror|-se )
  2428. _stopRenewOnError="1"
  2429. ;;
  2430. --insecure)
  2431. _insecure="1"
  2432. Le_Insecure="$_insecure"
  2433. ;;
  2434. --nocron)
  2435. _nocron="1"
  2436. ;;
  2437. *)
  2438. _err "Unknown parameter : $1"
  2439. return 1
  2440. ;;
  2441. esac
  2442. shift 1
  2443. done
  2444. if [ "$DEBUG" ] ; then
  2445. version
  2446. fi
  2447. case "${_CMD}" in
  2448. install) install "$_nocron" ;;
  2449. uninstall) uninstall "$_nocron" ;;
  2450. upgrade) upgrade ;;
  2451. issue)
  2452. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  2453. ;;
  2454. installcert)
  2455. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath"
  2456. ;;
  2457. renew)
  2458. renew "$_domain"
  2459. ;;
  2460. renewAll)
  2461. renewAll "$_stopRenewOnError"
  2462. ;;
  2463. revoke)
  2464. revoke "$_domain"
  2465. ;;
  2466. list)
  2467. list "$_listraw"
  2468. ;;
  2469. installcronjob) installcronjob ;;
  2470. uninstallcronjob) uninstallcronjob ;;
  2471. cron) cron ;;
  2472. toPkcs)
  2473. toPkcs "$_domain" "$_password"
  2474. ;;
  2475. createAccountKey)
  2476. createAccountKey "$_domain" "$_accountkeylength"
  2477. ;;
  2478. createDomainKey)
  2479. createDomainKey "$_domain" "$_keylength"
  2480. ;;
  2481. createCSR)
  2482. createCSR "$_domain" "$_altdomains"
  2483. ;;
  2484. *)
  2485. _err "Invalid command: $_CMD"
  2486. showhelp;
  2487. return 1
  2488. ;;
  2489. esac
  2490. _ret="$?"
  2491. if [ "$_ret" != "0" ] ; then
  2492. return $_ret
  2493. fi
  2494. if [ "$_useragent" ] ; then
  2495. _saveaccountconf "USER_AGENT" "$_useragent"
  2496. fi
  2497. if [ "$_accountemail" ] ; then
  2498. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  2499. fi
  2500. }
  2501. if [ "$INSTALLONLINE" ] ; then
  2502. INSTALLONLINE=""
  2503. _installOnline $BRANCH
  2504. exit
  2505. fi
  2506. if [ -z "$1" ] ; then
  2507. showhelp
  2508. else
  2509. if echo "$1" | grep "^-" >/dev/null 2>&1 ; then
  2510. _process "$@"
  2511. else
  2512. "$@"
  2513. fi
  2514. fi