acme.sh 170 KB

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