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.

4084 lines
101 KiB

9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
8 years ago
9 years ago
8 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
9 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
8 years ago
8 years ago
9 years ago
9 years ago
9 years ago
8 years ago
8 years ago
  1. #!/usr/bin/env sh
  2. VER=2.6.0
  3. PROJECT_NAME="acme.sh"
  4. PROJECT_ENTRY="acme.sh"
  5. PROJECT="https://github.com/Neilpang/$PROJECT_NAME"
  6. DEFAULT_INSTALL_HOME="$HOME/.$PROJECT_NAME"
  7. _SCRIPT_="$0"
  8. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  9. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.1.1-August-1-2016.pdf"
  10. DEFAULT_USER_AGENT="$PROJECT_ENTRY client v$VER : $PROJECT"
  11. DEFAULT_ACCOUNT_EMAIL=""
  12. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  13. VTYPE_HTTP="http-01"
  14. VTYPE_DNS="dns-01"
  15. VTYPE_TLS="tls-sni-01"
  16. VTYPE_TLS2="tls-sni-02"
  17. LOCAL_ANY_ADDRESS="0.0.0.0"
  18. MAX_RENEW=60
  19. DEFAULT_DNS_SLEEP=120
  20. NO_VALUE="no"
  21. W_TLS="tls"
  22. STATE_VERIFIED="verified_ok"
  23. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  24. END_CSR="-----END CERTIFICATE REQUEST-----"
  25. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  26. END_CERT="-----END CERTIFICATE-----"
  27. RENEW_SKIP=2
  28. ECC_SEP="_"
  29. ECC_SUFFIX="${ECC_SEP}ecc"
  30. LOG_LEVEL_1=1
  31. LOG_LEVEL_2=2
  32. LOG_LEVEL_3=3
  33. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  34. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  35. __INTERACTIVE=""
  36. if [ -t 1 ] ; then
  37. __INTERACTIVE="1"
  38. fi
  39. __green() {
  40. if [ "$__INTERACTIVE" ] ; then
  41. printf '\033[1;31;32m'
  42. fi
  43. printf -- "$1"
  44. if [ "$__INTERACTIVE" ] ; then
  45. printf '\033[0m'
  46. fi
  47. }
  48. __red() {
  49. if [ "$__INTERACTIVE" ] ; then
  50. printf '\033[1;31;40m'
  51. fi
  52. printf -- "$1"
  53. if [ "$__INTERACTIVE" ] ; then
  54. printf '\033[0m'
  55. fi
  56. }
  57. _printargs() {
  58. if [ -z "$2" ] ; then
  59. printf -- "[$(date)] $1"
  60. else
  61. printf -- "[$(date)] $1='$2'"
  62. fi
  63. printf "\n"
  64. }
  65. _log() {
  66. [ -z "$LOG_FILE" ] && return
  67. _printargs "$@" >> "$LOG_FILE"
  68. }
  69. _info() {
  70. _log "$@"
  71. _printargs "$@"
  72. }
  73. _err() {
  74. _log "$@"
  75. printf -- "[$(date)] " >&2
  76. if [ -z "$2" ] ; then
  77. __red "$1" >&2
  78. else
  79. __red "$1='$2'" >&2
  80. fi
  81. printf "\n" >&2
  82. return 1
  83. }
  84. _usage() {
  85. __red "$@" >&2
  86. printf "\n" >&2
  87. }
  88. _debug() {
  89. if [ -z "$LOG_LEVEL" ] || [ "$LOG_LEVEL" -ge "$LOG_LEVEL_1" ] ; then
  90. _log "$@"
  91. fi
  92. if [ -z "$DEBUG" ] ; then
  93. return
  94. fi
  95. _printargs "$@" >&2
  96. }
  97. _debug2() {
  98. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_2" ] ; then
  99. _log "$@"
  100. fi
  101. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  102. _debug "$@"
  103. fi
  104. }
  105. _debug3() {
  106. if [ "$LOG_LEVEL" ] && [ "$LOG_LEVEL" -ge "$LOG_LEVEL_3" ] ; then
  107. _log "$@"
  108. fi
  109. if [ "$DEBUG" ] && [ "$DEBUG" -ge "3" ] ; then
  110. _debug "$@"
  111. fi
  112. }
  113. _startswith(){
  114. _str="$1"
  115. _sub="$2"
  116. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  117. }
  118. _endswith(){
  119. _str="$1"
  120. _sub="$2"
  121. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  122. }
  123. _contains(){
  124. _str="$1"
  125. _sub="$2"
  126. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  127. }
  128. _hasfield() {
  129. _str="$1"
  130. _field="$2"
  131. _sep="$3"
  132. if [ -z "$_field" ] ; then
  133. _usage "Usage: str field [sep]"
  134. return 1
  135. fi
  136. if [ -z "$_sep" ] ; then
  137. _sep=","
  138. fi
  139. for f in $(echo "$_str" | tr ',' ' ') ; do
  140. if [ "$f" = "$_field" ] ; then
  141. _debug2 "'$_str' contains '$_field'"
  142. return 0 #contains ok
  143. fi
  144. done
  145. _debug2 "'$_str' does not contain '$_field'"
  146. return 1 #not contains
  147. }
  148. _getfield(){
  149. _str="$1"
  150. _findex="$2"
  151. _sep="$3"
  152. if [ -z "$_findex" ] ; then
  153. _usage "Usage: str field [sep]"
  154. return 1
  155. fi
  156. if [ -z "$_sep" ] ; then
  157. _sep=","
  158. fi
  159. _ffi=$_findex
  160. while [ "$_ffi" -gt "0" ]
  161. do
  162. _fv="$(echo "$_str" | cut -d $_sep -f $_ffi)"
  163. if [ "$_fv" ] ; then
  164. printf -- "%s" "$_fv"
  165. return 0
  166. fi
  167. _ffi="$(_math $_ffi - 1)"
  168. done
  169. printf -- "%s" "$_str"
  170. }
  171. _exists(){
  172. cmd="$1"
  173. if [ -z "$cmd" ] ; then
  174. _usage "Usage: _exists cmd"
  175. return 1
  176. fi
  177. if type command >/dev/null 2>&1 ; then
  178. command -v "$cmd" >/dev/null 2>&1
  179. else
  180. type "$cmd" >/dev/null 2>&1
  181. fi
  182. ret="$?"
  183. _debug3 "$cmd exists=$ret"
  184. return $ret
  185. }
  186. #a + b
  187. _math(){
  188. expr "$@"
  189. }
  190. _h_char_2_dec() {
  191. _ch=$1
  192. case "${_ch}" in
  193. a|A)
  194. printf "10"
  195. ;;
  196. b|B)
  197. printf "11"
  198. ;;
  199. c|C)
  200. printf "12"
  201. ;;
  202. d|D)
  203. printf "13"
  204. ;;
  205. e|E)
  206. printf "14"
  207. ;;
  208. f|F)
  209. printf "15"
  210. ;;
  211. *)
  212. printf "%s" "$_ch"
  213. ;;
  214. esac
  215. }
  216. _URGLY_PRINTF=""
  217. if [ "$(printf '\x41')" != 'A' ] ; then
  218. _URGLY_PRINTF=1
  219. fi
  220. _h2b() {
  221. hex=$(cat)
  222. i=1
  223. j=2
  224. if _exists let ; then
  225. uselet="1"
  226. fi
  227. _debug3 uselet "$uselet"
  228. _debug3 _URGLY_PRINTF "$_URGLY_PRINTF"
  229. while true ; do
  230. if [ -z "$_URGLY_PRINTF" ] ; then
  231. h="$(printf $hex | cut -c $i-$j)"
  232. if [ -z "$h" ] ; then
  233. break;
  234. fi
  235. printf "\x$h"
  236. else
  237. ic="$(printf $hex | cut -c $i)"
  238. jc="$(printf $hex | cut -c $j)"
  239. if [ -z "$ic$jc" ] ; then
  240. break;
  241. fi
  242. ic="$(_h_char_2_dec "$ic")"
  243. jc="$(_h_char_2_dec "$jc")"
  244. printf '\'"$(printf %o "$(_math $ic \* 16 + $jc)")"
  245. fi
  246. if [ "$uselet" ] ; then
  247. let "i+=2" >/dev/null
  248. let "j+=2" >/dev/null
  249. else
  250. i="$(_math $i + 2)"
  251. j="$(_math $j + 2)"
  252. fi
  253. done
  254. }
  255. #options file
  256. _sed_i() {
  257. options="$1"
  258. filename="$2"
  259. if [ -z "$filename" ] ; then
  260. _usage "Usage:_sed_i options filename"
  261. return 1
  262. fi
  263. _debug2 options "$options"
  264. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  265. _debug "Using sed -i"
  266. sed -i "$options" "$filename"
  267. else
  268. _debug "No -i support in sed"
  269. text="$(cat "$filename")"
  270. echo "$text" | sed "$options" > "$filename"
  271. fi
  272. }
  273. _egrep_o() {
  274. if _contains "$(egrep -o 2>&1)" "egrep: illegal option -- o" ; then
  275. sed -n 's/.*\('"$1"'\).*/\1/p'
  276. else
  277. egrep -o "$1"
  278. fi
  279. }
  280. #Usage: file startline endline
  281. _getfile() {
  282. filename="$1"
  283. startline="$2"
  284. endline="$3"
  285. if [ -z "$endline" ] ; then
  286. _usage "Usage: file startline endline"
  287. return 1
  288. fi
  289. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  290. if [ -z "$i" ] ; then
  291. _err "Can not find start line: $startline"
  292. return 1
  293. fi
  294. i="$(_math "$i" + 1)"
  295. _debug i "$i"
  296. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  297. if [ -z "$j" ] ; then
  298. _err "Can not find end line: $endline"
  299. return 1
  300. fi
  301. j="$(_math "$j" - 1)"
  302. _debug j "$j"
  303. sed -n "$i,${j}p" "$filename"
  304. }
  305. #Usage: multiline
  306. _base64() {
  307. if [ "$1" ] ; then
  308. openssl base64 -e
  309. else
  310. openssl base64 -e | tr -d '\r\n'
  311. fi
  312. }
  313. #Usage: multiline
  314. _dbase64() {
  315. if [ "$1" ] ; then
  316. openssl base64 -d -A
  317. else
  318. openssl base64 -d
  319. fi
  320. }
  321. #Usage: hashalg [outputhex]
  322. #Output Base64-encoded digest
  323. _digest() {
  324. alg="$1"
  325. if [ -z "$alg" ] ; then
  326. _usage "Usage: _digest hashalg"
  327. return 1
  328. fi
  329. outputhex="$2"
  330. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  331. if [ "$outputhex" ] ; then
  332. openssl dgst -$alg -hex | cut -d = -f 2 | tr -d ' '
  333. else
  334. openssl dgst -$alg -binary | _base64
  335. fi
  336. else
  337. _err "$alg is not supported yet"
  338. return 1
  339. fi
  340. }
  341. #Usage: keyfile hashalg
  342. #Output: Base64-encoded signature value
  343. _sign() {
  344. keyfile="$1"
  345. alg="$2"
  346. if [ -z "$alg" ] ; then
  347. _usage "Usage: _sign keyfile hashalg"
  348. return 1
  349. fi
  350. if [ "$alg" = "sha256" ] ; then
  351. openssl dgst -sha256 -sign "$keyfile" | _base64
  352. else
  353. _err "$alg is not supported yet"
  354. return 1
  355. fi
  356. }
  357. #keylength
  358. _isEccKey() {
  359. _length="$1"
  360. if [ -z "$_length" ] ;then
  361. return 1
  362. fi
  363. [ "$_length" != "1024" ] \
  364. && [ "$_length" != "2048" ] \
  365. && [ "$_length" != "3072" ] \
  366. && [ "$_length" != "4096" ] \
  367. && [ "$_length" != "8192" ]
  368. }
  369. # _createkey 2048|ec-256 file
  370. _createkey() {
  371. length="$1"
  372. f="$2"
  373. eccname="$length"
  374. if _startswith "$length" "ec-" ; then
  375. length=$(printf $length | cut -d '-' -f 2-100)
  376. if [ "$length" = "256" ] ; then
  377. eccname="prime256v1"
  378. fi
  379. if [ "$length" = "384" ] ; then
  380. eccname="secp384r1"
  381. fi
  382. if [ "$length" = "521" ] ; then
  383. eccname="secp521r1"
  384. fi
  385. fi
  386. if [ -z "$length" ] ; then
  387. length=2048
  388. fi
  389. _debug "Use length $length"
  390. if _isEccKey "$length" ; then
  391. _debug "Using ec name: $eccname"
  392. openssl ecparam -name $eccname -genkey 2>/dev/null > "$f"
  393. else
  394. _debug "Using RSA: $length"
  395. openssl genrsa $length 2>/dev/null > "$f"
  396. fi
  397. if [ "$?" != "0" ] ; then
  398. _err "Create key error."
  399. return 1
  400. fi
  401. }
  402. #_createcsr cn san_list keyfile csrfile conf
  403. _createcsr() {
  404. _debug _createcsr
  405. domain="$1"
  406. domainlist="$2"
  407. csrkey="$3"
  408. csr="$4"
  409. csrconf="$5"
  410. _debug2 domain "$domain"
  411. _debug2 domainlist "$domainlist"
  412. _debug2 csrkey "$csrkey"
  413. _debug2 csr "$csr"
  414. _debug2 csrconf "$csrconf"
  415. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" > "$csrconf"
  416. if [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  417. #single domain
  418. _info "Single domain" "$domain"
  419. else
  420. if _contains "$domainlist" "," ; then
  421. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  422. else
  423. alt="DNS:$domainlist"
  424. fi
  425. #multi
  426. _info "Multi domain" "$alt"
  427. printf -- "\nsubjectAltName=$alt" >> "$csrconf"
  428. fi
  429. if [ "$Le_OCSP_Stable" ] ; then
  430. _savedomainconf Le_OCSP_Stable "$Le_OCSP_Stable"
  431. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >> "$csrconf"
  432. fi
  433. openssl req -new -sha256 -key "$csrkey" -subj "/CN=$domain" -config "$csrconf" -out "$csr"
  434. }
  435. #_signcsr key csr conf cert
  436. _signcsr() {
  437. key="$1"
  438. csr="$2"
  439. conf="$3"
  440. cert="$4"
  441. _debug "_signcsr"
  442. _msg="$(openssl x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  443. _ret="$?"
  444. _debug "$_msg"
  445. return $_ret
  446. }
  447. #_csrfile
  448. _readSubjectFromCSR() {
  449. _csrfile="$1"
  450. if [ -z "$_csrfile" ] ; then
  451. _usage "_readSubjectFromCSR mycsr.csr"
  452. return 1
  453. fi
  454. openssl req -noout -in "$_csrfile" -subject | _egrep_o "CN=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d '\n'
  455. }
  456. #_csrfile
  457. #echo comma separated domain list
  458. _readSubjectAltNamesFromCSR() {
  459. _csrfile="$1"
  460. if [ -z "$_csrfile" ] ; then
  461. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  462. return 1
  463. fi
  464. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  465. _debug _csrsubj "$_csrsubj"
  466. _dnsAltnames="$(openssl req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  467. _debug _dnsAltnames "$_dnsAltnames"
  468. if _contains "$_dnsAltnames," "DNS:$_csrsubj," ; then
  469. _debug "AltNames contains subject"
  470. _dnsAltnames="$(printf "%s" "$_dnsAltnames," | sed "s/DNS:$_csrsubj,//g")"
  471. else
  472. _debug "AltNames doesn't contain subject"
  473. fi
  474. printf "%s" "$_dnsAltnames" | sed "s/DNS://g"
  475. }
  476. #_csrfile
  477. _readKeyLengthFromCSR() {
  478. _csrfile="$1"
  479. if [ -z "$_csrfile" ] ; then
  480. _usage "_readKeyLengthFromCSR mycsr.csr"
  481. return 1
  482. fi
  483. _outcsr="$(openssl req -noout -text -in "$_csrfile")"
  484. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey" ; then
  485. _debug "ECC CSR"
  486. echo "$_outcsr" | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  487. else
  488. _debug "RSA CSR"
  489. echo "$_outcsr" | _egrep_o "^ *Public-Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  490. fi
  491. }
  492. _ss() {
  493. _port="$1"
  494. if _exists "ss" ; then
  495. _debug "Using: ss"
  496. ss -ntpl | grep ":$_port "
  497. return 0
  498. fi
  499. if _exists "netstat" ; then
  500. _debug "Using: netstat"
  501. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  502. #for windows version netstat tool
  503. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  504. else
  505. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  506. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  507. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null ; then
  508. #for solaris
  509. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  510. else
  511. netstat -ntpl | grep ":$_port "
  512. fi
  513. fi
  514. return 0
  515. fi
  516. return 1
  517. }
  518. #domain [password] [isEcc]
  519. toPkcs() {
  520. domain="$1"
  521. pfxPassword="$2"
  522. if [ -z "$domain" ] ; then
  523. _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  524. return 1
  525. fi
  526. _isEcc="$3"
  527. _initpath "$domain" "$_isEcc"
  528. if [ "$pfxPassword" ] ; then
  529. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH" -password "pass:$pfxPassword"
  530. else
  531. openssl pkcs12 -export -out "$CERT_PFX_PATH" -inkey "$CERT_KEY_PATH" -in "$CERT_PATH" -certfile "$CA_CERT_PATH"
  532. fi
  533. if [ "$?" = "0" ] ; then
  534. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  535. fi
  536. }
  537. #[2048]
  538. createAccountKey() {
  539. _info "Creating account key"
  540. if [ -z "$1" ] ; then
  541. _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
  542. return
  543. fi
  544. length=$1
  545. if _isEccKey "$length" ; then
  546. length=2048
  547. fi
  548. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ] ; then
  549. _debug "Use default length 2048"
  550. length=2048
  551. fi
  552. _debug length "$length"
  553. _initpath
  554. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  555. _info "Account key exists, skip"
  556. return
  557. else
  558. #generate account key
  559. _createkey "$length" "$ACCOUNT_KEY_PATH"
  560. fi
  561. }
  562. #domain [length]
  563. createDomainKey() {
  564. _info "Creating domain key"
  565. if [ -z "$1" ] ; then
  566. _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
  567. return
  568. fi
  569. domain=$1
  570. length=$2
  571. _initpath $domain "$length"
  572. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  573. _createkey "$length" "$CERT_KEY_PATH"
  574. else
  575. if [ "$IS_RENEW" ] ; then
  576. _info "Domain key exists, skip"
  577. return 0
  578. else
  579. _err "Domain key exists, do you want to overwrite the key?"
  580. _err "Add '--force', and try again."
  581. return 1
  582. fi
  583. fi
  584. }
  585. # domain domainlist isEcc
  586. createCSR() {
  587. _info "Creating csr"
  588. if [ -z "$1" ] ; then
  589. _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  590. return
  591. fi
  592. domain="$1"
  593. domainlist="$2"
  594. _isEcc="$3"
  595. _initpath "$domain" "$_isEcc"
  596. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  597. _info "CSR exists, skip"
  598. return
  599. fi
  600. if [ ! -f "$CERT_KEY_PATH" ] ; then
  601. _err "The key file is not found: $CERT_KEY_PATH"
  602. _err "Please create the key file first."
  603. return 1
  604. fi
  605. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  606. }
  607. _urlencode() {
  608. __n=$(cat)
  609. echo $__n | tr '/+' '_-' | tr -d '= '
  610. }
  611. _time2str() {
  612. #BSD
  613. if date -u -d@$1 2>/dev/null ; then
  614. return
  615. fi
  616. #Linux
  617. if date -u -r $1 2>/dev/null ; then
  618. return
  619. fi
  620. #Soaris
  621. if _exists adb ; then
  622. echo $(echo "0t${1}=Y" | adb)
  623. fi
  624. }
  625. _normalizeJson() {
  626. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  627. }
  628. _stat() {
  629. #Linux
  630. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  631. return
  632. fi
  633. #BSD
  634. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  635. return
  636. fi
  637. return 1; #error, 'stat' not found
  638. }
  639. #keyfile
  640. _calcjwk() {
  641. keyfile="$1"
  642. if [ -z "$keyfile" ] ; then
  643. _usage "Usage: _calcjwk keyfile"
  644. return 1
  645. fi
  646. EC_SIGN=""
  647. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  648. _debug "RSA key"
  649. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  650. if [ "${#pub_exp}" = "5" ] ; then
  651. pub_exp=0$pub_exp
  652. fi
  653. _debug3 pub_exp "$pub_exp"
  654. e=$(echo $pub_exp | _h2b | _base64)
  655. _debug3 e "$e"
  656. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  657. _debug3 modulus "$modulus"
  658. n="$(printf "%s" "$modulus"| _h2b | _base64 | _urlencode )"
  659. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  660. _debug3 jwk "$jwk"
  661. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  662. HEADERPLACE_PART1='{"nonce": "'
  663. HEADERPLACE_PART2='", "alg": "RS256", "jwk": '$jwk'}'
  664. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  665. _debug "EC key"
  666. EC_SIGN="1"
  667. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  668. _debug3 crv "$crv"
  669. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  670. pubi=$(_math $pubi + 1)
  671. _debug3 pubi "$pubi"
  672. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  673. pubj=$(_math $pubj + 1)
  674. _debug3 pubj "$pubj"
  675. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  676. _debug3 pubtext "$pubtext"
  677. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  678. xlen=$(_math $xlen / 4)
  679. _debug3 xlen "$xlen"
  680. xend=$(_math "$xend" + 1)
  681. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  682. _debug3 x "$x"
  683. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  684. _debug3 x64 "$x64"
  685. xend=$(_math "$xend" + 1)
  686. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  687. _debug3 y "$y"
  688. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  689. _debug3 y64 "$y64"
  690. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  691. _debug3 jwk "$jwk"
  692. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  693. HEADERPLACE_PART1='{"nonce": "'
  694. HEADERPLACE_PART2='", "alg": "ES256", "jwk": '$jwk'}'
  695. else
  696. _err "Only RSA or EC key is supported."
  697. return 1
  698. fi
  699. _debug3 HEADER "$HEADER"
  700. }
  701. _time() {
  702. date -u "+%s"
  703. }
  704. _mktemp() {
  705. if _exists mktemp ; then
  706. if mktemp 2>/dev/null ; then
  707. return
  708. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null ; then
  709. #for Mac osx
  710. return
  711. fi
  712. fi
  713. if [ -d "/tmp" ] ; then
  714. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  715. return 0
  716. fi
  717. _err "Can not create temp file."
  718. }
  719. _inithttp() {
  720. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER" ; then
  721. HTTP_HEADER="$(_mktemp)"
  722. _debug2 HTTP_HEADER "$HTTP_HEADER"
  723. fi
  724. if [ -z "$CURL" ] ; then
  725. CURL="curl -L --silent --dump-header $HTTP_HEADER "
  726. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  727. _CURL_DUMP="$(_mktemp)"
  728. CURL="$CURL --trace-ascii $_CURL_DUMP "
  729. fi
  730. if [ "$CA_BUNDLE" ] ; then
  731. CURL="$CURL --cacert $CA_BUNDLE "
  732. fi
  733. if [ "$HTTPS_INSECURE" ] ; then
  734. CURL="$CURL --insecure "
  735. fi
  736. fi
  737. if [ -z "$WGET" ] ; then
  738. WGET="wget -q"
  739. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  740. WGET="$WGET -d "
  741. fi
  742. if [ "$CA_BUNDLE" ] ; then
  743. WGET="$WGET --ca-certificate $CA_BUNDLE "
  744. fi
  745. if [ "$HTTPS_INSECURE" ] ; then
  746. WGET="$WGET --no-check-certificate "
  747. fi
  748. fi
  749. }
  750. # body url [needbase64] [POST|PUT]
  751. _post() {
  752. body="$1"
  753. url="$2"
  754. needbase64="$3"
  755. httpmethod="$4"
  756. if [ -z "$httpmethod" ] ; then
  757. httpmethod="POST"
  758. fi
  759. _debug $httpmethod
  760. _debug "url" "$url"
  761. _debug2 "body" "$body"
  762. _inithttp
  763. if _exists "curl" ; then
  764. _CURL="$CURL"
  765. _debug "_CURL" "$_CURL"
  766. if [ "$needbase64" ] ; then
  767. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" | _base64)"
  768. else
  769. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$url" )"
  770. fi
  771. _ret="$?"
  772. if [ "$_ret" != "0" ] ; then
  773. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  774. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  775. _err "Here is the curl dump log:"
  776. _err "$(cat "$_CURL_DUMP")"
  777. fi
  778. fi
  779. elif _exists "wget" ; then
  780. _debug "WGET" "$WGET"
  781. if [ "$needbase64" ] ; then
  782. if [ "$httpmethod"="POST" ] ; then
  783. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  784. else
  785. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER" | _base64)"
  786. fi
  787. else
  788. if [ "$httpmethod"="POST" ] ; then
  789. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$url" 2>"$HTTP_HEADER")"
  790. else
  791. response="$($WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$url" 2>"$HTTP_HEADER")"
  792. fi
  793. fi
  794. _ret="$?"
  795. if [ "$_ret" = "8" ] ; then
  796. _ret=0
  797. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  798. fi
  799. if [ "$_ret" != "0" ] ; then
  800. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  801. fi
  802. _sed_i "s/^ *//g" "$HTTP_HEADER"
  803. else
  804. _ret="$?"
  805. _err "Neither curl nor wget is found, can not do $httpmethod."
  806. fi
  807. _debug "_ret" "$_ret"
  808. printf "%s" "$response"
  809. return $_ret
  810. }
  811. # url getheader timeout
  812. _get() {
  813. _debug GET
  814. url="$1"
  815. onlyheader="$2"
  816. t="$3"
  817. _debug url $url
  818. _debug "timeout" "$t"
  819. _inithttp
  820. if _exists "curl" ; then
  821. _CURL="$CURL"
  822. if [ "$t" ] ; then
  823. _CURL="$_CURL --connect-timeout $t"
  824. fi
  825. _debug "_CURL" "$_CURL"
  826. if [ "$onlyheader" ] ; then
  827. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" $url
  828. else
  829. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" $url
  830. fi
  831. ret=$?
  832. if [ "$ret" != "0" ] ; then
  833. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  834. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  835. _err "Here is the curl dump log:"
  836. _err "$(cat "$_CURL_DUMP")"
  837. fi
  838. fi
  839. elif _exists "wget" ; then
  840. _WGET="$WGET"
  841. if [ "$t" ] ; then
  842. _WGET="$_WGET --timeout=$t"
  843. fi
  844. _debug "_WGET" "$_WGET"
  845. if [ "$onlyheader" ] ; then
  846. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  847. else
  848. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - $url
  849. fi
  850. ret=$?
  851. if [ "$_ret" = "8" ] ; then
  852. _ret=0
  853. _debug "wget returns 8, the server returns a 'Bad request' respons, lets process the response later."
  854. fi
  855. if [ "$ret" != "0" ] ; then
  856. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  857. fi
  858. else
  859. ret=$?
  860. _err "Neither curl nor wget is found, can not do GET."
  861. fi
  862. _debug "ret" "$ret"
  863. return $ret
  864. }
  865. _head_n() {
  866. head -n $1
  867. }
  868. _tail_n() {
  869. if ! tail -n $1 2>/dev/null ; then
  870. #fix for solaris
  871. tail -$1
  872. fi
  873. }
  874. # url payload needbase64 keyfile
  875. _send_signed_request() {
  876. url=$1
  877. payload=$2
  878. needbase64=$3
  879. keyfile=$4
  880. if [ -z "$keyfile" ] ; then
  881. keyfile="$ACCOUNT_KEY_PATH"
  882. fi
  883. _debug url $url
  884. _debug payload "$payload"
  885. if ! _calcjwk "$keyfile" ; then
  886. return 1
  887. fi
  888. payload64=$(printf "%s" "$payload" | _base64 | _urlencode)
  889. _debug3 payload64 $payload64
  890. nonceurl="$API/directory"
  891. _headers="$(_get $nonceurl "onlyheader")"
  892. if [ "$?" != "0" ] ; then
  893. _err "Can not connect to $nonceurl to get nonce."
  894. return 1
  895. fi
  896. _debug3 _headers "$_headers"
  897. nonce="$( echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  898. _debug3 nonce "$nonce"
  899. protected="$HEADERPLACE_PART1$nonce$HEADERPLACE_PART2"
  900. _debug3 protected "$protected"
  901. protected64="$(printf "$protected" | _base64 | _urlencode)"
  902. _debug3 protected64 "$protected64"
  903. sig=$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  904. _debug3 sig "$sig"
  905. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  906. _debug3 body "$body"
  907. response="$(_post "$body" $url "$needbase64")"
  908. if [ "$?" != "0" ] ; then
  909. _err "Can not post to $url"
  910. return 1
  911. fi
  912. _debug2 original "$response"
  913. response="$( echo "$response" | _normalizeJson )"
  914. responseHeaders="$(cat $HTTP_HEADER)"
  915. _debug2 responseHeaders "$responseHeaders"
  916. _debug2 response "$response"
  917. code="$(grep "^HTTP" $HTTP_HEADER | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n" )"
  918. _debug code $code
  919. }
  920. #setopt "file" "opt" "=" "value" [";"]
  921. _setopt() {
  922. __conf="$1"
  923. __opt="$2"
  924. __sep="$3"
  925. __val="$4"
  926. __end="$5"
  927. if [ -z "$__opt" ] ; then
  928. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  929. return
  930. fi
  931. if [ ! -f "$__conf" ] ; then
  932. touch "$__conf"
  933. fi
  934. if grep -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  935. _debug3 OK
  936. if _contains "$__val" "&" ; then
  937. __val="$(echo $__val | sed 's/&/\\&/g')"
  938. fi
  939. text="$(cat $__conf)"
  940. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  941. elif grep -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  942. if _contains "$__val" "&" ; then
  943. __val="$(echo $__val | sed 's/&/\\&/g')"
  944. fi
  945. text="$(cat $__conf)"
  946. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  947. else
  948. _debug3 APP
  949. echo "$__opt$__sep$__val$__end" >> "$__conf"
  950. fi
  951. _debug2 "$(grep -n "^$__opt$__sep" $__conf)"
  952. }
  953. #_savedomainconf key value
  954. #save to domain.conf
  955. _savedomainconf() {
  956. _sdkey="$1"
  957. _sdvalue="$2"
  958. if [ "$DOMAIN_CONF" ] ; then
  959. _setopt "$DOMAIN_CONF" "$_sdkey" "=" "\"$_sdvalue\""
  960. else
  961. _err "DOMAIN_CONF is empty, can not save $_sdkey=$_sdvalue"
  962. fi
  963. }
  964. #_cleardomainconf key
  965. _cleardomainconf() {
  966. _sdkey="$1"
  967. if [ "$DOMAIN_CONF" ] ; then
  968. _sed_i "s/^$_sdkey.*$//" "$DOMAIN_CONF"
  969. else
  970. _err "DOMAIN_CONF is empty, can not save $_sdkey=$value"
  971. fi
  972. }
  973. #_readdomainconf key
  974. _readdomainconf() {
  975. _sdkey="$1"
  976. if [ "$DOMAIN_CONF" ] ; then
  977. (
  978. eval $(grep "^$_sdkey *=" "$DOMAIN_CONF")
  979. eval "printf \"%s\" \"\$$_sdkey\""
  980. )
  981. else
  982. _err "DOMAIN_CONF is empty, can not read $_sdkey"
  983. fi
  984. }
  985. #_saveaccountconf key value
  986. _saveaccountconf() {
  987. _sckey="$1"
  988. _scvalue="$2"
  989. if [ "$ACCOUNT_CONF_PATH" ] ; then
  990. _setopt "$ACCOUNT_CONF_PATH" "$_sckey" "=" "\"$_scvalue\""
  991. else
  992. _err "ACCOUNT_CONF_PATH is empty, can not save $_sckey=$_scvalue"
  993. fi
  994. }
  995. #_clearaccountconf key
  996. _clearaccountconf() {
  997. _scvalue="$1"
  998. if [ "$ACCOUNT_CONF_PATH" ] ; then
  999. _sed_i "s/^$_scvalue.*$//" "$ACCOUNT_CONF_PATH"
  1000. else
  1001. _err "ACCOUNT_CONF_PATH is empty, can not clear $_scvalue"
  1002. fi
  1003. }
  1004. # content localaddress
  1005. _startserver() {
  1006. content="$1"
  1007. ncaddr="$2"
  1008. _debug "ncaddr" "$ncaddr"
  1009. _debug "startserver: $$"
  1010. nchelp="$(nc -h 2>&1)"
  1011. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  1012. _NC="nc -q 1 -l $ncaddr"
  1013. else
  1014. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  1015. _NC="nc -c -l $ncaddr"
  1016. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  1017. _NC="nc -N -l $ncaddr"
  1018. else
  1019. _NC="nc -l $ncaddr"
  1020. fi
  1021. fi
  1022. _debug Le_HTTPPort "$Le_HTTPPort"
  1023. _debug Le_Listen_V4 "$Le_Listen_V4"
  1024. _debug Le_Listen_V6 "$Le_Listen_V6"
  1025. if [ "$Le_Listen_V4" ] ; then
  1026. _NC="$_NC -4"
  1027. elif [ "$Le_Listen_V6" ] ; then
  1028. _NC="$_NC -6"
  1029. fi
  1030. _debug "_NC" "$_NC"
  1031. # while true ; do
  1032. if [ "$DEBUG" ] ; then
  1033. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort ; then
  1034. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort ;
  1035. fi
  1036. else
  1037. if ! printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1; then
  1038. printf "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1
  1039. fi
  1040. fi
  1041. if [ "$?" != "0" ] ; then
  1042. _err "nc listen error."
  1043. exit 1
  1044. fi
  1045. # done
  1046. }
  1047. _stopserver(){
  1048. pid="$1"
  1049. _debug "pid" "$pid"
  1050. if [ -z "$pid" ] ; then
  1051. return
  1052. fi
  1053. _debug2 "Le_HTTPPort" "$Le_HTTPPort"
  1054. if [ "$Le_HTTPPort" ] ; then
  1055. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ] ; then
  1056. _get "http://localhost:$Le_HTTPPort" "" 1
  1057. else
  1058. _get "http://localhost:$Le_HTTPPort" "" 1 >/dev/null 2>&1
  1059. fi
  1060. fi
  1061. _debug2 "Le_TLSPort" "$Le_TLSPort"
  1062. if [ "$Le_TLSPort" ] ; then
  1063. if [ "$DEBUG" ] && [ "$DEBUG" -gt "3" ] ; then
  1064. _get "https://localhost:$Le_TLSPort" "" 1
  1065. _get "https://localhost:$Le_TLSPort" "" 1
  1066. else
  1067. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1068. _get "https://localhost:$Le_TLSPort" "" 1 >/dev/null 2>&1
  1069. fi
  1070. fi
  1071. }
  1072. # sleep sec
  1073. _sleep() {
  1074. _sleep_sec="$1"
  1075. if [ "$__INTERACTIVE" ] ; then
  1076. _sleep_c="$_sleep_sec"
  1077. while [ "$_sleep_c" -ge "0" ] ;
  1078. do
  1079. printf "\r \r"
  1080. __green "$_sleep_c"
  1081. _sleep_c="$(_math $_sleep_c - 1)"
  1082. sleep 1
  1083. done
  1084. printf "\r"
  1085. else
  1086. sleep "$_sleep_sec"
  1087. fi
  1088. }
  1089. # _starttlsserver san_a san_b port content _ncaddr
  1090. _starttlsserver() {
  1091. _info "Starting tls server."
  1092. san_a="$1"
  1093. san_b="$2"
  1094. port="$3"
  1095. content="$4"
  1096. opaddr="$5"
  1097. _debug san_a "$san_a"
  1098. _debug san_b "$san_b"
  1099. _debug port "$port"
  1100. #create key TLS_KEY
  1101. if ! _createkey "2048" "$TLS_KEY" ; then
  1102. _err "Create tls validation key error."
  1103. return 1
  1104. fi
  1105. #create csr
  1106. alt="$san_a"
  1107. if [ "$san_b" ] ; then
  1108. alt="$alt,$san_b"
  1109. fi
  1110. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" ; then
  1111. _err "Create tls validation csr error."
  1112. return 1
  1113. fi
  1114. #self signed
  1115. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT" ; then
  1116. _err "Create tls validation cert error."
  1117. return 1
  1118. fi
  1119. __S_OPENSSL="openssl s_server -cert $TLS_CERT -key $TLS_KEY "
  1120. if [ "$opaddr" ] ; then
  1121. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1122. else
  1123. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1124. fi
  1125. _debug Le_Listen_V4 "$Le_Listen_V4"
  1126. _debug Le_Listen_V6 "$Le_Listen_V6"
  1127. if [ "$Le_Listen_V4" ] ; then
  1128. __S_OPENSSL="$__S_OPENSSL -4"
  1129. elif [ "$Le_Listen_V6" ] ; then
  1130. __S_OPENSSL="$__S_OPENSSL -6"
  1131. fi
  1132. #start openssl
  1133. _debug "$__S_OPENSSL"
  1134. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ] ; then
  1135. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | $__S_OPENSSL -tlsextdebug ) &
  1136. else
  1137. (printf "HTTP/1.1 200 OK\r\n\r\n$content" | $__S_OPENSSL >/dev/null 2>&1) &
  1138. fi
  1139. serverproc="$!"
  1140. sleep 2
  1141. _debug serverproc $serverproc
  1142. }
  1143. #file
  1144. _readlink() {
  1145. _rf="$1"
  1146. if ! readlink -f "$_rf" 2>/dev/null; then
  1147. if _startswith "$_rf" "\./$PROJECT_ENTRY" ; then
  1148. printf -- "%s" "$(pwd)/$PROJECT_ENTRY"
  1149. return 0
  1150. fi
  1151. readlink "$_rf"
  1152. fi
  1153. }
  1154. __initHome() {
  1155. if [ -z "$_SCRIPT_HOME" ] ; then
  1156. if _exists readlink && _exists dirname ; then
  1157. _debug "Lets guess script dir."
  1158. _debug "_SCRIPT_" "$_SCRIPT_"
  1159. _script="$(_readlink "$_SCRIPT_")"
  1160. _debug "_script" "$_script"
  1161. _script_home="$(dirname "$_script")"
  1162. _debug "_script_home" "$_script_home"
  1163. if [ -d "$_script_home" ] ; then
  1164. _SCRIPT_HOME="$_script_home"
  1165. else
  1166. _err "It seems the script home is not correct:$_script_home"
  1167. fi
  1168. fi
  1169. fi
  1170. if [ -z "$LE_WORKING_DIR" ] ; then
  1171. if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ] ; then
  1172. _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1173. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1174. else
  1175. LE_WORKING_DIR="$_SCRIPT_HOME"
  1176. fi
  1177. fi
  1178. if [ -z "$LE_WORKING_DIR" ] ; then
  1179. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1180. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1181. fi
  1182. export LE_WORKING_DIR
  1183. _DEFAULT_ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  1184. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  1185. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ] ; then
  1186. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1187. fi
  1188. fi
  1189. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  1190. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1191. fi
  1192. DEFAULT_LOG_FILE="$LE_WORKING_DIR/$PROJECT_NAME.log"
  1193. DEFAULT_CA_HOME="$LE_WORKING_DIR/ca"
  1194. }
  1195. #[domain] [keylength]
  1196. _initpath() {
  1197. __initHome
  1198. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  1199. . "$ACCOUNT_CONF_PATH"
  1200. fi
  1201. if [ "$IN_CRON" ] ; then
  1202. if [ ! "$_USER_PATH_EXPORTED" ] ; then
  1203. _USER_PATH_EXPORTED=1
  1204. export PATH="$USER_PATH:$PATH"
  1205. fi
  1206. fi
  1207. if [ -z "$CA_HOME" ] ; then
  1208. CA_HOME="$DEFAULT_CA_HOME"
  1209. fi
  1210. if [ -z "$API" ] ; then
  1211. if [ -z "$STAGE" ] ; then
  1212. API="$DEFAULT_CA"
  1213. else
  1214. API="$STAGE_CA"
  1215. _info "Using stage api:$API"
  1216. fi
  1217. fi
  1218. _API_HOST="$(echo "$API" | cut -d : -f 2 | tr -d '/')"
  1219. CA_DIR="$CA_HOME/$_API_HOST"
  1220. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  1221. if [ -z "$CA_CONF" ] ; then
  1222. CA_CONF="$_DEFAULT_CA_CONF"
  1223. fi
  1224. if [ -f "$CA_CONF" ] ; then
  1225. . "$CA_CONF"
  1226. fi
  1227. if [ -z "$ACME_DIR" ] ; then
  1228. ACME_DIR="/home/.acme"
  1229. fi
  1230. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  1231. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR"
  1232. fi
  1233. if [ -z "$USER_AGENT" ] ; then
  1234. USER_AGENT="$DEFAULT_USER_AGENT"
  1235. fi
  1236. if [ -z "$HTTP_HEADER" ] ; then
  1237. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  1238. fi
  1239. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  1240. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  1241. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  1242. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  1243. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  1244. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  1245. fi
  1246. if [ -z "$ACCOUNT_JSON_PATH" ] ; then
  1247. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  1248. fi
  1249. _DEFAULT_CERT_HOME="$LE_WORKING_DIR"
  1250. if [ -z "$CERT_HOME" ] ; then
  1251. CERT_HOME="$_DEFAULT_CERT_HOME"
  1252. fi
  1253. if [ -z "$1" ] ; then
  1254. return 0
  1255. fi
  1256. mkdir -p "$CA_DIR"
  1257. domain="$1"
  1258. _ilength="$2"
  1259. if [ -z "$DOMAIN_PATH" ] ; then
  1260. domainhome="$CERT_HOME/$domain"
  1261. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  1262. DOMAIN_PATH="$domainhome"
  1263. if _isEccKey "$_ilength" ; then
  1264. DOMAIN_PATH="$domainhomeecc"
  1265. else
  1266. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ] ; then
  1267. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  1268. fi
  1269. fi
  1270. _debug DOMAIN_PATH "$DOMAIN_PATH"
  1271. fi
  1272. if [ ! -d "$DOMAIN_PATH" ] ; then
  1273. if ! mkdir -p "$DOMAIN_PATH" ; then
  1274. _err "Can not create domain path: $DOMAIN_PATH"
  1275. return 1
  1276. fi
  1277. fi
  1278. if [ -z "$DOMAIN_CONF" ] ; then
  1279. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  1280. fi
  1281. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  1282. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  1283. fi
  1284. if [ -z "$CSR_PATH" ] ; then
  1285. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  1286. fi
  1287. if [ -z "$CERT_KEY_PATH" ] ; then
  1288. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  1289. fi
  1290. if [ -z "$CERT_PATH" ] ; then
  1291. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  1292. fi
  1293. if [ -z "$CA_CERT_PATH" ] ; then
  1294. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  1295. fi
  1296. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  1297. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  1298. fi
  1299. if [ -z "$CERT_PFX_PATH" ] ; then
  1300. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  1301. fi
  1302. if [ -z "$TLS_CONF" ] ; then
  1303. TLS_CONF="$DOMAIN_PATH/tls.valdation.conf"
  1304. fi
  1305. if [ -z "$TLS_CERT" ] ; then
  1306. TLS_CERT="$DOMAIN_PATH/tls.valdation.cert"
  1307. fi
  1308. if [ -z "$TLS_KEY" ] ; then
  1309. TLS_KEY="$DOMAIN_PATH/tls.valdation.key"
  1310. fi
  1311. if [ -z "$TLS_CSR" ] ; then
  1312. TLS_CSR="$DOMAIN_PATH/tls.valdation.csr"
  1313. fi
  1314. }
  1315. _apachePath() {
  1316. _APACHECTL="apachectl"
  1317. if ! _exists apachectl ; then
  1318. if _exists apache2ctl ; then
  1319. _APACHECTL="apache2ctl"
  1320. else
  1321. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  1322. _err "Please use webroot mode to try again."
  1323. return 1
  1324. fi
  1325. fi
  1326. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  1327. _debug httpdconfname "$httpdconfname"
  1328. if _startswith "$httpdconfname" '/' ; then
  1329. httpdconf="$httpdconfname"
  1330. httpdconfname="$(basename $httpdconfname)"
  1331. else
  1332. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  1333. _debug httpdroot "$httpdroot"
  1334. httpdconf="$httpdroot/$httpdconfname"
  1335. httpdconfname="$(basename $httpdconfname)"
  1336. fi
  1337. _debug httpdconf "$httpdconf"
  1338. _debug httpdconfname "$httpdconfname"
  1339. if [ ! -f "$httpdconf" ] ; then
  1340. _err "Apache Config file not found" "$httpdconf"
  1341. return 1
  1342. fi
  1343. return 0
  1344. }
  1345. _restoreApache() {
  1346. if [ -z "$usingApache" ] ; then
  1347. return 0
  1348. fi
  1349. _initpath
  1350. if ! _apachePath ; then
  1351. return 1
  1352. fi
  1353. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  1354. _debug "No config file to restore."
  1355. return 0
  1356. fi
  1357. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" > "$httpdconf"
  1358. _debug "Restored: $httpdconf."
  1359. if ! $_APACHECTL -t >/dev/null 2>&1 ; then
  1360. _err "Sorry, restore apache config error, please contact me."
  1361. return 1;
  1362. fi
  1363. _debug "Restored successfully."
  1364. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1365. return 0
  1366. }
  1367. _setApache() {
  1368. _initpath
  1369. if ! _apachePath ; then
  1370. return 1
  1371. fi
  1372. #test the conf first
  1373. _info "Checking if there is an error in the apache config file before starting."
  1374. _msg="$($_APACHECTL -t 2>&1 )"
  1375. if [ "$?" != "0" ] ; then
  1376. _err "Sorry, apache config file has error, please fix it first, then try again."
  1377. _err "Don't worry, there is nothing changed to your system."
  1378. _err "$_msg"
  1379. return 1;
  1380. else
  1381. _info "OK"
  1382. fi
  1383. #backup the conf
  1384. _debug "Backup apache config file" "$httpdconf"
  1385. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/" ; then
  1386. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  1387. _err "This might be a bug of $PROJECT_NAME , pleae report issue: $PROJECT"
  1388. return 1
  1389. fi
  1390. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  1391. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  1392. _info "The backup file will be deleted on sucess, just forget it."
  1393. #add alias
  1394. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2 )"
  1395. _debug "apacheVer" "$apacheVer"
  1396. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  1397. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  1398. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ] ; then
  1399. echo "
  1400. Alias /.well-known/acme-challenge $ACME_DIR
  1401. <Directory $ACME_DIR >
  1402. Require all granted
  1403. </Directory>
  1404. " >> "$httpdconf"
  1405. else
  1406. echo "
  1407. Alias /.well-known/acme-challenge $ACME_DIR
  1408. <Directory $ACME_DIR >
  1409. Order allow,deny
  1410. Allow from all
  1411. </Directory>
  1412. " >> "$httpdconf"
  1413. fi
  1414. _msg="$($_APACHECTL -t 2>&1 )"
  1415. if [ "$?" != "0" ] ; then
  1416. _err "Sorry, apache config error"
  1417. if _restoreApache ; then
  1418. _err "The apache config file is restored."
  1419. else
  1420. _err "Sorry, The apache config file can not be restored, please report bug."
  1421. fi
  1422. return 1;
  1423. fi
  1424. if [ ! -d "$ACME_DIR" ] ; then
  1425. mkdir -p "$ACME_DIR"
  1426. chmod 755 "$ACME_DIR"
  1427. fi
  1428. if ! $_APACHECTL graceful ; then
  1429. _err "Sorry, $_APACHECTL graceful error, please contact me."
  1430. _restoreApache
  1431. return 1;
  1432. fi
  1433. usingApache="1"
  1434. return 0
  1435. }
  1436. _clearup() {
  1437. _stopserver $serverproc
  1438. serverproc=""
  1439. _restoreApache
  1440. if [ -z "$DEBUG" ] ; then
  1441. rm -f "$TLS_CONF"
  1442. rm -f "$TLS_CERT"
  1443. rm -f "$TLS_KEY"
  1444. rm -f "$TLS_CSR"
  1445. fi
  1446. }
  1447. # webroot removelevel tokenfile
  1448. _clearupwebbroot() {
  1449. __webroot="$1"
  1450. if [ -z "$__webroot" ] ; then
  1451. _debug "no webroot specified, skip"
  1452. return 0
  1453. fi
  1454. _rmpath=""
  1455. if [ "$2" = '1' ] ; then
  1456. _rmpath="$__webroot/.well-known"
  1457. elif [ "$2" = '2' ] ; then
  1458. _rmpath="$__webroot/.well-known/acme-challenge"
  1459. elif [ "$2" = '3' ] ; then
  1460. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  1461. else
  1462. _debug "Skip for removelevel:$2"
  1463. fi
  1464. if [ "$_rmpath" ] ; then
  1465. if [ "$DEBUG" ] ; then
  1466. _debug "Debugging, skip removing: $_rmpath"
  1467. else
  1468. rm -rf "$_rmpath"
  1469. fi
  1470. fi
  1471. return 0
  1472. }
  1473. _on_before_issue() {
  1474. _debug _on_before_issue
  1475. if _hasfield "$Le_Webroot" "$NO_VALUE" ; then
  1476. if ! _exists "nc" ; then
  1477. _err "Please install netcat(nc) tools first."
  1478. return 1
  1479. fi
  1480. elif ! _hasfield "$Le_Webroot" "$W_TLS" ; then
  1481. #no need to check anymore
  1482. return 0
  1483. fi
  1484. _debug Le_LocalAddress "$Le_LocalAddress"
  1485. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  1486. _index=1
  1487. _currentRoot=""
  1488. _addrIndex=1
  1489. for d in $alldomains
  1490. do
  1491. _debug "Check for domain" $d
  1492. _currentRoot="$(_getfield "$Le_Webroot" $_index)"
  1493. _debug "_currentRoot" "$_currentRoot"
  1494. _index=$(_math $_index + 1)
  1495. _checkport=""
  1496. if [ "$_currentRoot" = "$NO_VALUE" ] ; then
  1497. _info "Standalone mode."
  1498. if [ -z "$Le_HTTPPort" ] ; then
  1499. Le_HTTPPort=80
  1500. else
  1501. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  1502. fi
  1503. _checkport="$Le_HTTPPort"
  1504. elif [ "$_currentRoot" = "$W_TLS" ] ; then
  1505. _info "Standalone tls mode."
  1506. if [ -z "$Le_TLSPort" ] ; then
  1507. Le_TLSPort=443
  1508. else
  1509. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  1510. fi
  1511. _checkport="$Le_TLSPort"
  1512. fi
  1513. if [ "$_checkport" ] ; then
  1514. _debug _checkport "$_checkport"
  1515. _checkaddr="$(_getfield "$Le_LocalAddress" $_addrIndex)"
  1516. _debug _checkaddr "$_checkaddr"
  1517. _addrIndex="$(_math $_addrIndex + 1)"
  1518. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  1519. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  1520. if [ -z "$netprc" ] ; then
  1521. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  1522. fi
  1523. if [ "$netprc" ] ; then
  1524. _err "$netprc"
  1525. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  1526. _err "Please stop it first"
  1527. return 1
  1528. fi
  1529. fi
  1530. done
  1531. if _hasfield "$Le_Webroot" "apache" ; then
  1532. if ! _setApache ; then
  1533. _err "set up apache error. Report error to me."
  1534. return 1
  1535. fi
  1536. else
  1537. usingApache=""
  1538. fi
  1539. #run pre hook
  1540. if [ "$Le_PreHook" ] ; then
  1541. _info "Run pre hook:'$Le_PreHook'"
  1542. if ! (
  1543. cd "$DOMAIN_PATH" && eval "$Le_PreHook"
  1544. ) ; then
  1545. _err "Error when run pre hook."
  1546. return 1
  1547. fi
  1548. fi
  1549. }
  1550. _on_issue_err() {
  1551. _debug _on_issue_err
  1552. if [ "$LOG_FILE" ] ; then
  1553. _err "Please check log file for more details: $LOG_FILE"
  1554. else
  1555. _err "Please use add '--debug' or '--log' to check more details."
  1556. _err "See: $_DEBUG_WIKI"
  1557. fi
  1558. #run the post hook
  1559. if [ "$Le_PostHook" ] ; then
  1560. _info "Run post hook:'$Le_PostHook'"
  1561. if ! (
  1562. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1563. ) ; then
  1564. _err "Error when run post hook."
  1565. return 1
  1566. fi
  1567. fi
  1568. }
  1569. _on_issue_success() {
  1570. _debug _on_issue_success
  1571. #run the post hook
  1572. if [ "$Le_PostHook" ] ; then
  1573. _info "Run post hook:'$Le_PostHook'"
  1574. if ! (
  1575. cd "$DOMAIN_PATH" && eval "$Le_PostHook"
  1576. ) ; then
  1577. _err "Error when run post hook."
  1578. return 1
  1579. fi
  1580. fi
  1581. #run renew hook
  1582. if [ "$IS_RENEW" ] && [ "$Le_RenewHook" ] ; then
  1583. _info "Run renew hook:'$Le_RenewHook'"
  1584. if ! (
  1585. cd "$DOMAIN_PATH" && eval "$Le_RenewHook"
  1586. ) ; then
  1587. _err "Error when run renew hook."
  1588. return 1
  1589. fi
  1590. fi
  1591. }
  1592. updateaccount() {
  1593. _initpath
  1594. _regAccount
  1595. }
  1596. registeraccount() {
  1597. _initpath
  1598. _regAccount
  1599. }
  1600. _regAccount() {
  1601. _initpath
  1602. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  1603. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  1604. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  1605. fi
  1606. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  1607. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  1608. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  1609. fi
  1610. if [ ! -f "$ACCOUNT_KEY_PATH" ] ; then
  1611. _acck="no"
  1612. if [ "$Le_Keylength" ] ; then
  1613. _acck="$Le_Keylength"
  1614. fi
  1615. if ! createAccountKey "$_acck" ; then
  1616. _err "Create account key error."
  1617. return 1
  1618. fi
  1619. fi
  1620. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  1621. return 1
  1622. fi
  1623. _updateTos=""
  1624. _reg_res="new-reg"
  1625. while true ;
  1626. do
  1627. _debug AGREEMENT "$AGREEMENT"
  1628. accountkey_json=$(printf "%s" "$jwk" | tr -d ' ' )
  1629. thumbprint=$(printf "%s" "$accountkey_json" | _digest "sha256" | _urlencode)
  1630. regjson='{"resource": "'$_reg_res'", "agreement": "'$AGREEMENT'"}'
  1631. if [ "$ACCOUNT_EMAIL" ] ; then
  1632. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  1633. fi
  1634. if [ -z "$_updateTos" ] ; then
  1635. _info "Registering account"
  1636. if ! _send_signed_request "$API/acme/new-reg" "$regjson" ; then
  1637. _err "Register account Error: $response"
  1638. return 1
  1639. fi
  1640. if [ "$code" = "" ] || [ "$code" = '201' ] ; then
  1641. echo "$response" > $ACCOUNT_JSON_PATH
  1642. _info "Registered"
  1643. elif [ "$code" = '409' ] ; then
  1644. _info "Already registered"
  1645. else
  1646. _err "Register account Error: $response"
  1647. return 1
  1648. fi
  1649. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2| tr -d "\r\n")"
  1650. _debug "_accUri" "$_accUri"
  1651. _tos="$(echo "$responseHeaders" | grep "^Link:.*rel=\"terms-of-service\"" | _head_n 1 | _egrep_o "<.*>" | tr -d '<>')"
  1652. _debug "_tos" "$_tos"
  1653. if [ -z "$_tos" ] ; then
  1654. _debug "Use default tos: $DEFAULT_AGREEMENT"
  1655. _tos="$DEFAULT_AGREEMENT"
  1656. fi
  1657. if [ "$_tos" != "$AGREEMENT" ]; then
  1658. _updateTos=1
  1659. AGREEMENT="$_tos"
  1660. _reg_res="reg"
  1661. continue
  1662. fi
  1663. else
  1664. _debug "Update tos: $_tos"
  1665. if ! _send_signed_request "$_accUri" "$regjson" ; then
  1666. _err "Update tos error."
  1667. return 1
  1668. fi
  1669. if [ "$code" = '202' ] ; then
  1670. _info "Update success."
  1671. else
  1672. _err "Update error."
  1673. return 1
  1674. fi
  1675. fi
  1676. return 0
  1677. done
  1678. }
  1679. #webroot, domain domainlist keylength
  1680. issue() {
  1681. if [ -z "$2" ] ; then
  1682. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  1683. return 1
  1684. fi
  1685. Le_Webroot="$1"
  1686. Le_Domain="$2"
  1687. Le_Alt="$3"
  1688. Le_Keylength="$4"
  1689. Le_RealCertPath="$5"
  1690. Le_RealKeyPath="$6"
  1691. Le_RealCACertPath="$7"
  1692. Le_ReloadCmd="$8"
  1693. Le_RealFullChainPath="$9"
  1694. Le_PreHook="${10}"
  1695. Le_PostHook="${11}"
  1696. Le_RenewHook="${12}"
  1697. Le_LocalAddress="${13}"
  1698. #remove these later.
  1699. if [ "$Le_Webroot" = "dns-cf" ] ; then
  1700. Le_Webroot="dns_cf"
  1701. fi
  1702. if [ "$Le_Webroot" = "dns-dp" ] ; then
  1703. Le_Webroot="dns_dp"
  1704. fi
  1705. if [ "$Le_Webroot" = "dns-cx" ] ; then
  1706. Le_Webroot="dns_cx"
  1707. fi
  1708. _debug "Using api: $API"
  1709. if [ ! "$IS_RENEW" ] ; then
  1710. _initpath $Le_Domain "$Le_Keylength"
  1711. mkdir -p "$DOMAIN_PATH"
  1712. fi
  1713. if [ -f "$DOMAIN_CONF" ] ; then
  1714. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  1715. _debug Le_NextRenewTime "$Le_NextRenewTime"
  1716. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ $(_time) -lt $Le_NextRenewTime ] ; then
  1717. _saved_domain=$(_readdomainconf Le_Domain)
  1718. _debug _saved_domain "$_saved_domain"
  1719. _saved_alt=$(_readdomainconf Le_Alt)
  1720. _debug _saved_alt "$_saved_alt"
  1721. if [ "$_saved_domain,$_saved_alt" = "$Le_Domain,$Le_Alt" ] ; then
  1722. _info "Domains not changed."
  1723. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  1724. _info "Add '$(__red '--force')' to force to renew."
  1725. return $RENEW_SKIP
  1726. else
  1727. _info "Domains have changed."
  1728. fi
  1729. fi
  1730. fi
  1731. _savedomainconf "Le_Domain" "$Le_Domain"
  1732. _savedomainconf "Le_Alt" "$Le_Alt"
  1733. _savedomainconf "Le_Webroot" "$Le_Webroot"
  1734. _savedomainconf "Le_PreHook" "$Le_PreHook"
  1735. _savedomainconf "Le_PostHook" "$Le_PostHook"
  1736. _savedomainconf "Le_RenewHook" "$Le_RenewHook"
  1737. _savedomainconf "Le_LocalAddress" "$Le_LocalAddress"
  1738. Le_API="$API"
  1739. _savedomainconf "Le_API" "$Le_API"
  1740. if [ "$Le_Alt" = "$NO_VALUE" ] ; then
  1741. Le_Alt=""
  1742. fi
  1743. if [ "$Le_Keylength" = "$NO_VALUE" ] ; then
  1744. Le_Keylength=""
  1745. fi
  1746. if ! _on_before_issue ; then
  1747. _err "_on_before_issue."
  1748. return 1
  1749. fi
  1750. if ! _regAccount ; then
  1751. _on_issue_err
  1752. return 1
  1753. fi
  1754. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ] ; then
  1755. _info "Signing from existing CSR."
  1756. else
  1757. _key=$(_readdomainconf Le_Keylength)
  1758. _debug "Read key length:$_key"
  1759. if [ ! -f "$CERT_KEY_PATH" ] || [ "$Le_Keylength" != "$_key" ] ; then
  1760. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  1761. _err "Create domain key error."
  1762. _clearup
  1763. _on_issue_err
  1764. return 1
  1765. fi
  1766. fi
  1767. if ! _createcsr "$Le_Domain" "$Le_Alt" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF" ; then
  1768. _err "Create CSR error."
  1769. _clearup
  1770. _on_issue_err
  1771. return 1
  1772. fi
  1773. fi
  1774. _savedomainconf "Le_Keylength" "$Le_Keylength"
  1775. vlist="$Le_Vlist"
  1776. # verify each domain
  1777. _info "Verify each domain"
  1778. sep='#'
  1779. if [ -z "$vlist" ] ; then
  1780. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  1781. _index=1
  1782. _currentRoot=""
  1783. for d in $alldomains
  1784. do
  1785. _info "Getting webroot for domain" $d
  1786. _w="$(echo $Le_Webroot | cut -d , -f $_index)"
  1787. _info _w "$_w"
  1788. if [ "$_w" ] ; then
  1789. _currentRoot="$_w"
  1790. fi
  1791. _debug "_currentRoot" "$_currentRoot"
  1792. _index=$(_math $_index + 1)
  1793. vtype="$VTYPE_HTTP"
  1794. if _startswith "$_currentRoot" "dns" ; then
  1795. vtype="$VTYPE_DNS"
  1796. fi
  1797. if [ "$_currentRoot" = "$W_TLS" ] ; then
  1798. vtype="$VTYPE_TLS"
  1799. fi
  1800. _info "Getting new-authz for domain" $d
  1801. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}" ; then
  1802. _err "Can not get domain token."
  1803. _clearup
  1804. _on_issue_err
  1805. return 1
  1806. fi
  1807. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  1808. _err "new-authz error: $response"
  1809. _clearup
  1810. _on_issue_err
  1811. return 1
  1812. fi
  1813. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  1814. _debug entry "$entry"
  1815. if [ -z "$entry" ] ; then
  1816. _err "Error, can not get domain token $d"
  1817. _clearup
  1818. _on_issue_err
  1819. return 1
  1820. fi
  1821. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  1822. _debug token $token
  1823. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  1824. _debug uri $uri
  1825. keyauthorization="$token.$thumbprint"
  1826. _debug keyauthorization "$keyauthorization"
  1827. if printf "$response" | grep '"status":"valid"' >/dev/null 2>&1 ; then
  1828. _info "$d is already verified, skip."
  1829. keyauthorization=$STATE_VERIFIED
  1830. _debug keyauthorization "$keyauthorization"
  1831. fi
  1832. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  1833. _debug dvlist "$dvlist"
  1834. vlist="$vlist$dvlist,"
  1835. done
  1836. #add entry
  1837. dnsadded=""
  1838. ventries=$(echo "$vlist" | tr ',' ' ' )
  1839. for ventry in $ventries
  1840. do
  1841. d=$(echo $ventry | cut -d $sep -f 1)
  1842. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1843. vtype=$(echo $ventry | cut -d $sep -f 4)
  1844. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1845. if [ "$keyauthorization" = "$STATE_VERIFIED" ] ; then
  1846. _info "$d is already verified, skip $vtype."
  1847. continue
  1848. fi
  1849. if [ "$vtype" = "$VTYPE_DNS" ] ; then
  1850. dnsadded='0'
  1851. txtdomain="_acme-challenge.$d"
  1852. _debug txtdomain "$txtdomain"
  1853. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _urlencode)"
  1854. _debug txt "$txt"
  1855. #dns
  1856. #1. check use api
  1857. d_api=""
  1858. if [ -f "$LE_WORKING_DIR/$d/$_currentRoot" ] ; then
  1859. d_api="$LE_WORKING_DIR/$d/$_currentRoot"
  1860. elif [ -f "$LE_WORKING_DIR/$d/$_currentRoot.sh" ] ; then
  1861. d_api="$LE_WORKING_DIR/$d/$_currentRoot.sh"
  1862. elif [ -f "$LE_WORKING_DIR/$_currentRoot" ] ; then
  1863. d_api="$LE_WORKING_DIR/$_currentRoot"
  1864. elif [ -f "$LE_WORKING_DIR/$_currentRoot.sh" ] ; then
  1865. d_api="$LE_WORKING_DIR/$_currentRoot.sh"
  1866. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot" ] ; then
  1867. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot"
  1868. elif [ -f "$LE_WORKING_DIR/dnsapi/$_currentRoot.sh" ] ; then
  1869. d_api="$LE_WORKING_DIR/dnsapi/$_currentRoot.sh"
  1870. fi
  1871. _debug d_api "$d_api"
  1872. if [ "$d_api" ] ; then
  1873. _info "Found domain api file: $d_api"
  1874. else
  1875. _err "Add the following TXT record:"
  1876. _err "Domain: '$(__green $txtdomain)'"
  1877. _err "TXT value: '$(__green $txt)'"
  1878. _err "Please be aware that you prepend _acme-challenge. before your domain"
  1879. _err "so the resulting subdomain will be: $txtdomain"
  1880. continue
  1881. fi
  1882. (
  1883. if ! . $d_api ; then
  1884. _err "Load file $d_api error. Please check your api file and try again."
  1885. return 1
  1886. fi
  1887. addcommand="${_currentRoot}_add"
  1888. if ! _exists $addcommand ; then
  1889. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  1890. return 1
  1891. fi
  1892. if ! $addcommand $txtdomain $txt ; then
  1893. _err "Error add txt for domain:$txtdomain"
  1894. return 1
  1895. fi
  1896. )
  1897. if [ "$?" != "0" ] ; then
  1898. _clearup
  1899. _on_issue_err
  1900. return 1
  1901. fi
  1902. dnsadded='1'
  1903. fi
  1904. done
  1905. if [ "$dnsadded" = '0' ] ; then
  1906. _savedomainconf "Le_Vlist" "$vlist"
  1907. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  1908. _err "Please add the TXT records to the domains, and retry again."
  1909. _clearup
  1910. _on_issue_err
  1911. return 1
  1912. fi
  1913. fi
  1914. if [ "$dnsadded" = '1' ] ; then
  1915. if [ -z "$Le_DNSSleep" ] ; then
  1916. Le_DNSSleep=$DEFAULT_DNS_SLEEP
  1917. else
  1918. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  1919. fi
  1920. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  1921. _sleep $Le_DNSSleep
  1922. fi
  1923. _debug "ok, let's start to verify"
  1924. _ncIndex=1
  1925. ventries=$(echo "$vlist" | tr ',' ' ' )
  1926. for ventry in $ventries
  1927. do
  1928. d=$(echo $ventry | cut -d $sep -f 1)
  1929. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  1930. uri=$(echo $ventry | cut -d $sep -f 3)
  1931. vtype=$(echo $ventry | cut -d $sep -f 4)
  1932. _currentRoot=$(echo $ventry | cut -d $sep -f 5)
  1933. if [ "$keyauthorization" = "$STATE_VERIFIED" ] ; then
  1934. _info "$d is already verified, skip $vtype."
  1935. continue
  1936. fi
  1937. _info "Verifying:$d"
  1938. _debug "d" "$d"
  1939. _debug "keyauthorization" "$keyauthorization"
  1940. _debug "uri" "$uri"
  1941. removelevel=""
  1942. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  1943. _debug "_currentRoot" "$_currentRoot"
  1944. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  1945. if [ "$_currentRoot" = "$NO_VALUE" ] ; then
  1946. _info "Standalone mode server"
  1947. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex" )"
  1948. _ncIndex="$(_math $_ncIndex + 1)"
  1949. _startserver "$keyauthorization" "$_ncaddr" &
  1950. if [ "$?" != "0" ] ; then
  1951. _clearup
  1952. _on_issue_err
  1953. return 1
  1954. fi
  1955. serverproc="$!"
  1956. sleep 2
  1957. _debug serverproc $serverproc
  1958. else
  1959. if [ "$_currentRoot" = "apache" ] ; then
  1960. wellknown_path="$ACME_DIR"
  1961. else
  1962. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  1963. if [ ! -d "$_currentRoot/.well-known" ] ; then
  1964. removelevel='1'
  1965. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ] ; then
  1966. removelevel='2'
  1967. else
  1968. removelevel='3'
  1969. fi
  1970. fi
  1971. _debug wellknown_path "$wellknown_path"
  1972. _debug "writing token:$token to $wellknown_path/$token"
  1973. mkdir -p "$wellknown_path"
  1974. printf "%s" "$keyauthorization" > "$wellknown_path/$token"
  1975. if [ ! "$usingApache" ] ; then
  1976. if webroot_owner=$(_stat $_currentRoot) ; then
  1977. _debug "Changing owner/group of .well-known to $webroot_owner"
  1978. chown -R $webroot_owner "$_currentRoot/.well-known"
  1979. else
  1980. _debug "not chaning owner/group of webroot";
  1981. fi
  1982. fi
  1983. fi
  1984. elif [ "$vtype" = "$VTYPE_TLS" ] ; then
  1985. #create A
  1986. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  1987. #_debug2 _hash_A "$_hash_A"
  1988. #_x="$(echo $_hash_A | cut -c 1-32)"
  1989. #_debug2 _x "$_x"
  1990. #_y="$(echo $_hash_A | cut -c 33-64)"
  1991. #_debug2 _y "$_y"
  1992. #_SAN_A="$_x.$_y.token.acme.invalid"
  1993. #_debug2 _SAN_A "$_SAN_A"
  1994. #create B
  1995. _hash_B="$(printf "%s" $keyauthorization | _digest "sha256" "hex" )"
  1996. _debug2 _hash_B "$_hash_B"
  1997. _x="$(echo $_hash_B | cut -c 1-32)"
  1998. _debug2 _x "$_x"
  1999. _y="$(echo $_hash_B | cut -c 33-64)"
  2000. _debug2 _y "$_y"
  2001. #_SAN_B="$_x.$_y.ka.acme.invalid"
  2002. _SAN_B="$_x.$_y.acme.invalid"
  2003. _debug2 _SAN_B "$_SAN_B"
  2004. _ncaddr="$(_getfield "$Le_LocalAddress" "$_ncIndex" )"
  2005. _ncIndex="$(_math $_ncIndex + 1)"
  2006. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  2007. _err "Start tls server error."
  2008. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2009. _clearup
  2010. _on_issue_err
  2011. return 1
  2012. fi
  2013. fi
  2014. if ! _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}" ; then
  2015. _err "$d:Can not get challenge: $response"
  2016. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2017. _clearup
  2018. _on_issue_err
  2019. return 1
  2020. fi
  2021. if [ ! -z "$code" ] && [ ! "$code" = '202' ] ; then
  2022. _err "$d:Challenge error: $response"
  2023. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2024. _clearup
  2025. _on_issue_err
  2026. return 1
  2027. fi
  2028. waittimes=0
  2029. if [ -z "$MAX_RETRY_TIMES" ] ; then
  2030. MAX_RETRY_TIMES=30
  2031. fi
  2032. while true ; do
  2033. waittimes=$(_math $waittimes + 1)
  2034. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ] ; then
  2035. _err "$d:Timeout"
  2036. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2037. _clearup
  2038. _on_issue_err
  2039. return 1
  2040. fi
  2041. _debug "sleep 5 secs to verify"
  2042. sleep 5
  2043. _debug "checking"
  2044. response="$(_get $uri)"
  2045. if [ "$?" != "0" ] ; then
  2046. _err "$d:Verify error:$response"
  2047. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2048. _clearup
  2049. _on_issue_err
  2050. return 1
  2051. fi
  2052. _debug2 original "$response"
  2053. response="$(echo "$response" | _normalizeJson )"
  2054. _debug2 response "$response"
  2055. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  2056. if [ "$status" = "valid" ] ; then
  2057. _info "Success"
  2058. _stopserver $serverproc
  2059. serverproc=""
  2060. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2061. break;
  2062. fi
  2063. if [ "$status" = "invalid" ] ; then
  2064. error="$(echo "$response" | _egrep_o '"error":\{[^\}]*\}')"
  2065. _debug2 error "$error"
  2066. errordetail="$(echo $error | _egrep_o '"detail": *"[^"]*"' | cut -d '"' -f 4)"
  2067. _debug2 errordetail "$errordetail"
  2068. if [ "$errordetail" ] ; then
  2069. _err "$d:Verify error:$errordetail"
  2070. else
  2071. _err "$d:Verify error:$error"
  2072. fi
  2073. if [ "$DEBUG" ] ; then
  2074. if [ "$vtype" = "$VTYPE_HTTP" ] ; then
  2075. _debug "Debug: get token url."
  2076. _get "http://$d/.well-known/acme-challenge/$token"
  2077. fi
  2078. fi
  2079. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2080. _clearup
  2081. _on_issue_err
  2082. return 1;
  2083. fi
  2084. if [ "$status" = "pending" ] ; then
  2085. _info "Pending"
  2086. else
  2087. _err "$d:Verify error:$response"
  2088. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  2089. _clearup
  2090. _on_issue_err
  2091. return 1
  2092. fi
  2093. done
  2094. done
  2095. _clearup
  2096. _info "Verify finished, start to sign."
  2097. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  2098. if ! _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64" ; then
  2099. _err "Sign failed."
  2100. _on_issue_err
  2101. return 1
  2102. fi
  2103. _rcert="$response"
  2104. Le_LinkCert="$(grep -i '^Location.*$' $HTTP_HEADER | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  2105. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  2106. if [ "$Le_LinkCert" ] ; then
  2107. echo "$BEGIN_CERT" > "$CERT_PATH"
  2108. if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  2109. _debug "Get cert failed. Let's try last response."
  2110. printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  2111. fi
  2112. echo "$END_CERT" >> "$CERT_PATH"
  2113. _info "$(__green "Cert success.")"
  2114. cat "$CERT_PATH"
  2115. _info "Your cert is in $( __green " $CERT_PATH ")"
  2116. if [ -f "$CERT_KEY_PATH" ] ; then
  2117. _info "Your cert key is in $( __green " $CERT_KEY_PATH ")"
  2118. fi
  2119. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  2120. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ] ; then
  2121. USER_PATH="$PATH"
  2122. _saveaccountconf "USER_PATH" "$USER_PATH"
  2123. fi
  2124. fi
  2125. if [ -z "$Le_LinkCert" ] ; then
  2126. response="$(echo $response | _dbase64 "multiline" | _normalizeJson )"
  2127. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  2128. _on_issue_err
  2129. return 1
  2130. fi
  2131. _cleardomainconf "Le_Vlist"
  2132. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | _head_n 1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  2133. if ! _contains "$Le_LinkIssuer" ":" ; then
  2134. Le_LinkIssuer="$API$Le_LinkIssuer"
  2135. fi
  2136. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  2137. if [ "$Le_LinkIssuer" ] ; then
  2138. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  2139. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  2140. echo "$END_CERT" >> "$CA_CERT_PATH"
  2141. _info "The intermediate CA cert is in $( __green " $CA_CERT_PATH ")"
  2142. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  2143. _info "And the full chain certs is there: $( __green " $CERT_FULLCHAIN_PATH ")"
  2144. fi
  2145. Le_CertCreateTime=$(_time)
  2146. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  2147. Le_CertCreateTimeStr=$(date -u )
  2148. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  2149. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ] ; then
  2150. Le_RenewalDays=$MAX_RENEW
  2151. else
  2152. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  2153. fi
  2154. if [ "$CA_BUNDLE" ] ; then
  2155. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  2156. else
  2157. _clearaccountconf "CA_BUNDLE"
  2158. fi
  2159. if [ "$HTTPS_INSECURE" ] ; then
  2160. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  2161. else
  2162. _clearaccountconf "HTTPS_INSECURE"
  2163. fi
  2164. if [ "$Le_Listen_V4" ] ; then
  2165. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  2166. _cleardomainconf Le_Listen_V6
  2167. elif [ "$Le_Listen_V6" ] ; then
  2168. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  2169. _cleardomainconf Le_Listen_V4
  2170. fi
  2171. Le_NextRenewTime=$(_math $Le_CertCreateTime + $Le_RenewalDays \* 24 \* 60 \* 60)
  2172. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  2173. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  2174. Le_NextRenewTime=$(_math $Le_NextRenewTime - 86400)
  2175. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  2176. _on_issue_success
  2177. if [ "$Le_RealCertPath$Le_RealKeyPath$Le_RealCACertPath$Le_ReloadCmd$Le_RealFullChainPath" ] ; then
  2178. _installcert
  2179. fi
  2180. }
  2181. #domain [isEcc]
  2182. renew() {
  2183. Le_Domain="$1"
  2184. if [ -z "$Le_Domain" ] ; then
  2185. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  2186. return 1
  2187. fi
  2188. _isEcc="$2"
  2189. _initpath $Le_Domain "$_isEcc"
  2190. _info "$(__green "Renew: '$Le_Domain'")"
  2191. if [ ! -f "$DOMAIN_CONF" ] ; then
  2192. _info "'$Le_Domain' is not a issued domain, skip."
  2193. return 0;
  2194. fi
  2195. if [ "$Le_RenewalDays" ] ; then
  2196. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  2197. fi
  2198. . "$DOMAIN_CONF"
  2199. if [ "$Le_API" ] ; then
  2200. API="$Le_API"
  2201. fi
  2202. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ] ; then
  2203. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  2204. _info "Add '$(__red '--force')' to force to renew."
  2205. return $RENEW_SKIP
  2206. fi
  2207. IS_RENEW="1"
  2208. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd" "$Le_RealFullChainPath" "$Le_PreHook" "$Le_PostHook" "$Le_RenewHook" "$Le_LocalAddress"
  2209. res=$?
  2210. IS_RENEW=""
  2211. return $res
  2212. }
  2213. #renewAll [stopRenewOnError]
  2214. renewAll() {
  2215. _initpath
  2216. _stopRenewOnError="$1"
  2217. _debug "_stopRenewOnError" "$_stopRenewOnError"
  2218. _ret="0"
  2219. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  2220. d=$(echo $d | cut -d '/' -f 1)
  2221. (
  2222. if _endswith $d "$ECC_SUFFIX" ; then
  2223. _isEcc=$(echo $d | cut -d "$ECC_SEP" -f 2)
  2224. d=$(echo $d | cut -d "$ECC_SEP" -f 1)
  2225. fi
  2226. renew "$d" "$_isEcc"
  2227. )
  2228. rc="$?"
  2229. _debug "Return code: $rc"
  2230. if [ "$rc" != "0" ] ; then
  2231. if [ "$rc" = "$RENEW_SKIP" ] ; then
  2232. _info "Skipped $d"
  2233. elif [ "$_stopRenewOnError" ] ; then
  2234. _err "Error renew $d, stop now."
  2235. return $rc
  2236. else
  2237. _ret="$rc"
  2238. _err "Error renew $d, Go ahead to next one."
  2239. fi
  2240. fi
  2241. done
  2242. return $_ret
  2243. }
  2244. #csr webroot
  2245. signcsr(){
  2246. _csrfile="$1"
  2247. _csrW="$2"
  2248. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  2249. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  2250. return 1
  2251. fi
  2252. _initpath
  2253. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2254. if [ "$?" != "0" ] ; then
  2255. _err "Can not read subject from csr: $_csrfile"
  2256. return 1
  2257. fi
  2258. _debug _csrsubj "$_csrsubj"
  2259. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2260. if [ "$?" != "0" ] ; then
  2261. _err "Can not read domain list from csr: $_csrfile"
  2262. return 1
  2263. fi
  2264. _debug "_csrdomainlist" "$_csrdomainlist"
  2265. if [ -z "$_csrsubj" ] ; then
  2266. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  2267. _debug _csrsubj "$_csrsubj"
  2268. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  2269. _debug "_csrdomainlist" "$_csrdomainlist"
  2270. fi
  2271. if [ -z "$_csrsubj" ] ; then
  2272. _err "Can not read subject from csr: $_csrfile"
  2273. return 1
  2274. fi
  2275. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2276. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ] ; then
  2277. _err "Can not read key length from csr: $_csrfile"
  2278. return 1
  2279. fi
  2280. _initpath "$_csrsubj" "$_csrkeylength"
  2281. mkdir -p "$DOMAIN_PATH"
  2282. _info "Copy csr to: $CSR_PATH"
  2283. cp "$_csrfile" "$CSR_PATH"
  2284. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
  2285. }
  2286. showcsr() {
  2287. _csrfile="$1"
  2288. _csrd="$2"
  2289. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  2290. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  2291. return 1
  2292. fi
  2293. _initpath
  2294. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  2295. if [ "$?" != "0" ] || [ -z "$_csrsubj" ] ; then
  2296. _err "Can not read subject from csr: $_csrfile"
  2297. return 1
  2298. fi
  2299. _info "Subject=$_csrsubj"
  2300. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  2301. if [ "$?" != "0" ] ; then
  2302. _err "Can not read domain list from csr: $_csrfile"
  2303. return 1
  2304. fi
  2305. _debug "_csrdomainlist" "$_csrdomainlist"
  2306. _info "SubjectAltNames=$_csrdomainlist"
  2307. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  2308. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ] ; then
  2309. _err "Can not read key length from csr: $_csrfile"
  2310. return 1
  2311. fi
  2312. _info "KeyLength=$_csrkeylength"
  2313. }
  2314. list() {
  2315. _raw="$1"
  2316. _initpath
  2317. _sep="|"
  2318. if [ "$_raw" ] ; then
  2319. printf "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew\n"
  2320. for d in $(ls -F ${CERT_HOME}/ | grep [^.].*[.].*/$ ) ; do
  2321. d=$(echo $d | cut -d '/' -f 1)
  2322. (
  2323. if _endswith $d "$ECC_SUFFIX" ; then
  2324. _isEcc=$(echo $d | cut -d "$ECC_SEP" -f 2)
  2325. d=$(echo $d | cut -d "$ECC_SEP" -f 1)
  2326. fi
  2327. _initpath $d "$_isEcc"
  2328. if [ -f "$DOMAIN_CONF" ] ; then
  2329. . "$DOMAIN_CONF"
  2330. printf "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr\n"
  2331. fi
  2332. )
  2333. done
  2334. else
  2335. if _exists column ; then
  2336. list "raw" | column -t -s "$_sep"
  2337. else
  2338. list "raw" | tr "$_sep" '\t'
  2339. fi
  2340. fi
  2341. }
  2342. installcert() {
  2343. Le_Domain="$1"
  2344. if [ -z "$Le_Domain" ] ; then
  2345. _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--certpath cert-file-path] [--keypath key-file-path] [--capath ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchainpath fullchain-path]"
  2346. return 1
  2347. fi
  2348. Le_RealCertPath="$2"
  2349. Le_RealKeyPath="$3"
  2350. Le_RealCACertPath="$4"
  2351. Le_ReloadCmd="$5"
  2352. Le_RealFullChainPath="$6"
  2353. _isEcc="$7"
  2354. _initpath $Le_Domain "$_isEcc"
  2355. if [ ! -d "$DOMAIN_PATH" ] ; then
  2356. _err "Domain is not valid:'$Le_Domain'"
  2357. return 1
  2358. fi
  2359. _installcert
  2360. }
  2361. _installcert() {
  2362. _savedomainconf "Le_RealCertPath" "$Le_RealCertPath"
  2363. _savedomainconf "Le_RealCACertPath" "$Le_RealCACertPath"
  2364. _savedomainconf "Le_RealKeyPath" "$Le_RealKeyPath"
  2365. _savedomainconf "Le_ReloadCmd" "$Le_ReloadCmd"
  2366. _savedomainconf "Le_RealFullChainPath" "$Le_RealFullChainPath"
  2367. if [ "$Le_RealCertPath" = "$NO_VALUE" ] ; then
  2368. Le_RealCertPath=""
  2369. fi
  2370. if [ "$Le_RealKeyPath" = "$NO_VALUE" ] ; then
  2371. Le_RealKeyPath=""
  2372. fi
  2373. if [ "$Le_RealCACertPath" = "$NO_VALUE" ] ; then
  2374. Le_RealCACertPath=""
  2375. fi
  2376. if [ "$Le_ReloadCmd" = "$NO_VALUE" ] ; then
  2377. Le_ReloadCmd=""
  2378. fi
  2379. if [ "$Le_RealFullChainPath" = "$NO_VALUE" ] ; then
  2380. Le_RealFullChainPath=""
  2381. fi
  2382. _installed="0"
  2383. if [ "$Le_RealCertPath" ] ; then
  2384. _installed=1
  2385. _info "Installing cert to:$Le_RealCertPath"
  2386. if [ -f "$Le_RealCertPath" ] && [ ! "$IS_RENEW" ] ; then
  2387. cp "$Le_RealCertPath" "$Le_RealCertPath".bak
  2388. fi
  2389. cat "$CERT_PATH" > "$Le_RealCertPath"
  2390. fi
  2391. if [ "$Le_RealCACertPath" ] ; then
  2392. _installed=1
  2393. _info "Installing CA to:$Le_RealCACertPath"
  2394. if [ "$Le_RealCACertPath" = "$Le_RealCertPath" ] ; then
  2395. echo "" >> "$Le_RealCACertPath"
  2396. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  2397. else
  2398. if [ -f "$Le_RealCACertPath" ] && [ ! "$IS_RENEW" ] ; then
  2399. cp "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  2400. fi
  2401. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  2402. fi
  2403. fi
  2404. if [ "$Le_RealKeyPath" ] ; then
  2405. _installed=1
  2406. _info "Installing key to:$Le_RealKeyPath"
  2407. if [ -f "$Le_RealKeyPath" ] && [ ! "$IS_RENEW" ] ; then
  2408. cp "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  2409. fi
  2410. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  2411. fi
  2412. if [ "$Le_RealFullChainPath" ] ; then
  2413. _installed=1
  2414. _info "Installing full chain to:$Le_RealFullChainPath"
  2415. if [ -f "$Le_RealFullChainPath" ] && [ ! "$IS_RENEW" ] ; then
  2416. cp "$Le_RealFullChainPath" "$Le_RealFullChainPath".bak
  2417. fi
  2418. cat "$CERT_FULLCHAIN_PATH" > "$Le_RealFullChainPath"
  2419. fi
  2420. if [ "$Le_ReloadCmd" ] ; then
  2421. _installed=1
  2422. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  2423. if (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd") ; then
  2424. _info "$(__green "Reload success")"
  2425. else
  2426. _err "Reload error for :$Le_Domain"
  2427. fi
  2428. fi
  2429. }
  2430. installcronjob() {
  2431. _initpath
  2432. if ! _exists "crontab" ; then
  2433. _err "crontab doesn't exist, so, we can not install cron jobs."
  2434. _err "All your certs will not be renewed automatically."
  2435. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  2436. return 1
  2437. fi
  2438. _info "Installing cron job"
  2439. if ! crontab -l | grep "$PROJECT_ENTRY --cron" ; then
  2440. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ] ; then
  2441. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  2442. else
  2443. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  2444. return 1
  2445. fi
  2446. if _exists uname && uname -a | grep solaris >/dev/null ; then
  2447. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab --
  2448. else
  2449. crontab -l | { cat; echo "0 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"; } | crontab -
  2450. fi
  2451. fi
  2452. if [ "$?" != "0" ] ; then
  2453. _err "Install cron job failed. You need to manually renew your certs."
  2454. _err "Or you can add cronjob by yourself:"
  2455. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  2456. return 1
  2457. fi
  2458. }
  2459. uninstallcronjob() {
  2460. if ! _exists "crontab" ; then
  2461. return
  2462. fi
  2463. _info "Removing cron job"
  2464. cr="$(crontab -l | grep "$PROJECT_ENTRY --cron")"
  2465. if [ "$cr" ] ; then
  2466. if _exists uname && uname -a | grep solaris >/dev/null ; then
  2467. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab --
  2468. else
  2469. crontab -l | sed "/$PROJECT_ENTRY --cron/d" | crontab -
  2470. fi
  2471. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  2472. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  2473. fi
  2474. _initpath
  2475. }
  2476. revoke() {
  2477. Le_Domain="$1"
  2478. if [ -z "$Le_Domain" ] ; then
  2479. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com"
  2480. return 1
  2481. fi
  2482. _isEcc="$2"
  2483. _initpath $Le_Domain "$_isEcc"
  2484. if [ ! -f "$DOMAIN_CONF" ] ; then
  2485. _err "$Le_Domain is not a issued domain, skip."
  2486. return 1;
  2487. fi
  2488. if [ ! -f "$CERT_PATH" ] ; then
  2489. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  2490. return 1
  2491. fi
  2492. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}"| tr -d "\r\n" | _urlencode)"
  2493. if [ -z "$cert" ] ; then
  2494. _err "Cert for $Le_Domain is empty found, skip."
  2495. return 1
  2496. fi
  2497. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  2498. uri="$API/acme/revoke-cert"
  2499. _info "Try domain key first."
  2500. if _send_signed_request $uri "$data" "" "$CERT_KEY_PATH"; then
  2501. if [ -z "$response" ] ; then
  2502. _info "Revoke success."
  2503. rm -f $CERT_PATH
  2504. return 0
  2505. else
  2506. _err "Revoke error by domain key."
  2507. _err "$response"
  2508. fi
  2509. fi
  2510. _info "Then try account key."
  2511. if _send_signed_request $uri "$data" "" "$ACCOUNT_KEY_PATH" ; then
  2512. if [ -z "$response" ] ; then
  2513. _info "Revoke success."
  2514. rm -f $CERT_PATH
  2515. return 0
  2516. else
  2517. _err "Revoke error."
  2518. _debug "$response"
  2519. fi
  2520. fi
  2521. return 1
  2522. }
  2523. #domain vtype
  2524. _deactivate() {
  2525. _d_domain="$1"
  2526. _d_type="$2"
  2527. _initpath
  2528. _d_i=0
  2529. _d_max_retry=9
  2530. while [ "$_d_i" -lt "$_d_max_retry" ] ;
  2531. do
  2532. _info "Deactivate: $_d_domain"
  2533. _d_i="$(_math $_d_i + 1)"
  2534. if ! _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$_d_domain\"}}" ; then
  2535. _err "Can not get domain token."
  2536. return 1
  2537. fi
  2538. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2539. _debug "authzUri" "$authzUri"
  2540. if [ ! -z "$code" ] && [ ! "$code" = '201' ] ; then
  2541. _err "new-authz error: $response"
  2542. return 1
  2543. fi
  2544. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"status":"valid","uri"[^\}]*')"
  2545. _debug entry "$entry"
  2546. if [ -z "$entry" ] ; then
  2547. _info "No more valid entry found."
  2548. break
  2549. fi
  2550. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  2551. _debug _vtype $_vtype
  2552. _info "Found $_vtype"
  2553. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  2554. _debug uri $uri
  2555. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ] ; then
  2556. _info "Skip $_vtype"
  2557. continue
  2558. fi
  2559. _info "Deactivate: $_vtype"
  2560. if ! _send_signed_request "$authzUri" "{\"resource\": \"authz\", \"status\":\"deactivated\"}" ; then
  2561. _err "Can not deactivate $_vtype."
  2562. return 1
  2563. fi
  2564. _info "Deactivate: $_vtype success."
  2565. done
  2566. _debug "$_d_i"
  2567. if [ "$_d_i" -lt "$_d_max_retry" ] ; then
  2568. _info "Deactivated success!"
  2569. else
  2570. _err "Deactivate failed."
  2571. fi
  2572. }
  2573. deactivate() {
  2574. _d_domain_list="$1"
  2575. _d_type="$2"
  2576. _initpath
  2577. _debug _d_domain_list "$_d_domain_list"
  2578. if [ -z "$(echo $_d_domain_list | cut -d , -f 1 )" ] ; then
  2579. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  2580. return 1
  2581. fi
  2582. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' ' ) ;
  2583. do
  2584. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ] ; then
  2585. continue
  2586. fi
  2587. if ! _deactivate "$_d_dm" $_d_type ; then
  2588. return 1
  2589. fi
  2590. done
  2591. }
  2592. # Detect profile file if not specified as environment variable
  2593. _detect_profile() {
  2594. if [ -n "$PROFILE" -a -f "$PROFILE" ] ; then
  2595. echo "$PROFILE"
  2596. return
  2597. fi
  2598. DETECTED_PROFILE=''
  2599. SHELLTYPE="$(basename "/$SHELL")"
  2600. if [ "$SHELLTYPE" = "bash" ] ; then
  2601. if [ -f "$HOME/.bashrc" ] ; then
  2602. DETECTED_PROFILE="$HOME/.bashrc"
  2603. elif [ -f "$HOME/.bash_profile" ] ; then
  2604. DETECTED_PROFILE="$HOME/.bash_profile"
  2605. fi
  2606. elif [ "$SHELLTYPE" = "zsh" ] ; then
  2607. DETECTED_PROFILE="$HOME/.zshrc"
  2608. fi
  2609. if [ -z "$DETECTED_PROFILE" ] ; then
  2610. if [ -f "$HOME/.profile" ] ; then
  2611. DETECTED_PROFILE="$HOME/.profile"
  2612. elif [ -f "$HOME/.bashrc" ] ; then
  2613. DETECTED_PROFILE="$HOME/.bashrc"
  2614. elif [ -f "$HOME/.bash_profile" ] ; then
  2615. DETECTED_PROFILE="$HOME/.bash_profile"
  2616. elif [ -f "$HOME/.zshrc" ] ; then
  2617. DETECTED_PROFILE="$HOME/.zshrc"
  2618. fi
  2619. fi
  2620. if [ ! -z "$DETECTED_PROFILE" ] ; then
  2621. echo "$DETECTED_PROFILE"
  2622. fi
  2623. }
  2624. _initconf() {
  2625. _initpath
  2626. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  2627. echo "#ACCOUNT_CONF_PATH=xxxx
  2628. #Account configurations:
  2629. #Here are the supported macros, uncomment them to make them take effect.
  2630. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  2631. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  2632. #CERT_HOME=\"/path/to/cert/home\"
  2633. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  2634. #LOG_LEVEL=1
  2635. #AUTO_UPGRADE=\"1\"
  2636. #STAGE=1 # Use the staging api
  2637. #FORCE=1 # Force to issue cert
  2638. #DEBUG=1 # Debug mode
  2639. #USER_AGENT=\"$USER_AGENT\"
  2640. #USER_PATH=""
  2641. #dns api
  2642. #######################
  2643. #Cloudflare:
  2644. #api key
  2645. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  2646. #account email
  2647. #CF_Email=\"xxxx@sss.com\"
  2648. #######################
  2649. #Dnspod.cn:
  2650. #api key id
  2651. #DP_Id=\"1234\"
  2652. #api key
  2653. #DP_Key=\"sADDsdasdgdsf\"
  2654. #######################
  2655. #Cloudxns.com:
  2656. #CX_Key=\"1234\"
  2657. #
  2658. #CX_Secret=\"sADDsdasdgdsf\"
  2659. #######################
  2660. #Godaddy.com:
  2661. #GD_Key=\"sdfdsgdgdfdasfds\"
  2662. #
  2663. #GD_Secret=\"sADDsdasdfsdfdssdgdsf\"
  2664. #######################
  2665. #PowerDNS:
  2666. #PDNS_Url=\"http://ns.example.com:8081\"
  2667. #PDNS_ServerId=\"localhost\"
  2668. #PDNS_Token=\"0123456789ABCDEF\"
  2669. #PDNS_Ttl=60
  2670. " > $ACCOUNT_CONF_PATH
  2671. fi
  2672. }
  2673. # nocron
  2674. _precheck() {
  2675. _nocron="$1"
  2676. if ! _exists "curl" && ! _exists "wget"; then
  2677. _err "Please install curl or wget first, we need to access http resources."
  2678. return 1
  2679. fi
  2680. if [ -z "$_nocron" ] ; then
  2681. if ! _exists "crontab" ; then
  2682. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  2683. _err "We need to set cron job to renew the certs automatically."
  2684. _err "Otherwise, your certs will not be able to be renewed automatically."
  2685. if [ -z "$FORCE" ] ; then
  2686. _err "Please add '--force' and try install again to go without crontab."
  2687. _err "./$PROJECT_ENTRY --install --force"
  2688. return 1
  2689. fi
  2690. fi
  2691. fi
  2692. if ! _exists "openssl" ; then
  2693. _err "Please install openssl first."
  2694. _err "We need openssl to generate keys."
  2695. return 1
  2696. fi
  2697. if ! _exists "nc" ; then
  2698. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  2699. _err "We use nc for standalone server if you use standalone mode."
  2700. _err "If you don't use standalone mode, just ignore this warning."
  2701. fi
  2702. return 0
  2703. }
  2704. _setShebang() {
  2705. _file="$1"
  2706. _shebang="$2"
  2707. if [ -z "$_shebang" ] ; then
  2708. _usage "Usage: file shebang"
  2709. return 1
  2710. fi
  2711. cp "$_file" "$_file.tmp"
  2712. echo "$_shebang" > "$_file"
  2713. sed -n 2,99999p "$_file.tmp" >> "$_file"
  2714. rm -f "$_file.tmp"
  2715. }
  2716. _installalias() {
  2717. _initpath
  2718. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  2719. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ] ; then
  2720. echo "$(cat $_envfile)" | sed "s|^LE_WORKING_DIR.*$||" > "$_envfile"
  2721. echo "$(cat $_envfile)" | sed "s|^alias le.*$||" > "$_envfile"
  2722. echo "$(cat $_envfile)" | sed "s|^alias le.sh.*$||" > "$_envfile"
  2723. fi
  2724. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  2725. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  2726. _profile="$(_detect_profile)"
  2727. if [ "$_profile" ] ; then
  2728. _debug "Found profile: $_profile"
  2729. _setopt "$_profile" ". \"$_envfile\""
  2730. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  2731. else
  2732. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  2733. fi
  2734. #for csh
  2735. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  2736. _csh_profile="$HOME/.cshrc"
  2737. if [ -f "$_csh_profile" ] ; then
  2738. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  2739. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  2740. _setopt "$_csh_profile" "source \"$_cshfile\""
  2741. fi
  2742. #for tcsh
  2743. _tcsh_profile="$HOME/.tcshrc"
  2744. if [ -f "$_tcsh_profile" ] ; then
  2745. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  2746. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY\""
  2747. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  2748. fi
  2749. }
  2750. # nocron
  2751. install() {
  2752. if [ -z "$LE_WORKING_DIR" ] ; then
  2753. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  2754. fi
  2755. _nocron="$1"
  2756. if ! _initpath ; then
  2757. _err "Install failed."
  2758. return 1
  2759. fi
  2760. if [ "$_nocron" ] ; then
  2761. _debug "Skip install cron job"
  2762. fi
  2763. if ! _precheck "$_nocron" ; then
  2764. _err "Pre-check failed, can not install."
  2765. return 1
  2766. fi
  2767. #convert from le
  2768. if [ -d "$HOME/.le" ] ; then
  2769. for envfile in "le.env" "le.sh.env"
  2770. do
  2771. if [ -f "$HOME/.le/$envfile" ] ; then
  2772. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null ; then
  2773. _upgrading="1"
  2774. _info "You are upgrading from le.sh"
  2775. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  2776. mv "$HOME/.le" "$LE_WORKING_DIR"
  2777. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  2778. break;
  2779. fi
  2780. fi
  2781. done
  2782. fi
  2783. _info "Installing to $LE_WORKING_DIR"
  2784. if ! mkdir -p "$LE_WORKING_DIR" ; then
  2785. _err "Can not create working dir: $LE_WORKING_DIR"
  2786. return 1
  2787. fi
  2788. chmod 700 "$LE_WORKING_DIR"
  2789. cp $PROJECT_ENTRY "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  2790. if [ "$?" != "0" ] ; then
  2791. _err "Install failed, can not copy $PROJECT_ENTRY"
  2792. return 1
  2793. fi
  2794. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  2795. _installalias
  2796. if [ -d "dnsapi" ] ; then
  2797. mkdir -p $LE_WORKING_DIR/dnsapi
  2798. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  2799. fi
  2800. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  2801. _initconf
  2802. fi
  2803. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ] ; then
  2804. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  2805. fi
  2806. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ] ; then
  2807. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  2808. fi
  2809. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ] ; then
  2810. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  2811. fi
  2812. if [ -z "$_nocron" ] ; then
  2813. installcronjob
  2814. fi
  2815. if [ -z "$NO_DETECT_SH" ] ; then
  2816. #Modify shebang
  2817. if _exists bash ; then
  2818. _info "Good, bash is installed, change the shebang to use bash as prefered."
  2819. _shebang='#!/usr/bin/env bash'
  2820. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  2821. if [ -d "$LE_WORKING_DIR/dnsapi" ] ; then
  2822. for _apifile in $(ls "$LE_WORKING_DIR/dnsapi/"*.sh) ; do
  2823. _setShebang "$_apifile" "$_shebang"
  2824. done
  2825. fi
  2826. fi
  2827. fi
  2828. _info OK
  2829. }
  2830. # nocron
  2831. uninstall() {
  2832. _nocron="$1"
  2833. if [ -z "$_nocron" ] ; then
  2834. uninstallcronjob
  2835. fi
  2836. _initpath
  2837. _profile="$(_detect_profile)"
  2838. if [ "$_profile" ] ; then
  2839. text="$(cat $_profile)"
  2840. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" > "$_profile"
  2841. fi
  2842. _csh_profile="$HOME/.cshrc"
  2843. if [ -f "$_csh_profile" ] ; then
  2844. text="$(cat $_csh_profile)"
  2845. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_csh_profile"
  2846. fi
  2847. _tcsh_profile="$HOME/.tcshrc"
  2848. if [ -f "$_tcsh_profile" ] ; then
  2849. text="$(cat $_tcsh_profile)"
  2850. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" > "$_tcsh_profile"
  2851. fi
  2852. rm -f $LE_WORKING_DIR/$PROJECT_ENTRY
  2853. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  2854. }
  2855. cron() {
  2856. IN_CRON=1
  2857. _initpath
  2858. if [ "$AUTO_UPGRADE" = "1" ] ; then
  2859. export LE_WORKING_DIR
  2860. (
  2861. if ! upgrade ; then
  2862. _err "Cron:Upgrade failed!"
  2863. return 1
  2864. fi
  2865. )
  2866. . $LE_WORKING_DIR/$PROJECT_ENTRY >/dev/null
  2867. if [ -t 1 ] ; then
  2868. __INTERACTIVE="1"
  2869. fi
  2870. _info "Auto upgraded to: $VER"
  2871. fi
  2872. renewAll
  2873. _ret="$?"
  2874. IN_CRON=""
  2875. exit $_ret
  2876. }
  2877. version() {
  2878. echo "$PROJECT"
  2879. echo "v$VER"
  2880. }
  2881. showhelp() {
  2882. _initpath
  2883. version
  2884. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  2885. Commands:
  2886. --help, -h Show this help message.
  2887. --version, -v Show version info.
  2888. --install Install $PROJECT_NAME to your system.
  2889. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  2890. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT .
  2891. --issue Issue a cert.
  2892. --signcsr Issue a cert from an existing csr.
  2893. --installcert Install the issued cert to apache/nginx or any other server.
  2894. --renew, -r Renew a cert.
  2895. --renewAll Renew all the certs.
  2896. --revoke Revoke a cert.
  2897. --list List all the certs.
  2898. --showcsr Show the content of a csr.
  2899. --installcronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  2900. --uninstallcronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  2901. --cron Run cron job to renew all the certs.
  2902. --toPkcs Export the certificate and key to a pfx file.
  2903. --updateaccount Update account info.
  2904. --registeraccount Register account key.
  2905. --createAccountKey, -cak Create an account private key, professional use.
  2906. --createDomainKey, -cdk Create an domain private key, professional use.
  2907. --createCSR, -ccsr Create CSR , professional use.
  2908. --deactivate Deactivate the domain authz, professional use.
  2909. Parameters:
  2910. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  2911. --force, -f Used to force to install or force to renew a cert immediately.
  2912. --staging, --test Use staging server, just for test.
  2913. --debug Output debug info.
  2914. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  2915. --standalone Use standalone mode.
  2916. --tls Use standalone tls mode.
  2917. --apache Use apache mode.
  2918. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  2919. --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.
  2920. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  2921. --accountkeylength, -ak [2048] Specifies the account key length.
  2922. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  2923. --log-level 1|2 Specifies the log level, default is 1.
  2924. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  2925. --certpath /path/to/real/cert/file After issue/renew, the cert will be copied to this path.
  2926. --keypath /path/to/real/key/file After issue/renew, the key will be copied to this path.
  2927. --capath /path/to/real/ca/file After issue/renew, the intermediate cert will be copied to this path.
  2928. --fullchainpath /path/to/fullchain/file After issue/renew, the fullchain cert will be copied to this path.
  2929. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  2930. --accountconf Specifies a customized account config file.
  2931. --home Specifies the home dir for $PROJECT_NAME .
  2932. --certhome Specifies the home dir to save all the certs, only valid for '--install' command.
  2933. --useragent Specifies the user agent string. it will be saved for future use too.
  2934. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  2935. --accountkey Specifies the account key path, Only valid for the '--install' command.
  2936. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  2937. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  2938. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  2939. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  2940. --listraw Only used for '--list' command, list the certs in raw format.
  2941. --stopRenewOnError, -se Only valid for '--renewall' command. Stop if one cert has error in renewal.
  2942. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  2943. --ca-bundle Specifices the path to the CA certificate bundle to verify api server's certificate.
  2944. --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.
  2945. --ecc Specifies to use the ECC cert. Valid for '--installcert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  2946. --csr Specifies the input csr.
  2947. --pre-hook Command to be run before obtaining any certificates.
  2948. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obain/renew is success or failed.
  2949. --renew-hook Command to be run once for each successfully renewed certificate.
  2950. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  2951. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  2952. --listen-v4 Force standalone/tls server to listen at ipv4.
  2953. --listen-v6 Force standalone/tls server to listen at ipv6.
  2954. "
  2955. }
  2956. # nocron
  2957. _installOnline() {
  2958. _info "Installing from online archive."
  2959. _nocron="$1"
  2960. if [ ! "$BRANCH" ] ; then
  2961. BRANCH="master"
  2962. fi
  2963. target="$PROJECT/archive/$BRANCH.tar.gz"
  2964. _info "Downloading $target"
  2965. localname="$BRANCH.tar.gz"
  2966. if ! _get "$target" > $localname ; then
  2967. _err "Download error."
  2968. return 1
  2969. fi
  2970. (
  2971. _info "Extracting $localname"
  2972. tar xzf $localname
  2973. cd "$PROJECT_NAME-$BRANCH"
  2974. chmod +x $PROJECT_ENTRY
  2975. if ./$PROJECT_ENTRY install "$_nocron" ; then
  2976. _info "Install success!"
  2977. fi
  2978. cd ..
  2979. rm -rf "$PROJECT_NAME-$BRANCH"
  2980. rm -f "$localname"
  2981. )
  2982. }
  2983. upgrade() {
  2984. if (
  2985. _initpath
  2986. export LE_WORKING_DIR
  2987. cd "$LE_WORKING_DIR"
  2988. _installOnline "nocron"
  2989. ) ; then
  2990. _info "Upgrade success!"
  2991. exit 0
  2992. else
  2993. _err "Upgrade failed!"
  2994. exit 1
  2995. fi
  2996. }
  2997. _processAccountConf() {
  2998. if [ "$_useragent" ] ; then
  2999. _saveaccountconf "USER_AGENT" "$_useragent"
  3000. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ] ; then
  3001. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  3002. fi
  3003. if [ "$_accountemail" ] ; then
  3004. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  3005. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ] ; then
  3006. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  3007. fi
  3008. if [ "$_auto_upgrade" ] ; then
  3009. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  3010. elif [ "$AUTO_UPGRADE" ] ; then
  3011. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  3012. fi
  3013. }
  3014. _process() {
  3015. _CMD=""
  3016. _domain=""
  3017. _altdomains="$NO_VALUE"
  3018. _webroot=""
  3019. _keylength=""
  3020. _accountkeylength=""
  3021. _certpath=""
  3022. _keypath=""
  3023. _capath=""
  3024. _fullchainpath=""
  3025. _reloadcmd=""
  3026. _password=""
  3027. _accountconf=""
  3028. _useragent=""
  3029. _accountemail=""
  3030. _accountkey=""
  3031. _certhome=""
  3032. _httpport=""
  3033. _tlsport=""
  3034. _dnssleep=""
  3035. _listraw=""
  3036. _stopRenewOnError=""
  3037. _insecure=""
  3038. _ca_bundle=""
  3039. _nocron=""
  3040. _ecc=""
  3041. _csr=""
  3042. _pre_hook=""
  3043. _post_hook=""
  3044. _renew_hook=""
  3045. _logfile=""
  3046. _log=""
  3047. _local_address=""
  3048. _log_level=""
  3049. _auto_upgrade=""
  3050. _listen_v4=""
  3051. _listen_v6=""
  3052. while [ ${#} -gt 0 ] ; do
  3053. case "${1}" in
  3054. --help|-h)
  3055. showhelp
  3056. return
  3057. ;;
  3058. --version|-v)
  3059. version
  3060. return
  3061. ;;
  3062. --install)
  3063. _CMD="install"
  3064. ;;
  3065. --uninstall)
  3066. _CMD="uninstall"
  3067. ;;
  3068. --upgrade)
  3069. _CMD="upgrade"
  3070. ;;
  3071. --issue)
  3072. _CMD="issue"
  3073. ;;
  3074. --signcsr)
  3075. _CMD="signcsr"
  3076. ;;
  3077. --showcsr)
  3078. _CMD="showcsr"
  3079. ;;
  3080. --installcert|-i)
  3081. _CMD="installcert"
  3082. ;;
  3083. --renew|-r)
  3084. _CMD="renew"
  3085. ;;
  3086. --renewAll|--renewall)
  3087. _CMD="renewAll"
  3088. ;;
  3089. --revoke)
  3090. _CMD="revoke"
  3091. ;;
  3092. --list)
  3093. _CMD="list"
  3094. ;;
  3095. --installcronjob)
  3096. _CMD="installcronjob"
  3097. ;;
  3098. --uninstallcronjob)
  3099. _CMD="uninstallcronjob"
  3100. ;;
  3101. --cron)
  3102. _CMD="cron"
  3103. ;;
  3104. --toPkcs)
  3105. _CMD="toPkcs"
  3106. ;;
  3107. --createAccountKey|--createaccountkey|-cak)
  3108. _CMD="createAccountKey"
  3109. ;;
  3110. --createDomainKey|--createdomainkey|-cdk)
  3111. _CMD="createDomainKey"
  3112. ;;
  3113. --createCSR|--createcsr|-ccr)
  3114. _CMD="createCSR"
  3115. ;;
  3116. --deactivate)
  3117. _CMD="deactivate"
  3118. ;;
  3119. --updateaccount)
  3120. _CMD="updateaccount"
  3121. ;;
  3122. --registeraccount)
  3123. _CMD="registeraccount"
  3124. ;;
  3125. --domain|-d)
  3126. _dvalue="$2"
  3127. if [ "$_dvalue" ] ; then
  3128. if _startswith "$_dvalue" "-" ; then
  3129. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  3130. return 1
  3131. fi
  3132. if [ -z "$_domain" ] ; then
  3133. _domain="$_dvalue"
  3134. else
  3135. if [ "$_altdomains" = "$NO_VALUE" ] ; then
  3136. _altdomains="$_dvalue"
  3137. else
  3138. _altdomains="$_altdomains,$_dvalue"
  3139. fi
  3140. fi
  3141. fi
  3142. shift
  3143. ;;
  3144. --force|-f)
  3145. FORCE="1"
  3146. ;;
  3147. --staging|--test)
  3148. STAGE="1"
  3149. ;;
  3150. --debug)
  3151. if [ -z "$2" ] || _startswith "$2" "-" ; then
  3152. DEBUG="1"
  3153. else
  3154. DEBUG="$2"
  3155. shift
  3156. fi
  3157. ;;
  3158. --webroot|-w)
  3159. wvalue="$2"
  3160. if [ -z "$_webroot" ] ; then
  3161. _webroot="$wvalue"
  3162. else
  3163. _webroot="$_webroot,$wvalue"
  3164. fi
  3165. shift
  3166. ;;
  3167. --standalone)
  3168. wvalue="$NO_VALUE"
  3169. if [ -z "$_webroot" ] ; then
  3170. _webroot="$wvalue"
  3171. else
  3172. _webroot="$_webroot,$wvalue"
  3173. fi
  3174. ;;
  3175. --local-address)
  3176. lvalue="$2"
  3177. _local_address="$_local_address$lvalue,"
  3178. shift
  3179. ;;
  3180. --apache)
  3181. wvalue="apache"
  3182. if [ -z "$_webroot" ] ; then
  3183. _webroot="$wvalue"
  3184. else
  3185. _webroot="$_webroot,$wvalue"
  3186. fi
  3187. ;;
  3188. --tls)
  3189. wvalue="$W_TLS"
  3190. if [ -z "$_webroot" ] ; then
  3191. _webroot="$wvalue"
  3192. else
  3193. _webroot="$_webroot,$wvalue"
  3194. fi
  3195. ;;
  3196. --dns)
  3197. wvalue="dns"
  3198. if ! _startswith "$2" "-" ; then
  3199. wvalue="$2"
  3200. shift
  3201. fi
  3202. if [ -z "$_webroot" ] ; then
  3203. _webroot="$wvalue"
  3204. else
  3205. _webroot="$_webroot,$wvalue"
  3206. fi
  3207. ;;
  3208. --dnssleep)
  3209. _dnssleep="$2"
  3210. Le_DNSSleep="$_dnssleep"
  3211. shift
  3212. ;;
  3213. --keylength|-k)
  3214. _keylength="$2"
  3215. if [ "$_accountkeylength" = "$NO_VALUE" ] ; then
  3216. _accountkeylength="$2"
  3217. fi
  3218. shift
  3219. ;;
  3220. --accountkeylength|-ak)
  3221. _accountkeylength="$2"
  3222. shift
  3223. ;;
  3224. --certpath)
  3225. _certpath="$2"
  3226. shift
  3227. ;;
  3228. --keypath)
  3229. _keypath="$2"
  3230. shift
  3231. ;;
  3232. --capath)
  3233. _capath="$2"
  3234. shift
  3235. ;;
  3236. --fullchainpath)
  3237. _fullchainpath="$2"
  3238. shift
  3239. ;;
  3240. --reloadcmd|--reloadCmd)
  3241. _reloadcmd="$2"
  3242. shift
  3243. ;;
  3244. --password)
  3245. _password="$2"
  3246. shift
  3247. ;;
  3248. --accountconf)
  3249. _accountconf="$2"
  3250. ACCOUNT_CONF_PATH="$_accountconf"
  3251. shift
  3252. ;;
  3253. --home)
  3254. LE_WORKING_DIR="$2"
  3255. shift
  3256. ;;
  3257. --certhome)
  3258. _certhome="$2"
  3259. CERT_HOME="$_certhome"
  3260. shift
  3261. ;;
  3262. --useragent)
  3263. _useragent="$2"
  3264. USER_AGENT="$_useragent"
  3265. shift
  3266. ;;
  3267. --accountemail )
  3268. _accountemail="$2"
  3269. ACCOUNT_EMAIL="$_accountemail"
  3270. shift
  3271. ;;
  3272. --accountkey )
  3273. _accountkey="$2"
  3274. ACCOUNT_KEY_PATH="$_accountkey"
  3275. shift
  3276. ;;
  3277. --days )
  3278. _days="$2"
  3279. Le_RenewalDays="$_days"
  3280. shift
  3281. ;;
  3282. --httpport )
  3283. _httpport="$2"
  3284. Le_HTTPPort="$_httpport"
  3285. shift
  3286. ;;
  3287. --tlsport )
  3288. _tlsport="$2"
  3289. Le_TLSPort="$_tlsport"
  3290. shift
  3291. ;;
  3292. --listraw )
  3293. _listraw="raw"
  3294. ;;
  3295. --stopRenewOnError|--stoprenewonerror|-se )
  3296. _stopRenewOnError="1"
  3297. ;;
  3298. --insecure)
  3299. _insecure="1"
  3300. HTTPS_INSECURE="1"
  3301. ;;
  3302. --ca-bundle)
  3303. _ca_bundle="$(readlink -f $2)"
  3304. CA_BUNDLE="$_ca_bundle"
  3305. shift
  3306. ;;
  3307. --nocron)
  3308. _nocron="1"
  3309. ;;
  3310. --ecc)
  3311. _ecc="isEcc"
  3312. ;;
  3313. --csr)
  3314. _csr="$2"
  3315. shift
  3316. ;;
  3317. --pre-hook)
  3318. _pre_hook="$2"
  3319. shift
  3320. ;;
  3321. --post-hook)
  3322. _post_hook="$2"
  3323. shift
  3324. ;;
  3325. --renew-hook)
  3326. _renew_hook="$2"
  3327. shift
  3328. ;;
  3329. --ocsp-must-staple|--ocsp)
  3330. Le_OCSP_Stable="1"
  3331. ;;
  3332. --log|--logfile)
  3333. _log="1"
  3334. _logfile="$2"
  3335. if _startswith "$_logfile" '-' ; then
  3336. _logfile=""
  3337. else
  3338. shift
  3339. fi
  3340. LOG_FILE="$_logfile"
  3341. if [ -z "$LOG_LEVEL" ] ; then
  3342. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  3343. fi
  3344. ;;
  3345. --log-level)
  3346. _log_level="$2"
  3347. LOG_LEVEL="$_log_level"
  3348. shift
  3349. ;;
  3350. --auto-upgrade)
  3351. _auto_upgrade="$2"
  3352. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-' ; then
  3353. _auto_upgrade="1"
  3354. else
  3355. shift
  3356. fi
  3357. AUTO_UPGRADE="$_auto_upgrade"
  3358. ;;
  3359. --listen-v4)
  3360. _listen_v4="1"
  3361. Le_Listen_V4="$_listen_v4"
  3362. ;;
  3363. --listen-v6)
  3364. _listen_v6="1"
  3365. Le_Listen_V6="$_listen_v6"
  3366. ;;
  3367. *)
  3368. _err "Unknown parameter : $1"
  3369. return 1
  3370. ;;
  3371. esac
  3372. shift 1
  3373. done
  3374. if [ "${_CMD}" != "install" ] ; then
  3375. __initHome
  3376. if [ "$_log" ] && [ -z "$_logfile" ] ; then
  3377. _logfile="$DEFAULT_LOG_FILE"
  3378. fi
  3379. if [ "$_logfile" ] ; then
  3380. _saveaccountconf "LOG_FILE" "$_logfile"
  3381. fi
  3382. LOG_FILE="$_logfile"
  3383. if [ "$_log_level" ] ; then
  3384. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3385. LOG_LEVEL="$_log_level"
  3386. fi
  3387. _processAccountConf
  3388. fi
  3389. if [ "$DEBUG" ] ; then
  3390. version
  3391. fi
  3392. case "${_CMD}" in
  3393. install) install "$_nocron" ;;
  3394. uninstall) uninstall "$_nocron" ;;
  3395. upgrade) upgrade ;;
  3396. issue)
  3397. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
  3398. ;;
  3399. signcsr)
  3400. signcsr "$_csr" "$_webroot"
  3401. ;;
  3402. showcsr)
  3403. showcsr "$_csr" "$_domain"
  3404. ;;
  3405. installcert)
  3406. installcert "$_domain" "$_certpath" "$_keypath" "$_capath" "$_reloadcmd" "$_fullchainpath" "$_ecc"
  3407. ;;
  3408. renew)
  3409. renew "$_domain" "$_ecc"
  3410. ;;
  3411. renewAll)
  3412. renewAll "$_stopRenewOnError"
  3413. ;;
  3414. revoke)
  3415. revoke "$_domain" "$_ecc"
  3416. ;;
  3417. deactivate)
  3418. deactivate "$_domain,$_altdomains"
  3419. ;;
  3420. registeraccount)
  3421. registeraccount
  3422. ;;
  3423. updateaccount)
  3424. updateaccount
  3425. ;;
  3426. list)
  3427. list "$_listraw"
  3428. ;;
  3429. installcronjob) installcronjob ;;
  3430. uninstallcronjob) uninstallcronjob ;;
  3431. cron) cron ;;
  3432. toPkcs)
  3433. toPkcs "$_domain" "$_password" "$_ecc"
  3434. ;;
  3435. createAccountKey)
  3436. createAccountKey "$_accountkeylength"
  3437. ;;
  3438. createDomainKey)
  3439. createDomainKey "$_domain" "$_keylength"
  3440. ;;
  3441. createCSR)
  3442. createCSR "$_domain" "$_altdomains" "$_ecc"
  3443. ;;
  3444. *)
  3445. _err "Invalid command: $_CMD"
  3446. showhelp;
  3447. return 1
  3448. ;;
  3449. esac
  3450. _ret="$?"
  3451. if [ "$_ret" != "0" ] ; then
  3452. return $_ret
  3453. fi
  3454. if [ "${_CMD}" = "install" ] ; then
  3455. if [ "$_log" ] ; then
  3456. if [ -z "$LOG_FILE" ] ; then
  3457. LOG_FILE="$DEFAULT_LOG_FILE"
  3458. fi
  3459. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  3460. fi
  3461. if [ "$_log_level" ] ; then
  3462. _saveaccountconf "LOG_LEVEL" "$_log_level"
  3463. fi
  3464. _processAccountConf
  3465. fi
  3466. }
  3467. if [ "$INSTALLONLINE" ] ; then
  3468. INSTALLONLINE=""
  3469. _installOnline $BRANCH
  3470. exit
  3471. fi
  3472. main() {
  3473. [ -z "$1" ] && showhelp && return
  3474. if _startswith "$1" '-' ; then _process "$@"; else "$@";fi
  3475. }
  3476. main "$@"