acme.sh 174 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543
  1. #!/usr/bin/env sh
  2. VER=2.8.1
  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. _WINDOWS_SCHEDULER_NAME="$PROJECT_NAME.cron"
  8. _SCRIPT_="$0"
  9. _SUB_FOLDERS="dnsapi deploy"
  10. LETSENCRYPT_CA_V1="https://acme-v01.api.letsencrypt.org/directory"
  11. LETSENCRYPT_STAGING_CA_V1="https://acme-staging.api.letsencrypt.org/directory"
  12. LETSENCRYPT_CA_V2="https://acme-v02.api.letsencrypt.org/directory"
  13. LETSENCRYPT_STAGING_CA_V2="https://acme-staging-v02.api.letsencrypt.org/directory"
  14. DEFAULT_CA=$LETSENCRYPT_CA_V2
  15. DEFAULT_STAGING_CA=$LETSENCRYPT_STAGING_CA_V2
  16. DEFAULT_USER_AGENT="$PROJECT_NAME/$VER ($PROJECT)"
  17. DEFAULT_ACCOUNT_EMAIL=""
  18. DEFAULT_ACCOUNT_KEY_LENGTH=2048
  19. DEFAULT_DOMAIN_KEY_LENGTH=2048
  20. DEFAULT_OPENSSL_BIN="openssl"
  21. _OLD_CA_HOST="https://acme-v01.api.letsencrypt.org"
  22. _OLD_STAGE_CA_HOST="https://acme-staging.api.letsencrypt.org"
  23. VTYPE_HTTP="http-01"
  24. VTYPE_DNS="dns-01"
  25. VTYPE_ALPN="tls-alpn-01"
  26. LOCAL_ANY_ADDRESS="0.0.0.0"
  27. DEFAULT_RENEW=60
  28. DEFAULT_DNS_SLEEP=120
  29. NO_VALUE="no"
  30. W_DNS="dns"
  31. W_ALPN="alpn"
  32. DNS_ALIAS_PREFIX="="
  33. MODE_STATELESS="stateless"
  34. STATE_VERIFIED="verified_ok"
  35. NGINX="nginx:"
  36. NGINX_START="#ACME_NGINX_START"
  37. NGINX_END="#ACME_NGINX_END"
  38. BEGIN_CSR="-----BEGIN CERTIFICATE REQUEST-----"
  39. END_CSR="-----END CERTIFICATE REQUEST-----"
  40. BEGIN_CERT="-----BEGIN CERTIFICATE-----"
  41. END_CERT="-----END CERTIFICATE-----"
  42. CONTENT_TYPE_JSON="application/jose+json"
  43. RENEW_SKIP=2
  44. B64CONF_START="__ACME_BASE64__START_"
  45. B64CONF_END="__ACME_BASE64__END_"
  46. ECC_SEP="_"
  47. ECC_SUFFIX="${ECC_SEP}ecc"
  48. LOG_LEVEL_1=1
  49. LOG_LEVEL_2=2
  50. LOG_LEVEL_3=3
  51. DEFAULT_LOG_LEVEL="$LOG_LEVEL_1"
  52. DEBUG_LEVEL_1=1
  53. DEBUG_LEVEL_2=2
  54. DEBUG_LEVEL_3=3
  55. DEBUG_LEVEL_DEFAULT=$DEBUG_LEVEL_1
  56. DEBUG_LEVEL_NONE=0
  57. HIDDEN_VALUE="[hidden](please add '--output-insecure' to see this value)"
  58. SYSLOG_ERROR="user.error"
  59. SYSLOG_INFO="user.info"
  60. SYSLOG_DEBUG="user.debug"
  61. #error
  62. SYSLOG_LEVEL_ERROR=3
  63. #info
  64. SYSLOG_LEVEL_INFO=6
  65. #debug
  66. SYSLOG_LEVEL_DEBUG=7
  67. #debug2
  68. SYSLOG_LEVEL_DEBUG_2=8
  69. #debug3
  70. SYSLOG_LEVEL_DEBUG_3=9
  71. SYSLOG_LEVEL_DEFAULT=$SYSLOG_LEVEL_ERROR
  72. #none
  73. SYSLOG_LEVEL_NONE=0
  74. _DEBUG_WIKI="https://github.com/Neilpang/acme.sh/wiki/How-to-debug-acme.sh"
  75. _PREPARE_LINK="https://github.com/Neilpang/acme.sh/wiki/Install-preparations"
  76. _STATELESS_WIKI="https://github.com/Neilpang/acme.sh/wiki/Stateless-Mode"
  77. _DNS_ALIAS_WIKI="https://github.com/Neilpang/acme.sh/wiki/DNS-alias-mode"
  78. _DNS_MANUAL_WIKI="https://github.com/Neilpang/acme.sh/wiki/dns-manual-mode"
  79. _DNS_MANUAL_ERR="The dns manual mode can not renew automatically, you must issue it again manually. You'd better use the other modes instead."
  80. _DNS_MANUAL_WARN="It seems that you are using dns manual mode. please take care: $_DNS_MANUAL_ERR"
  81. _DNS_MANUAL_ERROR="It seems that you are using dns manual mode. Read this link first: $_DNS_MANUAL_WIKI"
  82. __INTERACTIVE=""
  83. if [ -t 1 ]; then
  84. __INTERACTIVE="1"
  85. fi
  86. __green() {
  87. if [ "${__INTERACTIVE}${ACME_NO_COLOR:-0}" = "10" -o "${ACME_FORCE_COLOR}" = "1" ]; then
  88. printf '\033[1;31;32m%b\033[0m' "$1"
  89. return
  90. fi
  91. printf -- "%b" "$1"
  92. }
  93. __red() {
  94. if [ "${__INTERACTIVE}${ACME_NO_COLOR:-0}" = "10" -o "${ACME_FORCE_COLOR}" = "1" ]; then
  95. printf '\033[1;31;40m%b\033[0m' "$1"
  96. return
  97. fi
  98. printf -- "%b" "$1"
  99. }
  100. _printargs() {
  101. _exitstatus="$?"
  102. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  103. printf -- "%s" "[$(date)] "
  104. fi
  105. if [ -z "$2" ]; then
  106. printf -- "%s" "$1"
  107. else
  108. printf -- "%s" "$1='$2'"
  109. fi
  110. printf "\n"
  111. # return the saved exit status
  112. return "$_exitstatus"
  113. }
  114. _dlg_versions() {
  115. echo "Diagnosis versions: "
  116. echo "openssl:$ACME_OPENSSL_BIN"
  117. if _exists "${ACME_OPENSSL_BIN:-openssl}"; then
  118. ${ACME_OPENSSL_BIN:-openssl} version 2>&1
  119. else
  120. echo "$ACME_OPENSSL_BIN doesn't exists."
  121. fi
  122. echo "apache:"
  123. if [ "$_APACHECTL" ] && _exists "$_APACHECTL"; then
  124. $_APACHECTL -V 2>&1
  125. else
  126. echo "apache doesn't exists."
  127. fi
  128. echo "nginx:"
  129. if _exists "nginx"; then
  130. nginx -V 2>&1
  131. else
  132. echo "nginx doesn't exists."
  133. fi
  134. echo "socat:"
  135. if _exists "socat"; then
  136. socat -h 2>&1
  137. else
  138. _debug "socat doesn't exists."
  139. fi
  140. }
  141. #class
  142. _syslog() {
  143. _exitstatus="$?"
  144. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" = "$SYSLOG_LEVEL_NONE" ]; then
  145. return
  146. fi
  147. _logclass="$1"
  148. shift
  149. if [ -z "$__logger_i" ]; then
  150. if _contains "$(logger --help 2>&1)" "-i"; then
  151. __logger_i="logger -i"
  152. else
  153. __logger_i="logger"
  154. fi
  155. fi
  156. $__logger_i -t "$PROJECT_NAME" -p "$_logclass" "$(_printargs "$@")" >/dev/null 2>&1
  157. return "$_exitstatus"
  158. }
  159. _log() {
  160. [ -z "$LOG_FILE" ] && return
  161. _printargs "$@" >>"$LOG_FILE"
  162. }
  163. _info() {
  164. _log "$@"
  165. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_INFO" ]; then
  166. _syslog "$SYSLOG_INFO" "$@"
  167. fi
  168. _printargs "$@"
  169. }
  170. _err() {
  171. _syslog "$SYSLOG_ERROR" "$@"
  172. _log "$@"
  173. if [ -z "$NO_TIMESTAMP" ] || [ "$NO_TIMESTAMP" = "0" ]; then
  174. printf -- "%s" "[$(date)] " >&2
  175. fi
  176. if [ -z "$2" ]; then
  177. __red "$1" >&2
  178. else
  179. __red "$1='$2'" >&2
  180. fi
  181. printf "\n" >&2
  182. return 1
  183. }
  184. _usage() {
  185. __red "$@" >&2
  186. printf "\n" >&2
  187. }
  188. _debug() {
  189. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_1" ]; then
  190. _log "$@"
  191. fi
  192. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG" ]; then
  193. _syslog "$SYSLOG_DEBUG" "$@"
  194. fi
  195. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_1" ]; then
  196. _printargs "$@" >&2
  197. fi
  198. }
  199. #output the sensitive messages
  200. _secure_debug() {
  201. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_1" ]; then
  202. if [ "$OUTPUT_INSECURE" = "1" ]; then
  203. _log "$@"
  204. else
  205. _log "$1" "$HIDDEN_VALUE"
  206. fi
  207. fi
  208. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG" ]; then
  209. _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
  210. fi
  211. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_1" ]; then
  212. if [ "$OUTPUT_INSECURE" = "1" ]; then
  213. _printargs "$@" >&2
  214. else
  215. _printargs "$1" "$HIDDEN_VALUE" >&2
  216. fi
  217. fi
  218. }
  219. _debug2() {
  220. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_2" ]; then
  221. _log "$@"
  222. fi
  223. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_2" ]; then
  224. _syslog "$SYSLOG_DEBUG" "$@"
  225. fi
  226. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
  227. _printargs "$@" >&2
  228. fi
  229. }
  230. _secure_debug2() {
  231. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_2" ]; then
  232. if [ "$OUTPUT_INSECURE" = "1" ]; then
  233. _log "$@"
  234. else
  235. _log "$1" "$HIDDEN_VALUE"
  236. fi
  237. fi
  238. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_2" ]; then
  239. _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
  240. fi
  241. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_2" ]; then
  242. if [ "$OUTPUT_INSECURE" = "1" ]; then
  243. _printargs "$@" >&2
  244. else
  245. _printargs "$1" "$HIDDEN_VALUE" >&2
  246. fi
  247. fi
  248. }
  249. _debug3() {
  250. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_3" ]; then
  251. _log "$@"
  252. fi
  253. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_3" ]; then
  254. _syslog "$SYSLOG_DEBUG" "$@"
  255. fi
  256. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_3" ]; then
  257. _printargs "$@" >&2
  258. fi
  259. }
  260. _secure_debug3() {
  261. if [ "${LOG_LEVEL:-$DEFAULT_LOG_LEVEL}" -ge "$LOG_LEVEL_3" ]; then
  262. if [ "$OUTPUT_INSECURE" = "1" ]; then
  263. _log "$@"
  264. else
  265. _log "$1" "$HIDDEN_VALUE"
  266. fi
  267. fi
  268. if [ "${SYS_LOG:-$SYSLOG_LEVEL_NONE}" -ge "$SYSLOG_LEVEL_DEBUG_3" ]; then
  269. _syslog "$SYSLOG_DEBUG" "$1" "$HIDDEN_VALUE"
  270. fi
  271. if [ "${DEBUG:-$DEBUG_LEVEL_NONE}" -ge "$DEBUG_LEVEL_3" ]; then
  272. if [ "$OUTPUT_INSECURE" = "1" ]; then
  273. _printargs "$@" >&2
  274. else
  275. _printargs "$1" "$HIDDEN_VALUE" >&2
  276. fi
  277. fi
  278. }
  279. _upper_case() {
  280. # shellcheck disable=SC2018,SC2019
  281. tr 'a-z' 'A-Z'
  282. }
  283. _lower_case() {
  284. # shellcheck disable=SC2018,SC2019
  285. tr 'A-Z' 'a-z'
  286. }
  287. _startswith() {
  288. _str="$1"
  289. _sub="$2"
  290. echo "$_str" | grep "^$_sub" >/dev/null 2>&1
  291. }
  292. _endswith() {
  293. _str="$1"
  294. _sub="$2"
  295. echo "$_str" | grep -- "$_sub\$" >/dev/null 2>&1
  296. }
  297. _contains() {
  298. _str="$1"
  299. _sub="$2"
  300. echo "$_str" | grep -- "$_sub" >/dev/null 2>&1
  301. }
  302. _hasfield() {
  303. _str="$1"
  304. _field="$2"
  305. _sep="$3"
  306. if [ -z "$_field" ]; then
  307. _usage "Usage: str field [sep]"
  308. return 1
  309. fi
  310. if [ -z "$_sep" ]; then
  311. _sep=","
  312. fi
  313. for f in $(echo "$_str" | tr "$_sep" ' '); do
  314. if [ "$f" = "$_field" ]; then
  315. _debug2 "'$_str' contains '$_field'"
  316. return 0 #contains ok
  317. fi
  318. done
  319. _debug2 "'$_str' does not contain '$_field'"
  320. return 1 #not contains
  321. }
  322. # str index [sep]
  323. _getfield() {
  324. _str="$1"
  325. _findex="$2"
  326. _sep="$3"
  327. if [ -z "$_findex" ]; then
  328. _usage "Usage: str field [sep]"
  329. return 1
  330. fi
  331. if [ -z "$_sep" ]; then
  332. _sep=","
  333. fi
  334. _ffi="$_findex"
  335. while [ "$_ffi" -gt "0" ]; do
  336. _fv="$(echo "$_str" | cut -d "$_sep" -f "$_ffi")"
  337. if [ "$_fv" ]; then
  338. printf -- "%s" "$_fv"
  339. return 0
  340. fi
  341. _ffi="$(_math "$_ffi" - 1)"
  342. done
  343. printf -- "%s" "$_str"
  344. }
  345. _exists() {
  346. cmd="$1"
  347. if [ -z "$cmd" ]; then
  348. _usage "Usage: _exists cmd"
  349. return 1
  350. fi
  351. if eval type type >/dev/null 2>&1; then
  352. eval type "$cmd" >/dev/null 2>&1
  353. elif command >/dev/null 2>&1; then
  354. command -v "$cmd" >/dev/null 2>&1
  355. else
  356. which "$cmd" >/dev/null 2>&1
  357. fi
  358. ret="$?"
  359. _debug3 "$cmd exists=$ret"
  360. return $ret
  361. }
  362. #a + b
  363. _math() {
  364. _m_opts="$@"
  365. printf "%s" "$(($_m_opts))"
  366. }
  367. _h_char_2_dec() {
  368. _ch=$1
  369. case "${_ch}" in
  370. a | A)
  371. printf "10"
  372. ;;
  373. b | B)
  374. printf "11"
  375. ;;
  376. c | C)
  377. printf "12"
  378. ;;
  379. d | D)
  380. printf "13"
  381. ;;
  382. e | E)
  383. printf "14"
  384. ;;
  385. f | F)
  386. printf "15"
  387. ;;
  388. *)
  389. printf "%s" "$_ch"
  390. ;;
  391. esac
  392. }
  393. _URGLY_PRINTF=""
  394. if [ "$(printf '\x41')" != 'A' ]; then
  395. _URGLY_PRINTF=1
  396. fi
  397. _ESCAPE_XARGS=""
  398. if _exists xargs && [ "$(printf %s '\\x41' | xargs printf)" = 'A' ]; then
  399. _ESCAPE_XARGS=1
  400. fi
  401. _h2b() {
  402. if _exists xxd && xxd -r -p 2>/dev/null; then
  403. return
  404. fi
  405. hex=$(cat)
  406. ic=""
  407. jc=""
  408. _debug2 _URGLY_PRINTF "$_URGLY_PRINTF"
  409. if [ -z "$_URGLY_PRINTF" ]; then
  410. if [ "$_ESCAPE_XARGS" ] && _exists xargs; then
  411. _debug2 "xargs"
  412. echo "$hex" | _upper_case | sed 's/\([0-9A-F]\{2\}\)/\\\\\\x\1/g' | xargs printf
  413. else
  414. for h in $(echo "$hex" | _upper_case | sed 's/\([0-9A-F]\{2\}\)/ \1/g'); do
  415. if [ -z "$h" ]; then
  416. break
  417. fi
  418. printf "\x$h%s"
  419. done
  420. fi
  421. else
  422. for c in $(echo "$hex" | _upper_case | sed 's/\([0-9A-F]\)/ \1/g'); do
  423. if [ -z "$ic" ]; then
  424. ic=$c
  425. continue
  426. fi
  427. jc=$c
  428. ic="$(_h_char_2_dec "$ic")"
  429. jc="$(_h_char_2_dec "$jc")"
  430. printf '\'"$(printf "%o" "$(_math "$ic" \* 16 + $jc)")""%s"
  431. ic=""
  432. jc=""
  433. done
  434. fi
  435. }
  436. _is_solaris() {
  437. _contains "${__OS__:=$(uname -a)}" "solaris" || _contains "${__OS__:=$(uname -a)}" "SunOS"
  438. }
  439. #_ascii_hex str
  440. #this can only process ascii chars, should only be used when od command is missing as a backup way.
  441. _ascii_hex() {
  442. _debug2 "Using _ascii_hex"
  443. _str="$1"
  444. _str_len=${#_str}
  445. _h_i=1
  446. while [ "$_h_i" -le "$_str_len" ]; do
  447. _str_c="$(printf "%s" "$_str" | cut -c "$_h_i")"
  448. printf " %02x" "'$_str_c"
  449. _h_i="$(_math "$_h_i" + 1)"
  450. done
  451. }
  452. #stdin output hexstr splited by one space
  453. #input:"abc"
  454. #output: " 61 62 63"
  455. _hex_dump() {
  456. if _exists od; then
  457. od -A n -v -t x1 | tr -s " " | sed 's/ $//' | tr -d "\r\t\n"
  458. elif _exists hexdump; then
  459. _debug3 "using hexdump"
  460. hexdump -v -e '/1 ""' -e '/1 " %02x" ""'
  461. elif _exists xxd; then
  462. _debug3 "using xxd"
  463. xxd -ps -c 20 -i | sed "s/ 0x/ /g" | tr -d ",\n" | tr -s " "
  464. else
  465. _debug3 "using _ascii_hex"
  466. str=$(cat)
  467. _ascii_hex "$str"
  468. fi
  469. }
  470. #url encode, no-preserved chars
  471. #A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
  472. #41 42 43 44 45 46 47 48 49 4a 4b 4c 4d 4e 4f 50 51 52 53 54 55 56 57 58 59 5a
  473. #a b c d e f g h i j k l m n o p q r s t u v w x y z
  474. #61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 71 72 73 74 75 76 77 78 79 7a
  475. #0 1 2 3 4 5 6 7 8 9 - _ . ~
  476. #30 31 32 33 34 35 36 37 38 39 2d 5f 2e 7e
  477. #stdin stdout
  478. _url_encode() {
  479. _hex_str=$(_hex_dump)
  480. _debug3 "_url_encode"
  481. _debug3 "_hex_str" "$_hex_str"
  482. for _hex_code in $_hex_str; do
  483. #upper case
  484. case "${_hex_code}" in
  485. "41")
  486. printf "%s" "A"
  487. ;;
  488. "42")
  489. printf "%s" "B"
  490. ;;
  491. "43")
  492. printf "%s" "C"
  493. ;;
  494. "44")
  495. printf "%s" "D"
  496. ;;
  497. "45")
  498. printf "%s" "E"
  499. ;;
  500. "46")
  501. printf "%s" "F"
  502. ;;
  503. "47")
  504. printf "%s" "G"
  505. ;;
  506. "48")
  507. printf "%s" "H"
  508. ;;
  509. "49")
  510. printf "%s" "I"
  511. ;;
  512. "4a")
  513. printf "%s" "J"
  514. ;;
  515. "4b")
  516. printf "%s" "K"
  517. ;;
  518. "4c")
  519. printf "%s" "L"
  520. ;;
  521. "4d")
  522. printf "%s" "M"
  523. ;;
  524. "4e")
  525. printf "%s" "N"
  526. ;;
  527. "4f")
  528. printf "%s" "O"
  529. ;;
  530. "50")
  531. printf "%s" "P"
  532. ;;
  533. "51")
  534. printf "%s" "Q"
  535. ;;
  536. "52")
  537. printf "%s" "R"
  538. ;;
  539. "53")
  540. printf "%s" "S"
  541. ;;
  542. "54")
  543. printf "%s" "T"
  544. ;;
  545. "55")
  546. printf "%s" "U"
  547. ;;
  548. "56")
  549. printf "%s" "V"
  550. ;;
  551. "57")
  552. printf "%s" "W"
  553. ;;
  554. "58")
  555. printf "%s" "X"
  556. ;;
  557. "59")
  558. printf "%s" "Y"
  559. ;;
  560. "5a")
  561. printf "%s" "Z"
  562. ;;
  563. #lower case
  564. "61")
  565. printf "%s" "a"
  566. ;;
  567. "62")
  568. printf "%s" "b"
  569. ;;
  570. "63")
  571. printf "%s" "c"
  572. ;;
  573. "64")
  574. printf "%s" "d"
  575. ;;
  576. "65")
  577. printf "%s" "e"
  578. ;;
  579. "66")
  580. printf "%s" "f"
  581. ;;
  582. "67")
  583. printf "%s" "g"
  584. ;;
  585. "68")
  586. printf "%s" "h"
  587. ;;
  588. "69")
  589. printf "%s" "i"
  590. ;;
  591. "6a")
  592. printf "%s" "j"
  593. ;;
  594. "6b")
  595. printf "%s" "k"
  596. ;;
  597. "6c")
  598. printf "%s" "l"
  599. ;;
  600. "6d")
  601. printf "%s" "m"
  602. ;;
  603. "6e")
  604. printf "%s" "n"
  605. ;;
  606. "6f")
  607. printf "%s" "o"
  608. ;;
  609. "70")
  610. printf "%s" "p"
  611. ;;
  612. "71")
  613. printf "%s" "q"
  614. ;;
  615. "72")
  616. printf "%s" "r"
  617. ;;
  618. "73")
  619. printf "%s" "s"
  620. ;;
  621. "74")
  622. printf "%s" "t"
  623. ;;
  624. "75")
  625. printf "%s" "u"
  626. ;;
  627. "76")
  628. printf "%s" "v"
  629. ;;
  630. "77")
  631. printf "%s" "w"
  632. ;;
  633. "78")
  634. printf "%s" "x"
  635. ;;
  636. "79")
  637. printf "%s" "y"
  638. ;;
  639. "7a")
  640. printf "%s" "z"
  641. ;;
  642. #numbers
  643. "30")
  644. printf "%s" "0"
  645. ;;
  646. "31")
  647. printf "%s" "1"
  648. ;;
  649. "32")
  650. printf "%s" "2"
  651. ;;
  652. "33")
  653. printf "%s" "3"
  654. ;;
  655. "34")
  656. printf "%s" "4"
  657. ;;
  658. "35")
  659. printf "%s" "5"
  660. ;;
  661. "36")
  662. printf "%s" "6"
  663. ;;
  664. "37")
  665. printf "%s" "7"
  666. ;;
  667. "38")
  668. printf "%s" "8"
  669. ;;
  670. "39")
  671. printf "%s" "9"
  672. ;;
  673. "2d")
  674. printf "%s" "-"
  675. ;;
  676. "5f")
  677. printf "%s" "_"
  678. ;;
  679. "2e")
  680. printf "%s" "."
  681. ;;
  682. "7e")
  683. printf "%s" "~"
  684. ;;
  685. #other hex
  686. *)
  687. printf '%%%s' "$_hex_code"
  688. ;;
  689. esac
  690. done
  691. }
  692. #options file
  693. _sed_i() {
  694. options="$1"
  695. filename="$2"
  696. if [ -z "$filename" ]; then
  697. _usage "Usage:_sed_i options filename"
  698. return 1
  699. fi
  700. _debug2 options "$options"
  701. if sed -h 2>&1 | grep "\-i\[SUFFIX]" >/dev/null 2>&1; then
  702. _debug "Using sed -i"
  703. sed -i "$options" "$filename"
  704. else
  705. _debug "No -i support in sed"
  706. text="$(cat "$filename")"
  707. echo "$text" | sed "$options" >"$filename"
  708. fi
  709. }
  710. _egrep_o() {
  711. if ! egrep -o "$1" 2>/dev/null; then
  712. sed -n 's/.*\('"$1"'\).*/\1/p'
  713. fi
  714. }
  715. #Usage: file startline endline
  716. _getfile() {
  717. filename="$1"
  718. startline="$2"
  719. endline="$3"
  720. if [ -z "$endline" ]; then
  721. _usage "Usage: file startline endline"
  722. return 1
  723. fi
  724. i="$(grep -n -- "$startline" "$filename" | cut -d : -f 1)"
  725. if [ -z "$i" ]; then
  726. _err "Can not find start line: $startline"
  727. return 1
  728. fi
  729. i="$(_math "$i" + 1)"
  730. _debug i "$i"
  731. j="$(grep -n -- "$endline" "$filename" | cut -d : -f 1)"
  732. if [ -z "$j" ]; then
  733. _err "Can not find end line: $endline"
  734. return 1
  735. fi
  736. j="$(_math "$j" - 1)"
  737. _debug j "$j"
  738. sed -n "$i,${j}p" "$filename"
  739. }
  740. #Usage: multiline
  741. _base64() {
  742. [ "" ] #urgly
  743. if [ "$1" ]; then
  744. _debug3 "base64 multiline:'$1'"
  745. ${ACME_OPENSSL_BIN:-openssl} base64 -e
  746. else
  747. _debug3 "base64 single line."
  748. ${ACME_OPENSSL_BIN:-openssl} base64 -e | tr -d '\r\n'
  749. fi
  750. }
  751. #Usage: multiline
  752. _dbase64() {
  753. if [ "$1" ]; then
  754. ${ACME_OPENSSL_BIN:-openssl} base64 -d -A
  755. else
  756. ${ACME_OPENSSL_BIN:-openssl} base64 -d
  757. fi
  758. }
  759. #file
  760. _checkcert() {
  761. _cf="$1"
  762. if [ "$DEBUG" ]; then
  763. openssl x509 -noout -text -in "$_cf"
  764. else
  765. openssl x509 -noout -text -in "$_cf" >/dev/null 2>&1
  766. fi
  767. }
  768. #Usage: hashalg [outputhex]
  769. #Output Base64-encoded digest
  770. _digest() {
  771. alg="$1"
  772. if [ -z "$alg" ]; then
  773. _usage "Usage: _digest hashalg"
  774. return 1
  775. fi
  776. outputhex="$2"
  777. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ] || [ "$alg" = "md5" ]; then
  778. if [ "$outputhex" ]; then
  779. ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hex | cut -d = -f 2 | tr -d ' '
  780. else
  781. ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -binary | _base64
  782. fi
  783. else
  784. _err "$alg is not supported yet"
  785. return 1
  786. fi
  787. }
  788. #Usage: hashalg secret_hex [outputhex]
  789. #Output binary hmac
  790. _hmac() {
  791. alg="$1"
  792. secret_hex="$2"
  793. outputhex="$3"
  794. if [ -z "$secret_hex" ]; then
  795. _usage "Usage: _hmac hashalg secret [outputhex]"
  796. return 1
  797. fi
  798. if [ "$alg" = "sha256" ] || [ "$alg" = "sha1" ]; then
  799. if [ "$outputhex" ]; then
  800. (${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" 2>/dev/null || ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hmac "$(printf "%s" "$secret_hex" | _h2b)") | cut -d = -f 2 | tr -d ' '
  801. else
  802. ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -mac HMAC -macopt "hexkey:$secret_hex" -binary 2>/dev/null || ${ACME_OPENSSL_BIN:-openssl} dgst -"$alg" -hmac "$(printf "%s" "$secret_hex" | _h2b)" -binary
  803. fi
  804. else
  805. _err "$alg is not supported yet"
  806. return 1
  807. fi
  808. }
  809. #Usage: keyfile hashalg
  810. #Output: Base64-encoded signature value
  811. _sign() {
  812. keyfile="$1"
  813. alg="$2"
  814. if [ -z "$alg" ]; then
  815. _usage "Usage: _sign keyfile hashalg"
  816. return 1
  817. fi
  818. _sign_openssl="${ACME_OPENSSL_BIN:-openssl} dgst -sign $keyfile "
  819. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  820. $_sign_openssl -$alg | _base64
  821. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  822. if ! _signedECText="$($_sign_openssl -sha$__ECC_KEY_LEN | ${ACME_OPENSSL_BIN:-openssl} asn1parse -inform DER)"; then
  823. _err "Sign failed: $_sign_openssl"
  824. _err "Key file: $keyfile"
  825. _err "Key content:$(wc -l <"$keyfile") lines"
  826. return 1
  827. fi
  828. _debug3 "_signedECText" "$_signedECText"
  829. _ec_r="$(echo "$_signedECText" | _head_n 2 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  830. _debug3 "_ec_r" "$_ec_r"
  831. _ec_s="$(echo "$_signedECText" | _head_n 3 | _tail_n 1 | cut -d : -f 4 | tr -d "\r\n")"
  832. _debug3 "_ec_s" "$_ec_s"
  833. printf "%s" "$_ec_r$_ec_s" | _h2b | _base64
  834. else
  835. _err "Unknown key file format."
  836. return 1
  837. fi
  838. }
  839. #keylength or isEcc flag (empty str => not ecc)
  840. _isEccKey() {
  841. _length="$1"
  842. if [ -z "$_length" ]; then
  843. return 1
  844. fi
  845. [ "$_length" != "1024" ] \
  846. && [ "$_length" != "2048" ] \
  847. && [ "$_length" != "3072" ] \
  848. && [ "$_length" != "4096" ] \
  849. && [ "$_length" != "8192" ]
  850. }
  851. # _createkey 2048|ec-256 file
  852. _createkey() {
  853. length="$1"
  854. f="$2"
  855. _debug2 "_createkey for file:$f"
  856. eccname="$length"
  857. if _startswith "$length" "ec-"; then
  858. length=$(printf "%s" "$length" | cut -d '-' -f 2-100)
  859. if [ "$length" = "256" ]; then
  860. eccname="prime256v1"
  861. fi
  862. if [ "$length" = "384" ]; then
  863. eccname="secp384r1"
  864. fi
  865. if [ "$length" = "521" ]; then
  866. eccname="secp521r1"
  867. fi
  868. fi
  869. if [ -z "$length" ]; then
  870. length=2048
  871. fi
  872. _debug "Use length $length"
  873. if ! touch "$f" >/dev/null 2>&1; then
  874. _f_path="$(dirname "$f")"
  875. _debug _f_path "$_f_path"
  876. if ! mkdir -p "$_f_path"; then
  877. _err "Can not create path: $_f_path"
  878. return 1
  879. fi
  880. fi
  881. if _isEccKey "$length"; then
  882. _debug "Using ec name: $eccname"
  883. ${ACME_OPENSSL_BIN:-openssl} ecparam -name "$eccname" -genkey 2>/dev/null >"$f"
  884. else
  885. _debug "Using RSA: $length"
  886. ${ACME_OPENSSL_BIN:-openssl} genrsa "$length" 2>/dev/null >"$f"
  887. fi
  888. if [ "$?" != "0" ]; then
  889. _err "Create key error."
  890. return 1
  891. fi
  892. }
  893. #domain
  894. _is_idn() {
  895. _is_idn_d="$1"
  896. _debug2 _is_idn_d "$_is_idn_d"
  897. _idn_temp=$(printf "%s" "$_is_idn_d" | tr -d '0-9' | tr -d 'a-z' | tr -d 'A-Z' | tr -d '*.,-')
  898. _debug2 _idn_temp "$_idn_temp"
  899. [ "$_idn_temp" ]
  900. }
  901. #aa.com
  902. #aa.com,bb.com,cc.com
  903. _idn() {
  904. __idn_d="$1"
  905. if ! _is_idn "$__idn_d"; then
  906. printf "%s" "$__idn_d"
  907. return 0
  908. fi
  909. if _exists idn; then
  910. if _contains "$__idn_d" ','; then
  911. _i_first="1"
  912. for f in $(echo "$__idn_d" | tr ',' ' '); do
  913. [ -z "$f" ] && continue
  914. if [ -z "$_i_first" ]; then
  915. printf "%s" ","
  916. else
  917. _i_first=""
  918. fi
  919. idn --quiet "$f" | tr -d "\r\n"
  920. done
  921. else
  922. idn "$__idn_d" | tr -d "\r\n"
  923. fi
  924. else
  925. _err "Please install idn to process IDN names."
  926. fi
  927. }
  928. #_createcsr cn san_list keyfile csrfile conf acmeValidationv1
  929. _createcsr() {
  930. _debug _createcsr
  931. domain="$1"
  932. domainlist="$2"
  933. csrkey="$3"
  934. csr="$4"
  935. csrconf="$5"
  936. acmeValidationv1="$6"
  937. _debug2 domain "$domain"
  938. _debug2 domainlist "$domainlist"
  939. _debug2 csrkey "$csrkey"
  940. _debug2 csr "$csr"
  941. _debug2 csrconf "$csrconf"
  942. printf "[ req_distinguished_name ]\n[ req ]\ndistinguished_name = req_distinguished_name\nreq_extensions = v3_req\n[ v3_req ]\n\nkeyUsage = nonRepudiation, digitalSignature, keyEncipherment" >"$csrconf"
  943. if [ "$acmeValidationv1" ]; then
  944. printf -- "\nsubjectAltName=DNS:$domainlist" >>"$csrconf"
  945. elif [ -z "$domainlist" ] || [ "$domainlist" = "$NO_VALUE" ]; then
  946. #single domain
  947. _info "Single domain" "$domain"
  948. printf -- "\nsubjectAltName=DNS:$domain" >>"$csrconf"
  949. else
  950. domainlist="$(_idn "$domainlist")"
  951. _debug2 domainlist "$domainlist"
  952. if _contains "$domainlist" ","; then
  953. alt="DNS:$domain,DNS:$(echo "$domainlist" | sed "s/,,/,/g" | sed "s/,/,DNS:/g")"
  954. else
  955. alt="DNS:$domain,DNS:$domainlist"
  956. fi
  957. #multi
  958. _info "Multi domain" "$alt"
  959. printf -- "\nsubjectAltName=$alt" >>"$csrconf"
  960. fi
  961. if [ "$Le_OCSP_Staple" ] || [ "$Le_OCSP_Stable" ]; then
  962. _savedomainconf Le_OCSP_Staple "$Le_OCSP_Staple"
  963. _cleardomainconf Le_OCSP_Stable
  964. printf -- "\nbasicConstraints = CA:FALSE\n1.3.6.1.5.5.7.1.24=DER:30:03:02:01:05" >>"$csrconf"
  965. fi
  966. if [ "$acmeValidationv1" ]; then
  967. printf "\n1.3.6.1.5.5.7.1.31=critical,DER:04:20:${acmeValidationv1}" >>"${csrconf}"
  968. fi
  969. _csr_cn="$(_idn "$domain")"
  970. _debug2 _csr_cn "$_csr_cn"
  971. if _contains "$(uname -a)" "MINGW"; then
  972. ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "//CN=$_csr_cn" -config "$csrconf" -out "$csr"
  973. else
  974. ${ACME_OPENSSL_BIN:-openssl} req -new -sha256 -key "$csrkey" -subj "/CN=$_csr_cn" -config "$csrconf" -out "$csr"
  975. fi
  976. }
  977. #_signcsr key csr conf cert
  978. _signcsr() {
  979. key="$1"
  980. csr="$2"
  981. conf="$3"
  982. cert="$4"
  983. _debug "_signcsr"
  984. _msg="$(${ACME_OPENSSL_BIN:-openssl} x509 -req -days 365 -in "$csr" -signkey "$key" -extensions v3_req -extfile "$conf" -out "$cert" 2>&1)"
  985. _ret="$?"
  986. _debug "$_msg"
  987. return $_ret
  988. }
  989. #_csrfile
  990. _readSubjectFromCSR() {
  991. _csrfile="$1"
  992. if [ -z "$_csrfile" ]; then
  993. _usage "_readSubjectFromCSR mycsr.csr"
  994. return 1
  995. fi
  996. ${ACME_OPENSSL_BIN:-openssl} req -noout -in "$_csrfile" -subject | tr ',' "\n" | _egrep_o "CN *=.*" | cut -d = -f 2 | cut -d / -f 1 | tr -d ' \n'
  997. }
  998. #_csrfile
  999. #echo comma separated domain list
  1000. _readSubjectAltNamesFromCSR() {
  1001. _csrfile="$1"
  1002. if [ -z "$_csrfile" ]; then
  1003. _usage "_readSubjectAltNamesFromCSR mycsr.csr"
  1004. return 1
  1005. fi
  1006. _csrsubj="$(_readSubjectFromCSR "$_csrfile")"
  1007. _debug _csrsubj "$_csrsubj"
  1008. _dnsAltnames="$(${ACME_OPENSSL_BIN:-openssl} req -noout -text -in "$_csrfile" | grep "^ *DNS:.*" | tr -d ' \n')"
  1009. _debug _dnsAltnames "$_dnsAltnames"
  1010. if _contains "$_dnsAltnames," "DNS:$_csrsubj,"; then
  1011. _debug "AltNames contains subject"
  1012. _excapedAlgnames="$(echo "$_dnsAltnames" | tr '*' '#')"
  1013. _debug _excapedAlgnames "$_excapedAlgnames"
  1014. _escapedSubject="$(echo "$_csrsubj" | tr '*' '#')"
  1015. _debug _escapedSubject "$_escapedSubject"
  1016. _dnsAltnames="$(echo "$_excapedAlgnames," | sed "s/DNS:$_escapedSubject,//g" | tr '#' '*' | sed "s/,\$//g")"
  1017. _debug _dnsAltnames "$_dnsAltnames"
  1018. else
  1019. _debug "AltNames doesn't contain subject"
  1020. fi
  1021. echo "$_dnsAltnames" | sed "s/DNS://g"
  1022. }
  1023. #_csrfile
  1024. _readKeyLengthFromCSR() {
  1025. _csrfile="$1"
  1026. if [ -z "$_csrfile" ]; then
  1027. _usage "_readKeyLengthFromCSR mycsr.csr"
  1028. return 1
  1029. fi
  1030. _outcsr="$(${ACME_OPENSSL_BIN:-openssl} req -noout -text -in "$_csrfile")"
  1031. _debug2 _outcsr "$_outcsr"
  1032. if _contains "$_outcsr" "Public Key Algorithm: id-ecPublicKey"; then
  1033. _debug "ECC CSR"
  1034. echo "$_outcsr" | tr "\t" " " | _egrep_o "^ *ASN1 OID:.*" | cut -d ':' -f 2 | tr -d ' '
  1035. else
  1036. _debug "RSA CSR"
  1037. _rkl="$(echo "$_outcsr" | tr "\t" " " | _egrep_o "^ *Public.Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1)"
  1038. if [ "$_rkl" ]; then
  1039. echo "$_rkl"
  1040. else
  1041. echo "$_outcsr" | tr "\t" " " | _egrep_o "RSA Public.Key:.*" | cut -d '(' -f 2 | cut -d ' ' -f 1
  1042. fi
  1043. fi
  1044. }
  1045. _ss() {
  1046. _port="$1"
  1047. if _exists "ss"; then
  1048. _debug "Using: ss"
  1049. ss -ntpl 2>/dev/null | grep ":$_port "
  1050. return 0
  1051. fi
  1052. if _exists "netstat"; then
  1053. _debug "Using: netstat"
  1054. if netstat -help 2>&1 | grep "\-p proto" >/dev/null; then
  1055. #for windows version netstat tool
  1056. netstat -an -p tcp | grep "LISTENING" | grep ":$_port "
  1057. else
  1058. if netstat -help 2>&1 | grep "\-p protocol" >/dev/null; then
  1059. netstat -an -p tcp | grep LISTEN | grep ":$_port "
  1060. elif netstat -help 2>&1 | grep -- '-P protocol' >/dev/null; then
  1061. #for solaris
  1062. netstat -an -P tcp | grep "\.$_port " | grep "LISTEN"
  1063. elif netstat -help 2>&1 | grep "\-p" >/dev/null; then
  1064. #for full linux
  1065. netstat -ntpl | grep ":$_port "
  1066. else
  1067. #for busybox (embedded linux; no pid support)
  1068. netstat -ntl 2>/dev/null | grep ":$_port "
  1069. fi
  1070. fi
  1071. return 0
  1072. fi
  1073. return 1
  1074. }
  1075. #outfile key cert cacert [password [name [caname]]]
  1076. _toPkcs() {
  1077. _cpfx="$1"
  1078. _ckey="$2"
  1079. _ccert="$3"
  1080. _cca="$4"
  1081. pfxPassword="$5"
  1082. pfxName="$6"
  1083. pfxCaname="$7"
  1084. if [ "$pfxCaname" ]; then
  1085. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword" -name "$pfxName" -caname "$pfxCaname"
  1086. elif [ "$pfxName" ]; then
  1087. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword" -name "$pfxName"
  1088. elif [ "$pfxPassword" ]; then
  1089. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca" -password "pass:$pfxPassword"
  1090. else
  1091. ${ACME_OPENSSL_BIN:-openssl} pkcs12 -export -out "$_cpfx" -inkey "$_ckey" -in "$_ccert" -certfile "$_cca"
  1092. fi
  1093. }
  1094. #domain [password] [isEcc]
  1095. toPkcs() {
  1096. domain="$1"
  1097. pfxPassword="$2"
  1098. if [ -z "$domain" ]; then
  1099. _usage "Usage: $PROJECT_ENTRY --toPkcs -d domain [--password pfx-password]"
  1100. return 1
  1101. fi
  1102. _isEcc="$3"
  1103. _initpath "$domain" "$_isEcc"
  1104. _toPkcs "$CERT_PFX_PATH" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$pfxPassword"
  1105. if [ "$?" = "0" ]; then
  1106. _info "Success, Pfx is exported to: $CERT_PFX_PATH"
  1107. fi
  1108. }
  1109. #domain [isEcc]
  1110. toPkcs8() {
  1111. domain="$1"
  1112. if [ -z "$domain" ]; then
  1113. _usage "Usage: $PROJECT_ENTRY --toPkcs8 -d domain [--ecc]"
  1114. return 1
  1115. fi
  1116. _isEcc="$2"
  1117. _initpath "$domain" "$_isEcc"
  1118. ${ACME_OPENSSL_BIN:-openssl} pkcs8 -topk8 -inform PEM -outform PEM -nocrypt -in "$CERT_KEY_PATH" -out "$CERT_PKCS8_PATH"
  1119. if [ "$?" = "0" ]; then
  1120. _info "Success, $CERT_PKCS8_PATH"
  1121. fi
  1122. }
  1123. #[2048]
  1124. createAccountKey() {
  1125. _info "Creating account key"
  1126. if [ -z "$1" ]; then
  1127. _usage "Usage: $PROJECT_ENTRY --createAccountKey --accountkeylength 2048"
  1128. return
  1129. fi
  1130. length=$1
  1131. _create_account_key "$length"
  1132. }
  1133. _create_account_key() {
  1134. length=$1
  1135. if [ -z "$length" ] || [ "$length" = "$NO_VALUE" ]; then
  1136. _debug "Use default length $DEFAULT_ACCOUNT_KEY_LENGTH"
  1137. length="$DEFAULT_ACCOUNT_KEY_LENGTH"
  1138. fi
  1139. _debug length "$length"
  1140. _initpath
  1141. mkdir -p "$CA_DIR"
  1142. if [ -f "$ACCOUNT_KEY_PATH" ]; then
  1143. _info "Account key exists, skip"
  1144. return
  1145. else
  1146. #generate account key
  1147. _createkey "$length" "$ACCOUNT_KEY_PATH"
  1148. chmod 600 "$ACCOUNT_KEY_PATH"
  1149. fi
  1150. }
  1151. #domain [length]
  1152. createDomainKey() {
  1153. _info "Creating domain key"
  1154. if [ -z "$1" ]; then
  1155. _usage "Usage: $PROJECT_ENTRY --createDomainKey -d domain.com [ --keylength 2048 ]"
  1156. return
  1157. fi
  1158. domain=$1
  1159. _cdl=$2
  1160. if [ -z "$_cdl" ]; then
  1161. _debug "Use DEFAULT_DOMAIN_KEY_LENGTH=$DEFAULT_DOMAIN_KEY_LENGTH"
  1162. _cdl="$DEFAULT_DOMAIN_KEY_LENGTH"
  1163. fi
  1164. _initpath "$domain" "$_cdl"
  1165. if [ ! -f "$CERT_KEY_PATH" ] || ([ "$FORCE" ] && ! [ "$IS_RENEW" ]) || [ "$Le_ForceNewDomainKey" = "1" ]; then
  1166. if _createkey "$_cdl" "$CERT_KEY_PATH"; then
  1167. _savedomainconf Le_Keylength "$_cdl"
  1168. _info "The domain key is here: $(__green $CERT_KEY_PATH)"
  1169. return 0
  1170. fi
  1171. else
  1172. if [ "$IS_RENEW" ]; then
  1173. _info "Domain key exists, skip"
  1174. return 0
  1175. else
  1176. _err "Domain key exists, do you want to overwrite the key?"
  1177. _err "Add '--force', and try again."
  1178. return 1
  1179. fi
  1180. fi
  1181. }
  1182. # domain domainlist isEcc
  1183. createCSR() {
  1184. _info "Creating csr"
  1185. if [ -z "$1" ]; then
  1186. _usage "Usage: $PROJECT_ENTRY --createCSR -d domain1.com [-d domain2.com -d domain3.com ... ]"
  1187. return
  1188. fi
  1189. domain="$1"
  1190. domainlist="$2"
  1191. _isEcc="$3"
  1192. _initpath "$domain" "$_isEcc"
  1193. if [ -f "$CSR_PATH" ] && [ "$IS_RENEW" ] && [ -z "$FORCE" ]; then
  1194. _info "CSR exists, skip"
  1195. return
  1196. fi
  1197. if [ ! -f "$CERT_KEY_PATH" ]; then
  1198. _err "The key file is not found: $CERT_KEY_PATH"
  1199. _err "Please create the key file first."
  1200. return 1
  1201. fi
  1202. _createcsr "$domain" "$domainlist" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"
  1203. }
  1204. _url_replace() {
  1205. tr '/+' '_-' | tr -d '= '
  1206. }
  1207. _time2str() {
  1208. #BSD
  1209. if date -u -r "$1" 2>/dev/null; then
  1210. return
  1211. fi
  1212. #Linux
  1213. if date -u -d@"$1" 2>/dev/null; then
  1214. return
  1215. fi
  1216. #Solaris
  1217. if _exists adb; then
  1218. _t_s_a=$(echo "0t${1}=Y" | adb)
  1219. echo "$_t_s_a"
  1220. fi
  1221. #Busybox
  1222. if echo "$1" | awk '{ print strftime("%c", $0); }' 2>/dev/null; then
  1223. return
  1224. fi
  1225. }
  1226. _normalizeJson() {
  1227. sed "s/\" *: *\([\"{\[]\)/\":\1/g" | sed "s/^ *\([^ ]\)/\1/" | tr -d "\r\n"
  1228. }
  1229. _stat() {
  1230. #Linux
  1231. if stat -c '%U:%G' "$1" 2>/dev/null; then
  1232. return
  1233. fi
  1234. #BSD
  1235. if stat -f '%Su:%Sg' "$1" 2>/dev/null; then
  1236. return
  1237. fi
  1238. return 1 #error, 'stat' not found
  1239. }
  1240. #keyfile
  1241. _calcjwk() {
  1242. keyfile="$1"
  1243. if [ -z "$keyfile" ]; then
  1244. _usage "Usage: _calcjwk keyfile"
  1245. return 1
  1246. fi
  1247. if [ "$JWK_HEADER" ] && [ "$__CACHED_JWK_KEY_FILE" = "$keyfile" ]; then
  1248. _debug2 "Use cached jwk for file: $__CACHED_JWK_KEY_FILE"
  1249. return 0
  1250. fi
  1251. if grep "BEGIN RSA PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  1252. _debug "RSA key"
  1253. pub_exp=$(${ACME_OPENSSL_BIN:-openssl} rsa -in "$keyfile" -noout -text | grep "^publicExponent:" | cut -d '(' -f 2 | cut -d 'x' -f 2 | cut -d ')' -f 1)
  1254. if [ "${#pub_exp}" = "5" ]; then
  1255. pub_exp=0$pub_exp
  1256. fi
  1257. _debug3 pub_exp "$pub_exp"
  1258. e=$(echo "$pub_exp" | _h2b | _base64)
  1259. _debug3 e "$e"
  1260. modulus=$(${ACME_OPENSSL_BIN:-openssl} rsa -in "$keyfile" -modulus -noout | cut -d '=' -f 2)
  1261. _debug3 modulus "$modulus"
  1262. n="$(printf "%s" "$modulus" | _h2b | _base64 | _url_replace)"
  1263. _debug3 n "$n"
  1264. jwk='{"e": "'$e'", "kty": "RSA", "n": "'$n'"}'
  1265. _debug3 jwk "$jwk"
  1266. JWK_HEADER='{"alg": "RS256", "jwk": '$jwk'}'
  1267. JWK_HEADERPLACE_PART1='{"nonce": "'
  1268. JWK_HEADERPLACE_PART2='", "alg": "RS256"'
  1269. elif grep "BEGIN EC PRIVATE KEY" "$keyfile" >/dev/null 2>&1; then
  1270. _debug "EC key"
  1271. crv="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep "^NIST CURVE:" | cut -d ":" -f 2 | tr -d " \r\n")"
  1272. _debug3 crv "$crv"
  1273. __ECC_KEY_LEN=$(echo "$crv" | cut -d "-" -f 2)
  1274. if [ "$__ECC_KEY_LEN" = "521" ]; then
  1275. __ECC_KEY_LEN=512
  1276. fi
  1277. _debug3 __ECC_KEY_LEN "$__ECC_KEY_LEN"
  1278. if [ -z "$crv" ]; then
  1279. _debug "Let's try ASN1 OID"
  1280. crv_oid="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep "^ASN1 OID:" | cut -d ":" -f 2 | tr -d " \r\n")"
  1281. _debug3 crv_oid "$crv_oid"
  1282. case "${crv_oid}" in
  1283. "prime256v1")
  1284. crv="P-256"
  1285. __ECC_KEY_LEN=256
  1286. ;;
  1287. "secp384r1")
  1288. crv="P-384"
  1289. __ECC_KEY_LEN=384
  1290. ;;
  1291. "secp521r1")
  1292. crv="P-521"
  1293. __ECC_KEY_LEN=512
  1294. ;;
  1295. *)
  1296. _err "ECC oid : $crv_oid"
  1297. return 1
  1298. ;;
  1299. esac
  1300. _debug3 crv "$crv"
  1301. fi
  1302. pubi="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep -n pub: | cut -d : -f 1)"
  1303. pubi=$(_math "$pubi" + 1)
  1304. _debug3 pubi "$pubi"
  1305. pubj="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | grep -n "ASN1 OID:" | cut -d : -f 1)"
  1306. pubj=$(_math "$pubj" - 1)
  1307. _debug3 pubj "$pubj"
  1308. pubtext="$(${ACME_OPENSSL_BIN:-openssl} ec -in "$keyfile" -noout -text 2>/dev/null | sed -n "$pubi,${pubj}p" | tr -d " \n\r")"
  1309. _debug3 pubtext "$pubtext"
  1310. xlen="$(printf "%s" "$pubtext" | tr -d ':' | wc -c)"
  1311. xlen=$(_math "$xlen" / 4)
  1312. _debug3 xlen "$xlen"
  1313. xend=$(_math "$xlen" + 1)
  1314. x="$(printf "%s" "$pubtext" | cut -d : -f 2-"$xend")"
  1315. _debug3 x "$x"
  1316. x64="$(printf "%s" "$x" | tr -d : | _h2b | _base64 | _url_replace)"
  1317. _debug3 x64 "$x64"
  1318. xend=$(_math "$xend" + 1)
  1319. y="$(printf "%s" "$pubtext" | cut -d : -f "$xend"-10000)"
  1320. _debug3 y "$y"
  1321. y64="$(printf "%s" "$y" | tr -d : | _h2b | _base64 | _url_replace)"
  1322. _debug3 y64 "$y64"
  1323. jwk='{"crv": "'$crv'", "kty": "EC", "x": "'$x64'", "y": "'$y64'"}'
  1324. _debug3 jwk "$jwk"
  1325. JWK_HEADER='{"alg": "ES'$__ECC_KEY_LEN'", "jwk": '$jwk'}'
  1326. JWK_HEADERPLACE_PART1='{"nonce": "'
  1327. JWK_HEADERPLACE_PART2='", "alg": "ES'$__ECC_KEY_LEN'"'
  1328. else
  1329. _err "Only RSA or EC key is supported. keyfile=$keyfile"
  1330. _debug2 "$(cat "$keyfile")"
  1331. return 1
  1332. fi
  1333. _debug3 JWK_HEADER "$JWK_HEADER"
  1334. __CACHED_JWK_KEY_FILE="$keyfile"
  1335. }
  1336. _time() {
  1337. date -u "+%s"
  1338. }
  1339. _utc_date() {
  1340. date -u "+%Y-%m-%d %H:%M:%S"
  1341. }
  1342. _mktemp() {
  1343. if _exists mktemp; then
  1344. if mktemp 2>/dev/null; then
  1345. return 0
  1346. elif _contains "$(mktemp 2>&1)" "-t prefix" && mktemp -t "$PROJECT_NAME" 2>/dev/null; then
  1347. #for Mac osx
  1348. return 0
  1349. fi
  1350. fi
  1351. if [ -d "/tmp" ]; then
  1352. echo "/tmp/${PROJECT_NAME}wefADf24sf.$(_time).tmp"
  1353. return 0
  1354. elif [ "$LE_TEMP_DIR" ] && mkdir -p "$LE_TEMP_DIR"; then
  1355. echo "/$LE_TEMP_DIR/wefADf24sf.$(_time).tmp"
  1356. return 0
  1357. fi
  1358. _err "Can not create temp file."
  1359. }
  1360. _inithttp() {
  1361. if [ -z "$HTTP_HEADER" ] || ! touch "$HTTP_HEADER"; then
  1362. HTTP_HEADER="$(_mktemp)"
  1363. _debug2 HTTP_HEADER "$HTTP_HEADER"
  1364. fi
  1365. if [ "$__HTTP_INITIALIZED" ]; then
  1366. if [ "$_ACME_CURL$_ACME_WGET" ]; then
  1367. _debug2 "Http already initialized."
  1368. return 0
  1369. fi
  1370. fi
  1371. if [ -z "$_ACME_CURL" ] && _exists "curl"; then
  1372. _ACME_CURL="curl -L --silent --dump-header $HTTP_HEADER "
  1373. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1374. _CURL_DUMP="$(_mktemp)"
  1375. _ACME_CURL="$_ACME_CURL --trace-ascii $_CURL_DUMP "
  1376. fi
  1377. if [ "$CA_PATH" ]; then
  1378. _ACME_CURL="$_ACME_CURL --capath $CA_PATH "
  1379. elif [ "$CA_BUNDLE" ]; then
  1380. _ACME_CURL="$_ACME_CURL --cacert $CA_BUNDLE "
  1381. fi
  1382. if _contains "$(curl --help 2>&1)" "--globoff"; then
  1383. _ACME_CURL="$_ACME_CURL -g "
  1384. fi
  1385. fi
  1386. if [ -z "$_ACME_WGET" ] && _exists "wget"; then
  1387. _ACME_WGET="wget -q"
  1388. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1389. _ACME_WGET="$_ACME_WGET -d "
  1390. fi
  1391. if [ "$CA_PATH" ]; then
  1392. _ACME_WGET="$_ACME_WGET --ca-directory=$CA_PATH "
  1393. elif [ "$CA_BUNDLE" ]; then
  1394. _ACME_WGET="$_ACME_WGET --ca-certificate=$CA_BUNDLE "
  1395. fi
  1396. fi
  1397. #from wget 1.14: do not skip body on 404 error
  1398. if [ "$_ACME_WGET" ] && _contains "$($_ACME_WGET --help 2>&1)" "--content-on-error"; then
  1399. _ACME_WGET="$_ACME_WGET --content-on-error "
  1400. fi
  1401. __HTTP_INITIALIZED=1
  1402. }
  1403. # body url [needbase64] [POST|PUT|DELETE] [ContentType]
  1404. _post() {
  1405. body="$1"
  1406. _post_url="$2"
  1407. needbase64="$3"
  1408. httpmethod="$4"
  1409. _postContentType="$5"
  1410. if [ -z "$httpmethod" ]; then
  1411. httpmethod="POST"
  1412. fi
  1413. _debug $httpmethod
  1414. _debug "_post_url" "$_post_url"
  1415. _debug2 "body" "$body"
  1416. _debug2 "_postContentType" "$_postContentType"
  1417. _inithttp
  1418. if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
  1419. _CURL="$_ACME_CURL"
  1420. if [ "$HTTPS_INSECURE" ]; then
  1421. _CURL="$_CURL --insecure "
  1422. fi
  1423. _debug "_CURL" "$_CURL"
  1424. if [ "$needbase64" ]; then
  1425. if [ "$_postContentType" ]; then
  1426. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
  1427. else
  1428. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
  1429. fi
  1430. else
  1431. if [ "$_postContentType" ]; then
  1432. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "Content-Type: $_postContentType" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
  1433. else
  1434. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
  1435. fi
  1436. fi
  1437. _ret="$?"
  1438. if [ "$_ret" != "0" ]; then
  1439. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  1440. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1441. _err "Here is the curl dump log:"
  1442. _err "$(cat "$_CURL_DUMP")"
  1443. fi
  1444. fi
  1445. elif [ "$_ACME_WGET" ]; then
  1446. _WGET="$_ACME_WGET"
  1447. if [ "$HTTPS_INSECURE" ]; then
  1448. _WGET="$_WGET --no-check-certificate "
  1449. fi
  1450. _debug "_WGET" "$_WGET"
  1451. if [ "$needbase64" ]; then
  1452. if [ "$httpmethod" = "POST" ]; then
  1453. if [ "$_postContentType" ]; then
  1454. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1455. else
  1456. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1457. fi
  1458. else
  1459. if [ "$_postContentType" ]; then
  1460. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1461. else
  1462. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER" | _base64)"
  1463. fi
  1464. fi
  1465. else
  1466. if [ "$httpmethod" = "POST" ]; then
  1467. if [ "$_postContentType" ]; then
  1468. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1469. else
  1470. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --post-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1471. fi
  1472. else
  1473. if [ "$_postContentType" ]; then
  1474. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --header "Content-Type: $_postContentType" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1475. else
  1476. response="$($_WGET -S -O - --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" --method $httpmethod --body-data="$body" "$_post_url" 2>"$HTTP_HEADER")"
  1477. fi
  1478. fi
  1479. fi
  1480. _ret="$?"
  1481. if [ "$_ret" = "8" ]; then
  1482. _ret=0
  1483. _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
  1484. fi
  1485. if [ "$_ret" != "0" ]; then
  1486. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  1487. fi
  1488. _sed_i "s/^ *//g" "$HTTP_HEADER"
  1489. else
  1490. _ret="$?"
  1491. _err "Neither curl nor wget is found, can not do $httpmethod."
  1492. fi
  1493. _debug "_ret" "$_ret"
  1494. printf "%s" "$response"
  1495. return $_ret
  1496. }
  1497. # url getheader timeout
  1498. _get() {
  1499. _debug GET
  1500. url="$1"
  1501. onlyheader="$2"
  1502. t="$3"
  1503. _debug url "$url"
  1504. _debug "timeout=$t"
  1505. _inithttp
  1506. if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
  1507. _CURL="$_ACME_CURL"
  1508. if [ "$HTTPS_INSECURE" ]; then
  1509. _CURL="$_CURL --insecure "
  1510. fi
  1511. if [ "$t" ]; then
  1512. _CURL="$_CURL --connect-timeout $t"
  1513. fi
  1514. _debug "_CURL" "$_CURL"
  1515. if [ "$onlyheader" ]; then
  1516. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1517. else
  1518. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1519. fi
  1520. ret=$?
  1521. if [ "$ret" != "0" ]; then
  1522. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  1523. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1524. _err "Here is the curl dump log:"
  1525. _err "$(cat "$_CURL_DUMP")"
  1526. fi
  1527. fi
  1528. elif [ "$_ACME_WGET" ]; then
  1529. _WGET="$_ACME_WGET"
  1530. if [ "$HTTPS_INSECURE" ]; then
  1531. _WGET="$_WGET --no-check-certificate "
  1532. fi
  1533. if [ "$t" ]; then
  1534. _WGET="$_WGET --timeout=$t"
  1535. fi
  1536. _debug "_WGET" "$_WGET"
  1537. if [ "$onlyheader" ]; then
  1538. $_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'
  1539. else
  1540. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
  1541. fi
  1542. ret=$?
  1543. if [ "$ret" = "8" ]; then
  1544. ret=0
  1545. _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
  1546. fi
  1547. if [ "$ret" != "0" ]; then
  1548. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  1549. fi
  1550. else
  1551. ret=$?
  1552. _err "Neither curl nor wget is found, can not do GET."
  1553. fi
  1554. _debug "ret" "$ret"
  1555. return $ret
  1556. }
  1557. _head_n() {
  1558. head -n "$1"
  1559. }
  1560. _tail_n() {
  1561. if ! tail -n "$1" 2>/dev/null; then
  1562. #fix for solaris
  1563. tail -"$1"
  1564. fi
  1565. }
  1566. # url payload needbase64 keyfile
  1567. _send_signed_request() {
  1568. url=$1
  1569. payload=$2
  1570. needbase64=$3
  1571. keyfile=$4
  1572. if [ -z "$keyfile" ]; then
  1573. keyfile="$ACCOUNT_KEY_PATH"
  1574. fi
  1575. _debug url "$url"
  1576. _debug payload "$payload"
  1577. if ! _calcjwk "$keyfile"; then
  1578. return 1
  1579. fi
  1580. __request_conent_type="$CONTENT_TYPE_JSON"
  1581. payload64=$(printf "%s" "$payload" | _base64 | _url_replace)
  1582. _debug3 payload64 "$payload64"
  1583. MAX_REQUEST_RETRY_TIMES=20
  1584. _sleep_retry_sec=1
  1585. _request_retry_times=0
  1586. while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
  1587. _request_retry_times=$(_math "$_request_retry_times" + 1)
  1588. _debug3 _request_retry_times "$_request_retry_times"
  1589. if [ -z "$_CACHED_NONCE" ]; then
  1590. _headers=""
  1591. if [ "$ACME_NEW_NONCE" ]; then
  1592. _debug2 "Get nonce with HEAD. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  1593. nonceurl="$ACME_NEW_NONCE"
  1594. if _post "" "$nonceurl" "" "HEAD" "$__request_conent_type"; then
  1595. _headers="$(cat "$HTTP_HEADER")"
  1596. _debug2 _headers "$_headers"
  1597. _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1598. fi
  1599. fi
  1600. if [ -z "$_CACHED_NONCE" ]; then
  1601. _debug2 "Get nonce with GET. ACME_DIRECTORY" "$ACME_DIRECTORY"
  1602. nonceurl="$ACME_DIRECTORY"
  1603. _headers="$(_get "$nonceurl" "onlyheader")"
  1604. _debug2 _headers "$_headers"
  1605. _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1606. fi
  1607. if [ -z "$_CACHED_NONCE" ] && [ "$ACME_NEW_NONCE" ]; then
  1608. _debug2 "Get nonce with GET. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  1609. nonceurl="$ACME_NEW_NONCE"
  1610. _headers="$(_get "$nonceurl" "onlyheader")"
  1611. _debug2 _headers "$_headers"
  1612. _CACHED_NONCE="$(echo "$_headers" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1613. fi
  1614. _debug2 _CACHED_NONCE "$_CACHED_NONCE"
  1615. if [ "$?" != "0" ]; then
  1616. _err "Can not connect to $nonceurl to get nonce."
  1617. return 1
  1618. fi
  1619. else
  1620. _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
  1621. fi
  1622. nonce="$_CACHED_NONCE"
  1623. _debug2 nonce "$nonce"
  1624. if [ -z "$nonce" ]; then
  1625. _info "Could not get nonce, let's try again."
  1626. _sleep 2
  1627. continue
  1628. fi
  1629. if [ "$ACME_VERSION" = "2" ]; then
  1630. if [ "$url" = "$ACME_NEW_ACCOUNT" ] || [ "$url" = "$ACME_REVOKE_CERT" ]; then
  1631. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1632. else
  1633. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"kid\": \"${ACCOUNT_URL}\""'}'
  1634. fi
  1635. else
  1636. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1637. fi
  1638. _debug3 protected "$protected"
  1639. protected64="$(printf "%s" "$protected" | _base64 | _url_replace)"
  1640. _debug3 protected64 "$protected64"
  1641. if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
  1642. _err "Sign request failed."
  1643. return 1
  1644. fi
  1645. _debug3 _sig_t "$_sig_t"
  1646. sig="$(printf "%s" "$_sig_t" | _url_replace)"
  1647. _debug3 sig "$sig"
  1648. body="{\"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1649. _debug3 body "$body"
  1650. response="$(_post "$body" "$url" "$needbase64" "POST" "$__request_conent_type")"
  1651. _CACHED_NONCE=""
  1652. if [ "$?" != "0" ]; then
  1653. _err "Can not post to $url"
  1654. return 1
  1655. fi
  1656. responseHeaders="$(cat "$HTTP_HEADER")"
  1657. _debug2 responseHeaders "$responseHeaders"
  1658. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1659. _debug code "$code"
  1660. _debug2 original "$response"
  1661. if echo "$responseHeaders" | grep -i "Content-Type: application/json" >/dev/null 2>&1; then
  1662. response="$(echo "$response" | _normalizeJson)"
  1663. fi
  1664. _debug2 response "$response"
  1665. _CACHED_NONCE="$(echo "$responseHeaders" | grep -i "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1666. if ! _startswith "$code" "2"; then
  1667. _body="$response"
  1668. if [ "$needbase64" ]; then
  1669. _body="$(echo "$_body" | _dbase64 multiline)"
  1670. _debug3 _body "$_body"
  1671. fi
  1672. if _contains "$_body" "JWS has invalid anti-replay nonce" || _contains "$_body" "JWS has an invalid anti-replay nonce"; then
  1673. _info "It seems the CA server is busy now, let's wait and retry. Sleeping $_sleep_retry_sec seconds."
  1674. _CACHED_NONCE=""
  1675. _sleep $_sleep_retry_sec
  1676. continue
  1677. fi
  1678. fi
  1679. break
  1680. done
  1681. }
  1682. #setopt "file" "opt" "=" "value" [";"]
  1683. _setopt() {
  1684. __conf="$1"
  1685. __opt="$2"
  1686. __sep="$3"
  1687. __val="$4"
  1688. __end="$5"
  1689. if [ -z "$__opt" ]; then
  1690. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1691. return
  1692. fi
  1693. if [ ! -f "$__conf" ]; then
  1694. touch "$__conf"
  1695. fi
  1696. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1697. _debug3 OK
  1698. if _contains "$__val" "&"; then
  1699. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1700. fi
  1701. text="$(cat "$__conf")"
  1702. printf -- "%s\n" "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1703. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1704. if _contains "$__val" "&"; then
  1705. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1706. fi
  1707. text="$(cat "$__conf")"
  1708. printf -- "%s\n" "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1709. else
  1710. _debug3 APP
  1711. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1712. fi
  1713. _debug3 "$(grep -n "^$__opt$__sep" "$__conf")"
  1714. }
  1715. #_save_conf file key value base64encode
  1716. #save to conf
  1717. _save_conf() {
  1718. _s_c_f="$1"
  1719. _sdkey="$2"
  1720. _sdvalue="$3"
  1721. _b64encode="$4"
  1722. if [ "$_sdvalue" ] && [ "$_b64encode" ]; then
  1723. _sdvalue="${B64CONF_START}$(printf "%s" "${_sdvalue}" | _base64)${B64CONF_END}"
  1724. fi
  1725. if [ "$_s_c_f" ]; then
  1726. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1727. else
  1728. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1729. fi
  1730. }
  1731. #_clear_conf file key
  1732. _clear_conf() {
  1733. _c_c_f="$1"
  1734. _sdkey="$2"
  1735. if [ "$_c_c_f" ]; then
  1736. _conf_data="$(cat "$_c_c_f")"
  1737. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1738. else
  1739. _err "config file is empty, can not clear"
  1740. fi
  1741. }
  1742. #_read_conf file key
  1743. _read_conf() {
  1744. _r_c_f="$1"
  1745. _sdkey="$2"
  1746. if [ -f "$_r_c_f" ]; then
  1747. _sdv="$(grep "^$_sdkey *=" "$_r_c_f" | cut -d = -f 2-1000 | tr -d "'")"
  1748. if _startswith "$_sdv" "${B64CONF_START}" && _endswith "$_sdv" "${B64CONF_END}"; then
  1749. _sdv="$(echo "$_sdv" | sed "s/${B64CONF_START}//" | sed "s/${B64CONF_END}//" | _dbase64)"
  1750. fi
  1751. printf "%s" "$_sdv"
  1752. else
  1753. _debug "config file is empty, can not read $_sdkey"
  1754. fi
  1755. }
  1756. #_savedomainconf key value base64encode
  1757. #save to domain.conf
  1758. _savedomainconf() {
  1759. _save_conf "$DOMAIN_CONF" "$@"
  1760. }
  1761. #_cleardomainconf key
  1762. _cleardomainconf() {
  1763. _clear_conf "$DOMAIN_CONF" "$1"
  1764. }
  1765. #_readdomainconf key
  1766. _readdomainconf() {
  1767. _read_conf "$DOMAIN_CONF" "$1"
  1768. }
  1769. #_saveaccountconf key value base64encode
  1770. _saveaccountconf() {
  1771. _save_conf "$ACCOUNT_CONF_PATH" "$@"
  1772. }
  1773. #key value base64encode
  1774. _saveaccountconf_mutable() {
  1775. _save_conf "$ACCOUNT_CONF_PATH" "SAVED_$1" "$2" "$3"
  1776. #remove later
  1777. _clearaccountconf "$1"
  1778. }
  1779. #key
  1780. _readaccountconf() {
  1781. _read_conf "$ACCOUNT_CONF_PATH" "$1"
  1782. }
  1783. #key
  1784. _readaccountconf_mutable() {
  1785. _rac_key="$1"
  1786. _readaccountconf "SAVED_$_rac_key"
  1787. }
  1788. #_clearaccountconf key
  1789. _clearaccountconf() {
  1790. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1791. }
  1792. #_savecaconf key value
  1793. _savecaconf() {
  1794. _save_conf "$CA_CONF" "$1" "$2"
  1795. }
  1796. #_readcaconf key
  1797. _readcaconf() {
  1798. _read_conf "$CA_CONF" "$1"
  1799. }
  1800. #_clearaccountconf key
  1801. _clearcaconf() {
  1802. _clear_conf "$CA_CONF" "$1"
  1803. }
  1804. # content localaddress
  1805. _startserver() {
  1806. content="$1"
  1807. ncaddr="$2"
  1808. _debug "content" "$content"
  1809. _debug "ncaddr" "$ncaddr"
  1810. _debug "startserver: $$"
  1811. _debug Le_HTTPPort "$Le_HTTPPort"
  1812. _debug Le_Listen_V4 "$Le_Listen_V4"
  1813. _debug Le_Listen_V6 "$Le_Listen_V6"
  1814. _NC="socat"
  1815. if [ "$Le_Listen_V4" ]; then
  1816. _NC="$_NC -4"
  1817. elif [ "$Le_Listen_V6" ]; then
  1818. _NC="$_NC -6"
  1819. fi
  1820. if [ "$DEBUG" ] && [ "$DEBUG" -gt "1" ]; then
  1821. _NC="$_NC -d -d -v"
  1822. fi
  1823. SOCAT_OPTIONS=TCP-LISTEN:$Le_HTTPPort,crlf,reuseaddr,fork
  1824. #Adding bind to local-address
  1825. if [ "$ncaddr" ]; then
  1826. SOCAT_OPTIONS="$SOCAT_OPTIONS,bind=${ncaddr}"
  1827. fi
  1828. _content_len="$(printf "%s" "$content" | wc -c)"
  1829. _debug _content_len "$_content_len"
  1830. _debug "_NC" "$_NC $SOCAT_OPTIONS"
  1831. $_NC $SOCAT_OPTIONS SYSTEM:"sleep 1; \
  1832. echo 'HTTP/1.0 200 OK'; \
  1833. echo 'Content-Length\: $_content_len'; \
  1834. echo ''; \
  1835. printf -- '$content';" &
  1836. serverproc="$!"
  1837. }
  1838. _stopserver() {
  1839. pid="$1"
  1840. _debug "pid" "$pid"
  1841. if [ -z "$pid" ]; then
  1842. return
  1843. fi
  1844. kill $pid
  1845. }
  1846. # sleep sec
  1847. _sleep() {
  1848. _sleep_sec="$1"
  1849. if [ "$__INTERACTIVE" ]; then
  1850. _sleep_c="$_sleep_sec"
  1851. while [ "$_sleep_c" -ge "0" ]; do
  1852. printf "\r \r"
  1853. __green "$_sleep_c"
  1854. _sleep_c="$(_math "$_sleep_c" - 1)"
  1855. sleep 1
  1856. done
  1857. printf "\r"
  1858. else
  1859. sleep "$_sleep_sec"
  1860. fi
  1861. }
  1862. # _starttlsserver san_a san_b port content _ncaddr acmeValidationv1
  1863. _starttlsserver() {
  1864. _info "Starting tls server."
  1865. san_a="$1"
  1866. san_b="$2"
  1867. port="$3"
  1868. content="$4"
  1869. opaddr="$5"
  1870. acmeValidationv1="$6"
  1871. _debug san_a "$san_a"
  1872. _debug san_b "$san_b"
  1873. _debug port "$port"
  1874. _debug acmeValidationv1 "$acmeValidationv1"
  1875. #create key TLS_KEY
  1876. if ! _createkey "2048" "$TLS_KEY"; then
  1877. _err "Create tls validation key error."
  1878. return 1
  1879. fi
  1880. #create csr
  1881. alt="$san_a"
  1882. if [ "$san_b" ]; then
  1883. alt="$alt,$san_b"
  1884. fi
  1885. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$acmeValidationv1"; then
  1886. _err "Create tls validation csr error."
  1887. return 1
  1888. fi
  1889. #self signed
  1890. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  1891. _err "Create tls validation cert error."
  1892. return 1
  1893. fi
  1894. __S_OPENSSL="${ACME_OPENSSL_BIN:-openssl} s_server -www -cert $TLS_CERT -key $TLS_KEY "
  1895. if [ "$opaddr" ]; then
  1896. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1897. else
  1898. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1899. fi
  1900. _debug Le_Listen_V4 "$Le_Listen_V4"
  1901. _debug Le_Listen_V6 "$Le_Listen_V6"
  1902. if [ "$Le_Listen_V4" ]; then
  1903. __S_OPENSSL="$__S_OPENSSL -4"
  1904. elif [ "$Le_Listen_V6" ]; then
  1905. __S_OPENSSL="$__S_OPENSSL -6"
  1906. fi
  1907. if [ "$acmeValidationv1" ]; then
  1908. __S_OPENSSL="$__S_OPENSSL -alpn acme-tls/1"
  1909. fi
  1910. _debug "$__S_OPENSSL"
  1911. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1912. $__S_OPENSSL -tlsextdebug &
  1913. else
  1914. $__S_OPENSSL >/dev/null 2>&1 &
  1915. fi
  1916. serverproc="$!"
  1917. sleep 1
  1918. _debug serverproc "$serverproc"
  1919. }
  1920. #file
  1921. _readlink() {
  1922. _rf="$1"
  1923. if ! readlink -f "$_rf" 2>/dev/null; then
  1924. if _startswith "$_rf" "/"; then
  1925. echo "$_rf"
  1926. return 0
  1927. fi
  1928. echo "$(pwd)/$_rf" | _conapath
  1929. fi
  1930. }
  1931. _conapath() {
  1932. sed "s#/\./#/#g"
  1933. }
  1934. __initHome() {
  1935. if [ -z "$_SCRIPT_HOME" ]; then
  1936. if _exists readlink && _exists dirname; then
  1937. _debug "Lets find script dir."
  1938. _debug "_SCRIPT_" "$_SCRIPT_"
  1939. _script="$(_readlink "$_SCRIPT_")"
  1940. _debug "_script" "$_script"
  1941. _script_home="$(dirname "$_script")"
  1942. _debug "_script_home" "$_script_home"
  1943. if [ -d "$_script_home" ]; then
  1944. _SCRIPT_HOME="$_script_home"
  1945. else
  1946. _err "It seems the script home is not correct:$_script_home"
  1947. fi
  1948. fi
  1949. fi
  1950. # if [ -z "$LE_WORKING_DIR" ]; then
  1951. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  1952. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1953. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1954. # else
  1955. # LE_WORKING_DIR="$_SCRIPT_HOME"
  1956. # fi
  1957. # fi
  1958. if [ -z "$LE_WORKING_DIR" ]; then
  1959. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1960. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1961. fi
  1962. export LE_WORKING_DIR
  1963. if [ -z "$LE_CONFIG_HOME" ]; then
  1964. LE_CONFIG_HOME="$LE_WORKING_DIR"
  1965. fi
  1966. _debug "Using config home:$LE_CONFIG_HOME"
  1967. export LE_CONFIG_HOME
  1968. _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
  1969. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1970. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  1971. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1972. fi
  1973. fi
  1974. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1975. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1976. fi
  1977. DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
  1978. DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
  1979. if [ -z "$LE_TEMP_DIR" ]; then
  1980. LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
  1981. fi
  1982. }
  1983. #server
  1984. _initAPI() {
  1985. _api_server="${1:-$ACME_DIRECTORY}"
  1986. _debug "_init api for server: $_api_server"
  1987. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1988. response=$(_get "$_api_server")
  1989. if [ "$?" != "0" ]; then
  1990. _debug2 "response" "$response"
  1991. _err "Can not init api."
  1992. return 1
  1993. fi
  1994. _debug2 "response" "$response"
  1995. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'key-change" *: *"[^"]*"' | cut -d '"' -f 3)
  1996. if [ -z "$ACME_KEY_CHANGE" ]; then
  1997. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'keyChange" *: *"[^"]*"' | cut -d '"' -f 3)
  1998. fi
  1999. export ACME_KEY_CHANGE
  2000. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'new-authz" *: *"[^"]*"' | cut -d '"' -f 3)
  2001. if [ -z "$ACME_NEW_AUTHZ" ]; then
  2002. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'newAuthz" *: *"[^"]*"' | cut -d '"' -f 3)
  2003. fi
  2004. export ACME_NEW_AUTHZ
  2005. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  2006. ACME_NEW_ORDER_RES="new-cert"
  2007. if [ -z "$ACME_NEW_ORDER" ]; then
  2008. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-order" *: *"[^"]*"' | cut -d '"' -f 3)
  2009. ACME_NEW_ORDER_RES="new-order"
  2010. if [ -z "$ACME_NEW_ORDER" ]; then
  2011. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'newOrder" *: *"[^"]*"' | cut -d '"' -f 3)
  2012. fi
  2013. fi
  2014. export ACME_NEW_ORDER
  2015. export ACME_NEW_ORDER_RES
  2016. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-reg" *: *"[^"]*"' | cut -d '"' -f 3)
  2017. ACME_NEW_ACCOUNT_RES="new-reg"
  2018. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  2019. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-account" *: *"[^"]*"' | cut -d '"' -f 3)
  2020. ACME_NEW_ACCOUNT_RES="new-account"
  2021. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  2022. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'newAccount" *: *"[^"]*"' | cut -d '"' -f 3)
  2023. if [ "$ACME_NEW_ACCOUNT" ]; then
  2024. export ACME_VERSION=2
  2025. fi
  2026. fi
  2027. fi
  2028. export ACME_NEW_ACCOUNT
  2029. export ACME_NEW_ACCOUNT_RES
  2030. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revoke-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  2031. if [ -z "$ACME_REVOKE_CERT" ]; then
  2032. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revokeCert" *: *"[^"]*"' | cut -d '"' -f 3)
  2033. fi
  2034. export ACME_REVOKE_CERT
  2035. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'new-nonce" *: *"[^"]*"' | cut -d '"' -f 3)
  2036. if [ -z "$ACME_NEW_NONCE" ]; then
  2037. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'newNonce" *: *"[^"]*"' | cut -d '"' -f 3)
  2038. fi
  2039. export ACME_NEW_NONCE
  2040. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'terms-of-service" *: *"[^"]*"' | cut -d '"' -f 3)
  2041. if [ -z "$ACME_AGREEMENT" ]; then
  2042. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'termsOfService" *: *"[^"]*"' | cut -d '"' -f 3)
  2043. fi
  2044. export ACME_AGREEMENT
  2045. _debug "ACME_KEY_CHANGE" "$ACME_KEY_CHANGE"
  2046. _debug "ACME_NEW_AUTHZ" "$ACME_NEW_AUTHZ"
  2047. _debug "ACME_NEW_ORDER" "$ACME_NEW_ORDER"
  2048. _debug "ACME_NEW_ACCOUNT" "$ACME_NEW_ACCOUNT"
  2049. _debug "ACME_REVOKE_CERT" "$ACME_REVOKE_CERT"
  2050. _debug "ACME_AGREEMENT" "$ACME_AGREEMENT"
  2051. _debug "ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  2052. _debug "ACME_VERSION" "$ACME_VERSION"
  2053. fi
  2054. }
  2055. #[domain] [keylength or isEcc flag]
  2056. _initpath() {
  2057. domain="$1"
  2058. _ilength="$2"
  2059. __initHome
  2060. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  2061. . "$ACCOUNT_CONF_PATH"
  2062. fi
  2063. if [ "$IN_CRON" ]; then
  2064. if [ ! "$_USER_PATH_EXPORTED" ]; then
  2065. _USER_PATH_EXPORTED=1
  2066. export PATH="$USER_PATH:$PATH"
  2067. fi
  2068. fi
  2069. if [ -z "$CA_HOME" ]; then
  2070. CA_HOME="$DEFAULT_CA_HOME"
  2071. fi
  2072. if [ "$ACME_VERSION" = "2" ]; then
  2073. DEFAULT_CA="$LETSENCRYPT_CA_V2"
  2074. DEFAULT_STAGING_CA="$LETSENCRYPT_STAGING_CA_V2"
  2075. fi
  2076. if [ -z "$ACME_DIRECTORY" ]; then
  2077. if [ -z "$STAGE" ]; then
  2078. ACME_DIRECTORY="$DEFAULT_CA"
  2079. else
  2080. ACME_DIRECTORY="$DEFAULT_STAGING_CA"
  2081. _info "Using stage ACME_DIRECTORY: $ACME_DIRECTORY"
  2082. fi
  2083. fi
  2084. _debug ACME_DIRECTORY "$ACME_DIRECTORY"
  2085. _ACME_SERVER_HOST="$(echo "$ACME_DIRECTORY" | cut -d : -f 2 | tr -s / | cut -d / -f 2)"
  2086. _debug2 "_ACME_SERVER_HOST" "$_ACME_SERVER_HOST"
  2087. CA_DIR="$CA_HOME/$_ACME_SERVER_HOST"
  2088. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  2089. if [ -z "$CA_CONF" ]; then
  2090. CA_CONF="$_DEFAULT_CA_CONF"
  2091. fi
  2092. _debug3 CA_CONF "$CA_CONF"
  2093. if [ -f "$CA_CONF" ]; then
  2094. . "$CA_CONF"
  2095. fi
  2096. if [ -z "$ACME_DIR" ]; then
  2097. ACME_DIR="/home/.acme"
  2098. fi
  2099. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  2100. APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
  2101. fi
  2102. if [ -z "$USER_AGENT" ]; then
  2103. USER_AGENT="$DEFAULT_USER_AGENT"
  2104. fi
  2105. if [ -z "$HTTP_HEADER" ]; then
  2106. HTTP_HEADER="$LE_CONFIG_HOME/http.header"
  2107. fi
  2108. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  2109. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  2110. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  2111. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  2112. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  2113. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  2114. fi
  2115. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  2116. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  2117. fi
  2118. _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
  2119. if [ -z "$CERT_HOME" ]; then
  2120. CERT_HOME="$_DEFAULT_CERT_HOME"
  2121. fi
  2122. if [ -z "$ACME_OPENSSL_BIN" ] || [ ! -f "$ACME_OPENSSL_BIN" ] || [ ! -x "$ACME_OPENSSL_BIN" ]; then
  2123. ACME_OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  2124. fi
  2125. if [ -z "$domain" ]; then
  2126. return 0
  2127. fi
  2128. if [ -z "$DOMAIN_PATH" ]; then
  2129. domainhome="$CERT_HOME/$domain"
  2130. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  2131. DOMAIN_PATH="$domainhome"
  2132. if _isEccKey "$_ilength"; then
  2133. DOMAIN_PATH="$domainhomeecc"
  2134. else
  2135. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  2136. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  2137. fi
  2138. fi
  2139. _debug DOMAIN_PATH "$DOMAIN_PATH"
  2140. fi
  2141. if [ -z "$DOMAIN_BACKUP_PATH" ]; then
  2142. DOMAIN_BACKUP_PATH="$DOMAIN_PATH/backup"
  2143. fi
  2144. if [ -z "$DOMAIN_CONF" ]; then
  2145. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  2146. fi
  2147. if [ -z "$DOMAIN_SSL_CONF" ]; then
  2148. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  2149. fi
  2150. if [ -z "$CSR_PATH" ]; then
  2151. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  2152. fi
  2153. if [ -z "$CERT_KEY_PATH" ]; then
  2154. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  2155. fi
  2156. if [ -z "$CERT_PATH" ]; then
  2157. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  2158. fi
  2159. if [ -z "$CA_CERT_PATH" ]; then
  2160. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  2161. fi
  2162. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  2163. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  2164. fi
  2165. if [ -z "$CERT_PFX_PATH" ]; then
  2166. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  2167. fi
  2168. if [ -z "$CERT_PKCS8_PATH" ]; then
  2169. CERT_PKCS8_PATH="$DOMAIN_PATH/$domain.pkcs8"
  2170. fi
  2171. if [ -z "$TLS_CONF" ]; then
  2172. TLS_CONF="$DOMAIN_PATH/tls.validation.conf"
  2173. fi
  2174. if [ -z "$TLS_CERT" ]; then
  2175. TLS_CERT="$DOMAIN_PATH/tls.validation.cert"
  2176. fi
  2177. if [ -z "$TLS_KEY" ]; then
  2178. TLS_KEY="$DOMAIN_PATH/tls.validation.key"
  2179. fi
  2180. if [ -z "$TLS_CSR" ]; then
  2181. TLS_CSR="$DOMAIN_PATH/tls.validation.csr"
  2182. fi
  2183. }
  2184. _exec() {
  2185. if [ -z "$_EXEC_TEMP_ERR" ]; then
  2186. _EXEC_TEMP_ERR="$(_mktemp)"
  2187. fi
  2188. if [ "$_EXEC_TEMP_ERR" ]; then
  2189. eval "$@ 2>>$_EXEC_TEMP_ERR"
  2190. else
  2191. eval "$@"
  2192. fi
  2193. }
  2194. _exec_err() {
  2195. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  2196. }
  2197. _apachePath() {
  2198. _APACHECTL="apachectl"
  2199. if ! _exists apachectl; then
  2200. if _exists apache2ctl; then
  2201. _APACHECTL="apache2ctl"
  2202. else
  2203. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  2204. _err "Please use webroot mode to try again."
  2205. return 1
  2206. fi
  2207. fi
  2208. if ! _exec $_APACHECTL -V >/dev/null; then
  2209. _exec_err
  2210. return 1
  2211. fi
  2212. if [ "$APACHE_HTTPD_CONF" ]; then
  2213. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  2214. httpdconf="$APACHE_HTTPD_CONF"
  2215. httpdconfname="$(basename "$httpdconfname")"
  2216. else
  2217. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  2218. _debug httpdconfname "$httpdconfname"
  2219. if [ -z "$httpdconfname" ]; then
  2220. _err "Can not read apache config file."
  2221. return 1
  2222. fi
  2223. if _startswith "$httpdconfname" '/'; then
  2224. httpdconf="$httpdconfname"
  2225. httpdconfname="$(basename "$httpdconfname")"
  2226. else
  2227. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  2228. _debug httpdroot "$httpdroot"
  2229. httpdconf="$httpdroot/$httpdconfname"
  2230. httpdconfname="$(basename "$httpdconfname")"
  2231. fi
  2232. fi
  2233. _debug httpdconf "$httpdconf"
  2234. _debug httpdconfname "$httpdconfname"
  2235. if [ ! -f "$httpdconf" ]; then
  2236. _err "Apache Config file not found" "$httpdconf"
  2237. return 1
  2238. fi
  2239. return 0
  2240. }
  2241. _restoreApache() {
  2242. if [ -z "$usingApache" ]; then
  2243. return 0
  2244. fi
  2245. _initpath
  2246. if ! _apachePath; then
  2247. return 1
  2248. fi
  2249. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  2250. _debug "No config file to restore."
  2251. return 0
  2252. fi
  2253. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  2254. _debug "Restored: $httpdconf."
  2255. if ! _exec $_APACHECTL -t; then
  2256. _exec_err
  2257. _err "Sorry, restore apache config error, please contact me."
  2258. return 1
  2259. fi
  2260. _debug "Restored successfully."
  2261. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2262. return 0
  2263. }
  2264. _setApache() {
  2265. _initpath
  2266. if ! _apachePath; then
  2267. return 1
  2268. fi
  2269. #test the conf first
  2270. _info "Checking if there is an error in the apache config file before starting."
  2271. if ! _exec "$_APACHECTL" -t >/dev/null; then
  2272. _exec_err
  2273. _err "The apache config file has error, please fix it first, then try again."
  2274. _err "Don't worry, there is nothing changed to your system."
  2275. return 1
  2276. else
  2277. _info "OK"
  2278. fi
  2279. #backup the conf
  2280. _debug "Backup apache config file" "$httpdconf"
  2281. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  2282. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  2283. _err "This might be a bug of $PROJECT_NAME , please report issue: $PROJECT"
  2284. return 1
  2285. fi
  2286. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2287. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  2288. _info "The backup file will be deleted on success, just forget it."
  2289. #add alias
  2290. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  2291. _debug "apacheVer" "$apacheVer"
  2292. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  2293. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  2294. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  2295. echo "
  2296. Alias /.well-known/acme-challenge $ACME_DIR
  2297. <Directory $ACME_DIR >
  2298. Require all granted
  2299. </Directory>
  2300. " >>"$httpdconf"
  2301. else
  2302. echo "
  2303. Alias /.well-known/acme-challenge $ACME_DIR
  2304. <Directory $ACME_DIR >
  2305. Order allow,deny
  2306. Allow from all
  2307. </Directory>
  2308. " >>"$httpdconf"
  2309. fi
  2310. _msg="$($_APACHECTL -t 2>&1)"
  2311. if [ "$?" != "0" ]; then
  2312. _err "Sorry, apache config error"
  2313. if _restoreApache; then
  2314. _err "The apache config file is restored."
  2315. else
  2316. _err "Sorry, The apache config file can not be restored, please report bug."
  2317. fi
  2318. return 1
  2319. fi
  2320. if [ ! -d "$ACME_DIR" ]; then
  2321. mkdir -p "$ACME_DIR"
  2322. chmod 755 "$ACME_DIR"
  2323. fi
  2324. if ! _exec "$_APACHECTL" graceful; then
  2325. _exec_err
  2326. _err "$_APACHECTL graceful error, please contact me."
  2327. _restoreApache
  2328. return 1
  2329. fi
  2330. usingApache="1"
  2331. return 0
  2332. }
  2333. #find the real nginx conf file
  2334. #backup
  2335. #set the nginx conf
  2336. #returns the real nginx conf file
  2337. _setNginx() {
  2338. _d="$1"
  2339. _croot="$2"
  2340. _thumbpt="$3"
  2341. FOUND_REAL_NGINX_CONF=""
  2342. FOUND_REAL_NGINX_CONF_LN=""
  2343. BACKUP_NGINX_CONF=""
  2344. _debug _croot "$_croot"
  2345. _start_f="$(echo "$_croot" | cut -d : -f 2)"
  2346. _debug _start_f "$_start_f"
  2347. if [ -z "$_start_f" ]; then
  2348. _debug "find start conf from nginx command"
  2349. if [ -z "$NGINX_CONF" ]; then
  2350. if ! _exists "nginx"; then
  2351. _err "nginx command is not found."
  2352. return 1
  2353. fi
  2354. NGINX_CONF="$(nginx -V 2>&1 | _egrep_o "--conf-path=[^ ]* " | tr -d " ")"
  2355. _debug NGINX_CONF "$NGINX_CONF"
  2356. NGINX_CONF="$(echo "$NGINX_CONF" | cut -d = -f 2)"
  2357. _debug NGINX_CONF "$NGINX_CONF"
  2358. if [ ! -f "$NGINX_CONF" ]; then
  2359. _err "'$NGINX_CONF' doesn't exist."
  2360. NGINX_CONF=""
  2361. return 1
  2362. fi
  2363. _debug "Found nginx conf file:$NGINX_CONF"
  2364. fi
  2365. _start_f="$NGINX_CONF"
  2366. fi
  2367. _debug "Start detect nginx conf for $_d from:$_start_f"
  2368. if ! _checkConf "$_d" "$_start_f"; then
  2369. _err "Can not find conf file for domain $d"
  2370. return 1
  2371. fi
  2372. _info "Found conf file: $FOUND_REAL_NGINX_CONF"
  2373. _ln=$FOUND_REAL_NGINX_CONF_LN
  2374. _debug "_ln" "$_ln"
  2375. _lnn=$(_math $_ln + 1)
  2376. _debug _lnn "$_lnn"
  2377. _start_tag="$(sed -n "$_lnn,${_lnn}p" "$FOUND_REAL_NGINX_CONF")"
  2378. _debug "_start_tag" "$_start_tag"
  2379. if [ "$_start_tag" = "$NGINX_START" ]; then
  2380. _info "The domain $_d is already configured, skip"
  2381. FOUND_REAL_NGINX_CONF=""
  2382. return 0
  2383. fi
  2384. mkdir -p "$DOMAIN_BACKUP_PATH"
  2385. _backup_conf="$DOMAIN_BACKUP_PATH/$_d.nginx.conf"
  2386. _debug _backup_conf "$_backup_conf"
  2387. BACKUP_NGINX_CONF="$_backup_conf"
  2388. _info "Backup $FOUND_REAL_NGINX_CONF to $_backup_conf"
  2389. if ! cp "$FOUND_REAL_NGINX_CONF" "$_backup_conf"; then
  2390. _err "backup error."
  2391. FOUND_REAL_NGINX_CONF=""
  2392. return 1
  2393. fi
  2394. if ! _exists "nginx"; then
  2395. _err "nginx command is not found."
  2396. return 1
  2397. fi
  2398. _info "Check the nginx conf before setting up."
  2399. if ! _exec "nginx -t" >/dev/null; then
  2400. _exec_err
  2401. return 1
  2402. fi
  2403. _info "OK, Set up nginx config file"
  2404. if ! sed -n "1,${_ln}p" "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"; then
  2405. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2406. _err "write nginx conf error, but don't worry, the file is restored to the original version."
  2407. return 1
  2408. fi
  2409. echo "$NGINX_START
  2410. location ~ \"^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)\$\" {
  2411. default_type text/plain;
  2412. return 200 \"\$1.$_thumbpt\";
  2413. }
  2414. #NGINX_START
  2415. " >>"$FOUND_REAL_NGINX_CONF"
  2416. if ! sed -n "${_lnn},99999p" "$_backup_conf" >>"$FOUND_REAL_NGINX_CONF"; then
  2417. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2418. _err "write nginx conf error, but don't worry, the file is restored."
  2419. return 1
  2420. fi
  2421. _debug3 "Modified config:$(cat $FOUND_REAL_NGINX_CONF)"
  2422. _info "nginx conf is done, let's check it again."
  2423. if ! _exec "nginx -t" >/dev/null; then
  2424. _exec_err
  2425. _err "It seems that nginx conf was broken, let's restore."
  2426. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2427. return 1
  2428. fi
  2429. _info "Reload nginx"
  2430. if ! _exec "nginx -s reload" >/dev/null; then
  2431. _exec_err
  2432. _err "It seems that nginx reload error, let's restore."
  2433. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2434. return 1
  2435. fi
  2436. return 0
  2437. }
  2438. #d , conf
  2439. _checkConf() {
  2440. _d="$1"
  2441. _c_file="$2"
  2442. _debug "Start _checkConf from:$_c_file"
  2443. if [ ! -f "$2" ] && ! echo "$2" | grep '*$' >/dev/null && echo "$2" | grep '*' >/dev/null; then
  2444. _debug "wildcard"
  2445. for _w_f in $2; do
  2446. if [ -f "$_w_f" ] && _checkConf "$1" "$_w_f"; then
  2447. return 0
  2448. fi
  2449. done
  2450. #not found
  2451. return 1
  2452. elif [ -f "$2" ]; then
  2453. _debug "single"
  2454. if _isRealNginxConf "$1" "$2"; then
  2455. _debug "$2 is found."
  2456. FOUND_REAL_NGINX_CONF="$2"
  2457. return 0
  2458. fi
  2459. if cat "$2" | tr "\t" " " | grep "^ *include *.*;" >/dev/null; then
  2460. _debug "Try include files"
  2461. for included in $(cat "$2" | tr "\t" " " | grep "^ *include *.*;" | sed "s/include //" | tr -d " ;"); do
  2462. _debug "check included $included"
  2463. if _checkConf "$1" "$included"; then
  2464. return 0
  2465. fi
  2466. done
  2467. fi
  2468. return 1
  2469. else
  2470. _debug "$2 not found."
  2471. return 1
  2472. fi
  2473. return 1
  2474. }
  2475. #d , conf
  2476. _isRealNginxConf() {
  2477. _debug "_isRealNginxConf $1 $2"
  2478. if [ -f "$2" ]; then
  2479. for _fln in $(tr "\t" ' ' <"$2" | grep -n "^ *server_name.* $1" | cut -d : -f 1); do
  2480. _debug _fln "$_fln"
  2481. if [ "$_fln" ]; then
  2482. _start=$(tr "\t" ' ' <"$2" | _head_n "$_fln" | grep -n "^ *server *" | grep -v server_name | _tail_n 1)
  2483. _debug "_start" "$_start"
  2484. _start_n=$(echo "$_start" | cut -d : -f 1)
  2485. _start_nn=$(_math $_start_n + 1)
  2486. _debug "_start_n" "$_start_n"
  2487. _debug "_start_nn" "$_start_nn"
  2488. _left="$(sed -n "${_start_nn},99999p" "$2")"
  2489. _debug2 _left "$_left"
  2490. _end="$(echo "$_left" | tr "\t" ' ' | grep -n "^ *server *" | grep -v server_name | _head_n 1)"
  2491. _debug "_end" "$_end"
  2492. if [ "$_end" ]; then
  2493. _end_n=$(echo "$_end" | cut -d : -f 1)
  2494. _debug "_end_n" "$_end_n"
  2495. _seg_n=$(echo "$_left" | sed -n "1,${_end_n}p")
  2496. else
  2497. _seg_n="$_left"
  2498. fi
  2499. _debug "_seg_n" "$_seg_n"
  2500. _skip_ssl=1
  2501. for _listen_i in $(echo "$_seg_n" | tr "\t" ' ' | grep "^ *listen" | tr -d " "); do
  2502. if [ "$_listen_i" ]; then
  2503. if [ "$(echo "$_listen_i" | _egrep_o "listen.*ssl")" ]; then
  2504. _debug2 "$_listen_i is ssl"
  2505. else
  2506. _debug2 "$_listen_i is plain text"
  2507. _skip_ssl=""
  2508. break
  2509. fi
  2510. fi
  2511. done
  2512. if [ "$_skip_ssl" = "1" ]; then
  2513. _debug "ssl on, skip"
  2514. else
  2515. FOUND_REAL_NGINX_CONF_LN=$_fln
  2516. _debug3 "found FOUND_REAL_NGINX_CONF_LN" "$FOUND_REAL_NGINX_CONF_LN"
  2517. return 0
  2518. fi
  2519. fi
  2520. done
  2521. fi
  2522. return 1
  2523. }
  2524. #restore all the nginx conf
  2525. _restoreNginx() {
  2526. if [ -z "$NGINX_RESTORE_VLIST" ]; then
  2527. _debug "No need to restore nginx, skip."
  2528. return
  2529. fi
  2530. _debug "_restoreNginx"
  2531. _debug "NGINX_RESTORE_VLIST" "$NGINX_RESTORE_VLIST"
  2532. for ng_entry in $(echo "$NGINX_RESTORE_VLIST" | tr "$dvsep" ' '); do
  2533. _debug "ng_entry" "$ng_entry"
  2534. _nd=$(echo "$ng_entry" | cut -d "$sep" -f 1)
  2535. _ngconf=$(echo "$ng_entry" | cut -d "$sep" -f 2)
  2536. _ngbackupconf=$(echo "$ng_entry" | cut -d "$sep" -f 3)
  2537. _info "Restoring from $_ngbackupconf to $_ngconf"
  2538. cat "$_ngbackupconf" >"$_ngconf"
  2539. done
  2540. _info "Reload nginx"
  2541. if ! _exec "nginx -s reload" >/dev/null; then
  2542. _exec_err
  2543. _err "It seems that nginx reload error, please report bug."
  2544. return 1
  2545. fi
  2546. return 0
  2547. }
  2548. _clearup() {
  2549. _stopserver "$serverproc"
  2550. serverproc=""
  2551. _restoreApache
  2552. _restoreNginx
  2553. _clearupdns
  2554. if [ -z "$DEBUG" ]; then
  2555. rm -f "$TLS_CONF"
  2556. rm -f "$TLS_CERT"
  2557. rm -f "$TLS_KEY"
  2558. rm -f "$TLS_CSR"
  2559. fi
  2560. }
  2561. _clearupdns() {
  2562. _debug "_clearupdns"
  2563. _debug "dns_entries" "$dns_entries"
  2564. if [ -z "$dns_entries" ]; then
  2565. _debug "skip dns."
  2566. return
  2567. fi
  2568. _info "Removing DNS records."
  2569. for entry in $dns_entries; do
  2570. d=$(_getfield "$entry" 1)
  2571. txtdomain=$(_getfield "$entry" 2)
  2572. aliasDomain=$(_getfield "$entry" 3)
  2573. txt=$(_getfield "$entry" 5)
  2574. d_api=$(_getfield "$entry" 6)
  2575. _debug "d" "$d"
  2576. _debug "txtdomain" "$txtdomain"
  2577. _debug "aliasDomain" "$aliasDomain"
  2578. _debug "txt" "$txt"
  2579. _debug "d_api" "$d_api"
  2580. if [ "$d_api" = "$txt" ]; then
  2581. d_api=""
  2582. fi
  2583. if [ -z "$d_api" ]; then
  2584. _info "Not Found domain api file: $d_api"
  2585. continue
  2586. fi
  2587. if [ "$aliasDomain" ]; then
  2588. txtdomain="$aliasDomain"
  2589. fi
  2590. (
  2591. if ! . "$d_api"; then
  2592. _err "Load file $d_api error. Please check your api file and try again."
  2593. return 1
  2594. fi
  2595. rmcommand="${_currentRoot}_rm"
  2596. if ! _exists "$rmcommand"; then
  2597. _err "It seems that your api file doesn't define $rmcommand"
  2598. return 1
  2599. fi
  2600. if ! $rmcommand "$txtdomain" "$txt"; then
  2601. _err "Error removing txt for domain:$txtdomain"
  2602. return 1
  2603. fi
  2604. )
  2605. done
  2606. }
  2607. # webroot removelevel tokenfile
  2608. _clearupwebbroot() {
  2609. __webroot="$1"
  2610. if [ -z "$__webroot" ]; then
  2611. _debug "no webroot specified, skip"
  2612. return 0
  2613. fi
  2614. _rmpath=""
  2615. if [ "$2" = '1' ]; then
  2616. _rmpath="$__webroot/.well-known"
  2617. elif [ "$2" = '2' ]; then
  2618. _rmpath="$__webroot/.well-known/acme-challenge"
  2619. elif [ "$2" = '3' ]; then
  2620. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  2621. else
  2622. _debug "Skip for removelevel:$2"
  2623. fi
  2624. if [ "$_rmpath" ]; then
  2625. if [ "$DEBUG" ]; then
  2626. _debug "Debugging, skip removing: $_rmpath"
  2627. else
  2628. rm -rf "$_rmpath"
  2629. fi
  2630. fi
  2631. return 0
  2632. }
  2633. _on_before_issue() {
  2634. _chk_web_roots="$1"
  2635. _chk_main_domain="$2"
  2636. _chk_alt_domains="$3"
  2637. _chk_pre_hook="$4"
  2638. _chk_local_addr="$5"
  2639. _debug _on_before_issue
  2640. _debug _chk_main_domain "$_chk_main_domain"
  2641. _debug _chk_alt_domains "$_chk_alt_domains"
  2642. #run pre hook
  2643. if [ "$_chk_pre_hook" ]; then
  2644. _info "Run pre hook:'$_chk_pre_hook'"
  2645. if ! (
  2646. cd "$DOMAIN_PATH" && eval "$_chk_pre_hook"
  2647. ); then
  2648. _err "Error when run pre hook."
  2649. return 1
  2650. fi
  2651. fi
  2652. if _hasfield "$_chk_web_roots" "$NO_VALUE"; then
  2653. if ! _exists "socat"; then
  2654. _err "Please install socat tools first."
  2655. return 1
  2656. fi
  2657. fi
  2658. _debug Le_LocalAddress "$_chk_local_addr"
  2659. _index=1
  2660. _currentRoot=""
  2661. _addrIndex=1
  2662. _w_index=1
  2663. while true; do
  2664. d="$(echo "$_chk_main_domain,$_chk_alt_domains," | cut -d , -f "$_w_index")"
  2665. _w_index="$(_math "$_w_index" + 1)"
  2666. _debug d "$d"
  2667. if [ -z "$d" ]; then
  2668. break
  2669. fi
  2670. _debug "Check for domain" "$d"
  2671. _currentRoot="$(_getfield "$_chk_web_roots" $_index)"
  2672. _debug "_currentRoot" "$_currentRoot"
  2673. _index=$(_math $_index + 1)
  2674. _checkport=""
  2675. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2676. _info "Standalone mode."
  2677. if [ -z "$Le_HTTPPort" ]; then
  2678. Le_HTTPPort=80
  2679. _cleardomainconf "Le_HTTPPort"
  2680. else
  2681. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  2682. fi
  2683. _checkport="$Le_HTTPPort"
  2684. elif [ "$_currentRoot" = "$W_ALPN" ]; then
  2685. _info "Standalone alpn mode."
  2686. if [ -z "$Le_TLSPort" ]; then
  2687. Le_TLSPort=443
  2688. else
  2689. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  2690. fi
  2691. _checkport="$Le_TLSPort"
  2692. fi
  2693. if [ "$_checkport" ]; then
  2694. _debug _checkport "$_checkport"
  2695. _checkaddr="$(_getfield "$_chk_local_addr" $_addrIndex)"
  2696. _debug _checkaddr "$_checkaddr"
  2697. _addrIndex="$(_math $_addrIndex + 1)"
  2698. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  2699. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  2700. if [ -z "$netprc" ]; then
  2701. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  2702. fi
  2703. if [ "$netprc" ]; then
  2704. _err "$netprc"
  2705. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  2706. _err "Please stop it first"
  2707. return 1
  2708. fi
  2709. fi
  2710. done
  2711. if _hasfield "$_chk_web_roots" "apache"; then
  2712. if ! _setApache; then
  2713. _err "set up apache error. Report error to me."
  2714. return 1
  2715. fi
  2716. else
  2717. usingApache=""
  2718. fi
  2719. }
  2720. _on_issue_err() {
  2721. _chk_post_hook="$1"
  2722. _chk_vlist="$2"
  2723. _debug _on_issue_err
  2724. if [ "$LOG_FILE" ]; then
  2725. _err "Please check log file for more details: $LOG_FILE"
  2726. else
  2727. _err "Please add '--debug' or '--log' to check more details."
  2728. _err "See: $_DEBUG_WIKI"
  2729. fi
  2730. #run the post hook
  2731. if [ "$_chk_post_hook" ]; then
  2732. _info "Run post hook:'$_chk_post_hook'"
  2733. if ! (
  2734. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2735. ); then
  2736. _err "Error when run post hook."
  2737. return 1
  2738. fi
  2739. fi
  2740. #trigger the validation to flush the pending authz
  2741. _debug2 "_chk_vlist" "$_chk_vlist"
  2742. if [ "$_chk_vlist" ]; then
  2743. (
  2744. _debug2 "start to deactivate authz"
  2745. ventries=$(echo "$_chk_vlist" | tr "$dvsep" ' ')
  2746. for ventry in $ventries; do
  2747. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2748. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2749. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2750. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2751. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2752. __trigger_validation "$uri" "$keyauthorization"
  2753. done
  2754. )
  2755. fi
  2756. if [ "$IS_RENEW" = "1" ] && _hasfield "$Le_Webroot" "$W_DNS"; then
  2757. _err "$_DNS_MANUAL_ERR"
  2758. fi
  2759. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  2760. _debug "$(_dlg_versions)"
  2761. fi
  2762. }
  2763. _on_issue_success() {
  2764. _chk_post_hook="$1"
  2765. _chk_renew_hook="$2"
  2766. _debug _on_issue_success
  2767. #run the post hook
  2768. if [ "$_chk_post_hook" ]; then
  2769. _info "Run post hook:'$_chk_post_hook'"
  2770. if ! (
  2771. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2772. ); then
  2773. _err "Error when run post hook."
  2774. return 1
  2775. fi
  2776. fi
  2777. #run renew hook
  2778. if [ "$IS_RENEW" ] && [ "$_chk_renew_hook" ]; then
  2779. _info "Run renew hook:'$_chk_renew_hook'"
  2780. if ! (
  2781. cd "$DOMAIN_PATH" && eval "$_chk_renew_hook"
  2782. ); then
  2783. _err "Error when run renew hook."
  2784. return 1
  2785. fi
  2786. fi
  2787. if _hasfield "$Le_Webroot" "$W_DNS"; then
  2788. _err "$_DNS_MANUAL_WARN"
  2789. fi
  2790. }
  2791. updateaccount() {
  2792. _initpath
  2793. _regAccount
  2794. }
  2795. registeraccount() {
  2796. _reg_length="$1"
  2797. _initpath
  2798. _regAccount "$_reg_length"
  2799. }
  2800. __calcAccountKeyHash() {
  2801. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  2802. }
  2803. __calc_account_thumbprint() {
  2804. printf "%s" "$jwk" | tr -d ' ' | _digest "sha256" | _url_replace
  2805. }
  2806. #keylength
  2807. _regAccount() {
  2808. _initpath
  2809. _reg_length="$1"
  2810. _debug3 _regAccount "$_regAccount"
  2811. _initAPI
  2812. mkdir -p "$CA_DIR"
  2813. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2814. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2815. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2816. fi
  2817. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2818. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2819. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2820. fi
  2821. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2822. if ! _create_account_key "$_reg_length"; then
  2823. _err "Create account key error."
  2824. return 1
  2825. fi
  2826. fi
  2827. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2828. return 1
  2829. fi
  2830. if [ "$ACME_VERSION" = "2" ]; then
  2831. regjson='{"termsOfServiceAgreed": true}'
  2832. if [ "$ACCOUNT_EMAIL" ]; then
  2833. regjson='{"contact": ["mailto: '$ACCOUNT_EMAIL'"], "termsOfServiceAgreed": true}'
  2834. fi
  2835. else
  2836. _reg_res="$ACME_NEW_ACCOUNT_RES"
  2837. regjson='{"resource": "'$_reg_res'", "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2838. if [ "$ACCOUNT_EMAIL" ]; then
  2839. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2840. fi
  2841. fi
  2842. _info "Registering account"
  2843. if ! _send_signed_request "${ACME_NEW_ACCOUNT}" "$regjson"; then
  2844. _err "Register account Error: $response"
  2845. return 1
  2846. fi
  2847. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  2848. echo "$response" >"$ACCOUNT_JSON_PATH"
  2849. _info "Registered"
  2850. elif [ "$code" = '409' ] || [ "$code" = '200' ]; then
  2851. _info "Already registered"
  2852. else
  2853. _err "Register account Error: $response"
  2854. return 1
  2855. fi
  2856. _debug2 responseHeaders "$responseHeaders"
  2857. _accUri="$(echo "$responseHeaders" | grep -i "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2858. _debug "_accUri" "$_accUri"
  2859. if [ -z "$_accUri" ]; then
  2860. _err "Can not find account id url."
  2861. _err "$responseHeaders"
  2862. return 1
  2863. fi
  2864. _savecaconf "ACCOUNT_URL" "$_accUri"
  2865. export ACCOUNT_URL="$_accUri"
  2866. CA_KEY_HASH="$(__calcAccountKeyHash)"
  2867. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  2868. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  2869. if [ "$code" = '403' ]; then
  2870. _err "It seems that the account key is already deactivated, please use a new account key."
  2871. return 1
  2872. fi
  2873. ACCOUNT_THUMBPRINT="$(__calc_account_thumbprint)"
  2874. _info "ACCOUNT_THUMBPRINT" "$ACCOUNT_THUMBPRINT"
  2875. }
  2876. #Implement deactivate account
  2877. deactivateaccount() {
  2878. _initpath
  2879. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2880. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2881. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2882. fi
  2883. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2884. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2885. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2886. fi
  2887. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2888. _err "Account key is not found at: $ACCOUNT_KEY_PATH"
  2889. return 1
  2890. fi
  2891. _accUri=$(_readcaconf "ACCOUNT_URL")
  2892. _debug _accUri "$_accUri"
  2893. if [ -z "$_accUri" ]; then
  2894. _err "The account url is empty, please run '--update-account' first to update the account info first,"
  2895. _err "Then try again."
  2896. return 1
  2897. fi
  2898. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2899. return 1
  2900. fi
  2901. _initAPI
  2902. if [ "$ACME_VERSION" = "2" ]; then
  2903. _djson="{\"status\":\"deactivated\"}"
  2904. else
  2905. _djson="{\"resource\": \"reg\", \"status\":\"deactivated\"}"
  2906. fi
  2907. if _send_signed_request "$_accUri" "$_djson" && _contains "$response" '"deactivated"'; then
  2908. _info "Deactivate account success for $_accUri."
  2909. _accid=$(echo "$response" | _egrep_o "\"id\" *: *[^,]*," | cut -d : -f 2 | tr -d ' ,')
  2910. elif [ "$code" = "403" ]; then
  2911. _info "The account is already deactivated."
  2912. _accid=$(_getfield "$_accUri" "999" "/")
  2913. else
  2914. _err "Deactivate: account failed for $_accUri."
  2915. return 1
  2916. fi
  2917. _debug "Account id: $_accid"
  2918. if [ "$_accid" ]; then
  2919. _deactivated_account_path="$CA_DIR/deactivated/$_accid"
  2920. _debug _deactivated_account_path "$_deactivated_account_path"
  2921. if mkdir -p "$_deactivated_account_path"; then
  2922. _info "Moving deactivated account info to $_deactivated_account_path/"
  2923. mv "$CA_CONF" "$_deactivated_account_path/"
  2924. mv "$ACCOUNT_JSON_PATH" "$_deactivated_account_path/"
  2925. mv "$ACCOUNT_KEY_PATH" "$_deactivated_account_path/"
  2926. else
  2927. _err "Can not create dir: $_deactivated_account_path, try to remove the deactivated account key."
  2928. rm -f "$CA_CONF"
  2929. rm -f "$ACCOUNT_JSON_PATH"
  2930. rm -f "$ACCOUNT_KEY_PATH"
  2931. fi
  2932. fi
  2933. }
  2934. # domain folder file
  2935. _findHook() {
  2936. _hookdomain="$1"
  2937. _hookcat="$2"
  2938. _hookname="$3"
  2939. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  2940. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  2941. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  2942. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  2943. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  2944. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  2945. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  2946. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  2947. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  2948. d_api="$LE_WORKING_DIR/$_hookname"
  2949. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  2950. d_api="$LE_WORKING_DIR/$_hookname.sh"
  2951. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  2952. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  2953. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  2954. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  2955. fi
  2956. printf "%s" "$d_api"
  2957. }
  2958. #domain
  2959. __get_domain_new_authz() {
  2960. _gdnd="$1"
  2961. _info "Getting new-authz for domain" "$_gdnd"
  2962. _initAPI
  2963. _Max_new_authz_retry_times=5
  2964. _authz_i=0
  2965. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  2966. _debug "Try new-authz for the $_authz_i time."
  2967. if ! _send_signed_request "${ACME_NEW_AUTHZ}" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  2968. _err "Can not get domain new authz."
  2969. return 1
  2970. fi
  2971. if _contains "$response" "No registration exists matching provided key"; then
  2972. _err "It seems there is an error, but it's recovered now, please try again."
  2973. _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
  2974. _clearcaconf "CA_KEY_HASH"
  2975. break
  2976. fi
  2977. if ! _contains "$response" "An error occurred while processing your request"; then
  2978. _info "The new-authz request is ok."
  2979. break
  2980. fi
  2981. _authz_i="$(_math "$_authz_i" + 1)"
  2982. _info "The server is busy, Sleep $_authz_i to retry."
  2983. _sleep "$_authz_i"
  2984. done
  2985. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  2986. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  2987. fi
  2988. if [ "$code" ] && [ "$code" != '201' ]; then
  2989. _err "new-authz error: $response"
  2990. return 1
  2991. fi
  2992. }
  2993. #uri keyAuthorization
  2994. __trigger_validation() {
  2995. _debug2 "Trigger domain validation."
  2996. _t_url="$1"
  2997. _debug2 _t_url "$_t_url"
  2998. _t_key_authz="$2"
  2999. _debug2 _t_key_authz "$_t_key_authz"
  3000. _t_vtype="$3"
  3001. _debug2 _t_vtype "$_t_vtype"
  3002. if [ "$ACME_VERSION" = "2" ]; then
  3003. _send_signed_request "$_t_url" "{}"
  3004. else
  3005. _send_signed_request "$_t_url" "{\"resource\": \"challenge\", \"type\": \"$_t_vtype\", \"keyAuthorization\": \"$_t_key_authz\"}"
  3006. fi
  3007. }
  3008. #endpoint domain type
  3009. _ns_lookup() {
  3010. _ns_ep="$1"
  3011. _ns_domain="$2"
  3012. _ns_type="$3"
  3013. _debug2 "_ns_ep" "$_ns_ep"
  3014. _debug2 "_ns_domain" "$_ns_domain"
  3015. _debug2 "_ns_type" "$_ns_type"
  3016. response="$(_H1="accept: application/dns-json" _get "$_ns_ep?name=$_ns_domain&type=$_ns_type")"
  3017. _ret=$?
  3018. _debug2 "response" "$response"
  3019. if [ "$_ret" != "0" ]; then
  3020. return $_ret
  3021. fi
  3022. _answers="$(echo "$response" | tr '{}' '<>' | _egrep_o '"Answer":\[[^]]*]' | tr '<>' '\n\n')"
  3023. _debug2 "_answers" "$_answers"
  3024. echo "$_answers"
  3025. }
  3026. #domain, type
  3027. _ns_lookup_cf() {
  3028. _cf_ld="$1"
  3029. _cf_ld_type="$2"
  3030. _cf_ep="https://cloudflare-dns.com/dns-query"
  3031. _ns_lookup "$_cf_ep" "$_cf_ld" "$_cf_ld_type"
  3032. }
  3033. #domain, type
  3034. _ns_purge_cf() {
  3035. _cf_d="$1"
  3036. _cf_d_type="$2"
  3037. _debug "Cloudflare purge $_cf_d_type record for domain $_cf_d"
  3038. _cf_purl="https://1.1.1.1/api/v1/purge?domain=$_cf_d&type=$_cf_d_type"
  3039. response="$(_post "" "$_cf_purl")"
  3040. _debug2 response "$response"
  3041. }
  3042. #txtdomain, alias, txt
  3043. __check_txt() {
  3044. _c_txtdomain="$1"
  3045. _c_aliasdomain="$2"
  3046. _c_txt="$3"
  3047. _debug "_c_txtdomain" "$_c_txtdomain"
  3048. _debug "_c_aliasdomain" "$_c_aliasdomain"
  3049. _debug "_c_txt" "$_c_txt"
  3050. _answers="$(_ns_lookup_cf "$_c_aliasdomain" TXT)"
  3051. _contains "$_answers" "$_c_txt"
  3052. }
  3053. #txtdomain
  3054. __purge_txt() {
  3055. _p_txtdomain="$1"
  3056. _debug _p_txtdomain "$_p_txtdomain"
  3057. _ns_purge_cf "$_p_txtdomain" "TXT"
  3058. }
  3059. #wait and check each dns entries
  3060. _check_dns_entries() {
  3061. _success_txt=","
  3062. _end_time="$(_time)"
  3063. _end_time="$(_math "$_end_time" + 1200)" #let's check no more than 20 minutes.
  3064. while [ "$(_time)" -le "$_end_time" ]; do
  3065. _left=""
  3066. for entry in $dns_entries; do
  3067. d=$(_getfield "$entry" 1)
  3068. txtdomain=$(_getfield "$entry" 2)
  3069. aliasDomain=$(_getfield "$entry" 3)
  3070. txt=$(_getfield "$entry" 5)
  3071. d_api=$(_getfield "$entry" 6)
  3072. _debug "d" "$d"
  3073. _debug "txtdomain" "$txtdomain"
  3074. _debug "aliasDomain" "$aliasDomain"
  3075. _debug "txt" "$txt"
  3076. _debug "d_api" "$d_api"
  3077. _info "Checking $d for $aliasDomain"
  3078. if _contains "$_success_txt" ",$txt,"; then
  3079. _info "Already success, continue next one."
  3080. continue
  3081. fi
  3082. if __check_txt "$txtdomain" "$aliasDomain" "$txt"; then
  3083. _info "Domain $d '$aliasDomain' success."
  3084. _success_txt="$_success_txt,$txt,"
  3085. continue
  3086. fi
  3087. _left=1
  3088. _info "Not valid yet, let's wait 10 seconds and check next one."
  3089. _sleep 10
  3090. __purge_txt "$txtdomain"
  3091. if [ "$txtdomain" != "$aliasDomain" ]; then
  3092. __purge_txt "$aliasDomain"
  3093. fi
  3094. done
  3095. if [ "$_left" ]; then
  3096. _info "Let's wait 10 seconds and check again".
  3097. _sleep 10
  3098. else
  3099. _info "All success, let's return"
  3100. break
  3101. fi
  3102. done
  3103. }
  3104. #webroot, domain domainlist keylength
  3105. issue() {
  3106. if [ -z "$2" ]; then
  3107. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  3108. return 1
  3109. fi
  3110. if [ -z "$1" ]; then
  3111. _usage "Please specify at least one validation method: '--webroot', '--standalone', '--apache', '--nginx' or '--dns' etc."
  3112. return 1
  3113. fi
  3114. _web_roots="$1"
  3115. _main_domain="$2"
  3116. _alt_domains="$3"
  3117. if _contains "$_main_domain" ","; then
  3118. _main_domain=$(echo "$2,$3" | cut -d , -f 1)
  3119. _alt_domains=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
  3120. fi
  3121. _debug _main_domain "$_main_domain"
  3122. _debug _alt_domains "$_alt_domains"
  3123. _key_length="$4"
  3124. _real_cert="$5"
  3125. _real_key="$6"
  3126. _real_ca="$7"
  3127. _reload_cmd="$8"
  3128. _real_fullchain="$9"
  3129. _pre_hook="${10}"
  3130. _post_hook="${11}"
  3131. _renew_hook="${12}"
  3132. _local_addr="${13}"
  3133. _challenge_alias="${14}"
  3134. #remove these later.
  3135. if [ "$_web_roots" = "dns-cf" ]; then
  3136. _web_roots="dns_cf"
  3137. fi
  3138. if [ "$_web_roots" = "dns-dp" ]; then
  3139. _web_roots="dns_dp"
  3140. fi
  3141. if [ "$_web_roots" = "dns-cx" ]; then
  3142. _web_roots="dns_cx"
  3143. fi
  3144. if [ ! "$IS_RENEW" ]; then
  3145. _initpath "$_main_domain" "$_key_length"
  3146. mkdir -p "$DOMAIN_PATH"
  3147. fi
  3148. if _hasfield "$_web_roots" "$W_DNS" && [ -z "$FORCE_DNS_MANUAL" ]; then
  3149. _err "$_DNS_MANUAL_ERROR"
  3150. return 1
  3151. fi
  3152. _debug "Using ACME_DIRECTORY: $ACME_DIRECTORY"
  3153. _initAPI
  3154. if [ -f "$DOMAIN_CONF" ]; then
  3155. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  3156. _debug Le_NextRenewTime "$Le_NextRenewTime"
  3157. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  3158. _saved_domain=$(_readdomainconf Le_Domain)
  3159. _debug _saved_domain "$_saved_domain"
  3160. _saved_alt=$(_readdomainconf Le_Alt)
  3161. _debug _saved_alt "$_saved_alt"
  3162. if [ "$_saved_domain,$_saved_alt" = "$_main_domain,$_alt_domains" ]; then
  3163. _info "Domains not changed."
  3164. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  3165. _info "Add '$(__red '--force')' to force to renew."
  3166. return $RENEW_SKIP
  3167. else
  3168. _info "Domains have changed."
  3169. fi
  3170. fi
  3171. fi
  3172. _savedomainconf "Le_Domain" "$_main_domain"
  3173. _savedomainconf "Le_Alt" "$_alt_domains"
  3174. _savedomainconf "Le_Webroot" "$_web_roots"
  3175. _savedomainconf "Le_PreHook" "$_pre_hook" "base64"
  3176. _savedomainconf "Le_PostHook" "$_post_hook" "base64"
  3177. _savedomainconf "Le_RenewHook" "$_renew_hook" "base64"
  3178. if [ "$_local_addr" ]; then
  3179. _savedomainconf "Le_LocalAddress" "$_local_addr"
  3180. else
  3181. _cleardomainconf "Le_LocalAddress"
  3182. fi
  3183. if [ "$_challenge_alias" ]; then
  3184. _savedomainconf "Le_ChallengeAlias" "$_challenge_alias"
  3185. else
  3186. _cleardomainconf "Le_ChallengeAlias"
  3187. fi
  3188. if [ "$ACME_DIRECTORY" != "$DEFAULT_CA" ]; then
  3189. Le_API="$ACME_DIRECTORY"
  3190. _savedomainconf "Le_API" "$Le_API"
  3191. else
  3192. _cleardomainconf Le_API
  3193. fi
  3194. if [ "$_alt_domains" = "$NO_VALUE" ]; then
  3195. _alt_domains=""
  3196. fi
  3197. if [ "$_key_length" = "$NO_VALUE" ]; then
  3198. _key_length=""
  3199. fi
  3200. if ! _on_before_issue "$_web_roots" "$_main_domain" "$_alt_domains" "$_pre_hook" "$_local_addr"; then
  3201. _err "_on_before_issue."
  3202. return 1
  3203. fi
  3204. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  3205. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  3206. if [ -z "$ACCOUNT_URL" ] || [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  3207. if ! _regAccount "$_accountkeylength"; then
  3208. _on_issue_err "$_post_hook"
  3209. return 1
  3210. fi
  3211. else
  3212. _debug "_saved_account_key_hash is not changed, skip register account."
  3213. fi
  3214. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  3215. _info "Signing from existing CSR."
  3216. else
  3217. _key=$(_readdomainconf Le_Keylength)
  3218. _debug "Read key length:$_key"
  3219. if [ ! -f "$CERT_KEY_PATH" ] || [ "$_key_length" != "$_key" ] || [ "$Le_ForceNewDomainKey" = "1" ]; then
  3220. if ! createDomainKey "$_main_domain" "$_key_length"; then
  3221. _err "Create domain key error."
  3222. _clearup
  3223. _on_issue_err "$_post_hook"
  3224. return 1
  3225. fi
  3226. fi
  3227. if ! _createcsr "$_main_domain" "$_alt_domains" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  3228. _err "Create CSR error."
  3229. _clearup
  3230. _on_issue_err "$_post_hook"
  3231. return 1
  3232. fi
  3233. fi
  3234. _savedomainconf "Le_Keylength" "$_key_length"
  3235. vlist="$Le_Vlist"
  3236. _info "Getting domain auth token for each domain"
  3237. sep='#'
  3238. dvsep=','
  3239. if [ -z "$vlist" ]; then
  3240. if [ "$ACME_VERSION" = "2" ]; then
  3241. #make new order request
  3242. _identifiers="{\"type\":\"dns\",\"value\":\"$_main_domain\"}"
  3243. _w_index=1
  3244. while true; do
  3245. d="$(echo "$_alt_domains," | cut -d , -f "$_w_index")"
  3246. _w_index="$(_math "$_w_index" + 1)"
  3247. _debug d "$d"
  3248. if [ -z "$d" ]; then
  3249. break
  3250. fi
  3251. _identifiers="$_identifiers,{\"type\":\"dns\",\"value\":\"$d\"}"
  3252. done
  3253. _debug2 _identifiers "$_identifiers"
  3254. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  3255. _err "Create new order error."
  3256. _clearup
  3257. _on_issue_err "$_post_hook"
  3258. return 1
  3259. fi
  3260. Le_OrderFinalize="$(echo "$response" | _egrep_o '"finalize" *: *"[^"]*"' | cut -d '"' -f 4)"
  3261. _debug Le_OrderFinalize "$Le_OrderFinalize"
  3262. if [ -z "$Le_OrderFinalize" ]; then
  3263. _err "Create new order error. Le_OrderFinalize not found. $response"
  3264. _clearup
  3265. _on_issue_err "$_post_hook"
  3266. return 1
  3267. fi
  3268. #for dns manual mode
  3269. _savedomainconf "Le_OrderFinalize" "$Le_OrderFinalize"
  3270. _authorizations_seg="$(echo "$response" | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  3271. _debug2 _authorizations_seg "$_authorizations_seg"
  3272. if [ -z "$_authorizations_seg" ]; then
  3273. _err "_authorizations_seg not found."
  3274. _clearup
  3275. _on_issue_err "$_post_hook"
  3276. return 1
  3277. fi
  3278. #domain and authz map
  3279. _authorizations_map=""
  3280. for _authz_url in $(echo "$_authorizations_seg" | tr ',' ' '); do
  3281. _debug2 "_authz_url" "$_authz_url"
  3282. if ! _send_signed_request "$_authz_url"; then
  3283. _err "get to authz error."
  3284. _err "_authorizations_seg" "$_authorizations_seg"
  3285. _err "_authz_url" "$_authz_url"
  3286. _clearup
  3287. _on_issue_err "$_post_hook"
  3288. return 1
  3289. fi
  3290. response="$(echo "$response" | _normalizeJson)"
  3291. _debug2 response "$response"
  3292. _d="$(echo "$response" | _egrep_o '"value" *: *"[^"]*"' | cut -d : -f 2 | tr -d ' "')"
  3293. if _contains "$response" "\"wildcard\" *: *true"; then
  3294. _d="*.$_d"
  3295. fi
  3296. _debug2 _d "$_d"
  3297. _authorizations_map="$_d,$response
  3298. $_authorizations_map"
  3299. done
  3300. _debug2 _authorizations_map "$_authorizations_map"
  3301. fi
  3302. _index=0
  3303. _currentRoot=""
  3304. _w_index=1
  3305. while true; do
  3306. d="$(echo "$_main_domain,$_alt_domains," | cut -d , -f "$_w_index")"
  3307. _w_index="$(_math "$_w_index" + 1)"
  3308. _debug d "$d"
  3309. if [ -z "$d" ]; then
  3310. break
  3311. fi
  3312. _info "Getting webroot for domain" "$d"
  3313. _index=$(_math $_index + 1)
  3314. _w="$(echo $_web_roots | cut -d , -f $_index)"
  3315. _debug _w "$_w"
  3316. if [ "$_w" ]; then
  3317. _currentRoot="$_w"
  3318. fi
  3319. _debug "_currentRoot" "$_currentRoot"
  3320. vtype="$VTYPE_HTTP"
  3321. #todo, v2 wildcard force to use dns
  3322. if _startswith "$_currentRoot" "$W_DNS"; then
  3323. vtype="$VTYPE_DNS"
  3324. fi
  3325. if [ "$_currentRoot" = "$W_ALPN" ]; then
  3326. vtype="$VTYPE_ALPN"
  3327. fi
  3328. if [ "$ACME_VERSION" = "2" ]; then
  3329. response="$(echo "$_authorizations_map" | grep "^$d," | sed "s/$d,//")"
  3330. _debug2 "response" "$response"
  3331. if [ -z "$response" ]; then
  3332. _err "get to authz error."
  3333. _err "_authorizations_map" "$_authorizations_map"
  3334. _clearup
  3335. _on_issue_err "$_post_hook"
  3336. return 1
  3337. fi
  3338. else
  3339. if ! __get_domain_new_authz "$d"; then
  3340. _clearup
  3341. _on_issue_err "$_post_hook"
  3342. return 1
  3343. fi
  3344. fi
  3345. if [ -z "$thumbprint" ]; then
  3346. thumbprint="$(__calc_account_thumbprint)"
  3347. fi
  3348. entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  3349. _debug entry "$entry"
  3350. if [ -z "$entry" ]; then
  3351. _err "Error, can not get domain token entry $d"
  3352. _supported_vtypes="$(echo "$response" | _egrep_o "\"challenges\":\[[^]]*]" | tr '{' "\n" | grep type | cut -d '"' -f 4 | tr "\n" ' ')"
  3353. if [ "$_supported_vtypes" ]; then
  3354. _err "The supported validation types are: $_supported_vtypes, but you specified: $vtype"
  3355. fi
  3356. _clearup
  3357. _on_issue_err "$_post_hook"
  3358. return 1
  3359. fi
  3360. token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  3361. _debug token "$token"
  3362. if [ -z "$token" ]; then
  3363. _err "Error, can not get domain token $entry"
  3364. _clearup
  3365. _on_issue_err "$_post_hook"
  3366. return 1
  3367. fi
  3368. if [ "$ACME_VERSION" = "2" ]; then
  3369. uri="$(echo "$entry" | _egrep_o '"url":"[^"]*' | cut -d '"' -f 4 | _head_n 1)"
  3370. else
  3371. uri="$(echo "$entry" | _egrep_o '"uri":"[^"]*' | cut -d '"' -f 4)"
  3372. fi
  3373. _debug uri "$uri"
  3374. if [ -z "$uri" ]; then
  3375. _err "Error, can not get domain uri. $entry"
  3376. _clearup
  3377. _on_issue_err "$_post_hook"
  3378. return 1
  3379. fi
  3380. keyauthorization="$token.$thumbprint"
  3381. _debug keyauthorization "$keyauthorization"
  3382. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  3383. _debug "$d is already verified."
  3384. keyauthorization="$STATE_VERIFIED"
  3385. _debug keyauthorization "$keyauthorization"
  3386. fi
  3387. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  3388. _debug dvlist "$dvlist"
  3389. vlist="$vlist$dvlist$dvsep"
  3390. done
  3391. _debug vlist "$vlist"
  3392. #add entry
  3393. dns_entries=""
  3394. dnsadded=""
  3395. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3396. _alias_index=1
  3397. for ventry in $ventries; do
  3398. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3399. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3400. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3401. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3402. _debug d "$d"
  3403. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3404. _debug "$d is already verified, skip $vtype."
  3405. _alias_index="$(_math "$_alias_index" + 1)"
  3406. continue
  3407. fi
  3408. if [ "$vtype" = "$VTYPE_DNS" ]; then
  3409. dnsadded='0'
  3410. _dns_root_d="$d"
  3411. if _startswith "$_dns_root_d" "*."; then
  3412. _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
  3413. fi
  3414. _d_alias="$(_getfield "$_challenge_alias" "$_alias_index")"
  3415. _alias_index="$(_math "$_alias_index" + 1)"
  3416. _debug "_d_alias" "$_d_alias"
  3417. if [ "$_d_alias" ]; then
  3418. if _startswith "$_d_alias" "$DNS_ALIAS_PREFIX"; then
  3419. txtdomain="$(echo "$_d_alias" | sed "s/$DNS_ALIAS_PREFIX//")"
  3420. else
  3421. txtdomain="_acme-challenge.$_d_alias"
  3422. fi
  3423. dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$txtdomain$dvsep$_currentRoot"
  3424. else
  3425. txtdomain="_acme-challenge.$_dns_root_d"
  3426. dns_entry="${_dns_root_d}${dvsep}_acme-challenge.$_dns_root_d$dvsep$dvsep$_currentRoot"
  3427. fi
  3428. _debug txtdomain "$txtdomain"
  3429. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  3430. _debug txt "$txt"
  3431. d_api="$(_findHook "$_dns_root_d" dnsapi "$_currentRoot")"
  3432. _debug d_api "$d_api"
  3433. dns_entry="$dns_entry$dvsep$txt${dvsep}$d_api"
  3434. _debug2 dns_entry "$dns_entry"
  3435. if [ "$d_api" ]; then
  3436. _info "Found domain api file: $d_api"
  3437. else
  3438. if [ "$_currentRoot" != "$W_DNS" ]; then
  3439. _err "Can not find dns api hook for: $_currentRoot"
  3440. _info "You need to add the txt record manually."
  3441. fi
  3442. _info "$(__red "Add the following TXT record:")"
  3443. _info "$(__red "Domain: '$(__green "$txtdomain")'")"
  3444. _info "$(__red "TXT value: '$(__green "$txt")'")"
  3445. _info "$(__red "Please be aware that you prepend _acme-challenge. before your domain")"
  3446. _info "$(__red "so the resulting subdomain will be: $txtdomain")"
  3447. continue
  3448. fi
  3449. (
  3450. if ! . "$d_api"; then
  3451. _err "Load file $d_api error. Please check your api file and try again."
  3452. return 1
  3453. fi
  3454. addcommand="${_currentRoot}_add"
  3455. if ! _exists "$addcommand"; then
  3456. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  3457. return 1
  3458. fi
  3459. if ! $addcommand "$txtdomain" "$txt"; then
  3460. _err "Error add txt for domain:$txtdomain"
  3461. return 1
  3462. fi
  3463. )
  3464. if [ "$?" != "0" ]; then
  3465. _on_issue_err "$_post_hook" "$vlist"
  3466. _clearup
  3467. return 1
  3468. fi
  3469. dns_entries="$dns_entries$dns_entry
  3470. "
  3471. _debug2 "$dns_entries"
  3472. dnsadded='1'
  3473. fi
  3474. done
  3475. if [ "$dnsadded" = '0' ]; then
  3476. _savedomainconf "Le_Vlist" "$vlist"
  3477. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  3478. _err "Please add the TXT records to the domains, and re-run with --renew."
  3479. _on_issue_err "$_post_hook"
  3480. _clearup
  3481. return 1
  3482. fi
  3483. fi
  3484. if [ "$dns_entries" ]; then
  3485. if [ -z "$Le_DNSSleep" ]; then
  3486. _info "Let's check each dns records now. Sleep 20 seconds first."
  3487. _sleep 20
  3488. if ! _check_dns_entries; then
  3489. _err "check dns error."
  3490. _on_issue_err "$_post_hook"
  3491. _clearup
  3492. return 1
  3493. fi
  3494. else
  3495. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  3496. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  3497. _sleep "$Le_DNSSleep"
  3498. fi
  3499. fi
  3500. NGINX_RESTORE_VLIST=""
  3501. _debug "ok, let's start to verify"
  3502. _ncIndex=1
  3503. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3504. for ventry in $ventries; do
  3505. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3506. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3507. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  3508. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3509. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3510. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3511. _info "$d is already verified, skip $vtype."
  3512. continue
  3513. fi
  3514. _info "Verifying: $d"
  3515. _debug "d" "$d"
  3516. _debug "keyauthorization" "$keyauthorization"
  3517. _debug "uri" "$uri"
  3518. removelevel=""
  3519. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  3520. _debug "_currentRoot" "$_currentRoot"
  3521. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3522. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  3523. _info "Standalone mode server"
  3524. _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
  3525. _ncIndex="$(_math $_ncIndex + 1)"
  3526. _startserver "$keyauthorization" "$_ncaddr"
  3527. if [ "$?" != "0" ]; then
  3528. _clearup
  3529. _on_issue_err "$_post_hook" "$vlist"
  3530. return 1
  3531. fi
  3532. sleep 1
  3533. _debug serverproc "$serverproc"
  3534. elif [ "$_currentRoot" = "$MODE_STATELESS" ]; then
  3535. _info "Stateless mode for domain:$d"
  3536. _sleep 1
  3537. elif _startswith "$_currentRoot" "$NGINX"; then
  3538. _info "Nginx mode for domain:$d"
  3539. #set up nginx server
  3540. FOUND_REAL_NGINX_CONF=""
  3541. BACKUP_NGINX_CONF=""
  3542. if ! _setNginx "$d" "$_currentRoot" "$thumbprint"; then
  3543. _clearup
  3544. _on_issue_err "$_post_hook" "$vlist"
  3545. return 1
  3546. fi
  3547. if [ "$FOUND_REAL_NGINX_CONF" ]; then
  3548. _realConf="$FOUND_REAL_NGINX_CONF"
  3549. _backup="$BACKUP_NGINX_CONF"
  3550. _debug _realConf "$_realConf"
  3551. NGINX_RESTORE_VLIST="$d$sep$_realConf$sep$_backup$dvsep$NGINX_RESTORE_VLIST"
  3552. fi
  3553. _sleep 1
  3554. else
  3555. if [ "$_currentRoot" = "apache" ]; then
  3556. wellknown_path="$ACME_DIR"
  3557. else
  3558. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  3559. if [ ! -d "$_currentRoot/.well-known" ]; then
  3560. removelevel='1'
  3561. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  3562. removelevel='2'
  3563. else
  3564. removelevel='3'
  3565. fi
  3566. fi
  3567. _debug wellknown_path "$wellknown_path"
  3568. _debug "writing token:$token to $wellknown_path/$token"
  3569. mkdir -p "$wellknown_path"
  3570. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  3571. _err "$d:Can not write token to file : $wellknown_path/$token"
  3572. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3573. _clearup
  3574. _on_issue_err "$_post_hook" "$vlist"
  3575. return 1
  3576. fi
  3577. if [ ! "$usingApache" ]; then
  3578. if webroot_owner=$(_stat "$_currentRoot"); then
  3579. _debug "Changing owner/group of .well-known to $webroot_owner"
  3580. if ! _exec "chown -R \"$webroot_owner\" \"$_currentRoot/.well-known\""; then
  3581. _debug "$(cat "$_EXEC_TEMP_ERR")"
  3582. _exec_err >/dev/null 2>&1
  3583. fi
  3584. else
  3585. _debug "not changing owner/group of webroot"
  3586. fi
  3587. fi
  3588. fi
  3589. elif [ "$vtype" = "$VTYPE_ALPN" ]; then
  3590. acmevalidationv1="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  3591. _debug acmevalidationv1 "$acmevalidationv1"
  3592. if ! _starttlsserver "$d" "" "$Le_TLSPort" "$keyauthorization" "$_ncaddr" "$acmevalidationv1"; then
  3593. _err "Start tls server error."
  3594. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3595. _clearup
  3596. _on_issue_err "$_post_hook" "$vlist"
  3597. return 1
  3598. fi
  3599. fi
  3600. if ! __trigger_validation "$uri" "$keyauthorization" "$vtype"; then
  3601. _err "$d:Can not get challenge: $response"
  3602. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3603. _clearup
  3604. _on_issue_err "$_post_hook" "$vlist"
  3605. return 1
  3606. fi
  3607. if [ "$code" ] && [ "$code" != '202' ]; then
  3608. if [ "$code" = '200' ]; then
  3609. _debug "trigger validation code: $code"
  3610. else
  3611. _err "$d:Challenge error: $response"
  3612. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3613. _clearup
  3614. _on_issue_err "$_post_hook" "$vlist"
  3615. return 1
  3616. fi
  3617. fi
  3618. waittimes=0
  3619. if [ -z "$MAX_RETRY_TIMES" ]; then
  3620. MAX_RETRY_TIMES=30
  3621. fi
  3622. while true; do
  3623. waittimes=$(_math "$waittimes" + 1)
  3624. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  3625. _err "$d:Timeout"
  3626. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3627. _clearup
  3628. _on_issue_err "$_post_hook" "$vlist"
  3629. return 1
  3630. fi
  3631. _debug "sleep 2 secs to verify"
  3632. sleep 2
  3633. _debug "checking"
  3634. if [ "$ACME_VERSION" = "2" ]; then
  3635. _send_signed_request "$uri"
  3636. else
  3637. response="$(_get "$uri")"
  3638. fi
  3639. if [ "$?" != "0" ]; then
  3640. _err "$d:Verify error:$response"
  3641. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3642. _clearup
  3643. _on_issue_err "$_post_hook" "$vlist"
  3644. return 1
  3645. fi
  3646. _debug2 original "$response"
  3647. response="$(echo "$response" | _normalizeJson)"
  3648. _debug2 response "$response"
  3649. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  3650. if [ "$status" = "valid" ]; then
  3651. _info "$(__green Success)"
  3652. _stopserver "$serverproc"
  3653. serverproc=""
  3654. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3655. break
  3656. fi
  3657. if [ "$status" = "invalid" ]; then
  3658. error="$(echo "$response" | _egrep_o '"error":\{[^\}]*')"
  3659. _debug2 error "$error"
  3660. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  3661. _debug2 errordetail "$errordetail"
  3662. if [ "$errordetail" ]; then
  3663. _err "$d:Verify error:$errordetail"
  3664. else
  3665. _err "$d:Verify error:$error"
  3666. fi
  3667. if [ "$DEBUG" ]; then
  3668. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3669. _debug "Debug: get token url."
  3670. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  3671. fi
  3672. fi
  3673. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3674. _clearup
  3675. _on_issue_err "$_post_hook" "$vlist"
  3676. return 1
  3677. fi
  3678. if [ "$status" = "pending" ]; then
  3679. _info "Pending"
  3680. else
  3681. _err "$d:Verify error:$response"
  3682. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3683. _clearup
  3684. _on_issue_err "$_post_hook" "$vlist"
  3685. return 1
  3686. fi
  3687. done
  3688. done
  3689. _clearup
  3690. _info "Verify finished, start to sign."
  3691. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _url_replace)"
  3692. if [ "$ACME_VERSION" = "2" ]; then
  3693. _info "Lets finalize the order, Le_OrderFinalize: $Le_OrderFinalize"
  3694. if ! _send_signed_request "${Le_OrderFinalize}" "{\"csr\": \"$der\"}"; then
  3695. _err "Sign failed."
  3696. _on_issue_err "$_post_hook"
  3697. return 1
  3698. fi
  3699. if [ "$code" != "200" ]; then
  3700. _err "Sign failed, finalize code is not 200."
  3701. _err "$response"
  3702. _on_issue_err "$_post_hook"
  3703. return 1
  3704. fi
  3705. Le_LinkOrder="$(echo "$responseHeaders" | grep -i '^Location.*$' | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  3706. if [ -z "$Le_LinkOrder" ]; then
  3707. _err "Sign error, can not get order link location header"
  3708. _err "responseHeaders" "$responseHeaders"
  3709. _on_issue_err "$_post_hook"
  3710. return 1
  3711. fi
  3712. _savedomainconf "Le_LinkOrder" "$Le_LinkOrder"
  3713. _link_cert_retry=0
  3714. _MAX_CERT_RETRY=5
  3715. while [ "$_link_cert_retry" -lt "$_MAX_CERT_RETRY" ]; do
  3716. if _contains "$response" "\"status\":\"valid\""; then
  3717. _debug "Order status is valid."
  3718. Le_LinkCert="$(echo "$response" | _egrep_o '"certificate" *: *"[^"]*"' | cut -d '"' -f 4)"
  3719. _debug Le_LinkCert "$Le_LinkCert"
  3720. if [ -z "$Le_LinkCert" ]; then
  3721. _err "Sign error, can not find Le_LinkCert"
  3722. _err "$response"
  3723. _on_issue_err "$_post_hook"
  3724. return 1
  3725. fi
  3726. break
  3727. elif _contains "$response" "\"processing\""; then
  3728. _info "Order status is processing, lets sleep and retry."
  3729. _sleep 2
  3730. else
  3731. _err "Sign error, wrong status"
  3732. _err "$response"
  3733. _on_issue_err "$_post_hook"
  3734. return 1
  3735. fi
  3736. if ! _send_signed_request "$Le_LinkOrder"; then
  3737. _err "Sign failed, can not post to Le_LinkOrder cert:$Le_LinkOrder."
  3738. _err "$response"
  3739. _on_issue_err "$_post_hook"
  3740. return 1
  3741. fi
  3742. _link_cert_retry="$(_math $_link_cert_retry + 1)"
  3743. done
  3744. if [ -z "$Le_LinkCert" ]; then
  3745. _err "Sign failed, can not get Le_LinkCert, retry time limit."
  3746. _err "$response"
  3747. _on_issue_err "$_post_hook"
  3748. return 1
  3749. fi
  3750. _info "Download cert, Le_LinkCert: $Le_LinkCert"
  3751. if ! _send_signed_request "$Le_LinkCert"; then
  3752. _err "Sign failed, can not download cert:$Le_LinkCert."
  3753. _err "$response"
  3754. _on_issue_err "$_post_hook"
  3755. return 1
  3756. fi
  3757. echo "$response" >"$CERT_PATH"
  3758. if [ "$(grep -- "$BEGIN_CERT" "$CERT_PATH" | wc -l)" -gt "1" ]; then
  3759. _debug "Found cert chain"
  3760. cat "$CERT_PATH" >"$CERT_FULLCHAIN_PATH"
  3761. _end_n="$(grep -n -- "$END_CERT" "$CERT_FULLCHAIN_PATH" | _head_n 1 | cut -d : -f 1)"
  3762. _debug _end_n "$_end_n"
  3763. sed -n "1,${_end_n}p" "$CERT_FULLCHAIN_PATH" >"$CERT_PATH"
  3764. _end_n="$(_math $_end_n + 1)"
  3765. sed -n "${_end_n},9999p" "$CERT_FULLCHAIN_PATH" >"$CA_CERT_PATH"
  3766. fi
  3767. else
  3768. if ! _send_signed_request "${ACME_NEW_ORDER}" "{\"resource\": \"$ACME_NEW_ORDER_RES\", \"csr\": \"$der\"}" "needbase64"; then
  3769. _err "Sign failed. $response"
  3770. _on_issue_err "$_post_hook"
  3771. return 1
  3772. fi
  3773. _rcert="$response"
  3774. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _tail_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  3775. echo "$BEGIN_CERT" >"$CERT_PATH"
  3776. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  3777. # _debug "Get cert failed. Let's try last response."
  3778. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  3779. #fi
  3780. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  3781. _debug "Try cert link."
  3782. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  3783. fi
  3784. echo "$END_CERT" >>"$CERT_PATH"
  3785. fi
  3786. _debug "Le_LinkCert" "$Le_LinkCert"
  3787. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  3788. if [ -z "$Le_LinkCert" ] || ! _checkcert "$CERT_PATH"; then
  3789. response="$(echo "$response" | _dbase64 "multiline" | tr -d '\0' | _normalizeJson)"
  3790. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  3791. _on_issue_err "$_post_hook"
  3792. return 1
  3793. fi
  3794. if [ "$Le_LinkCert" ]; then
  3795. _info "$(__green "Cert success.")"
  3796. cat "$CERT_PATH"
  3797. _info "Your cert is in $(__green " $CERT_PATH ")"
  3798. if [ -f "$CERT_KEY_PATH" ]; then
  3799. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  3800. fi
  3801. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
  3802. USER_PATH="$PATH"
  3803. _saveaccountconf "USER_PATH" "$USER_PATH"
  3804. fi
  3805. fi
  3806. _cleardomainconf "Le_Vlist"
  3807. if [ "$ACME_VERSION" = "2" ]; then
  3808. _debug "v2 chain."
  3809. else
  3810. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  3811. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  3812. if [ "$Le_LinkIssuer" ]; then
  3813. if ! _contains "$Le_LinkIssuer" ":"; then
  3814. _info "$(__red "Relative issuer link found.")"
  3815. Le_LinkIssuer="$_ACME_SERVER_HOST$Le_LinkIssuer"
  3816. fi
  3817. _debug Le_LinkIssuer "$Le_LinkIssuer"
  3818. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  3819. _link_issuer_retry=0
  3820. _MAX_ISSUER_RETRY=5
  3821. while [ "$_link_issuer_retry" -lt "$_MAX_ISSUER_RETRY" ]; do
  3822. _debug _link_issuer_retry "$_link_issuer_retry"
  3823. if [ "$ACME_VERSION" = "2" ]; then
  3824. if _send_signed_request "$Le_LinkIssuer"; then
  3825. echo "$response" >"$CA_CERT_PATH"
  3826. break
  3827. fi
  3828. else
  3829. if _get "$Le_LinkIssuer" >"$CA_CERT_PATH.der"; then
  3830. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  3831. _base64 "multiline" <"$CA_CERT_PATH.der" >>"$CA_CERT_PATH"
  3832. echo "$END_CERT" >>"$CA_CERT_PATH"
  3833. if ! _checkcert "$CA_CERT_PATH"; then
  3834. _err "Can not get the ca cert."
  3835. break
  3836. fi
  3837. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  3838. rm -f "$CA_CERT_PATH.der"
  3839. break
  3840. fi
  3841. fi
  3842. _link_issuer_retry=$(_math $_link_issuer_retry + 1)
  3843. _sleep "$_link_issuer_retry"
  3844. done
  3845. if [ "$_link_issuer_retry" = "$_MAX_ISSUER_RETRY" ]; then
  3846. _err "Max retry for issuer ca cert is reached."
  3847. fi
  3848. else
  3849. _debug "No Le_LinkIssuer header found."
  3850. fi
  3851. fi
  3852. [ -f "$CA_CERT_PATH" ] && _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  3853. [ -f "$CERT_FULLCHAIN_PATH" ] && _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  3854. Le_CertCreateTime=$(_time)
  3855. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  3856. Le_CertCreateTimeStr=$(date -u)
  3857. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  3858. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ]; then
  3859. Le_RenewalDays="$DEFAULT_RENEW"
  3860. else
  3861. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  3862. fi
  3863. if [ "$CA_BUNDLE" ]; then
  3864. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  3865. else
  3866. _clearaccountconf "CA_BUNDLE"
  3867. fi
  3868. if [ "$CA_PATH" ]; then
  3869. _saveaccountconf CA_PATH "$CA_PATH"
  3870. else
  3871. _clearaccountconf "CA_PATH"
  3872. fi
  3873. if [ "$HTTPS_INSECURE" ]; then
  3874. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  3875. else
  3876. _clearaccountconf "HTTPS_INSECURE"
  3877. fi
  3878. if [ "$Le_Listen_V4" ]; then
  3879. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  3880. _cleardomainconf Le_Listen_V6
  3881. elif [ "$Le_Listen_V6" ]; then
  3882. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  3883. _cleardomainconf Le_Listen_V4
  3884. fi
  3885. if [ "$Le_ForceNewDomainKey" = "1" ]; then
  3886. _savedomainconf "Le_ForceNewDomainKey" "$Le_ForceNewDomainKey"
  3887. else
  3888. _cleardomainconf Le_ForceNewDomainKey
  3889. fi
  3890. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  3891. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  3892. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  3893. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  3894. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  3895. if [ "$_real_cert$_real_key$_real_ca$_reload_cmd$_real_fullchain" ]; then
  3896. _savedomainconf "Le_RealCertPath" "$_real_cert"
  3897. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  3898. _savedomainconf "Le_RealKeyPath" "$_real_key"
  3899. _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
  3900. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  3901. if ! _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"; then
  3902. return 1
  3903. fi
  3904. fi
  3905. if ! _on_issue_success "$_post_hook" "$_renew_hook"; then
  3906. _err "Call hook error."
  3907. return 1
  3908. fi
  3909. }
  3910. #domain [isEcc]
  3911. renew() {
  3912. Le_Domain="$1"
  3913. if [ -z "$Le_Domain" ]; then
  3914. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  3915. return 1
  3916. fi
  3917. _isEcc="$2"
  3918. _initpath "$Le_Domain" "$_isEcc"
  3919. _info "$(__green "Renew: '$Le_Domain'")"
  3920. if [ ! -f "$DOMAIN_CONF" ]; then
  3921. _info "'$Le_Domain' is not a issued domain, skip."
  3922. return 0
  3923. fi
  3924. if [ "$Le_RenewalDays" ]; then
  3925. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  3926. fi
  3927. . "$DOMAIN_CONF"
  3928. _debug Le_API "$Le_API"
  3929. if [ "$Le_API" = "$LETSENCRYPT_CA_V1" ]; then
  3930. _cleardomainconf Le_API
  3931. Le_API="$DEFAULT_CA"
  3932. fi
  3933. if [ "$Le_API" = "$LETSENCRYPT_STAGING_CA_V1" ]; then
  3934. _cleardomainconf Le_API
  3935. Le_API="$DEFAULT_STAGING_CA"
  3936. fi
  3937. if [ "$Le_API" ]; then
  3938. if [ "$_OLD_CA_HOST" = "$Le_API" ]; then
  3939. export Le_API="$DEFAULT_CA"
  3940. _savedomainconf Le_API "$Le_API"
  3941. fi
  3942. if [ "$_OLD_STAGE_CA_HOST" = "$Le_API" ]; then
  3943. export Le_API="$DEFAULT_STAGING_CA"
  3944. _savedomainconf Le_API "$Le_API"
  3945. fi
  3946. export ACME_DIRECTORY="$Le_API"
  3947. #reload ca configs
  3948. ACCOUNT_KEY_PATH=""
  3949. ACCOUNT_JSON_PATH=""
  3950. CA_CONF=""
  3951. _debug3 "initpath again."
  3952. _initpath "$Le_Domain" "$_isEcc"
  3953. fi
  3954. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  3955. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  3956. _info "Add '$(__red '--force')' to force to renew."
  3957. return "$RENEW_SKIP"
  3958. fi
  3959. if [ "$IN_CRON" = "1" ] && [ -z "$Le_CertCreateTime" ]; then
  3960. _info "Skip invalid cert for: $Le_Domain"
  3961. return 0
  3962. fi
  3963. IS_RENEW="1"
  3964. Le_ReloadCmd="$(_readdomainconf Le_ReloadCmd)"
  3965. Le_PreHook="$(_readdomainconf Le_PreHook)"
  3966. Le_PostHook="$(_readdomainconf Le_PostHook)"
  3967. Le_RenewHook="$(_readdomainconf Le_RenewHook)"
  3968. 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" "$Le_ChallengeAlias"
  3969. res="$?"
  3970. if [ "$res" != "0" ]; then
  3971. return "$res"
  3972. fi
  3973. if [ "$Le_DeployHook" ]; then
  3974. _deploy "$Le_Domain" "$Le_DeployHook"
  3975. res="$?"
  3976. fi
  3977. IS_RENEW=""
  3978. return "$res"
  3979. }
  3980. #renewAll [stopRenewOnError]
  3981. renewAll() {
  3982. _initpath
  3983. _stopRenewOnError="$1"
  3984. _debug "_stopRenewOnError" "$_stopRenewOnError"
  3985. _ret="0"
  3986. for di in "${CERT_HOME}"/*.*/; do
  3987. _debug di "$di"
  3988. if ! [ -d "$di" ]; then
  3989. _debug "Not directory, skip: $di"
  3990. continue
  3991. fi
  3992. d=$(basename "$di")
  3993. _debug d "$d"
  3994. (
  3995. if _endswith "$d" "$ECC_SUFFIX"; then
  3996. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  3997. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  3998. fi
  3999. renew "$d" "$_isEcc"
  4000. )
  4001. rc="$?"
  4002. _debug "Return code: $rc"
  4003. if [ "$rc" != "0" ]; then
  4004. if [ "$rc" = "$RENEW_SKIP" ]; then
  4005. _info "Skipped $d"
  4006. elif [ "$_stopRenewOnError" ]; then
  4007. _err "Error renew $d, stop now."
  4008. return "$rc"
  4009. else
  4010. _ret="$rc"
  4011. _err "Error renew $d."
  4012. fi
  4013. fi
  4014. done
  4015. return "$_ret"
  4016. }
  4017. #csr webroot
  4018. signcsr() {
  4019. _csrfile="$1"
  4020. _csrW="$2"
  4021. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  4022. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  4023. return 1
  4024. fi
  4025. _real_cert="$3"
  4026. _real_key="$4"
  4027. _real_ca="$5"
  4028. _reload_cmd="$6"
  4029. _real_fullchain="$7"
  4030. _pre_hook="${8}"
  4031. _post_hook="${9}"
  4032. _renew_hook="${10}"
  4033. _local_addr="${11}"
  4034. _challenge_alias="${12}"
  4035. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  4036. if [ "$?" != "0" ]; then
  4037. _err "Can not read subject from csr: $_csrfile"
  4038. return 1
  4039. fi
  4040. _debug _csrsubj "$_csrsubj"
  4041. if _contains "$_csrsubj" ' ' || ! _contains "$_csrsubj" '.'; then
  4042. _info "It seems that the subject: $_csrsubj is not a valid domain name. Drop it."
  4043. _csrsubj=""
  4044. fi
  4045. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  4046. if [ "$?" != "0" ]; then
  4047. _err "Can not read domain list from csr: $_csrfile"
  4048. return 1
  4049. fi
  4050. _debug "_csrdomainlist" "$_csrdomainlist"
  4051. if [ -z "$_csrsubj" ]; then
  4052. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  4053. _debug _csrsubj "$_csrsubj"
  4054. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  4055. _debug "_csrdomainlist" "$_csrdomainlist"
  4056. fi
  4057. if [ -z "$_csrsubj" ]; then
  4058. _err "Can not read subject from csr: $_csrfile"
  4059. return 1
  4060. fi
  4061. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  4062. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  4063. _err "Can not read key length from csr: $_csrfile"
  4064. return 1
  4065. fi
  4066. if [ -z "$ACME_VERSION" ] && _contains "$_csrsubj,$_csrdomainlist" "*."; then
  4067. export ACME_VERSION=2
  4068. fi
  4069. _initpath "$_csrsubj" "$_csrkeylength"
  4070. mkdir -p "$DOMAIN_PATH"
  4071. _info "Copy csr to: $CSR_PATH"
  4072. cp "$_csrfile" "$CSR_PATH"
  4073. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength" "$_real_cert" "$_real_key" "$_real_ca" "$_reload_cmd" "$_real_fullchain" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_addr" "$_challenge_alias"
  4074. }
  4075. showcsr() {
  4076. _csrfile="$1"
  4077. _csrd="$2"
  4078. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  4079. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  4080. return 1
  4081. fi
  4082. _initpath
  4083. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  4084. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  4085. _err "Can not read subject from csr: $_csrfile"
  4086. return 1
  4087. fi
  4088. _info "Subject=$_csrsubj"
  4089. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  4090. if [ "$?" != "0" ]; then
  4091. _err "Can not read domain list from csr: $_csrfile"
  4092. return 1
  4093. fi
  4094. _debug "_csrdomainlist" "$_csrdomainlist"
  4095. _info "SubjectAltNames=$_csrdomainlist"
  4096. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  4097. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  4098. _err "Can not read key length from csr: $_csrfile"
  4099. return 1
  4100. fi
  4101. _info "KeyLength=$_csrkeylength"
  4102. }
  4103. list() {
  4104. _raw="$1"
  4105. _initpath
  4106. _sep="|"
  4107. if [ "$_raw" ]; then
  4108. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
  4109. for di in "${CERT_HOME}"/*.*/; do
  4110. if ! [ -d "$di" ]; then
  4111. _debug "Not directory, skip: $di"
  4112. continue
  4113. fi
  4114. d=$(basename "$di")
  4115. _debug d "$d"
  4116. (
  4117. if _endswith "$d" "$ECC_SUFFIX"; then
  4118. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  4119. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  4120. fi
  4121. _initpath "$d" "$_isEcc"
  4122. if [ -f "$DOMAIN_CONF" ]; then
  4123. . "$DOMAIN_CONF"
  4124. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  4125. fi
  4126. )
  4127. done
  4128. else
  4129. if _exists column; then
  4130. list "raw" | column -t -s "$_sep"
  4131. else
  4132. list "raw" | tr "$_sep" '\t'
  4133. fi
  4134. fi
  4135. }
  4136. _deploy() {
  4137. _d="$1"
  4138. _hooks="$2"
  4139. for _d_api in $(echo "$_hooks" | tr ',' " "); do
  4140. _deployApi="$(_findHook "$_d" deploy "$_d_api")"
  4141. if [ -z "$_deployApi" ]; then
  4142. _err "The deploy hook $_d_api is not found."
  4143. return 1
  4144. fi
  4145. _debug _deployApi "$_deployApi"
  4146. if ! (
  4147. if ! . "$_deployApi"; then
  4148. _err "Load file $_deployApi error. Please check your api file and try again."
  4149. return 1
  4150. fi
  4151. d_command="${_d_api}_deploy"
  4152. if ! _exists "$d_command"; then
  4153. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  4154. return 1
  4155. fi
  4156. if ! $d_command "$_d" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  4157. _err "Error deploy for domain:$_d"
  4158. return 1
  4159. fi
  4160. ); then
  4161. _err "Deploy error."
  4162. return 1
  4163. else
  4164. _info "$(__green Success)"
  4165. fi
  4166. done
  4167. }
  4168. #domain hooks
  4169. deploy() {
  4170. _d="$1"
  4171. _hooks="$2"
  4172. _isEcc="$3"
  4173. if [ -z "$_hooks" ]; then
  4174. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  4175. return 1
  4176. fi
  4177. _initpath "$_d" "$_isEcc"
  4178. if [ ! -d "$DOMAIN_PATH" ]; then
  4179. _err "The domain '$_d' is not a cert name. You must use the cert name to specify the cert to install."
  4180. _err "Can not find path:'$DOMAIN_PATH'"
  4181. return 1
  4182. fi
  4183. . "$DOMAIN_CONF"
  4184. _savedomainconf Le_DeployHook "$_hooks"
  4185. _deploy "$_d" "$_hooks"
  4186. }
  4187. installcert() {
  4188. _main_domain="$1"
  4189. if [ -z "$_main_domain" ]; then
  4190. _usage "Usage: $PROJECT_ENTRY --installcert -d domain.com [--ecc] [--cert-file cert-file-path] [--key-file key-file-path] [--ca-file ca-cert-file-path] [ --reloadCmd reloadCmd] [--fullchain-file fullchain-path]"
  4191. return 1
  4192. fi
  4193. _real_cert="$2"
  4194. _real_key="$3"
  4195. _real_ca="$4"
  4196. _reload_cmd="$5"
  4197. _real_fullchain="$6"
  4198. _isEcc="$7"
  4199. _initpath "$_main_domain" "$_isEcc"
  4200. if [ ! -d "$DOMAIN_PATH" ]; then
  4201. _err "The domain '$_main_domain' is not a cert name. You must use the cert name to specify the cert to install."
  4202. _err "Can not find path:'$DOMAIN_PATH'"
  4203. return 1
  4204. fi
  4205. _savedomainconf "Le_RealCertPath" "$_real_cert"
  4206. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  4207. _savedomainconf "Le_RealKeyPath" "$_real_key"
  4208. _savedomainconf "Le_ReloadCmd" "$_reload_cmd" "base64"
  4209. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  4210. _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"
  4211. }
  4212. #domain cert key ca fullchain reloadcmd backup-prefix
  4213. _installcert() {
  4214. _main_domain="$1"
  4215. _real_cert="$2"
  4216. _real_key="$3"
  4217. _real_ca="$4"
  4218. _real_fullchain="$5"
  4219. _reload_cmd="$6"
  4220. _backup_prefix="$7"
  4221. if [ "$_real_cert" = "$NO_VALUE" ]; then
  4222. _real_cert=""
  4223. fi
  4224. if [ "$_real_key" = "$NO_VALUE" ]; then
  4225. _real_key=""
  4226. fi
  4227. if [ "$_real_ca" = "$NO_VALUE" ]; then
  4228. _real_ca=""
  4229. fi
  4230. if [ "$_reload_cmd" = "$NO_VALUE" ]; then
  4231. _reload_cmd=""
  4232. fi
  4233. if [ "$_real_fullchain" = "$NO_VALUE" ]; then
  4234. _real_fullchain=""
  4235. fi
  4236. _backup_path="$DOMAIN_BACKUP_PATH/$_backup_prefix"
  4237. mkdir -p "$_backup_path"
  4238. if [ "$_real_cert" ]; then
  4239. _info "Installing cert to:$_real_cert"
  4240. if [ -f "$_real_cert" ] && [ ! "$IS_RENEW" ]; then
  4241. cp "$_real_cert" "$_backup_path/cert.bak"
  4242. fi
  4243. cat "$CERT_PATH" >"$_real_cert" || return 1
  4244. fi
  4245. if [ "$_real_ca" ]; then
  4246. _info "Installing CA to:$_real_ca"
  4247. if [ "$_real_ca" = "$_real_cert" ]; then
  4248. echo "" >>"$_real_ca"
  4249. cat "$CA_CERT_PATH" >>"$_real_ca" || return 1
  4250. else
  4251. if [ -f "$_real_ca" ] && [ ! "$IS_RENEW" ]; then
  4252. cp "$_real_ca" "$_backup_path/ca.bak"
  4253. fi
  4254. cat "$CA_CERT_PATH" >"$_real_ca" || return 1
  4255. fi
  4256. fi
  4257. if [ "$_real_key" ]; then
  4258. _info "Installing key to:$_real_key"
  4259. if [ -f "$_real_key" ] && [ ! "$IS_RENEW" ]; then
  4260. cp "$_real_key" "$_backup_path/key.bak"
  4261. fi
  4262. if [ -f "$_real_key" ]; then
  4263. cat "$CERT_KEY_PATH" >"$_real_key" || return 1
  4264. else
  4265. cat "$CERT_KEY_PATH" >"$_real_key" || return 1
  4266. chmod 600 "$_real_key"
  4267. fi
  4268. fi
  4269. if [ "$_real_fullchain" ]; then
  4270. _info "Installing full chain to:$_real_fullchain"
  4271. if [ -f "$_real_fullchain" ] && [ ! "$IS_RENEW" ]; then
  4272. cp "$_real_fullchain" "$_backup_path/fullchain.bak"
  4273. fi
  4274. cat "$CERT_FULLCHAIN_PATH" >"$_real_fullchain" || return 1
  4275. fi
  4276. if [ "$_reload_cmd" ]; then
  4277. _info "Run reload cmd: $_reload_cmd"
  4278. if (
  4279. export CERT_PATH
  4280. export CERT_KEY_PATH
  4281. export CA_CERT_PATH
  4282. export CERT_FULLCHAIN_PATH
  4283. export Le_Domain="$_main_domain"
  4284. cd "$DOMAIN_PATH" && eval "$_reload_cmd"
  4285. ); then
  4286. _info "$(__green "Reload success")"
  4287. else
  4288. _err "Reload error for :$Le_Domain"
  4289. fi
  4290. fi
  4291. }
  4292. __read_password() {
  4293. unset _pp
  4294. prompt="Enter Password:"
  4295. while IFS= read -p "$prompt" -r -s -n 1 char; do
  4296. if [ "$char" = $'\0' ]; then
  4297. break
  4298. fi
  4299. prompt='*'
  4300. _pp="$_pp$char"
  4301. done
  4302. echo "$_pp"
  4303. }
  4304. _install_win_taskscheduler() {
  4305. _lesh="$1"
  4306. _centry="$2"
  4307. _randomminute="$3"
  4308. if ! _exists cygpath; then
  4309. _err "cygpath not found"
  4310. return 1
  4311. fi
  4312. if ! _exists schtasks; then
  4313. _err "schtasks.exe is not found, are you on Windows?"
  4314. return 1
  4315. fi
  4316. _winbash="$(cygpath -w $(which bash))"
  4317. _debug _winbash "$_winbash"
  4318. if [ -z "$_winbash" ]; then
  4319. _err "can not find bash path"
  4320. return 1
  4321. fi
  4322. _myname="$(whoami)"
  4323. _debug "_myname" "$_myname"
  4324. if [ -z "$_myname" ]; then
  4325. _err "can not find my user name"
  4326. return 1
  4327. fi
  4328. _debug "_lesh" "$_lesh"
  4329. _info "To install scheduler task in your Windows account, you must input your windows password."
  4330. _info "$PROJECT_NAME doesn't save your password."
  4331. _info "Please input your Windows password for: $(__green "$_myname")"
  4332. _password="$(__read_password)"
  4333. #SCHTASKS.exe '/create' '/SC' 'DAILY' '/TN' "$_WINDOWS_SCHEDULER_NAME" '/F' '/ST' "00:$_randomminute" '/RU' "$_myname" '/RP' "$_password" '/TR' "$_winbash -l -c '$_lesh --cron --home \"$LE_WORKING_DIR\" $_centry'" >/dev/null
  4334. echo SCHTASKS.exe '/create' '/SC' 'DAILY' '/TN' "$_WINDOWS_SCHEDULER_NAME" '/F' '/ST' "00:$_randomminute" '/RU' "$_myname" '/RP' "$_password" '/TR' "\"$_winbash -l -c '$_lesh --cron --home \"$LE_WORKING_DIR\" $_centry'\"" | cmd.exe >/dev/null
  4335. echo
  4336. }
  4337. _uninstall_win_taskscheduler() {
  4338. if ! _exists schtasks; then
  4339. _err "schtasks.exe is not found, are you on Windows?"
  4340. return 1
  4341. fi
  4342. if ! echo SCHTASKS /query /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null; then
  4343. _debug "scheduler $_WINDOWS_SCHEDULER_NAME is not found."
  4344. else
  4345. _info "Removing $_WINDOWS_SCHEDULER_NAME"
  4346. echo SCHTASKS /delete /f /tn "$_WINDOWS_SCHEDULER_NAME" | cmd.exe >/dev/null
  4347. fi
  4348. }
  4349. #confighome
  4350. installcronjob() {
  4351. _c_home="$1"
  4352. _initpath
  4353. _CRONTAB="crontab"
  4354. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  4355. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  4356. else
  4357. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  4358. return 1
  4359. fi
  4360. if [ "$_c_home" ]; then
  4361. _c_entry="--config-home \"$_c_home\" "
  4362. fi
  4363. _t=$(_time)
  4364. random_minute=$(_math $_t % 60)
  4365. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  4366. _CRONTAB="fcrontab"
  4367. fi
  4368. if ! _exists "$_CRONTAB"; then
  4369. if _exists cygpath && _exists schtasks.exe; then
  4370. _info "It seems you are on Windows, let's install Windows scheduler task."
  4371. if _install_win_taskscheduler "$lesh" "$_c_entry" "$random_minute"; then
  4372. _info "Install Windows scheduler task success."
  4373. return 0
  4374. else
  4375. _err "Install Windows scheduler task failed."
  4376. return 1
  4377. fi
  4378. fi
  4379. _err "crontab/fcrontab doesn't exist, so, we can not install cron jobs."
  4380. _err "All your certs will not be renewed automatically."
  4381. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  4382. return 1
  4383. fi
  4384. _info "Installing cron job"
  4385. if ! $_CRONTAB -l | grep "$PROJECT_ENTRY --cron"; then
  4386. if _exists uname && uname -a | grep SunOS >/dev/null; then
  4387. $_CRONTAB -l | {
  4388. cat
  4389. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  4390. } | $_CRONTAB --
  4391. else
  4392. $_CRONTAB -l | {
  4393. cat
  4394. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  4395. } | $_CRONTAB -
  4396. fi
  4397. fi
  4398. if [ "$?" != "0" ]; then
  4399. _err "Install cron job failed. You need to manually renew your certs."
  4400. _err "Or you can add cronjob by yourself:"
  4401. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  4402. return 1
  4403. fi
  4404. }
  4405. uninstallcronjob() {
  4406. _CRONTAB="crontab"
  4407. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  4408. _CRONTAB="fcrontab"
  4409. fi
  4410. if ! _exists "$_CRONTAB"; then
  4411. if _exists cygpath && _exists schtasks.exe; then
  4412. _info "It seems you are on Windows, let's uninstall Windows scheduler task."
  4413. if _uninstall_win_taskscheduler; then
  4414. _info "Uninstall Windows scheduler task success."
  4415. return 0
  4416. else
  4417. _err "Uninstall Windows scheduler task failed."
  4418. return 1
  4419. fi
  4420. fi
  4421. return
  4422. fi
  4423. _info "Removing cron job"
  4424. cr="$($_CRONTAB -l | grep "$PROJECT_ENTRY --cron")"
  4425. if [ "$cr" ]; then
  4426. if _exists uname && uname -a | grep solaris >/dev/null; then
  4427. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB --
  4428. else
  4429. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB -
  4430. fi
  4431. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  4432. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  4433. if _contains "$cr" "--config-home"; then
  4434. LE_CONFIG_HOME="$(echo "$cr" | cut -d ' ' -f 11 | tr -d '"')"
  4435. _debug LE_CONFIG_HOME "$LE_CONFIG_HOME"
  4436. fi
  4437. fi
  4438. _initpath
  4439. }
  4440. revoke() {
  4441. Le_Domain="$1"
  4442. if [ -z "$Le_Domain" ]; then
  4443. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com [--ecc]"
  4444. return 1
  4445. fi
  4446. _isEcc="$2"
  4447. _initpath "$Le_Domain" "$_isEcc"
  4448. if [ ! -f "$DOMAIN_CONF" ]; then
  4449. _err "$Le_Domain is not a issued domain, skip."
  4450. return 1
  4451. fi
  4452. if [ ! -f "$CERT_PATH" ]; then
  4453. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  4454. return 1
  4455. fi
  4456. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _url_replace)"
  4457. if [ -z "$cert" ]; then
  4458. _err "Cert for $Le_Domain is empty found, skip."
  4459. return 1
  4460. fi
  4461. _initAPI
  4462. if [ "$ACME_VERSION" = "2" ]; then
  4463. data="{\"certificate\": \"$cert\"}"
  4464. else
  4465. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  4466. fi
  4467. uri="${ACME_REVOKE_CERT}"
  4468. if [ -f "$CERT_KEY_PATH" ]; then
  4469. _info "Try domain key first."
  4470. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  4471. if [ -z "$response" ]; then
  4472. _info "Revoke success."
  4473. rm -f "$CERT_PATH"
  4474. return 0
  4475. else
  4476. _err "Revoke error by domain key."
  4477. _err "$response"
  4478. fi
  4479. fi
  4480. else
  4481. _info "Domain key file doesn't exists."
  4482. fi
  4483. _info "Try account key."
  4484. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  4485. if [ -z "$response" ]; then
  4486. _info "Revoke success."
  4487. rm -f "$CERT_PATH"
  4488. return 0
  4489. else
  4490. _err "Revoke error."
  4491. _debug "$response"
  4492. fi
  4493. fi
  4494. return 1
  4495. }
  4496. #domain ecc
  4497. remove() {
  4498. Le_Domain="$1"
  4499. if [ -z "$Le_Domain" ]; then
  4500. _usage "Usage: $PROJECT_ENTRY --remove -d domain.com [--ecc]"
  4501. return 1
  4502. fi
  4503. _isEcc="$2"
  4504. _initpath "$Le_Domain" "$_isEcc"
  4505. _removed_conf="$DOMAIN_CONF.removed"
  4506. if [ ! -f "$DOMAIN_CONF" ]; then
  4507. if [ -f "$_removed_conf" ]; then
  4508. _err "$Le_Domain is already removed, You can remove the folder by yourself: $DOMAIN_PATH"
  4509. else
  4510. _err "$Le_Domain is not a issued domain, skip."
  4511. fi
  4512. return 1
  4513. fi
  4514. if mv "$DOMAIN_CONF" "$_removed_conf"; then
  4515. _info "$Le_Domain is removed, the key and cert files are in $(__green $DOMAIN_PATH)"
  4516. _info "You can remove them by yourself."
  4517. return 0
  4518. else
  4519. _err "Remove $Le_Domain failed."
  4520. return 1
  4521. fi
  4522. }
  4523. #domain vtype
  4524. _deactivate() {
  4525. _d_domain="$1"
  4526. _d_type="$2"
  4527. _initpath
  4528. if [ "$ACME_VERSION" = "2" ]; then
  4529. _identifiers="{\"type\":\"dns\",\"value\":\"$_d_domain\"}"
  4530. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  4531. _err "Can not get domain new order."
  4532. return 1
  4533. fi
  4534. _authorizations_seg="$(echo "$response" | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  4535. _debug2 _authorizations_seg "$_authorizations_seg"
  4536. if [ -z "$_authorizations_seg" ]; then
  4537. _err "_authorizations_seg not found."
  4538. _clearup
  4539. _on_issue_err "$_post_hook"
  4540. return 1
  4541. fi
  4542. authzUri="$_authorizations_seg"
  4543. _debug2 "authzUri" "$authzUri"
  4544. if ! _send_signed_request "$authzUri"; then
  4545. _err "get to authz error."
  4546. _err "_authorizations_seg" "$_authorizations_seg"
  4547. _err "authzUri" "$authzUri"
  4548. _clearup
  4549. _on_issue_err "$_post_hook"
  4550. return 1
  4551. fi
  4552. response="$(echo "$response" | _normalizeJson)"
  4553. _debug2 response "$response"
  4554. _URL_NAME="url"
  4555. else
  4556. if ! __get_domain_new_authz "$_d_domain"; then
  4557. _err "Can not get domain new authz token."
  4558. return 1
  4559. fi
  4560. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  4561. _debug "authzUri" "$authzUri"
  4562. if [ "$code" ] && [ ! "$code" = '201' ]; then
  4563. _err "new-authz error: $response"
  4564. return 1
  4565. fi
  4566. _URL_NAME="uri"
  4567. fi
  4568. entries="$(echo "$response" | _egrep_o "{ *\"type\":\"[^\"]*\", *\"status\": *\"valid\", *\"$_URL_NAME\"[^}]*")"
  4569. if [ -z "$entries" ]; then
  4570. _info "No valid entries found."
  4571. if [ -z "$thumbprint" ]; then
  4572. thumbprint="$(__calc_account_thumbprint)"
  4573. fi
  4574. _debug "Trigger validation."
  4575. vtype="$VTYPE_DNS"
  4576. entry="$(echo "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  4577. _debug entry "$entry"
  4578. if [ -z "$entry" ]; then
  4579. _err "Error, can not get domain token $d"
  4580. return 1
  4581. fi
  4582. token="$(echo "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  4583. _debug token "$token"
  4584. uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  4585. _debug uri "$uri"
  4586. keyauthorization="$token.$thumbprint"
  4587. _debug keyauthorization "$keyauthorization"
  4588. __trigger_validation "$uri" "$keyauthorization"
  4589. fi
  4590. _d_i=0
  4591. _d_max_retry=$(echo "$entries" | wc -l)
  4592. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  4593. _info "Deactivate: $_d_domain"
  4594. _d_i="$(_math $_d_i + 1)"
  4595. entry="$(echo "$entries" | sed -n "${_d_i}p")"
  4596. _debug entry "$entry"
  4597. if [ -z "$entry" ]; then
  4598. _info "No more valid entry found."
  4599. break
  4600. fi
  4601. _vtype="$(echo "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  4602. _debug _vtype "$_vtype"
  4603. _info "Found $_vtype"
  4604. uri="$(echo "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  4605. _debug uri "$uri"
  4606. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  4607. _info "Skip $_vtype"
  4608. continue
  4609. fi
  4610. _info "Deactivate: $_vtype"
  4611. if [ "$ACME_VERSION" = "2" ]; then
  4612. _djson="{\"status\":\"deactivated\"}"
  4613. else
  4614. _djson="{\"resource\": \"authz\", \"status\":\"deactivated\"}"
  4615. fi
  4616. if _send_signed_request "$authzUri" "$_djson" && _contains "$response" '"deactivated"'; then
  4617. _info "Deactivate: $_vtype success."
  4618. else
  4619. _err "Can not deactivate $_vtype."
  4620. break
  4621. fi
  4622. done
  4623. _debug "$_d_i"
  4624. if [ "$_d_i" -eq "$_d_max_retry" ]; then
  4625. _info "Deactivated success!"
  4626. else
  4627. _err "Deactivate failed."
  4628. fi
  4629. }
  4630. deactivate() {
  4631. _d_domain_list="$1"
  4632. _d_type="$2"
  4633. _initpath
  4634. _initAPI
  4635. _debug _d_domain_list "$_d_domain_list"
  4636. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  4637. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  4638. return 1
  4639. fi
  4640. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  4641. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  4642. continue
  4643. fi
  4644. if ! _deactivate "$_d_dm" "$_d_type"; then
  4645. return 1
  4646. fi
  4647. done
  4648. }
  4649. # Detect profile file if not specified as environment variable
  4650. _detect_profile() {
  4651. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  4652. echo "$PROFILE"
  4653. return
  4654. fi
  4655. DETECTED_PROFILE=''
  4656. SHELLTYPE="$(basename "/$SHELL")"
  4657. if [ "$SHELLTYPE" = "bash" ]; then
  4658. if [ -f "$HOME/.bashrc" ]; then
  4659. DETECTED_PROFILE="$HOME/.bashrc"
  4660. elif [ -f "$HOME/.bash_profile" ]; then
  4661. DETECTED_PROFILE="$HOME/.bash_profile"
  4662. fi
  4663. elif [ "$SHELLTYPE" = "zsh" ]; then
  4664. DETECTED_PROFILE="$HOME/.zshrc"
  4665. fi
  4666. if [ -z "$DETECTED_PROFILE" ]; then
  4667. if [ -f "$HOME/.profile" ]; then
  4668. DETECTED_PROFILE="$HOME/.profile"
  4669. elif [ -f "$HOME/.bashrc" ]; then
  4670. DETECTED_PROFILE="$HOME/.bashrc"
  4671. elif [ -f "$HOME/.bash_profile" ]; then
  4672. DETECTED_PROFILE="$HOME/.bash_profile"
  4673. elif [ -f "$HOME/.zshrc" ]; then
  4674. DETECTED_PROFILE="$HOME/.zshrc"
  4675. fi
  4676. fi
  4677. echo "$DETECTED_PROFILE"
  4678. }
  4679. _initconf() {
  4680. _initpath
  4681. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  4682. echo "
  4683. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  4684. #LOG_LEVEL=1
  4685. #AUTO_UPGRADE=\"1\"
  4686. #NO_TIMESTAMP=1
  4687. " >"$ACCOUNT_CONF_PATH"
  4688. fi
  4689. }
  4690. # nocron
  4691. _precheck() {
  4692. _nocron="$1"
  4693. if ! _exists "curl" && ! _exists "wget"; then
  4694. _err "Please install curl or wget first, we need to access http resources."
  4695. return 1
  4696. fi
  4697. if [ -z "$_nocron" ]; then
  4698. if ! _exists "crontab" && ! _exists "fcrontab"; then
  4699. if _exists cygpath && _exists schtasks.exe; then
  4700. _info "It seems you are on Windows, we will install Windows scheduler task."
  4701. else
  4702. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  4703. _err "We need to set cron job to renew the certs automatically."
  4704. _err "Otherwise, your certs will not be able to be renewed automatically."
  4705. if [ -z "$FORCE" ]; then
  4706. _err "Please add '--force' and try install again to go without crontab."
  4707. _err "./$PROJECT_ENTRY --install --force"
  4708. return 1
  4709. fi
  4710. fi
  4711. fi
  4712. fi
  4713. if ! _exists "${ACME_OPENSSL_BIN:-openssl}"; then
  4714. _err "Please install openssl first. ACME_OPENSSL_BIN=$ACME_OPENSSL_BIN"
  4715. _err "We need openssl to generate keys."
  4716. return 1
  4717. fi
  4718. if ! _exists "socat"; then
  4719. _err "It is recommended to install socat first."
  4720. _err "We use socat for standalone server if you use standalone mode."
  4721. _err "If you don't use standalone mode, just ignore this warning."
  4722. fi
  4723. return 0
  4724. }
  4725. _setShebang() {
  4726. _file="$1"
  4727. _shebang="$2"
  4728. if [ -z "$_shebang" ]; then
  4729. _usage "Usage: file shebang"
  4730. return 1
  4731. fi
  4732. cp "$_file" "$_file.tmp"
  4733. echo "$_shebang" >"$_file"
  4734. sed -n 2,99999p "$_file.tmp" >>"$_file"
  4735. rm -f "$_file.tmp"
  4736. }
  4737. #confighome
  4738. _installalias() {
  4739. _c_home="$1"
  4740. _initpath
  4741. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  4742. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  4743. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  4744. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  4745. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  4746. fi
  4747. if [ "$_c_home" ]; then
  4748. _c_entry=" --config-home '$_c_home'"
  4749. fi
  4750. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  4751. if [ "$_c_home" ]; then
  4752. _setopt "$_envfile" "export LE_CONFIG_HOME" "=" "\"$LE_CONFIG_HOME\""
  4753. else
  4754. _sed_i "/^export LE_CONFIG_HOME/d" "$_envfile"
  4755. fi
  4756. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4757. _profile="$(_detect_profile)"
  4758. if [ "$_profile" ]; then
  4759. _debug "Found profile: $_profile"
  4760. _info "Installing alias to '$_profile'"
  4761. _setopt "$_profile" ". \"$_envfile\""
  4762. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  4763. else
  4764. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  4765. fi
  4766. #for csh
  4767. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  4768. _csh_profile="$HOME/.cshrc"
  4769. if [ -f "$_csh_profile" ]; then
  4770. _info "Installing alias to '$_csh_profile'"
  4771. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  4772. if [ "$_c_home" ]; then
  4773. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  4774. else
  4775. _sed_i "/^setenv LE_CONFIG_HOME/d" "$_cshfile"
  4776. fi
  4777. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4778. _setopt "$_csh_profile" "source \"$_cshfile\""
  4779. fi
  4780. #for tcsh
  4781. _tcsh_profile="$HOME/.tcshrc"
  4782. if [ -f "$_tcsh_profile" ]; then
  4783. _info "Installing alias to '$_tcsh_profile'"
  4784. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  4785. if [ "$_c_home" ]; then
  4786. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  4787. fi
  4788. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4789. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  4790. fi
  4791. }
  4792. # nocron confighome noprofile
  4793. install() {
  4794. if [ -z "$LE_WORKING_DIR" ]; then
  4795. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  4796. fi
  4797. _nocron="$1"
  4798. _c_home="$2"
  4799. _noprofile="$3"
  4800. if ! _initpath; then
  4801. _err "Install failed."
  4802. return 1
  4803. fi
  4804. if [ "$_nocron" ]; then
  4805. _debug "Skip install cron job"
  4806. fi
  4807. if [ "$IN_CRON" != "1" ]; then
  4808. if ! _precheck "$_nocron"; then
  4809. _err "Pre-check failed, can not install."
  4810. return 1
  4811. fi
  4812. fi
  4813. if [ -z "$_c_home" ] && [ "$LE_CONFIG_HOME" != "$LE_WORKING_DIR" ]; then
  4814. _info "Using config home: $LE_CONFIG_HOME"
  4815. _c_home="$LE_CONFIG_HOME"
  4816. fi
  4817. #convert from le
  4818. if [ -d "$HOME/.le" ]; then
  4819. for envfile in "le.env" "le.sh.env"; do
  4820. if [ -f "$HOME/.le/$envfile" ]; then
  4821. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  4822. _upgrading="1"
  4823. _info "You are upgrading from le.sh"
  4824. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  4825. mv "$HOME/.le" "$LE_WORKING_DIR"
  4826. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  4827. break
  4828. fi
  4829. fi
  4830. done
  4831. fi
  4832. _info "Installing to $LE_WORKING_DIR"
  4833. if [ ! -d "$LE_WORKING_DIR" ]; then
  4834. if ! mkdir -p "$LE_WORKING_DIR"; then
  4835. _err "Can not create working dir: $LE_WORKING_DIR"
  4836. return 1
  4837. fi
  4838. chmod 700 "$LE_WORKING_DIR"
  4839. fi
  4840. if [ ! -d "$LE_CONFIG_HOME" ]; then
  4841. if ! mkdir -p "$LE_CONFIG_HOME"; then
  4842. _err "Can not create config dir: $LE_CONFIG_HOME"
  4843. return 1
  4844. fi
  4845. chmod 700 "$LE_CONFIG_HOME"
  4846. fi
  4847. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  4848. if [ "$?" != "0" ]; then
  4849. _err "Install failed, can not copy $PROJECT_ENTRY"
  4850. return 1
  4851. fi
  4852. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  4853. if [ "$IN_CRON" != "1" ] && [ -z "$_noprofile" ]; then
  4854. _installalias "$_c_home"
  4855. fi
  4856. for subf in $_SUB_FOLDERS; do
  4857. if [ -d "$subf" ]; then
  4858. mkdir -p "$LE_WORKING_DIR/$subf"
  4859. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  4860. fi
  4861. done
  4862. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  4863. _initconf
  4864. fi
  4865. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  4866. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  4867. fi
  4868. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  4869. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  4870. fi
  4871. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  4872. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  4873. fi
  4874. if [ -z "$_nocron" ]; then
  4875. installcronjob "$_c_home"
  4876. fi
  4877. if [ -z "$NO_DETECT_SH" ]; then
  4878. #Modify shebang
  4879. if _exists bash; then
  4880. _bash_path="$(bash -c "command -v bash 2>/dev/null")"
  4881. if [ -z "$_bash_path" ]; then
  4882. _bash_path="$(bash -c 'echo $SHELL')"
  4883. fi
  4884. fi
  4885. if [ "$_bash_path" ]; then
  4886. _info "Good, bash is found, so change the shebang to use bash as preferred."
  4887. _shebang='#!'"$_bash_path"
  4888. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  4889. for subf in $_SUB_FOLDERS; do
  4890. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  4891. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  4892. _setShebang "$_apifile" "$_shebang"
  4893. done
  4894. fi
  4895. done
  4896. fi
  4897. fi
  4898. _info OK
  4899. }
  4900. # nocron
  4901. uninstall() {
  4902. _nocron="$1"
  4903. if [ -z "$_nocron" ]; then
  4904. uninstallcronjob
  4905. fi
  4906. _initpath
  4907. _uninstallalias
  4908. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  4909. _info "The keys and certs are in \"$(__green "$LE_CONFIG_HOME")\", you can remove them by yourself."
  4910. }
  4911. _uninstallalias() {
  4912. _initpath
  4913. _profile="$(_detect_profile)"
  4914. if [ "$_profile" ]; then
  4915. _info "Uninstalling alias from: '$_profile'"
  4916. text="$(cat "$_profile")"
  4917. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  4918. fi
  4919. _csh_profile="$HOME/.cshrc"
  4920. if [ -f "$_csh_profile" ]; then
  4921. _info "Uninstalling alias from: '$_csh_profile'"
  4922. text="$(cat "$_csh_profile")"
  4923. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  4924. fi
  4925. _tcsh_profile="$HOME/.tcshrc"
  4926. if [ -f "$_tcsh_profile" ]; then
  4927. _info "Uninstalling alias from: '$_csh_profile'"
  4928. text="$(cat "$_tcsh_profile")"
  4929. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  4930. fi
  4931. }
  4932. cron() {
  4933. export IN_CRON=1
  4934. _initpath
  4935. _info "$(__green "===Starting cron===")"
  4936. if [ "$AUTO_UPGRADE" = "1" ]; then
  4937. export LE_WORKING_DIR
  4938. (
  4939. if ! upgrade; then
  4940. _err "Cron:Upgrade failed!"
  4941. return 1
  4942. fi
  4943. )
  4944. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  4945. if [ -t 1 ]; then
  4946. __INTERACTIVE="1"
  4947. fi
  4948. _info "Auto upgraded to: $VER"
  4949. fi
  4950. renewAll
  4951. _ret="$?"
  4952. IN_CRON=""
  4953. _info "$(__green "===End cron===")"
  4954. exit $_ret
  4955. }
  4956. version() {
  4957. echo "$PROJECT"
  4958. echo "v$VER"
  4959. }
  4960. showhelp() {
  4961. _initpath
  4962. version
  4963. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  4964. Commands:
  4965. --help, -h Show this help message.
  4966. --version, -v Show version info.
  4967. --install Install $PROJECT_NAME to your system.
  4968. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  4969. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT.
  4970. --issue Issue a cert.
  4971. --signcsr Issue a cert from an existing csr.
  4972. --deploy Deploy the cert to your server.
  4973. --install-cert Install the issued cert to apache/nginx or any other server.
  4974. --renew, -r Renew a cert.
  4975. --renew-all Renew all the certs.
  4976. --revoke Revoke a cert.
  4977. --remove Remove the cert from list of certs known to $PROJECT_NAME.
  4978. --list List all the certs.
  4979. --showcsr Show the content of a csr.
  4980. --install-cronjob Install the cron job to renew certs, you don't need to call this. The 'install' command can automatically install the cron job.
  4981. --uninstall-cronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  4982. --cron Run cron job to renew all the certs.
  4983. --toPkcs Export the certificate and key to a pfx file.
  4984. --toPkcs8 Convert to pkcs8 format.
  4985. --update-account Update account info.
  4986. --register-account Register account key.
  4987. --deactivate-account Deactivate the account.
  4988. --create-account-key Create an account private key, professional use.
  4989. --create-domain-key Create an domain private key, professional use.
  4990. --createCSR, -ccsr Create CSR , professional use.
  4991. --deactivate Deactivate the domain authz, professional use.
  4992. Parameters:
  4993. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  4994. --challenge-alias domain.tld The challenge domain alias for DNS alias mode: $_DNS_ALIAS_WIKI
  4995. --domain-alias domain.tld The domain alias for DNS alias mode: $_DNS_ALIAS_WIKI
  4996. --force, -f Used to force to install or force to renew a cert immediately.
  4997. --staging, --test Use staging server, just for test.
  4998. --debug Output debug info.
  4999. --output-insecure Output all the sensitive messages. By default all the credentials/sensitive messages are hidden from the output/debug/log for secure.
  5000. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  5001. --standalone Use standalone mode.
  5002. --alpn Use standalone alpn mode.
  5003. --stateless Use stateless mode, see: $_STATELESS_WIKI
  5004. --apache Use apache mode.
  5005. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  5006. --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.
  5007. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  5008. --accountkeylength, -ak [2048] Specifies the account key length.
  5009. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  5010. --log-level 1|2 Specifies the log level, default is 1.
  5011. --syslog [0|3|6|7] Syslog level, 0: disable syslog, 3: error, 6: info, 7: debug.
  5012. These parameters are to install the cert to nginx/apache or any other server after issue/renew a cert:
  5013. --cert-file After issue/renew, the cert will be copied to this path.
  5014. --key-file After issue/renew, the key will be copied to this path.
  5015. --ca-file After issue/renew, the intermediate cert will be copied to this path.
  5016. --fullchain-file After issue/renew, the fullchain cert will be copied to this path.
  5017. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  5018. --server SERVER ACME Directory Resource URI. (default: https://acme-v01.api.letsencrypt.org/directory)
  5019. --accountconf Specifies a customized account config file.
  5020. --home Specifies the home dir for $PROJECT_NAME.
  5021. --cert-home Specifies the home dir to save all the certs, only valid for '--install' command.
  5022. --config-home Specifies the home dir to save all the configurations.
  5023. --useragent Specifies the user agent string. it will be saved for future use too.
  5024. --accountemail Specifies the account email, only valid for the '--install' and '--update-account' command.
  5025. --accountkey Specifies the account key path, only valid for the '--install' command.
  5026. --days Specifies the days to renew the cert when using '--issue' command. The default value is $DEFAULT_RENEW days.
  5027. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  5028. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  5029. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  5030. --listraw Only used for '--list' command, list the certs in raw format.
  5031. --stopRenewOnError, -se Only valid for '--renew-all' command. Stop if one cert has error in renewal.
  5032. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  5033. --ca-bundle Specifies the path to the CA certificate bundle to verify api server's certificate.
  5034. --ca-path Specifies directory containing CA certificates in PEM format, used by wget or curl.
  5035. --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.
  5036. --no-color Do not output color text.
  5037. --force-color Force output of color text. Useful for non-interactive use with the aha tool for HTML E-Mails.
  5038. --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  5039. --csr Specifies the input csr.
  5040. --pre-hook Command to be run before obtaining any certificates.
  5041. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obtain/renew is success or failed.
  5042. --renew-hook Command to be run once for each successfully renewed certificate.
  5043. --deploy-hook The hook file to deploy cert
  5044. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  5045. --always-force-new-domain-key Generate new domain key when renewal. Otherwise, the domain key is not changed by default.
  5046. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  5047. --listen-v4 Force standalone/tls server to listen at ipv4.
  5048. --listen-v6 Force standalone/tls server to listen at ipv6.
  5049. --openssl-bin Specifies a custom openssl bin location.
  5050. --use-wget Force to use wget, if you have both curl and wget installed.
  5051. --yes-I-know-dns-manual-mode-enough-go-ahead-please Force to use dns manual mode: $_DNS_MANUAL_WIKI
  5052. --branch, -b Only valid for '--upgrade' command, specifies the branch name to upgrade to.
  5053. "
  5054. }
  5055. # nocron noprofile
  5056. _installOnline() {
  5057. _info "Installing from online archive."
  5058. _nocron="$1"
  5059. _noprofile="$2"
  5060. if [ ! "$BRANCH" ]; then
  5061. BRANCH="master"
  5062. fi
  5063. target="$PROJECT/archive/$BRANCH.tar.gz"
  5064. _info "Downloading $target"
  5065. localname="$BRANCH.tar.gz"
  5066. if ! _get "$target" >$localname; then
  5067. _err "Download error."
  5068. return 1
  5069. fi
  5070. (
  5071. _info "Extracting $localname"
  5072. if ! (tar xzf $localname || gtar xzf $localname); then
  5073. _err "Extraction error."
  5074. exit 1
  5075. fi
  5076. cd "$PROJECT_NAME-$BRANCH"
  5077. chmod +x $PROJECT_ENTRY
  5078. if ./$PROJECT_ENTRY install "$_nocron" "" "$_noprofile"; then
  5079. _info "Install success!"
  5080. fi
  5081. cd ..
  5082. rm -rf "$PROJECT_NAME-$BRANCH"
  5083. rm -f "$localname"
  5084. )
  5085. }
  5086. upgrade() {
  5087. if (
  5088. _initpath
  5089. export LE_WORKING_DIR
  5090. cd "$LE_WORKING_DIR"
  5091. _installOnline "nocron" "noprofile"
  5092. ); then
  5093. _info "Upgrade success!"
  5094. exit 0
  5095. else
  5096. _err "Upgrade failed!"
  5097. exit 1
  5098. fi
  5099. }
  5100. _processAccountConf() {
  5101. if [ "$_useragent" ]; then
  5102. _saveaccountconf "USER_AGENT" "$_useragent"
  5103. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  5104. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  5105. fi
  5106. if [ "$_accountemail" ]; then
  5107. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  5108. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  5109. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  5110. fi
  5111. if [ "$_openssl_bin" ]; then
  5112. _saveaccountconf "ACME_OPENSSL_BIN" "$_openssl_bin"
  5113. elif [ "$ACME_OPENSSL_BIN" ] && [ "$ACME_OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  5114. _saveaccountconf "ACME_OPENSSL_BIN" "$ACME_OPENSSL_BIN"
  5115. fi
  5116. if [ "$_auto_upgrade" ]; then
  5117. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  5118. elif [ "$AUTO_UPGRADE" ]; then
  5119. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  5120. fi
  5121. if [ "$_use_wget" ]; then
  5122. _saveaccountconf "ACME_USE_WGET" "$_use_wget"
  5123. elif [ "$ACME_USE_WGET" ]; then
  5124. _saveaccountconf "ACME_USE_WGET" "$ACME_USE_WGET"
  5125. fi
  5126. }
  5127. _process() {
  5128. _CMD=""
  5129. _domain=""
  5130. _altdomains="$NO_VALUE"
  5131. _webroot=""
  5132. _challenge_alias=""
  5133. _keylength=""
  5134. _accountkeylength=""
  5135. _cert_file=""
  5136. _key_file=""
  5137. _ca_file=""
  5138. _fullchain_file=""
  5139. _reloadcmd=""
  5140. _password=""
  5141. _accountconf=""
  5142. _useragent=""
  5143. _accountemail=""
  5144. _accountkey=""
  5145. _certhome=""
  5146. _confighome=""
  5147. _httpport=""
  5148. _tlsport=""
  5149. _dnssleep=""
  5150. _listraw=""
  5151. _stopRenewOnError=""
  5152. #_insecure=""
  5153. _ca_bundle=""
  5154. _ca_path=""
  5155. _nocron=""
  5156. _ecc=""
  5157. _csr=""
  5158. _pre_hook=""
  5159. _post_hook=""
  5160. _renew_hook=""
  5161. _deploy_hook=""
  5162. _logfile=""
  5163. _log=""
  5164. _local_address=""
  5165. _log_level=""
  5166. _auto_upgrade=""
  5167. _listen_v4=""
  5168. _listen_v6=""
  5169. _openssl_bin=""
  5170. _syslog=""
  5171. _use_wget=""
  5172. _server=""
  5173. while [ ${#} -gt 0 ]; do
  5174. case "${1}" in
  5175. --help | -h)
  5176. showhelp
  5177. return
  5178. ;;
  5179. --version | -v)
  5180. version
  5181. return
  5182. ;;
  5183. --install)
  5184. _CMD="install"
  5185. ;;
  5186. --uninstall)
  5187. _CMD="uninstall"
  5188. ;;
  5189. --upgrade)
  5190. _CMD="upgrade"
  5191. ;;
  5192. --issue)
  5193. _CMD="issue"
  5194. ;;
  5195. --deploy)
  5196. _CMD="deploy"
  5197. ;;
  5198. --signcsr)
  5199. _CMD="signcsr"
  5200. ;;
  5201. --showcsr)
  5202. _CMD="showcsr"
  5203. ;;
  5204. --installcert | -i | --install-cert)
  5205. _CMD="installcert"
  5206. ;;
  5207. --renew | -r)
  5208. _CMD="renew"
  5209. ;;
  5210. --renewAll | --renewall | --renew-all)
  5211. _CMD="renewAll"
  5212. ;;
  5213. --revoke)
  5214. _CMD="revoke"
  5215. ;;
  5216. --remove)
  5217. _CMD="remove"
  5218. ;;
  5219. --list)
  5220. _CMD="list"
  5221. ;;
  5222. --installcronjob | --install-cronjob)
  5223. _CMD="installcronjob"
  5224. ;;
  5225. --uninstallcronjob | --uninstall-cronjob)
  5226. _CMD="uninstallcronjob"
  5227. ;;
  5228. --cron)
  5229. _CMD="cron"
  5230. ;;
  5231. --toPkcs)
  5232. _CMD="toPkcs"
  5233. ;;
  5234. --toPkcs8)
  5235. _CMD="toPkcs8"
  5236. ;;
  5237. --createAccountKey | --createaccountkey | -cak | --create-account-key)
  5238. _CMD="createAccountKey"
  5239. ;;
  5240. --createDomainKey | --createdomainkey | -cdk | --create-domain-key)
  5241. _CMD="createDomainKey"
  5242. ;;
  5243. --createCSR | --createcsr | -ccr)
  5244. _CMD="createCSR"
  5245. ;;
  5246. --deactivate)
  5247. _CMD="deactivate"
  5248. ;;
  5249. --updateaccount | --update-account)
  5250. _CMD="updateaccount"
  5251. ;;
  5252. --registeraccount | --register-account)
  5253. _CMD="registeraccount"
  5254. ;;
  5255. --deactivate-account)
  5256. _CMD="deactivateaccount"
  5257. ;;
  5258. --domain | -d)
  5259. _dvalue="$2"
  5260. if [ "$_dvalue" ]; then
  5261. if _startswith "$_dvalue" "-"; then
  5262. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  5263. return 1
  5264. fi
  5265. if _is_idn "$_dvalue" && ! _exists idn; then
  5266. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  5267. return 1
  5268. fi
  5269. if _startswith "$_dvalue" "*."; then
  5270. _debug "Wildcard domain"
  5271. export ACME_VERSION=2
  5272. fi
  5273. if [ -z "$_domain" ]; then
  5274. _domain="$_dvalue"
  5275. else
  5276. if [ "$_altdomains" = "$NO_VALUE" ]; then
  5277. _altdomains="$_dvalue"
  5278. else
  5279. _altdomains="$_altdomains,$_dvalue"
  5280. fi
  5281. fi
  5282. fi
  5283. shift
  5284. ;;
  5285. --force | -f)
  5286. FORCE="1"
  5287. ;;
  5288. --staging | --test)
  5289. STAGE="1"
  5290. ;;
  5291. --server)
  5292. ACME_DIRECTORY="$2"
  5293. _server="$ACME_DIRECTORY"
  5294. export ACME_DIRECTORY
  5295. shift
  5296. ;;
  5297. --debug)
  5298. if [ -z "$2" ] || _startswith "$2" "-"; then
  5299. DEBUG="$DEBUG_LEVEL_DEFAULT"
  5300. else
  5301. DEBUG="$2"
  5302. shift
  5303. fi
  5304. ;;
  5305. --output-insecure)
  5306. export OUTPUT_INSECURE=1
  5307. ;;
  5308. --webroot | -w)
  5309. wvalue="$2"
  5310. if [ -z "$_webroot" ]; then
  5311. _webroot="$wvalue"
  5312. else
  5313. _webroot="$_webroot,$wvalue"
  5314. fi
  5315. shift
  5316. ;;
  5317. --challenge-alias)
  5318. cvalue="$2"
  5319. _challenge_alias="$_challenge_alias$cvalue,"
  5320. shift
  5321. ;;
  5322. --domain-alias)
  5323. cvalue="$DNS_ALIAS_PREFIX$2"
  5324. _challenge_alias="$_challenge_alias$cvalue,"
  5325. shift
  5326. ;;
  5327. --standalone)
  5328. wvalue="$NO_VALUE"
  5329. if [ -z "$_webroot" ]; then
  5330. _webroot="$wvalue"
  5331. else
  5332. _webroot="$_webroot,$wvalue"
  5333. fi
  5334. ;;
  5335. --alpn)
  5336. wvalue="$W_ALPN"
  5337. if [ -z "$_webroot" ]; then
  5338. _webroot="$wvalue"
  5339. else
  5340. _webroot="$_webroot,$wvalue"
  5341. fi
  5342. ;;
  5343. --stateless)
  5344. wvalue="$MODE_STATELESS"
  5345. if [ -z "$_webroot" ]; then
  5346. _webroot="$wvalue"
  5347. else
  5348. _webroot="$_webroot,$wvalue"
  5349. fi
  5350. ;;
  5351. --local-address)
  5352. lvalue="$2"
  5353. _local_address="$_local_address$lvalue,"
  5354. shift
  5355. ;;
  5356. --apache)
  5357. wvalue="apache"
  5358. if [ -z "$_webroot" ]; then
  5359. _webroot="$wvalue"
  5360. else
  5361. _webroot="$_webroot,$wvalue"
  5362. fi
  5363. ;;
  5364. --nginx)
  5365. wvalue="$NGINX"
  5366. if [ -z "$_webroot" ]; then
  5367. _webroot="$wvalue"
  5368. else
  5369. _webroot="$_webroot,$wvalue"
  5370. fi
  5371. ;;
  5372. --dns)
  5373. wvalue="$W_DNS"
  5374. if [ "$2" ] && ! _startswith "$2" "-"; then
  5375. wvalue="$2"
  5376. shift
  5377. fi
  5378. if [ -z "$_webroot" ]; then
  5379. _webroot="$wvalue"
  5380. else
  5381. _webroot="$_webroot,$wvalue"
  5382. fi
  5383. ;;
  5384. --dnssleep)
  5385. _dnssleep="$2"
  5386. Le_DNSSleep="$_dnssleep"
  5387. shift
  5388. ;;
  5389. --keylength | -k)
  5390. _keylength="$2"
  5391. shift
  5392. ;;
  5393. --accountkeylength | -ak)
  5394. _accountkeylength="$2"
  5395. shift
  5396. ;;
  5397. --cert-file | --certpath)
  5398. _cert_file="$2"
  5399. shift
  5400. ;;
  5401. --key-file | --keypath)
  5402. _key_file="$2"
  5403. shift
  5404. ;;
  5405. --ca-file | --capath)
  5406. _ca_file="$2"
  5407. shift
  5408. ;;
  5409. --fullchain-file | --fullchainpath)
  5410. _fullchain_file="$2"
  5411. shift
  5412. ;;
  5413. --reloadcmd | --reloadCmd)
  5414. _reloadcmd="$2"
  5415. shift
  5416. ;;
  5417. --password)
  5418. _password="$2"
  5419. shift
  5420. ;;
  5421. --accountconf)
  5422. _accountconf="$2"
  5423. ACCOUNT_CONF_PATH="$_accountconf"
  5424. shift
  5425. ;;
  5426. --home)
  5427. LE_WORKING_DIR="$2"
  5428. shift
  5429. ;;
  5430. --certhome | --cert-home)
  5431. _certhome="$2"
  5432. CERT_HOME="$_certhome"
  5433. shift
  5434. ;;
  5435. --config-home)
  5436. _confighome="$2"
  5437. LE_CONFIG_HOME="$_confighome"
  5438. shift
  5439. ;;
  5440. --useragent)
  5441. _useragent="$2"
  5442. USER_AGENT="$_useragent"
  5443. shift
  5444. ;;
  5445. --accountemail)
  5446. _accountemail="$2"
  5447. ACCOUNT_EMAIL="$_accountemail"
  5448. shift
  5449. ;;
  5450. --accountkey)
  5451. _accountkey="$2"
  5452. ACCOUNT_KEY_PATH="$_accountkey"
  5453. shift
  5454. ;;
  5455. --days)
  5456. _days="$2"
  5457. Le_RenewalDays="$_days"
  5458. shift
  5459. ;;
  5460. --httpport)
  5461. _httpport="$2"
  5462. Le_HTTPPort="$_httpport"
  5463. shift
  5464. ;;
  5465. --tlsport)
  5466. _tlsport="$2"
  5467. Le_TLSPort="$_tlsport"
  5468. shift
  5469. ;;
  5470. --listraw)
  5471. _listraw="raw"
  5472. ;;
  5473. --stopRenewOnError | --stoprenewonerror | -se)
  5474. _stopRenewOnError="1"
  5475. ;;
  5476. --insecure)
  5477. #_insecure="1"
  5478. HTTPS_INSECURE="1"
  5479. ;;
  5480. --ca-bundle)
  5481. _ca_bundle="$(_readlink "$2")"
  5482. CA_BUNDLE="$_ca_bundle"
  5483. shift
  5484. ;;
  5485. --ca-path)
  5486. _ca_path="$2"
  5487. CA_PATH="$_ca_path"
  5488. shift
  5489. ;;
  5490. --nocron)
  5491. _nocron="1"
  5492. ;;
  5493. --no-color)
  5494. export ACME_NO_COLOR=1
  5495. ;;
  5496. --force-color)
  5497. export ACME_FORCE_COLOR=1
  5498. ;;
  5499. --ecc)
  5500. _ecc="isEcc"
  5501. ;;
  5502. --csr)
  5503. _csr="$2"
  5504. shift
  5505. ;;
  5506. --pre-hook)
  5507. _pre_hook="$2"
  5508. shift
  5509. ;;
  5510. --post-hook)
  5511. _post_hook="$2"
  5512. shift
  5513. ;;
  5514. --renew-hook)
  5515. _renew_hook="$2"
  5516. shift
  5517. ;;
  5518. --deploy-hook)
  5519. if [ -z "$2" ] || _startswith "$2" "-"; then
  5520. _usage "Please specify a value for '--deploy-hook'"
  5521. return 1
  5522. fi
  5523. _deploy_hook="$_deploy_hook$2,"
  5524. shift
  5525. ;;
  5526. --ocsp-must-staple | --ocsp)
  5527. Le_OCSP_Staple="1"
  5528. ;;
  5529. --always-force-new-domain-key)
  5530. if [ -z "$2" ] || _startswith "$2" "-"; then
  5531. Le_ForceNewDomainKey=1
  5532. else
  5533. Le_ForceNewDomainKey="$2"
  5534. shift
  5535. fi
  5536. ;;
  5537. --yes-I-know-dns-manual-mode-enough-go-ahead-please)
  5538. export FORCE_DNS_MANUAL=1
  5539. ;;
  5540. --log | --logfile)
  5541. _log="1"
  5542. _logfile="$2"
  5543. if _startswith "$_logfile" '-'; then
  5544. _logfile=""
  5545. else
  5546. shift
  5547. fi
  5548. LOG_FILE="$_logfile"
  5549. if [ -z "$LOG_LEVEL" ]; then
  5550. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  5551. fi
  5552. ;;
  5553. --log-level)
  5554. _log_level="$2"
  5555. LOG_LEVEL="$_log_level"
  5556. shift
  5557. ;;
  5558. --syslog)
  5559. if ! _startswith "$2" '-'; then
  5560. _syslog="$2"
  5561. shift
  5562. fi
  5563. if [ -z "$_syslog" ]; then
  5564. _syslog="$SYSLOG_LEVEL_DEFAULT"
  5565. fi
  5566. ;;
  5567. --auto-upgrade)
  5568. _auto_upgrade="$2"
  5569. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  5570. _auto_upgrade="1"
  5571. else
  5572. shift
  5573. fi
  5574. AUTO_UPGRADE="$_auto_upgrade"
  5575. ;;
  5576. --listen-v4)
  5577. _listen_v4="1"
  5578. Le_Listen_V4="$_listen_v4"
  5579. ;;
  5580. --listen-v6)
  5581. _listen_v6="1"
  5582. Le_Listen_V6="$_listen_v6"
  5583. ;;
  5584. --openssl-bin)
  5585. _openssl_bin="$2"
  5586. ACME_OPENSSL_BIN="$_openssl_bin"
  5587. shift
  5588. ;;
  5589. --use-wget)
  5590. _use_wget="1"
  5591. ACME_USE_WGET="1"
  5592. ;;
  5593. --branch | -b)
  5594. export BRANCH="$2"
  5595. shift
  5596. ;;
  5597. *)
  5598. _err "Unknown parameter : $1"
  5599. return 1
  5600. ;;
  5601. esac
  5602. shift 1
  5603. done
  5604. if [ "${_CMD}" != "install" ]; then
  5605. __initHome
  5606. if [ "$_log" ]; then
  5607. if [ -z "$_logfile" ]; then
  5608. _logfile="$DEFAULT_LOG_FILE"
  5609. fi
  5610. fi
  5611. if [ "$_logfile" ]; then
  5612. _saveaccountconf "LOG_FILE" "$_logfile"
  5613. LOG_FILE="$_logfile"
  5614. fi
  5615. if [ "$_log_level" ]; then
  5616. _saveaccountconf "LOG_LEVEL" "$_log_level"
  5617. LOG_LEVEL="$_log_level"
  5618. fi
  5619. if [ "$_syslog" ]; then
  5620. if _exists logger; then
  5621. if [ "$_syslog" = "0" ]; then
  5622. _clearaccountconf "SYS_LOG"
  5623. else
  5624. _saveaccountconf "SYS_LOG" "$_syslog"
  5625. fi
  5626. SYS_LOG="$_syslog"
  5627. else
  5628. _err "The 'logger' command is not found, can not enable syslog."
  5629. _clearaccountconf "SYS_LOG"
  5630. SYS_LOG=""
  5631. fi
  5632. fi
  5633. _processAccountConf
  5634. fi
  5635. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  5636. if [ "$DEBUG" ]; then
  5637. version
  5638. if [ "$_server" ]; then
  5639. _debug "Using server: $_server"
  5640. fi
  5641. fi
  5642. case "${_CMD}" in
  5643. install) install "$_nocron" "$_confighome" ;;
  5644. uninstall) uninstall "$_nocron" ;;
  5645. upgrade) upgrade ;;
  5646. issue)
  5647. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
  5648. ;;
  5649. deploy)
  5650. deploy "$_domain" "$_deploy_hook" "$_ecc"
  5651. ;;
  5652. signcsr)
  5653. signcsr "$_csr" "$_webroot" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address" "$_challenge_alias"
  5654. ;;
  5655. showcsr)
  5656. showcsr "$_csr" "$_domain"
  5657. ;;
  5658. installcert)
  5659. installcert "$_domain" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_ecc"
  5660. ;;
  5661. renew)
  5662. renew "$_domain" "$_ecc"
  5663. ;;
  5664. renewAll)
  5665. renewAll "$_stopRenewOnError"
  5666. ;;
  5667. revoke)
  5668. revoke "$_domain" "$_ecc"
  5669. ;;
  5670. remove)
  5671. remove "$_domain" "$_ecc"
  5672. ;;
  5673. deactivate)
  5674. deactivate "$_domain,$_altdomains"
  5675. ;;
  5676. registeraccount)
  5677. registeraccount "$_accountkeylength"
  5678. ;;
  5679. updateaccount)
  5680. updateaccount
  5681. ;;
  5682. deactivateaccount)
  5683. deactivateaccount
  5684. ;;
  5685. list)
  5686. list "$_listraw"
  5687. ;;
  5688. installcronjob) installcronjob "$_confighome" ;;
  5689. uninstallcronjob) uninstallcronjob ;;
  5690. cron) cron ;;
  5691. toPkcs)
  5692. toPkcs "$_domain" "$_password" "$_ecc"
  5693. ;;
  5694. toPkcs8)
  5695. toPkcs8 "$_domain" "$_ecc"
  5696. ;;
  5697. createAccountKey)
  5698. createAccountKey "$_accountkeylength"
  5699. ;;
  5700. createDomainKey)
  5701. createDomainKey "$_domain" "$_keylength"
  5702. ;;
  5703. createCSR)
  5704. createCSR "$_domain" "$_altdomains" "$_ecc"
  5705. ;;
  5706. *)
  5707. if [ "$_CMD" ]; then
  5708. _err "Invalid command: $_CMD"
  5709. fi
  5710. showhelp
  5711. return 1
  5712. ;;
  5713. esac
  5714. _ret="$?"
  5715. if [ "$_ret" != "0" ]; then
  5716. return $_ret
  5717. fi
  5718. if [ "${_CMD}" = "install" ]; then
  5719. if [ "$_log" ]; then
  5720. if [ -z "$LOG_FILE" ]; then
  5721. LOG_FILE="$DEFAULT_LOG_FILE"
  5722. fi
  5723. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  5724. fi
  5725. if [ "$_log_level" ]; then
  5726. _saveaccountconf "LOG_LEVEL" "$_log_level"
  5727. fi
  5728. if [ "$_syslog" ]; then
  5729. if _exists logger; then
  5730. if [ "$_syslog" = "0" ]; then
  5731. _clearaccountconf "SYS_LOG"
  5732. else
  5733. _saveaccountconf "SYS_LOG" "$_syslog"
  5734. fi
  5735. else
  5736. _err "The 'logger' command is not found, can not enable syslog."
  5737. _clearaccountconf "SYS_LOG"
  5738. SYS_LOG=""
  5739. fi
  5740. fi
  5741. _processAccountConf
  5742. fi
  5743. }
  5744. if [ "$INSTALLONLINE" ]; then
  5745. INSTALLONLINE=""
  5746. _installOnline
  5747. exit
  5748. fi
  5749. main() {
  5750. [ -z "$1" ] && showhelp && return
  5751. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  5752. }
  5753. main "$@"