acme.sh 158 KB

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