le.sh 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683
  1. #!/usr/bin/env bash
  2. VER=1.2.1
  3. PROJECT="https://github.com/Neilpang/le"
  4. DEFAULT_CA="https://acme-v01.api.letsencrypt.org"
  5. DEFAULT_AGREEMENT="https://letsencrypt.org/documents/LE-SA-v1.0.1-July-27-2015.pdf"
  6. DEFAULT_USER_AGENT="le.sh client: $PROJECT"
  7. STAGE_CA="https://acme-staging.api.letsencrypt.org"
  8. VTYPE_HTTP="http-01"
  9. VTYPE_DNS="dns-01"
  10. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  11. END_CSR="-----END CERTIFICATE REQUEST-----"
  12. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  13. END_CERT="-----END CERTIFICATE-----"
  14. if [ -z "$AGREEMENT" ] ; then
  15. AGREEMENT="$DEFAULT_AGREEMENT"
  16. fi
  17. _info() {
  18. if [ -z "$2" ] ; then
  19. echo "$1"
  20. else
  21. echo "$1"="$2"
  22. fi
  23. }
  24. _err() {
  25. if [ -z "$2" ] ; then
  26. echo "$1" >&2
  27. else
  28. echo "$1"="'$2'" >&2
  29. fi
  30. return 1
  31. }
  32. _debug() {
  33. if [ -z "$DEBUG" ] ; then
  34. return
  35. fi
  36. _err "$1" "$2"
  37. return 0
  38. }
  39. _exists() {
  40. cmd="$1"
  41. if [ -z "$cmd" ] ; then
  42. _err "Usage: _exists cmd"
  43. return 1
  44. fi
  45. command -v $cmd >/dev/null 2>&1
  46. ret="$?"
  47. _debug "$cmd exists=$ret"
  48. return $ret
  49. }
  50. _h2b() {
  51. hex=$(cat)
  52. i=1
  53. j=2
  54. while [ '1' ] ; do
  55. h=$(printf $hex | cut -c $i-$j)
  56. if [ -z "$h" ] ; then
  57. break;
  58. fi
  59. printf "\x$h"
  60. let "i+=2"
  61. let "j+=2"
  62. done
  63. }
  64. #options file
  65. _sed_i() {
  66. options="$1"
  67. filename="$2"
  68. if [ -z "$filename" ] ; then
  69. _err "Usage:_sed_i options filename"
  70. return 1
  71. fi
  72. if sed -h 2>&1 | grep "\-i[SUFFIX]" ; then
  73. _debug "Using sed -i"
  74. sed -i ""
  75. else
  76. _debug "No -i support in sed"
  77. text="$(cat $filename)"
  78. echo "$text" | sed "$options" > "$filename"
  79. fi
  80. }
  81. #Usage: file startline endline
  82. _getfile() {
  83. filename="$1"
  84. startline="$2"
  85. endline="$3"
  86. if [ -z "$endline" ] ; then
  87. _err "Usage: file startline endline"
  88. return 1
  89. fi
  90. i="$(grep -n -- "$startline" $filename | cut -d : -f 1)"
  91. if [ -z "$i" ] ; then
  92. _err "Can not find start line: $startline"
  93. return 1
  94. fi
  95. let "i+=1"
  96. _debug i $i
  97. j="$(grep -n -- "$endline" $filename | cut -d : -f 1)"
  98. if [ -z "$j" ] ; then
  99. _err "Can not find end line: $endline"
  100. return 1
  101. fi
  102. let "j-=1"
  103. _debug j $j
  104. sed -n $i,${j}p "$filename"
  105. }
  106. #Usage: multiline
  107. _base64() {
  108. if [ "$1" ] ; then
  109. openssl base64 -e
  110. else
  111. openssl base64 -e | tr -d '\r\n'
  112. fi
  113. }
  114. #Usage: multiline
  115. _dbase64() {
  116. if [ "$1" ] ; then
  117. openssl base64 -d -A
  118. else
  119. openssl base64 -d
  120. fi
  121. }
  122. #Usage: hashalg
  123. #Output Base64-encoded digest
  124. _digest() {
  125. alg="$1"
  126. if [ -z "$alg" ] ; then
  127. _err "Usage: _digest hashalg"
  128. return 1
  129. fi
  130. if [ "$alg" == "sha256" ] ; then
  131. openssl dgst -sha256 -binary | _base64
  132. else
  133. _err "$alg is not supported yet"
  134. return 1
  135. fi
  136. }
  137. #Usage: keyfile hashalg
  138. #Output: Base64-encoded signature value
  139. _sign() {
  140. keyfile="$1"
  141. alg="$2"
  142. if [ -z "$alg" ] ; then
  143. _err "Usage: _sign keyfile hashalg"
  144. return 1
  145. fi
  146. if [ "$alg" == "sha256" ] ; then
  147. openssl dgst -sha256 -sign "$keyfile" | _base64
  148. else
  149. _err "$alg is not supported yet"
  150. return 1
  151. fi
  152. }
  153. _ss() {
  154. _port="$1"
  155. if _exists "ss" ; then
  156. _debug "Using: ss"
  157. ss -ntpl | grep :$_port" "
  158. return 0
  159. fi
  160. if _exists "netstat" ; then
  161. _debug "Using: netstat"
  162. if netstat -h 2>&1 | grep "\-p proto" >/dev/null ; then
  163. #for windows version netstat tool
  164. netstat -anb -p tcp | grep "LISTENING" | grep :$_port" "
  165. else
  166. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null ; then
  167. netstat -an -p tcp | grep LISTEN | grep :$_port" "
  168. else
  169. netstat -ntpl | grep :$_port" "
  170. fi
  171. fi
  172. return 0
  173. fi
  174. return 1
  175. }
  176. #domain [2048]
  177. createAccountKey() {
  178. _info "Creating account key"
  179. if [ -z "$1" ] ; then
  180. echo Usage: createAccountKey account-domain [2048]
  181. return
  182. fi
  183. account=$1
  184. length=$2
  185. if [[ "$length" == "ec-"* ]] ; then
  186. length=2048
  187. fi
  188. if [ -z "$2" ] ; then
  189. _info "Use default length 2048"
  190. length=2048
  191. fi
  192. _initpath
  193. if [ -f "$ACCOUNT_KEY_PATH" ] ; then
  194. _info "Account key exists, skip"
  195. return
  196. else
  197. #generate account key
  198. openssl genrsa $length 2>/dev/null > "$ACCOUNT_KEY_PATH"
  199. fi
  200. }
  201. #domain length
  202. createDomainKey() {
  203. _info "Creating domain key"
  204. if [ -z "$1" ] ; then
  205. echo Usage: createDomainKey domain [2048]
  206. return
  207. fi
  208. domain=$1
  209. length=$2
  210. isec=""
  211. if [[ "$length" == "ec-"* ]] ; then
  212. isec="1"
  213. length=$(printf $length | cut -d '-' -f 2-100)
  214. eccname="$length"
  215. fi
  216. if [ -z "$length" ] ; then
  217. if [ "$isec" ] ; then
  218. length=256
  219. else
  220. length=2048
  221. fi
  222. fi
  223. _info "Use length $length"
  224. if [ "$isec" ] ; then
  225. if [ "$length" == "256" ] ; then
  226. eccname="prime256v1"
  227. fi
  228. if [ "$length" == "384" ] ; then
  229. eccname="secp384r1"
  230. fi
  231. if [ "$length" == "521" ] ; then
  232. eccname="secp521r1"
  233. fi
  234. _info "Using ec name: $eccname"
  235. fi
  236. _initpath $domain
  237. if [ ! -f "$CERT_KEY_PATH" ] || ( [ "$FORCE" ] && ! [ "$IS_RENEW" ] ); then
  238. #generate account key
  239. if [ "$isec" ] ; then
  240. openssl ecparam -name $eccname -genkey 2>/dev/null > "$CERT_KEY_PATH"
  241. else
  242. openssl genrsa $length 2>/dev/null > "$CERT_KEY_PATH"
  243. fi
  244. else
  245. if [ "$IS_RENEW" ] ; then
  246. _info "Domain key exists, skip"
  247. return 0
  248. else
  249. _err "Domain key exists, do you want to overwrite the key?"
  250. _err "Set FORCE=1, and try again."
  251. return 1
  252. fi
  253. fi
  254. }
  255. # domain domainlist
  256. createCSR() {
  257. _info "Creating csr"
  258. if [ -z "$1" ] ; then
  259. echo Usage: $0 domain [domainlist]
  260. return
  261. fi
  262. domain=$1
  263. _initpath $domain
  264. domainlist=$2
  265. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && ! [ "$FORCE" ]; then
  266. _info "CSR exists, skip"
  267. return
  268. fi
  269. if [ -z "$domainlist" ] ; then
  270. #single domain
  271. _info "Single domain" $domain
  272. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n" > "$DOMAIN_SSL_CONF"
  273. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  274. else
  275. alt="DNS:$(echo $domainlist | sed "s/,/,DNS:/g")"
  276. #multi
  277. _info "Multi domain" "$alt"
  278. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\n[SAN]\nsubjectAltName=$alt" > "$DOMAIN_SSL_CONF"
  279. openssl req -new -sha256 -key "$CERT_KEY_PATH" -subj "/CN=$domain" -reqexts SAN -config "$DOMAIN_SSL_CONF" -out "$CSR_PATH"
  280. fi
  281. }
  282. _urlencode() {
  283. __n=$(cat)
  284. echo $__n | tr '/+' '_-' | tr -d '= '
  285. }
  286. _time2str() {
  287. #BSD
  288. if date -u -d@$1 2>/dev/null ; then
  289. return
  290. fi
  291. #Linux
  292. if date -u -r $1 2>/dev/null ; then
  293. return
  294. fi
  295. }
  296. _stat() {
  297. #Linux
  298. if stat -c '%U:%G' "$1" 2>/dev/null ; then
  299. return
  300. fi
  301. #BSD
  302. if stat -f '%Su:%Sg' "$1" 2>/dev/null ; then
  303. return
  304. fi
  305. }
  306. #keyfile
  307. _calcjwk() {
  308. keyfile="$1"
  309. if [ -z "$keyfile" ] ; then
  310. _err "Usage: _calcjwk keyfile"
  311. return 1
  312. fi
  313. EC_SIGN=""
  314. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  315. _debug "RSA key"
  316. pub_exp=$(openssl rsa -in $keyfile -noout -text | grep "^publicExponent:"| cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  317. if [ "${#pub_exp}" == "5" ] ; then
  318. pub_exp=0$pub_exp
  319. fi
  320. _debug pub_exp "$pub_exp"
  321. e=$(echo $pub_exp | _h2b | _base64)
  322. _debug e "$e"
  323. modulus=$(openssl rsa -in $keyfile -modulus -noout | cut -d '=' -f 2 )
  324. n=$(echo $modulus| _h2b | _base64 | _urlencode )
  325. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  326. _debug jwk "$jwk"
  327. HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  328. HEADERPLACE='{"nonce": "NONCE", "alg": "RS256", "jwk": '$jwk'}'
  329. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" > /dev/null 2>&1 ; then
  330. _debug "EC key"
  331. EC_SIGN="1"
  332. crv="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  333. _debug crv $crv
  334. pubi="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  335. _debug pubi $pubi
  336. let "pubi=pubi+1"
  337. pubj="$(openssl ec -in $keyfile -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  338. _debug pubj $pubj
  339. let "pubj=pubj-1"
  340. pubtext="$(openssl ec -in $keyfile -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  341. _debug pubtext "$pubtext"
  342. xlen="$(printf "$pubtext" | tr -d ':' | wc -c)"
  343. let "xlen=xlen/4"
  344. _debug xlen $xlen
  345. let "xend=xlen+1"
  346. x="$(printf $pubtext | cut -d : -f 2-$xend)"
  347. _debug x $x
  348. x64="$(printf $x | tr -d : | _h2b | _base64 | _urlencode)"
  349. _debug x64 $x64
  350. let "xend+=1"
  351. y="$(printf $pubtext | cut -d : -f $xend-10000)"
  352. _debug y $y
  353. y64="$(printf $y | tr -d : | _h2b | _base64 | _urlencode)"
  354. _debug y64 $y64
  355. jwk='{"kty": "EC", "crv": "'$crv'", "x": "'$x64'", "y": "'$y64'"}'
  356. _debug jwk "$jwk"
  357. HEADER='{"alg": "ES256", "jwk": '$jwk'}'
  358. HEADERPLACE='{"nonce": "NONCE", "alg": "ES256", "jwk": '$jwk'}'
  359. else
  360. _err "Only RSA or EC key is supported."
  361. return 1
  362. fi
  363. _debug HEADER "$HEADER"
  364. }
  365. # body url [needbase64]
  366. _post() {
  367. body="$1"
  368. url="$2"
  369. needbase64="$3"
  370. if _exists "curl" ; then
  371. CURL="$CURL --dump-header $HTTP_HEADER "
  372. if [ "$needbase64" ] ; then
  373. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url | _base64)"
  374. else
  375. response="$($CURL -A "User-Agent: $USER_AGENT" -X POST --data "$body" $url)"
  376. fi
  377. else
  378. if [ "$needbase64" ] ; then
  379. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER" | _base64)"
  380. else
  381. response="$($WGET -S -O - --user-agent="$USER_AGENT" --post-data="$body" $url 2>"$HTTP_HEADER")"
  382. fi
  383. _sed_i "s/^ *//g" "$HTTP_HEADER"
  384. fi
  385. echo -n "$response"
  386. }
  387. # url getheader
  388. _get() {
  389. url="$1"
  390. onlyheader="$2"
  391. _debug url $url
  392. if _exists "curl" ; then
  393. if [ "$onlyheader" ] ; then
  394. $CURL -I -A "User-Agent: $USER_AGENT" $url
  395. else
  396. $CURL -A "User-Agent: $USER_AGENT" $url
  397. fi
  398. else
  399. _debug "WGET" "$WGET"
  400. if [ "$onlyheader" ] ; then
  401. eval $WGET --user-agent=\"$USER_AGENT\" -S -O /dev/null $url 2>&1 | sed 's/^[ ]*//g'
  402. else
  403. eval $WGET --user-agent=\"$USER_AGENT\" -O - $url
  404. fi
  405. fi
  406. ret=$?
  407. return $ret
  408. }
  409. # url payload needbase64 keyfile
  410. _send_signed_request() {
  411. url=$1
  412. payload=$2
  413. needbase64=$3
  414. keyfile=$4
  415. if [ -z "$keyfile" ] ; then
  416. keyfile="$ACCOUNT_KEY_PATH"
  417. fi
  418. _debug url $url
  419. _debug payload "$payload"
  420. if ! _calcjwk "$keyfile" ; then
  421. return 1
  422. fi
  423. payload64=$(echo -n $payload | _base64 | _urlencode)
  424. _debug payload64 $payload64
  425. nonceurl="$API/directory"
  426. nonce="$(_get $nonceurl "onlyheader" | grep -o "Replay-Nonce:.*$" | head -1 | tr -d "\r\n" | cut -d ' ' -f 2)"
  427. _debug nonce "$nonce"
  428. protected="$(printf "$HEADERPLACE" | sed "s/NONCE/$nonce/" )"
  429. _debug protected "$protected"
  430. protected64="$(printf "$protected" | _base64 | _urlencode)"
  431. _debug protected64 "$protected64"
  432. sig=$(echo -n "$protected64.$payload64" | _sign "$keyfile" "sha256" | _urlencode)
  433. _debug sig "$sig"
  434. body="{\"header\": $HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  435. _debug body "$body"
  436. response="$(_post "$body" $url "$needbase64" )"
  437. responseHeaders="$(cat $HTTP_HEADER)"
  438. _debug responseHeaders "$responseHeaders"
  439. _debug response "$response"
  440. code="$(grep "^HTTP" $HTTP_HEADER | tail -1 | cut -d " " -f 2 | tr -d "\r\n" )"
  441. _debug code $code
  442. }
  443. #setopt "file" "opt" "=" "value" [";"]
  444. _setopt() {
  445. __conf="$1"
  446. __opt="$2"
  447. __sep="$3"
  448. __val="$4"
  449. __end="$5"
  450. if [ -z "$__opt" ] ; then
  451. echo usage: _setopt '"file" "opt" "=" "value" [";"]'
  452. return
  453. fi
  454. if [ ! -f "$__conf" ] ; then
  455. touch "$__conf"
  456. fi
  457. if grep -H -n "^$__opt$__sep" "$__conf" > /dev/null ; then
  458. _debug OK
  459. if [[ "$__val" == *"&"* ]] ; then
  460. __val="$(echo $__val | sed 's/&/\\&/g')"
  461. fi
  462. text="$(cat $__conf)"
  463. echo "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  464. elif grep -H -n "^#$__opt$__sep" "$__conf" > /dev/null ; then
  465. if [[ "$__val" == *"&"* ]] ; then
  466. __val="$(echo $__val | sed 's/&/\\&/g')"
  467. fi
  468. text="$(cat $__conf)"
  469. echo "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" > "$__conf"
  470. else
  471. _debug APP
  472. echo "$__opt$__sep$__val$__end" >> "$__conf"
  473. fi
  474. _debug "$(grep -H -n "^$__opt$__sep" $__conf)"
  475. }
  476. #_savedomainconf key value
  477. #save to domain.conf
  478. _savedomainconf() {
  479. key="$1"
  480. value="$2"
  481. if [ "$DOMAIN_CONF" ] ; then
  482. _setopt $DOMAIN_CONF "$key" "=" "$value"
  483. else
  484. _err "DOMAIN_CONF is empty, can not save $key=$value"
  485. fi
  486. }
  487. #_saveaccountconf key value
  488. _saveaccountconf() {
  489. key="$1"
  490. value="$2"
  491. if [ "$ACCOUNT_CONF_PATH" ] ; then
  492. _setopt $ACCOUNT_CONF_PATH "$key" "=" "$value"
  493. else
  494. _err "ACCOUNT_CONF_PATH is empty, can not save $key=$value"
  495. fi
  496. }
  497. _startserver() {
  498. content="$1"
  499. nchelp="$(nc -h 2>&1)"
  500. if echo "$nchelp" | grep "\-q[ ,]" >/dev/null ; then
  501. _NC="nc -q 1 -l"
  502. else
  503. if echo "$nchelp" | grep "GNU netcat" >/dev/null && echo "$nchelp" | grep "\-c, \-\-close" >/dev/null ; then
  504. _NC="nc -c -l"
  505. elif echo "$nchelp" | grep "\-N" |grep "Shutdown the network socket after EOF on stdin" >/dev/null ; then
  506. _NC="nc -N -l"
  507. else
  508. _NC="nc -l"
  509. fi
  510. fi
  511. _debug "_NC" "$_NC"
  512. # while true ; do
  513. if [ "$DEBUG" ] ; then
  514. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort -vv ; then
  515. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort -vv ;
  516. fi
  517. else
  518. if ! echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC -p $Le_HTTPPort > /dev/null 2>&1; then
  519. echo -e -n "HTTP/1.1 200 OK\r\n\r\n$content" | $_NC $Le_HTTPPort > /dev/null 2>&1
  520. fi
  521. fi
  522. if [ "$?" != "0" ] ; then
  523. _err "nc listen error."
  524. return 1
  525. fi
  526. # done
  527. }
  528. _stopserver() {
  529. pid="$1"
  530. }
  531. _initpath() {
  532. if [ -z "$LE_WORKING_DIR" ]; then
  533. LE_WORKING_DIR=$HOME/.le
  534. fi
  535. if [ -z "$ACCOUNT_CONF_PATH" ] ; then
  536. ACCOUNT_CONF_PATH="$LE_WORKING_DIR/account.conf"
  537. fi
  538. if [ -f "$ACCOUNT_CONF_PATH" ] ; then
  539. source "$ACCOUNT_CONF_PATH"
  540. fi
  541. if [ -z "$API" ] ; then
  542. if [ -z "$STAGE" ] ; then
  543. API="$DEFAULT_CA"
  544. else
  545. API="$STAGE_CA"
  546. _info "Using stage api:$API"
  547. fi
  548. fi
  549. if [ -z "$ACME_DIR" ] ; then
  550. ACME_DIR="/home/.acme"
  551. fi
  552. if [ -z "$APACHE_CONF_BACKUP_DIR" ] ; then
  553. APACHE_CONF_BACKUP_DIR="$LE_WORKING_DIR/"
  554. fi
  555. if [ -z "$USER_AGENT" ] ; then
  556. USER_AGENT="$DEFAULT_USER_AGENT"
  557. fi
  558. HTTP_HEADER="$LE_WORKING_DIR/http.header"
  559. WGET="wget -q"
  560. if [ "$DEBUG" ] ; then
  561. WGET="$WGET -d "
  562. fi
  563. dp="$LE_WORKING_DIR/curl.dump"
  564. CURL="curl -L --silent"
  565. if [ "$DEBUG" ] ; then
  566. CURL="$CURL -L --trace-ascii $dp "
  567. fi
  568. domain="$1"
  569. if [ -z "$ACCOUNT_KEY_PATH" ] ; then
  570. ACCOUNT_KEY_PATH="$LE_WORKING_DIR/account.key"
  571. fi
  572. if [ -z "$domain" ] ; then
  573. return 0
  574. fi
  575. domainhome="$LE_WORKING_DIR/$domain"
  576. mkdir -p "$domainhome"
  577. if [ -z "$DOMAIN_PATH" ] ; then
  578. DOMAIN_PATH="$domainhome"
  579. fi
  580. if [ -z "$DOMAIN_CONF" ] ; then
  581. DOMAIN_CONF="$domainhome/$domain.conf"
  582. fi
  583. if [ -z "$DOMAIN_SSL_CONF" ] ; then
  584. DOMAIN_SSL_CONF="$domainhome/$domain.ssl.conf"
  585. fi
  586. if [ -z "$CSR_PATH" ] ; then
  587. CSR_PATH="$domainhome/$domain.csr"
  588. fi
  589. if [ -z "$CERT_KEY_PATH" ] ; then
  590. CERT_KEY_PATH="$domainhome/$domain.key"
  591. fi
  592. if [ -z "$CERT_PATH" ] ; then
  593. CERT_PATH="$domainhome/$domain.cer"
  594. fi
  595. if [ -z "$CA_CERT_PATH" ] ; then
  596. CA_CERT_PATH="$domainhome/ca.cer"
  597. fi
  598. if [ -z "$CERT_FULLCHAIN_PATH" ] ; then
  599. CERT_FULLCHAIN_PATH="$domainhome/fullchain.cer"
  600. fi
  601. }
  602. _apachePath() {
  603. httpdconfname="$(apachectl -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"' )"
  604. if [[ "$httpdconfname" == '/'* ]] ; then
  605. httpdconf="$httpdconfname"
  606. httpdconfname="$(basename $httpdconfname)"
  607. else
  608. httpdroot="$(apachectl -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"' )"
  609. httpdconf="$httpdroot/$httpdconfname"
  610. fi
  611. if [ ! -f $httpdconf ] ; then
  612. _err "Apache Config file not found" $httpdconf
  613. return 1
  614. fi
  615. return 0
  616. }
  617. _restoreApache() {
  618. if [ -z "$usingApache" ] ; then
  619. return 0
  620. fi
  621. _initpath
  622. if ! _apachePath ; then
  623. return 1
  624. fi
  625. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ] ; then
  626. _debug "No config file to restore."
  627. return 0
  628. fi
  629. cp -p "$APACHE_CONF_BACKUP_DIR/$httpdconfname" "$httpdconf"
  630. if ! apachectl -t ; then
  631. _err "Sorry, restore apache config error, please contact me."
  632. return 1;
  633. fi
  634. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  635. return 0
  636. }
  637. _setApache() {
  638. _initpath
  639. if ! _apachePath ; then
  640. return 1
  641. fi
  642. #backup the conf
  643. _debug "Backup apache config file" $httpdconf
  644. cp -p $httpdconf $APACHE_CONF_BACKUP_DIR/
  645. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  646. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  647. _info "The backup file will be deleted on sucess, just forget it."
  648. #add alias
  649. echo "
  650. Alias /.well-known/acme-challenge $ACME_DIR
  651. <Directory $ACME_DIR >
  652. Require all granted
  653. </Directory>
  654. " >> $httpdconf
  655. if ! apachectl -t ; then
  656. _err "Sorry, apache config error, please contact me."
  657. _restoreApache
  658. return 1;
  659. fi
  660. if [ ! -d "$ACME_DIR" ] ; then
  661. mkdir -p "$ACME_DIR"
  662. chmod 755 "$ACME_DIR"
  663. fi
  664. if ! apachectl graceful ; then
  665. _err "Sorry, apachectl graceful error, please contact me."
  666. _restoreApache
  667. return 1;
  668. fi
  669. usingApache="1"
  670. return 0
  671. }
  672. _clearup () {
  673. _stopserver $serverproc
  674. serverproc=""
  675. _restoreApache
  676. }
  677. # webroot removelevel tokenfile
  678. _clearupwebbroot() {
  679. __webroot="$1"
  680. if [ -z "$__webroot" ] ; then
  681. _debug "no webroot specified, skip"
  682. return 0
  683. fi
  684. if [ "$2" == '1' ] ; then
  685. _debug "remove $__webroot/.well-known"
  686. rm -rf "$__webroot/.well-known"
  687. elif [ "$2" == '2' ] ; then
  688. _debug "remove $__webroot/.well-known/acme-challenge"
  689. rm -rf "$__webroot/.well-known/acme-challenge"
  690. elif [ "$2" == '3' ] ; then
  691. _debug "remove $__webroot/.well-known/acme-challenge/$3"
  692. rm -rf "$__webroot/.well-known/acme-challenge/$3"
  693. else
  694. _info "Skip for removelevel:$2"
  695. fi
  696. return 0
  697. }
  698. issue() {
  699. if [ -z "$2" ] ; then
  700. _err "Usage: le issue webroot|no|apache|dns a.com [www.a.com,b.com,c.com]|no [key-length]|no"
  701. return 1
  702. fi
  703. Le_Webroot="$1"
  704. Le_Domain="$2"
  705. Le_Alt="$3"
  706. Le_Keylength="$4"
  707. Le_RealCertPath="$5"
  708. Le_RealKeyPath="$6"
  709. Le_RealCACertPath="$7"
  710. Le_ReloadCmd="$8"
  711. _initpath $Le_Domain
  712. if [ -f "$DOMAIN_CONF" ] ; then
  713. Le_NextRenewTime=$(grep "^Le_NextRenewTime=" "$DOMAIN_CONF" | cut -d '=' -f 2)
  714. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  715. _info "Skip, Next renewal time is: $(grep "^Le_NextRenewTimeStr" "$DOMAIN_CONF" | cut -d '=' -f 2)"
  716. return 2
  717. fi
  718. fi
  719. _setopt "$DOMAIN_CONF" "Le_Domain" "=" "$Le_Domain"
  720. _setopt "$DOMAIN_CONF" "Le_Alt" "=" "$Le_Alt"
  721. _setopt "$DOMAIN_CONF" "Le_Webroot" "=" "$Le_Webroot"
  722. _setopt "$DOMAIN_CONF" "Le_Keylength" "=" "$Le_Keylength"
  723. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  724. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  725. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  726. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  727. if [ "$Le_Alt" == "no" ] ; then
  728. Le_Alt=""
  729. fi
  730. if [ "$Le_Keylength" == "no" ] ; then
  731. Le_Keylength=""
  732. fi
  733. if [ "$Le_RealCertPath" == "no" ] ; then
  734. Le_RealCertPath=""
  735. fi
  736. if [ "$Le_RealKeyPath" == "no" ] ; then
  737. Le_RealKeyPath=""
  738. fi
  739. if [ "$Le_RealCACertPath" == "no" ] ; then
  740. Le_RealCACertPath=""
  741. fi
  742. if [ "$Le_ReloadCmd" == "no" ] ; then
  743. Le_ReloadCmd=""
  744. fi
  745. if [ "$Le_Webroot" == "no" ] ; then
  746. _info "Standalone mode."
  747. if ! command -v "nc" > /dev/null ; then
  748. _err "Please install netcat(nc) tools first."
  749. return 1
  750. fi
  751. if [ -z "$Le_HTTPPort" ] ; then
  752. Le_HTTPPort=80
  753. fi
  754. _setopt "$DOMAIN_CONF" "Le_HTTPPort" "=" "$Le_HTTPPort"
  755. netprc="$(_ss "$Le_HTTPPort" | grep "$Le_HTTPPort")"
  756. if [ "$netprc" ] ; then
  757. _err "$netprc"
  758. _err "tcp port $Le_HTTPPort is already used by $(echo "$netprc" | cut -d : -f 4)"
  759. _err "Please stop it first"
  760. return 1
  761. fi
  762. fi
  763. if [ "$Le_Webroot" == "apache" ] ; then
  764. if ! _setApache ; then
  765. _err "set up apache error. Report error to me."
  766. return 1
  767. fi
  768. wellknown_path="$ACME_DIR"
  769. else
  770. usingApache=""
  771. fi
  772. createAccountKey $Le_Domain $Le_Keylength
  773. if ! _calcjwk "$ACCOUNT_KEY_PATH" ; then
  774. return 1
  775. fi
  776. accountkey_json=$(echo -n "$jwk" | tr -d ' ' )
  777. thumbprint=$(echo -n "$accountkey_json" | _digest "sha256" | _urlencode)
  778. accountkeyhash="$(cat "$ACCOUNT_KEY_PATH" | _digest "sha256" )"
  779. if [ "$accountkeyhash" != "$ACCOUNT_KEY_HASH" ] ; then
  780. _info "Registering account"
  781. regjson='{"resource": "new-reg", "agreement": "'$AGREEMENT'"}'
  782. if [ "$ACCOUNT_EMAIL" ] ; then
  783. regjson='{"resource": "new-reg", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "agreement": "'$AGREEMENT'"}'
  784. fi
  785. _send_signed_request "$API/acme/new-reg" "$regjson"
  786. if [ "$code" == "" ] || [ "$code" == '201' ] ; then
  787. _info "Registered"
  788. echo $response > $LE_WORKING_DIR/account.json
  789. elif [ "$code" == '409' ] ; then
  790. _info "Already registered"
  791. else
  792. _err "Register account Error: $response"
  793. _clearup
  794. return 1
  795. fi
  796. ACCOUNT_KEY_HASH="$accountkeyhash"
  797. _saveaccountconf "ACCOUNT_KEY_HASH" "$ACCOUNT_KEY_HASH"
  798. else
  799. _info "Skip register account key"
  800. fi
  801. if ! createDomainKey $Le_Domain $Le_Keylength ; then
  802. _err "Create domain key error."
  803. return 1
  804. fi
  805. if ! createCSR $Le_Domain $Le_Alt ; then
  806. _err "Create CSR error."
  807. return 1
  808. fi
  809. vtype="$VTYPE_HTTP"
  810. if [[ "$Le_Webroot" == "dns"* ]] ; then
  811. vtype="$VTYPE_DNS"
  812. fi
  813. vlist="$Le_Vlist"
  814. # verify each domain
  815. _info "Verify each domain"
  816. sep='#'
  817. if [ -z "$vlist" ] ; then
  818. alldomains=$(echo "$Le_Domain,$Le_Alt" | tr ',' ' ' )
  819. for d in $alldomains
  820. do
  821. _info "Getting token for domain" $d
  822. _send_signed_request "$API/acme/new-authz" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$d\"}}"
  823. if [ ! -z "$code" ] && [ ! "$code" == '201' ] ; then
  824. _err "new-authz error: $response"
  825. _clearup
  826. return 1
  827. fi
  828. entry="$(printf $response | egrep -o '\{[^{]*"type":"'$vtype'"[^}]*')"
  829. _debug entry "$entry"
  830. token="$(printf "$entry" | egrep -o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  831. _debug token $token
  832. uri="$(printf "$entry" | egrep -o '"uri":"[^"]*'| cut -d : -f 2,3 | tr -d '"' )"
  833. _debug uri $uri
  834. keyauthorization="$token.$thumbprint"
  835. _debug keyauthorization "$keyauthorization"
  836. dvlist="$d$sep$keyauthorization$sep$uri"
  837. _debug dvlist "$dvlist"
  838. vlist="$vlist$dvlist,"
  839. done
  840. #add entry
  841. dnsadded=""
  842. ventries=$(echo "$vlist" | tr ',' ' ' )
  843. for ventry in $ventries
  844. do
  845. d=$(echo $ventry | cut -d $sep -f 1)
  846. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  847. if [ "$vtype" == "$VTYPE_DNS" ] ; then
  848. dnsadded='0'
  849. txtdomain="_acme-challenge.$d"
  850. _debug txtdomain "$txtdomain"
  851. txt="$(echo -e -n $keyauthorization | _digest "sha256" | _urlencode)"
  852. _debug txt "$txt"
  853. #dns
  854. #1. check use api
  855. d_api=""
  856. if [ -f "$LE_WORKING_DIR/$d/$Le_Webroot" ] ; then
  857. d_api="$LE_WORKING_DIR/$d/$Le_Webroot"
  858. elif [ -f "$LE_WORKING_DIR/$d/$Le_Webroot.sh" ] ; then
  859. d_api="$LE_WORKING_DIR/$d/$Le_Webroot.sh"
  860. elif [ -f "$LE_WORKING_DIR/$Le_Webroot" ] ; then
  861. d_api="$LE_WORKING_DIR/$Le_Webroot"
  862. elif [ -f "$LE_WORKING_DIR/$Le_Webroot.sh" ] ; then
  863. d_api="$LE_WORKING_DIR/$Le_Webroot.sh"
  864. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot" ] ; then
  865. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot"
  866. elif [ -f "$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh" ] ; then
  867. d_api="$LE_WORKING_DIR/dnsapi/$Le_Webroot.sh"
  868. fi
  869. _debug d_api "$d_api"
  870. if [ "$d_api" ]; then
  871. _info "Found domain api file: $d_api"
  872. else
  873. _err "Add the following TXT record:"
  874. _err "Domain: $txtdomain"
  875. _err "TXT value: $txt"
  876. _err "Please be aware that you prepend _acme-challenge. before your domain"
  877. _err "so the resulting subdomain will be: $txtdomain"
  878. continue
  879. fi
  880. (
  881. if ! source $d_api ; then
  882. _err "Load file $d_api error. Please check your api file and try again."
  883. return 1
  884. fi
  885. addcommand="$Le_Webroot-add"
  886. if ! command -v $addcommand ; then
  887. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  888. return 1
  889. fi
  890. if ! $addcommand $txtdomain $txt ; then
  891. _err "Error add txt for domain:$txtdomain"
  892. return 1
  893. fi
  894. )
  895. if [[ "$?" != "0" ]] ; then
  896. return 1
  897. fi
  898. dnsadded='1'
  899. fi
  900. done
  901. if [ "$dnsadded" == '0' ] ; then
  902. _setopt "$DOMAIN_CONF" "Le_Vlist" "=" "\"$vlist\""
  903. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  904. _err "Please add the TXT records to the domains, and retry again."
  905. return 1
  906. fi
  907. fi
  908. if [ "$dnsadded" == '1' ] ; then
  909. _info "Sleep 60 seconds for the txt records to take effect"
  910. sleep 60
  911. fi
  912. _debug "ok, let's start to verify"
  913. ventries=$(echo "$vlist" | tr ',' ' ' )
  914. for ventry in $ventries
  915. do
  916. d=$(echo $ventry | cut -d $sep -f 1)
  917. keyauthorization=$(echo $ventry | cut -d $sep -f 2)
  918. uri=$(echo $ventry | cut -d $sep -f 3)
  919. _info "Verifying:$d"
  920. _debug "d" "$d"
  921. _debug "keyauthorization" "$keyauthorization"
  922. _debug "uri" "$uri"
  923. removelevel=""
  924. token=""
  925. if [ "$vtype" == "$VTYPE_HTTP" ] ; then
  926. if [ "$Le_Webroot" == "no" ] ; then
  927. _info "Standalone mode server"
  928. _startserver "$keyauthorization" &
  929. serverproc="$!"
  930. sleep 2
  931. _debug serverproc $serverproc
  932. else
  933. if [ -z "$wellknown_path" ] ; then
  934. wellknown_path="$Le_Webroot/.well-known/acme-challenge"
  935. fi
  936. _debug wellknown_path "$wellknown_path"
  937. if [ ! -d "$Le_Webroot/.well-known" ] ; then
  938. removelevel='1'
  939. elif [ ! -d "$Le_Webroot/.well-known/acme-challenge" ] ; then
  940. removelevel='2'
  941. else
  942. removelevel='3'
  943. fi
  944. token="$(echo -e -n "$keyauthorization" | cut -d '.' -f 1)"
  945. _debug "writing token:$token to $wellknown_path/$token"
  946. mkdir -p "$wellknown_path"
  947. echo -n "$keyauthorization" > "$wellknown_path/$token"
  948. webroot_owner=$(_stat $Le_Webroot)
  949. _debug "Changing owner/group of .well-known to $webroot_owner"
  950. chown -R $webroot_owner "$Le_Webroot/.well-known"
  951. fi
  952. fi
  953. _send_signed_request $uri "{\"resource\": \"challenge\", \"keyAuthorization\": \"$keyauthorization\"}"
  954. if [ ! -z "$code" ] && [ ! "$code" == '202' ] ; then
  955. _err "$d:Challenge error: $response"
  956. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  957. _clearup
  958. return 1
  959. fi
  960. while [ "1" ] ; do
  961. _debug "sleep 5 secs to verify"
  962. sleep 5
  963. _debug "checking"
  964. response="$(_get $uri)"
  965. if [ "$?" != "0" ] ; then
  966. _err "$d:Verify error:$response"
  967. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  968. _clearup
  969. return 1
  970. fi
  971. status=$(echo $response | egrep -o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  972. if [ "$status" == "valid" ] ; then
  973. _info "Success"
  974. _stopserver $serverproc
  975. serverproc=""
  976. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  977. break;
  978. fi
  979. if [ "$status" == "invalid" ] ; then
  980. error=$(echo $response | egrep -o '"error":{[^}]*}' | grep -o '"detail":"[^"]*"' | cut -d '"' -f 4)
  981. _err "$d:Verify error:$error"
  982. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  983. _clearup
  984. return 1;
  985. fi
  986. if [ "$status" == "pending" ] ; then
  987. _info "Pending"
  988. else
  989. _err "$d:Verify error:$response"
  990. _clearupwebbroot "$Le_Webroot" "$removelevel" "$token"
  991. _clearup
  992. return 1
  993. fi
  994. done
  995. done
  996. _clearup
  997. _info "Verify finished, start to sign."
  998. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _urlencode)"
  999. _send_signed_request "$API/acme/new-cert" "{\"resource\": \"new-cert\", \"csr\": \"$der\"}" "needbase64"
  1000. Le_LinkCert="$(grep -i -o '^Location.*$' $HTTP_HEADER | head -1 | tr -d "\r\n" | cut -d " " -f 2)"
  1001. _setopt "$DOMAIN_CONF" "Le_LinkCert" "=" "$Le_LinkCert"
  1002. if [ "$Le_LinkCert" ] ; then
  1003. echo "$BEGIN_CERT" > "$CERT_PATH"
  1004. _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH"
  1005. echo "$END_CERT" >> "$CERT_PATH"
  1006. _info "Cert success."
  1007. cat "$CERT_PATH"
  1008. _info "Your cert is in $CERT_PATH"
  1009. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  1010. fi
  1011. if [ -z "$Le_LinkCert" ] ; then
  1012. response="$(echo $response | _dbase64 "multiline" )"
  1013. _err "Sign failed: $(echo "$response" | grep -o '"detail":"[^"]*"')"
  1014. return 1
  1015. fi
  1016. _setopt "$DOMAIN_CONF" 'Le_Vlist' '=' "\"\""
  1017. Le_LinkIssuer=$(grep -i '^Link' $HTTP_HEADER | head -1 | cut -d " " -f 2| cut -d ';' -f 1 | tr -d '<>' )
  1018. _setopt "$DOMAIN_CONF" "Le_LinkIssuer" "=" "$Le_LinkIssuer"
  1019. if [ "$Le_LinkIssuer" ] ; then
  1020. echo "$BEGIN_CERT" > "$CA_CERT_PATH"
  1021. _get "$Le_LinkIssuer" | _base64 "multiline" >> "$CA_CERT_PATH"
  1022. echo "$END_CERT" >> "$CA_CERT_PATH"
  1023. _info "The intermediate CA cert is in $CA_CERT_PATH"
  1024. cat "$CA_CERT_PATH" >> "$CERT_FULLCHAIN_PATH"
  1025. _info "And the full chain certs is there: $CERT_FULLCHAIN_PATH"
  1026. fi
  1027. Le_CertCreateTime=$(date -u "+%s")
  1028. _setopt "$DOMAIN_CONF" "Le_CertCreateTime" "=" "$Le_CertCreateTime"
  1029. Le_CertCreateTimeStr=$(date -u )
  1030. _setopt "$DOMAIN_CONF" "Le_CertCreateTimeStr" "=" "\"$Le_CertCreateTimeStr\""
  1031. if [ ! "$Le_RenewalDays" ] ; then
  1032. Le_RenewalDays=80
  1033. fi
  1034. _setopt "$DOMAIN_CONF" "Le_RenewalDays" "=" "$Le_RenewalDays"
  1035. let "Le_NextRenewTime=Le_CertCreateTime+Le_RenewalDays*24*60*60"
  1036. _setopt "$DOMAIN_CONF" "Le_NextRenewTime" "=" "$Le_NextRenewTime"
  1037. Le_NextRenewTimeStr=$( _time2str $Le_NextRenewTime )
  1038. _setopt "$DOMAIN_CONF" "Le_NextRenewTimeStr" "=" "\"$Le_NextRenewTimeStr\""
  1039. installcert $Le_Domain "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  1040. }
  1041. renew() {
  1042. Le_Domain="$1"
  1043. if [ -z "$Le_Domain" ] ; then
  1044. _err "Usage: $0 domain.com"
  1045. return 1
  1046. fi
  1047. _initpath $Le_Domain
  1048. if [ ! -f "$DOMAIN_CONF" ] ; then
  1049. _info "$Le_Domain is not a issued domain, skip."
  1050. return 0;
  1051. fi
  1052. source "$DOMAIN_CONF"
  1053. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(date -u "+%s" )" -lt "$Le_NextRenewTime" ] ; then
  1054. _info "Skip, Next renewal time is: $Le_NextRenewTimeStr"
  1055. return 2
  1056. fi
  1057. IS_RENEW="1"
  1058. issue "$Le_Webroot" "$Le_Domain" "$Le_Alt" "$Le_Keylength" "$Le_RealCertPath" "$Le_RealKeyPath" "$Le_RealCACertPath" "$Le_ReloadCmd"
  1059. local res=$?
  1060. IS_RENEW=""
  1061. return $res
  1062. }
  1063. renewAll() {
  1064. _initpath
  1065. _info "renewAll"
  1066. for d in $(ls -F ${LE_WORKING_DIR}/ | grep [^.].*[.].*/$ ) ; do
  1067. d=$(echo $d | cut -d '/' -f 1)
  1068. _info "renew $d"
  1069. Le_LinkCert=""
  1070. Le_Domain=""
  1071. Le_Alt="no"
  1072. Le_Webroot=""
  1073. Le_Keylength=""
  1074. Le_LinkIssuer=""
  1075. Le_CertCreateTime=""
  1076. Le_CertCreateTimeStr=""
  1077. Le_RenewalDays=""
  1078. Le_NextRenewTime=""
  1079. Le_NextRenewTimeStr=""
  1080. Le_RealCertPath=""
  1081. Le_RealKeyPath=""
  1082. Le_RealCACertPath=""
  1083. Le_ReloadCmd=""
  1084. DOMAIN_PATH=""
  1085. DOMAIN_CONF=""
  1086. DOMAIN_SSL_CONF=""
  1087. CSR_PATH=""
  1088. CERT_KEY_PATH=""
  1089. CERT_PATH=""
  1090. CA_CERT_PATH=""
  1091. CERT_FULLCHAIN_PATH=""
  1092. ACCOUNT_KEY_PATH=""
  1093. wellknown_path=""
  1094. renew "$d"
  1095. done
  1096. }
  1097. installcert() {
  1098. Le_Domain="$1"
  1099. if [ -z "$Le_Domain" ] ; then
  1100. _err "Usage: $0 domain.com [cert-file-path]|no [key-file-path]|no [ca-cert-file-path]|no [reloadCmd]|no"
  1101. return 1
  1102. fi
  1103. Le_RealCertPath="$2"
  1104. Le_RealKeyPath="$3"
  1105. Le_RealCACertPath="$4"
  1106. Le_ReloadCmd="$5"
  1107. _initpath $Le_Domain
  1108. _setopt "$DOMAIN_CONF" "Le_RealCertPath" "=" "\"$Le_RealCertPath\""
  1109. _setopt "$DOMAIN_CONF" "Le_RealCACertPath" "=" "\"$Le_RealCACertPath\""
  1110. _setopt "$DOMAIN_CONF" "Le_RealKeyPath" "=" "\"$Le_RealKeyPath\""
  1111. _setopt "$DOMAIN_CONF" "Le_ReloadCmd" "=" "\"$Le_ReloadCmd\""
  1112. if [ "$Le_RealCertPath" ] ; then
  1113. if [ -f "$Le_RealCertPath" ] ; then
  1114. cp -p "$Le_RealCertPath" "$Le_RealCertPath".bak
  1115. fi
  1116. cat "$CERT_PATH" > "$Le_RealCertPath"
  1117. fi
  1118. if [ "$Le_RealCACertPath" ] ; then
  1119. if [ -f "$Le_RealCACertPath" ] ; then
  1120. cp -p "$Le_RealCACertPath" "$Le_RealCACertPath".bak
  1121. fi
  1122. if [ "$Le_RealCACertPath" == "$Le_RealCertPath" ] ; then
  1123. echo "" >> "$Le_RealCACertPath"
  1124. cat "$CA_CERT_PATH" >> "$Le_RealCACertPath"
  1125. else
  1126. cat "$CA_CERT_PATH" > "$Le_RealCACertPath"
  1127. fi
  1128. fi
  1129. if [ "$Le_RealKeyPath" ] ; then
  1130. if [ -f "$Le_RealKeyPath" ] ; then
  1131. cp -p "$Le_RealKeyPath" "$Le_RealKeyPath".bak
  1132. fi
  1133. cat "$CERT_KEY_PATH" > "$Le_RealKeyPath"
  1134. fi
  1135. if [ "$Le_ReloadCmd" ] ; then
  1136. _info "Run Le_ReloadCmd: $Le_ReloadCmd"
  1137. (cd "$DOMAIN_PATH" && eval "$Le_ReloadCmd")
  1138. fi
  1139. }
  1140. installcronjob() {
  1141. _initpath
  1142. if ! _exists "crontab" ; then
  1143. _err "crontab doesn't exist, so, we can not install cron jobs."
  1144. _err "All your certs will not be renewed automatically."
  1145. _err "You must add your own cron job to call 'le.sh cron' everyday."
  1146. return 1
  1147. fi
  1148. _info "Installing cron job"
  1149. if ! crontab -l | grep 'le.sh cron' ; then
  1150. if [ -f "$LE_WORKING_DIR/le.sh" ] ; then
  1151. lesh="\"$LE_WORKING_DIR\"/le.sh"
  1152. else
  1153. _err "Can not install cronjob, le.sh not found."
  1154. return 1
  1155. fi
  1156. crontab -l | { cat; echo "0 0 * * * LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"; } | crontab -
  1157. fi
  1158. if [ "$?" != "0" ] ; then
  1159. _err "Install cron job failed. You need to manually renew your certs."
  1160. _err "Or you can add cronjob by yourself:"
  1161. _err "LE_WORKING_DIR=\"$LE_WORKING_DIR\" $lesh cron > /dev/null"
  1162. return 1
  1163. fi
  1164. }
  1165. uninstallcronjob() {
  1166. if ! _exists "crontab" ; then
  1167. return
  1168. fi
  1169. _info "Removing cron job"
  1170. cr="$(crontab -l | grep 'le.sh cron')"
  1171. if [ "$cr" ] ; then
  1172. crontab -l | sed "/le.sh cron/d" | crontab -
  1173. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 6 | cut -d '=' -f 2 | tr -d '"')"
  1174. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  1175. fi
  1176. _initpath
  1177. }
  1178. # Detect profile file if not specified as environment variable
  1179. _detect_profile() {
  1180. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  1181. echo "$PROFILE"
  1182. return
  1183. fi
  1184. local DETECTED_PROFILE
  1185. DETECTED_PROFILE=''
  1186. local SHELLTYPE
  1187. SHELLTYPE="$(basename "/$SHELL")"
  1188. if [ "$SHELLTYPE" = "bash" ]; then
  1189. if [ -f "$HOME/.bashrc" ]; then
  1190. DETECTED_PROFILE="$HOME/.bashrc"
  1191. elif [ -f "$HOME/.bash_profile" ]; then
  1192. DETECTED_PROFILE="$HOME/.bash_profile"
  1193. fi
  1194. elif [ "$SHELLTYPE" = "zsh" ]; then
  1195. DETECTED_PROFILE="$HOME/.zshrc"
  1196. fi
  1197. if [ -z "$DETECTED_PROFILE" ]; then
  1198. if [ -f "$HOME/.profile" ]; then
  1199. DETECTED_PROFILE="$HOME/.profile"
  1200. elif [ -f "$HOME/.bashrc" ]; then
  1201. DETECTED_PROFILE="$HOME/.bashrc"
  1202. elif [ -f "$HOME/.bash_profile" ]; then
  1203. DETECTED_PROFILE="$HOME/.bash_profile"
  1204. elif [ -f "$HOME/.zshrc" ]; then
  1205. DETECTED_PROFILE="$HOME/.zshrc"
  1206. fi
  1207. fi
  1208. if [ ! -z "$DETECTED_PROFILE" ]; then
  1209. echo "$DETECTED_PROFILE"
  1210. fi
  1211. }
  1212. _initconf() {
  1213. _initpath
  1214. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1215. echo "#Account configurations:
  1216. #Here are the supported macros, uncomment them to make them take effect.
  1217. #ACCOUNT_EMAIL=aaa@aaa.com # the account email used to register account.
  1218. #ACCOUNT_KEY_PATH=\"/path/to/account.key\"
  1219. #STAGE=1 # Use the staging api
  1220. #FORCE=1 # Force to issue cert
  1221. #DEBUG=1 # Debug mode
  1222. #ACCOUNT_KEY_HASH=account key hash
  1223. USER_AGENT=\"le.sh client: $PROJECT\"
  1224. #dns api
  1225. #######################
  1226. #Cloudflare:
  1227. #api key
  1228. #CF_Key=\"sdfsdfsdfljlbjkljlkjsdfoiwje\"
  1229. #account email
  1230. #CF_Email=\"xxxx@sss.com\"
  1231. #######################
  1232. #Dnspod.cn:
  1233. #api key id
  1234. #DP_Id=\"1234\"
  1235. #api key
  1236. #DP_Key=\"sADDsdasdgdsf\"
  1237. #######################
  1238. #Cloudxns.com:
  1239. #CX_Key=\"1234\"
  1240. #
  1241. #CX_Secret=\"sADDsdasdgdsf\"
  1242. " > $ACCOUNT_CONF_PATH
  1243. fi
  1244. }
  1245. _precheck() {
  1246. if ! _exists "curl" && ! _exists "wget"; then
  1247. _err "Please install curl or wget first, we need to access http resources."
  1248. return 1
  1249. fi
  1250. if ! _exists "crontab" ; then
  1251. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  1252. _err "We need to set cron job to renew the certs automatically."
  1253. _err "Otherwise, your certs will not be able to be renewed automatically."
  1254. if [ -z "$FORCE" ] ; then
  1255. _err "Please define 'FORCE=1' and try install again to go without crontab."
  1256. _err "FORCE=1 ./le.sh install"
  1257. return 1
  1258. fi
  1259. fi
  1260. if ! _exists "openssl" ; then
  1261. _err "Please install openssl first."
  1262. _err "We need openssl to generate keys."
  1263. return 1
  1264. fi
  1265. if ! _exists "nc" ; then
  1266. _err "It is recommended to install nc first, try to install 'nc' or 'netcat'."
  1267. _err "We use nc for standalone server if you use standalone mode."
  1268. _err "If you don't use standalone mode, just ignore this warning."
  1269. fi
  1270. return 0
  1271. }
  1272. install() {
  1273. if ! _initpath ; then
  1274. _err "Install failed."
  1275. return 1
  1276. fi
  1277. if ! _precheck ; then
  1278. _err "Pre-check failed, can not install."
  1279. return 1
  1280. fi
  1281. _info "Installing to $LE_WORKING_DIR"
  1282. if ! mkdir -p "$LE_WORKING_DIR" ; then
  1283. _err "Can not craete working dir: $LE_WORKING_DIR"
  1284. return 1
  1285. fi
  1286. cp le.sh "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/le.sh"
  1287. if [ "$?" != "0" ] ; then
  1288. _err "Install failed, can not copy le.sh"
  1289. return 1
  1290. fi
  1291. _info "Installed to $LE_WORKING_DIR/le.sh"
  1292. _profile="$(_detect_profile)"
  1293. if [ "$_profile" ] ; then
  1294. _debug "Found profile: $_profile"
  1295. echo "LE_WORKING_DIR=$LE_WORKING_DIR
  1296. alias le=\"$LE_WORKING_DIR/le.sh\"
  1297. alias le.sh=\"$LE_WORKING_DIR/le.sh\"
  1298. " > "$LE_WORKING_DIR/le.env"
  1299. echo "" >> "$_profile"
  1300. _setopt "$_profile" "source \"$LE_WORKING_DIR/le.env\""
  1301. _info "OK, Close and reopen your terminal to start using le"
  1302. else
  1303. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use le.sh"
  1304. fi
  1305. mkdir -p $LE_WORKING_DIR/dnsapi
  1306. cp dnsapi/* $LE_WORKING_DIR/dnsapi/
  1307. #to keep compatible mv the .acc file to .key file
  1308. if [ -f "$LE_WORKING_DIR/account.acc" ] ; then
  1309. mv "$LE_WORKING_DIR/account.acc" "$LE_WORKING_DIR/account.key"
  1310. fi
  1311. installcronjob
  1312. if [ ! -f "$ACCOUNT_CONF_PATH" ] ; then
  1313. _initconf
  1314. fi
  1315. _info OK
  1316. }
  1317. uninstall() {
  1318. uninstallcronjob
  1319. _initpath
  1320. _profile="$(_detect_profile)"
  1321. if [ "$_profile" ] ; then
  1322. text="$(cat $_profile)"
  1323. echo "$text" | sed "s|^source.*le.env.*$||" > "$_profile"
  1324. fi
  1325. rm -f $LE_WORKING_DIR/le.sh
  1326. _info "The keys and certs are in $LE_WORKING_DIR, you can remove them by yourself."
  1327. }
  1328. cron() {
  1329. renewAll
  1330. }
  1331. version() {
  1332. _info "$PROJECT"
  1333. _info "v$VER"
  1334. }
  1335. showhelp() {
  1336. version
  1337. echo "Usage: le.sh [command] ...[args]....
  1338. Avalible commands:
  1339. install:
  1340. Install le.sh to your system.
  1341. issue:
  1342. Issue a cert.
  1343. installcert:
  1344. Install the issued cert to apache/nginx or any other server.
  1345. renew:
  1346. Renew a cert.
  1347. renewAll:
  1348. Renew all the certs.
  1349. uninstall:
  1350. Uninstall le.sh, and uninstall the cron job.
  1351. version:
  1352. Show version info.
  1353. installcronjob:
  1354. Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  1355. uninstallcronjob:
  1356. Uninstall the cron job. The 'uninstall' command can do this automatically.
  1357. createAccountKey:
  1358. Create an account private key, professional use.
  1359. createDomainKey:
  1360. Create an domain private key, professional use.
  1361. createCSR:
  1362. Create CSR , professional use.
  1363. "
  1364. }
  1365. _installOnline() {
  1366. _info "Installing from online archive."
  1367. if [ ! "$BRANCH" ] ; then
  1368. BRANCH="master"
  1369. fi
  1370. _initpath
  1371. target="$PROJECT/archive/$BRANCH.tar.gz"
  1372. _info "Downloading $target"
  1373. localname="$BRANCH.tar.gz"
  1374. if ! _get "$target" > $localname ; then
  1375. _debug "Download error."
  1376. return 1
  1377. fi
  1378. _info "Extracting $localname"
  1379. tar xzf $localname
  1380. cd "le-$BRANCH"
  1381. chmod +x le.sh
  1382. if ./le.sh install ; then
  1383. _info "Install success!"
  1384. fi
  1385. cd ..
  1386. rm -rf "le-$BRANCH"
  1387. rm -f "$localname"
  1388. }
  1389. if [ "$INSTALLONLINE" ] ; then
  1390. INSTALLONLINE=""
  1391. _installOnline $BRANCH
  1392. exit
  1393. fi
  1394. if [ -z "$1" ] ; then
  1395. showhelp
  1396. else
  1397. "$@"
  1398. fi