acme.sh 112 KB

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