acme.sh 74 KB

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