acme.sh 156 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029
  1. #!/usr/bin/env sh
  2. VER=2.7.6
  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. fi
  1351. if [ -z "$_ACME_WGET" ] && _exists "wget"; then
  1352. _ACME_WGET="wget -q"
  1353. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1354. _ACME_WGET="$_ACME_WGET -d "
  1355. fi
  1356. if [ "$CA_PATH" ]; then
  1357. _ACME_WGET="$_ACME_WGET --ca-directory=$CA_PATH "
  1358. elif [ "$CA_BUNDLE" ]; then
  1359. _ACME_WGET="$_ACME_WGET --ca-certificate=$CA_BUNDLE "
  1360. fi
  1361. fi
  1362. #from wget 1.14: do not skip body on 404 error
  1363. if [ "$_ACME_WGET" ] && _contains "$($_ACME_WGET --help 2>&1)" "--content-on-error"; then
  1364. _ACME_WGET="$_ACME_WGET --content-on-error "
  1365. fi
  1366. __HTTP_INITIALIZED=1
  1367. }
  1368. # body url [needbase64] [POST|PUT]
  1369. _post() {
  1370. body="$1"
  1371. _post_url="$2"
  1372. needbase64="$3"
  1373. httpmethod="$4"
  1374. if [ -z "$httpmethod" ]; then
  1375. httpmethod="POST"
  1376. fi
  1377. _debug $httpmethod
  1378. _debug "_post_url" "$_post_url"
  1379. _debug2 "body" "$body"
  1380. _inithttp
  1381. if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
  1382. _CURL="$_ACME_CURL"
  1383. if [ "$HTTPS_INSECURE" ]; then
  1384. _CURL="$_CURL --insecure "
  1385. fi
  1386. _debug "_CURL" "$_CURL"
  1387. if [ "$needbase64" ]; then
  1388. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url" | _base64)"
  1389. else
  1390. response="$($_CURL --user-agent "$USER_AGENT" -X $httpmethod -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" --data "$body" "$_post_url")"
  1391. fi
  1392. _ret="$?"
  1393. if [ "$_ret" != "0" ]; then
  1394. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $_ret"
  1395. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1396. _err "Here is the curl dump log:"
  1397. _err "$(cat "$_CURL_DUMP")"
  1398. fi
  1399. fi
  1400. elif [ "$_ACME_WGET" ]; then
  1401. _WGET="$_ACME_WGET"
  1402. if [ "$HTTPS_INSECURE" ]; then
  1403. _WGET="$_WGET --no-check-certificate "
  1404. fi
  1405. _debug "_WGET" "$_WGET"
  1406. if [ "$needbase64" ]; then
  1407. if [ "$httpmethod" = "POST" ]; then
  1408. 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)"
  1409. else
  1410. 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)"
  1411. fi
  1412. else
  1413. if [ "$httpmethod" = "POST" ]; then
  1414. 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")"
  1415. else
  1416. 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")"
  1417. fi
  1418. fi
  1419. _ret="$?"
  1420. if [ "$_ret" = "8" ]; then
  1421. _ret=0
  1422. _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
  1423. fi
  1424. if [ "$_ret" != "0" ]; then
  1425. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $_ret"
  1426. fi
  1427. _sed_i "s/^ *//g" "$HTTP_HEADER"
  1428. else
  1429. _ret="$?"
  1430. _err "Neither curl nor wget is found, can not do $httpmethod."
  1431. fi
  1432. _debug "_ret" "$_ret"
  1433. printf "%s" "$response"
  1434. return $_ret
  1435. }
  1436. # url getheader timeout
  1437. _get() {
  1438. _debug GET
  1439. url="$1"
  1440. onlyheader="$2"
  1441. t="$3"
  1442. _debug url "$url"
  1443. _debug "timeout=$t"
  1444. _inithttp
  1445. if [ "$_ACME_CURL" ] && [ "${ACME_USE_WGET:-0}" = "0" ]; then
  1446. _CURL="$_ACME_CURL"
  1447. if [ "$HTTPS_INSECURE" ]; then
  1448. _CURL="$_CURL --insecure "
  1449. fi
  1450. if [ "$t" ]; then
  1451. _CURL="$_CURL --connect-timeout $t"
  1452. fi
  1453. _debug "_CURL" "$_CURL"
  1454. if [ "$onlyheader" ]; then
  1455. $_CURL -I --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1456. else
  1457. $_CURL --user-agent "$USER_AGENT" -H "$_H1" -H "$_H2" -H "$_H3" -H "$_H4" -H "$_H5" "$url"
  1458. fi
  1459. ret=$?
  1460. if [ "$ret" != "0" ]; then
  1461. _err "Please refer to https://curl.haxx.se/libcurl/c/libcurl-errors.html for error code: $ret"
  1462. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1463. _err "Here is the curl dump log:"
  1464. _err "$(cat "$_CURL_DUMP")"
  1465. fi
  1466. fi
  1467. elif [ "$_ACME_WGET" ]; then
  1468. _WGET="$_ACME_WGET"
  1469. if [ "$HTTPS_INSECURE" ]; then
  1470. _WGET="$_WGET --no-check-certificate "
  1471. fi
  1472. if [ "$t" ]; then
  1473. _WGET="$_WGET --timeout=$t"
  1474. fi
  1475. _debug "_WGET" "$_WGET"
  1476. if [ "$onlyheader" ]; then
  1477. $_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'
  1478. else
  1479. $_WGET --user-agent="$USER_AGENT" --header "$_H5" --header "$_H4" --header "$_H3" --header "$_H2" --header "$_H1" -O - "$url"
  1480. fi
  1481. ret=$?
  1482. if [ "$ret" = "8" ]; then
  1483. ret=0
  1484. _debug "wget returns 8, the server returns a 'Bad request' response, lets process the response later."
  1485. fi
  1486. if [ "$ret" != "0" ]; then
  1487. _err "Please refer to https://www.gnu.org/software/wget/manual/html_node/Exit-Status.html for error code: $ret"
  1488. fi
  1489. else
  1490. ret=$?
  1491. _err "Neither curl nor wget is found, can not do GET."
  1492. fi
  1493. _debug "ret" "$ret"
  1494. return $ret
  1495. }
  1496. _head_n() {
  1497. head -n "$1"
  1498. }
  1499. _tail_n() {
  1500. if ! tail -n "$1" 2>/dev/null; then
  1501. #fix for solaris
  1502. tail -"$1"
  1503. fi
  1504. }
  1505. # url payload needbase64 keyfile
  1506. _send_signed_request() {
  1507. url=$1
  1508. payload=$2
  1509. needbase64=$3
  1510. keyfile=$4
  1511. if [ -z "$keyfile" ]; then
  1512. keyfile="$ACCOUNT_KEY_PATH"
  1513. fi
  1514. _debug url "$url"
  1515. _debug payload "$payload"
  1516. if ! _calcjwk "$keyfile"; then
  1517. return 1
  1518. fi
  1519. payload64=$(printf "%s" "$payload" | _base64 | _url_replace)
  1520. _debug3 payload64 "$payload64"
  1521. MAX_REQUEST_RETRY_TIMES=5
  1522. _request_retry_times=0
  1523. while [ "${_request_retry_times}" -lt "$MAX_REQUEST_RETRY_TIMES" ]; do
  1524. _debug3 _request_retry_times "$_request_retry_times"
  1525. if [ -z "$_CACHED_NONCE" ]; then
  1526. _headers=""
  1527. if [ "$ACME_NEW_NONCE" ]; then
  1528. _debug2 "Get nonce. ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  1529. nonceurl="$ACME_NEW_NONCE"
  1530. if _post "" "$nonceurl" "" "HEAD"; then
  1531. _headers="$(cat "$HTTP_HEADER")"
  1532. fi
  1533. fi
  1534. if [ -z "$_headers" ]; then
  1535. _debug2 "Get nonce. ACME_DIRECTORY" "$ACME_DIRECTORY"
  1536. nonceurl="$ACME_DIRECTORY"
  1537. _headers="$(_get "$nonceurl" "onlyheader")"
  1538. fi
  1539. if [ "$?" != "0" ]; then
  1540. _err "Can not connect to $nonceurl to get nonce."
  1541. return 1
  1542. fi
  1543. _debug2 _headers "$_headers"
  1544. _CACHED_NONCE="$(echo "$_headers" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1545. _debug2 _CACHED_NONCE "$_CACHED_NONCE"
  1546. else
  1547. _debug2 "Use _CACHED_NONCE" "$_CACHED_NONCE"
  1548. fi
  1549. nonce="$_CACHED_NONCE"
  1550. _debug2 nonce "$nonce"
  1551. if [ "$ACME_VERSION" = "2" ]; then
  1552. if [ "$url" = "$ACME_NEW_ACCOUNT" ] || [ "$url" = "$ACME_REVOKE_CERT" ]; then
  1553. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1554. else
  1555. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"kid\": \"$ACCOUNT_URL\""'}'
  1556. fi
  1557. else
  1558. protected="$JWK_HEADERPLACE_PART1$nonce\", \"url\": \"${url}$JWK_HEADERPLACE_PART2, \"jwk\": $jwk"'}'
  1559. fi
  1560. _debug3 protected "$protected"
  1561. protected64="$(printf "%s" "$protected" | _base64 | _url_replace)"
  1562. _debug3 protected64 "$protected64"
  1563. if ! _sig_t="$(printf "%s" "$protected64.$payload64" | _sign "$keyfile" "sha256")"; then
  1564. _err "Sign request failed."
  1565. return 1
  1566. fi
  1567. _debug3 _sig_t "$_sig_t"
  1568. sig="$(printf "%s" "$_sig_t" | _url_replace)"
  1569. _debug3 sig "$sig"
  1570. if [ "$ACME_VERSION" = "2" ]; then
  1571. body="{\"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1572. else
  1573. body="{\"header\": $JWK_HEADER, \"protected\": \"$protected64\", \"payload\": \"$payload64\", \"signature\": \"$sig\"}"
  1574. fi
  1575. _debug3 body "$body"
  1576. response="$(_post "$body" "$url" "$needbase64")"
  1577. _CACHED_NONCE=""
  1578. if [ "$?" != "0" ]; then
  1579. _err "Can not post to $url"
  1580. return 1
  1581. fi
  1582. _debug2 original "$response"
  1583. response="$(echo "$response" | _normalizeJson)"
  1584. responseHeaders="$(cat "$HTTP_HEADER")"
  1585. _debug2 responseHeaders "$responseHeaders"
  1586. _debug2 response "$response"
  1587. code="$(grep "^HTTP" "$HTTP_HEADER" | _tail_n 1 | cut -d " " -f 2 | tr -d "\r\n")"
  1588. _debug code "$code"
  1589. _CACHED_NONCE="$(echo "$responseHeaders" | grep "Replay-Nonce:" | _head_n 1 | tr -d "\r\n " | cut -d ':' -f 2)"
  1590. _body="$response"
  1591. if [ "$needbase64" ]; then
  1592. _body="$(echo "$_body" | _dbase64)"
  1593. _debug2 _body "$_body"
  1594. fi
  1595. if _contains "$_body" "JWS has invalid anti-replay nonce"; then
  1596. _info "It seems the CA server is busy now, let's wait and retry."
  1597. _request_retry_times=$(_math "$_request_retry_times" + 1)
  1598. _sleep 5
  1599. continue
  1600. fi
  1601. break
  1602. done
  1603. }
  1604. #setopt "file" "opt" "=" "value" [";"]
  1605. _setopt() {
  1606. __conf="$1"
  1607. __opt="$2"
  1608. __sep="$3"
  1609. __val="$4"
  1610. __end="$5"
  1611. if [ -z "$__opt" ]; then
  1612. _usage usage: _setopt '"file" "opt" "=" "value" [";"]'
  1613. return
  1614. fi
  1615. if [ ! -f "$__conf" ]; then
  1616. touch "$__conf"
  1617. fi
  1618. if grep -n "^$__opt$__sep" "$__conf" >/dev/null; then
  1619. _debug3 OK
  1620. if _contains "$__val" "&"; then
  1621. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1622. fi
  1623. text="$(cat "$__conf")"
  1624. printf -- "%s\n" "$text" | sed "s|^$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1625. elif grep -n "^#$__opt$__sep" "$__conf" >/dev/null; then
  1626. if _contains "$__val" "&"; then
  1627. __val="$(echo "$__val" | sed 's/&/\\&/g')"
  1628. fi
  1629. text="$(cat "$__conf")"
  1630. printf -- "%s\n" "$text" | sed "s|^#$__opt$__sep.*$|$__opt$__sep$__val$__end|" >"$__conf"
  1631. else
  1632. _debug3 APP
  1633. echo "$__opt$__sep$__val$__end" >>"$__conf"
  1634. fi
  1635. _debug3 "$(grep -n "^$__opt$__sep" "$__conf")"
  1636. }
  1637. #_save_conf file key value
  1638. #save to conf
  1639. _save_conf() {
  1640. _s_c_f="$1"
  1641. _sdkey="$2"
  1642. _sdvalue="$3"
  1643. if [ "$_s_c_f" ]; then
  1644. _setopt "$_s_c_f" "$_sdkey" "=" "'$_sdvalue'"
  1645. else
  1646. _err "config file is empty, can not save $_sdkey=$_sdvalue"
  1647. fi
  1648. }
  1649. #_clear_conf file key
  1650. _clear_conf() {
  1651. _c_c_f="$1"
  1652. _sdkey="$2"
  1653. if [ "$_c_c_f" ]; then
  1654. _conf_data="$(cat "$_c_c_f")"
  1655. echo "$_conf_data" | sed "s/^$_sdkey *=.*$//" >"$_c_c_f"
  1656. else
  1657. _err "config file is empty, can not clear"
  1658. fi
  1659. }
  1660. #_read_conf file key
  1661. _read_conf() {
  1662. _r_c_f="$1"
  1663. _sdkey="$2"
  1664. if [ -f "$_r_c_f" ]; then
  1665. (
  1666. eval "$(grep "^$_sdkey *=" "$_r_c_f")"
  1667. eval "printf \"%s\" \"\$$_sdkey\""
  1668. )
  1669. else
  1670. _debug "config file is empty, can not read $_sdkey"
  1671. fi
  1672. }
  1673. #_savedomainconf key value
  1674. #save to domain.conf
  1675. _savedomainconf() {
  1676. _save_conf "$DOMAIN_CONF" "$1" "$2"
  1677. }
  1678. #_cleardomainconf key
  1679. _cleardomainconf() {
  1680. _clear_conf "$DOMAIN_CONF" "$1"
  1681. }
  1682. #_readdomainconf key
  1683. _readdomainconf() {
  1684. _read_conf "$DOMAIN_CONF" "$1"
  1685. }
  1686. #_saveaccountconf key value
  1687. _saveaccountconf() {
  1688. _save_conf "$ACCOUNT_CONF_PATH" "$1" "$2"
  1689. }
  1690. #key value
  1691. _saveaccountconf_mutable() {
  1692. _save_conf "$ACCOUNT_CONF_PATH" "SAVED_$1" "$2"
  1693. #remove later
  1694. _clearaccountconf "$1"
  1695. }
  1696. #key
  1697. _readaccountconf() {
  1698. _read_conf "$ACCOUNT_CONF_PATH" "$1"
  1699. }
  1700. #key
  1701. _readaccountconf_mutable() {
  1702. _rac_key="$1"
  1703. _readaccountconf "SAVED_$_rac_key"
  1704. }
  1705. #_clearaccountconf key
  1706. _clearaccountconf() {
  1707. _clear_conf "$ACCOUNT_CONF_PATH" "$1"
  1708. }
  1709. #_savecaconf key value
  1710. _savecaconf() {
  1711. _save_conf "$CA_CONF" "$1" "$2"
  1712. }
  1713. #_readcaconf key
  1714. _readcaconf() {
  1715. _read_conf "$CA_CONF" "$1"
  1716. }
  1717. #_clearaccountconf key
  1718. _clearcaconf() {
  1719. _clear_conf "$CA_CONF" "$1"
  1720. }
  1721. # content localaddress
  1722. _startserver() {
  1723. content="$1"
  1724. ncaddr="$2"
  1725. _debug "ncaddr" "$ncaddr"
  1726. _debug "startserver: $$"
  1727. _debug Le_HTTPPort "$Le_HTTPPort"
  1728. _debug Le_Listen_V4 "$Le_Listen_V4"
  1729. _debug Le_Listen_V6 "$Le_Listen_V6"
  1730. _NC="socat"
  1731. if [ "$Le_Listen_V4" ]; then
  1732. _NC="$_NC -4"
  1733. elif [ "$Le_Listen_V6" ]; then
  1734. _NC="$_NC -6"
  1735. fi
  1736. _debug "_NC" "$_NC"
  1737. #todo listen address
  1738. $_NC TCP-LISTEN:$Le_HTTPPort,crlf,reuseaddr,fork SYSTEM:"sleep 0.5; echo HTTP/1.1 200 OK; echo ; echo $content; echo;" &
  1739. serverproc="$!"
  1740. }
  1741. _stopserver() {
  1742. pid="$1"
  1743. _debug "pid" "$pid"
  1744. if [ -z "$pid" ]; then
  1745. return
  1746. fi
  1747. kill $pid
  1748. }
  1749. # sleep sec
  1750. _sleep() {
  1751. _sleep_sec="$1"
  1752. if [ "$__INTERACTIVE" ]; then
  1753. _sleep_c="$_sleep_sec"
  1754. while [ "$_sleep_c" -ge "0" ]; do
  1755. printf "\r \r"
  1756. __green "$_sleep_c"
  1757. _sleep_c="$(_math "$_sleep_c" - 1)"
  1758. sleep 1
  1759. done
  1760. printf "\r"
  1761. else
  1762. sleep "$_sleep_sec"
  1763. fi
  1764. }
  1765. # _starttlsserver san_a san_b port content _ncaddr
  1766. _starttlsserver() {
  1767. _info "Starting tls server."
  1768. san_a="$1"
  1769. san_b="$2"
  1770. port="$3"
  1771. content="$4"
  1772. opaddr="$5"
  1773. _debug san_a "$san_a"
  1774. _debug san_b "$san_b"
  1775. _debug port "$port"
  1776. #create key TLS_KEY
  1777. if ! _createkey "2048" "$TLS_KEY"; then
  1778. _err "Create tls validation key error."
  1779. return 1
  1780. fi
  1781. #create csr
  1782. alt="$san_a"
  1783. if [ "$san_b" ]; then
  1784. alt="$alt,$san_b"
  1785. fi
  1786. if ! _createcsr "tls.acme.sh" "$alt" "$TLS_KEY" "$TLS_CSR" "$TLS_CONF"; then
  1787. _err "Create tls validation csr error."
  1788. return 1
  1789. fi
  1790. #self signed
  1791. if ! _signcsr "$TLS_KEY" "$TLS_CSR" "$TLS_CONF" "$TLS_CERT"; then
  1792. _err "Create tls validation cert error."
  1793. return 1
  1794. fi
  1795. __S_OPENSSL="${ACME_OPENSSL_BIN:-openssl} s_server -www -cert $TLS_CERT -key $TLS_KEY "
  1796. if [ "$opaddr" ]; then
  1797. __S_OPENSSL="$__S_OPENSSL -accept $opaddr:$port"
  1798. else
  1799. __S_OPENSSL="$__S_OPENSSL -accept $port"
  1800. fi
  1801. _debug Le_Listen_V4 "$Le_Listen_V4"
  1802. _debug Le_Listen_V6 "$Le_Listen_V6"
  1803. if [ "$Le_Listen_V4" ]; then
  1804. __S_OPENSSL="$__S_OPENSSL -4"
  1805. elif [ "$Le_Listen_V6" ]; then
  1806. __S_OPENSSL="$__S_OPENSSL -6"
  1807. fi
  1808. _debug "$__S_OPENSSL"
  1809. if [ "$DEBUG" ] && [ "$DEBUG" -ge "2" ]; then
  1810. $__S_OPENSSL -tlsextdebug &
  1811. else
  1812. $__S_OPENSSL >/dev/null 2>&1 &
  1813. fi
  1814. serverproc="$!"
  1815. sleep 1
  1816. _debug serverproc "$serverproc"
  1817. }
  1818. #file
  1819. _readlink() {
  1820. _rf="$1"
  1821. if ! readlink -f "$_rf" 2>/dev/null; then
  1822. if _startswith "$_rf" "/"; then
  1823. echo "$_rf"
  1824. return 0
  1825. fi
  1826. echo "$(pwd)/$_rf" | _conapath
  1827. fi
  1828. }
  1829. _conapath() {
  1830. sed "s#/\./#/#g"
  1831. }
  1832. __initHome() {
  1833. if [ -z "$_SCRIPT_HOME" ]; then
  1834. if _exists readlink && _exists dirname; then
  1835. _debug "Lets find script dir."
  1836. _debug "_SCRIPT_" "$_SCRIPT_"
  1837. _script="$(_readlink "$_SCRIPT_")"
  1838. _debug "_script" "$_script"
  1839. _script_home="$(dirname "$_script")"
  1840. _debug "_script_home" "$_script_home"
  1841. if [ -d "$_script_home" ]; then
  1842. _SCRIPT_HOME="$_script_home"
  1843. else
  1844. _err "It seems the script home is not correct:$_script_home"
  1845. fi
  1846. fi
  1847. fi
  1848. # if [ -z "$LE_WORKING_DIR" ]; then
  1849. # if [ -f "$DEFAULT_INSTALL_HOME/account.conf" ]; then
  1850. # _debug "It seems that $PROJECT_NAME is already installed in $DEFAULT_INSTALL_HOME"
  1851. # LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1852. # else
  1853. # LE_WORKING_DIR="$_SCRIPT_HOME"
  1854. # fi
  1855. # fi
  1856. if [ -z "$LE_WORKING_DIR" ]; then
  1857. _debug "Using default home:$DEFAULT_INSTALL_HOME"
  1858. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  1859. fi
  1860. export LE_WORKING_DIR
  1861. if [ -z "$LE_CONFIG_HOME" ]; then
  1862. LE_CONFIG_HOME="$LE_WORKING_DIR"
  1863. fi
  1864. _debug "Using config home:$LE_CONFIG_HOME"
  1865. export LE_CONFIG_HOME
  1866. _DEFAULT_ACCOUNT_CONF_PATH="$LE_CONFIG_HOME/account.conf"
  1867. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1868. if [ -f "$_DEFAULT_ACCOUNT_CONF_PATH" ]; then
  1869. . "$_DEFAULT_ACCOUNT_CONF_PATH"
  1870. fi
  1871. fi
  1872. if [ -z "$ACCOUNT_CONF_PATH" ]; then
  1873. ACCOUNT_CONF_PATH="$_DEFAULT_ACCOUNT_CONF_PATH"
  1874. fi
  1875. DEFAULT_LOG_FILE="$LE_CONFIG_HOME/$PROJECT_NAME.log"
  1876. DEFAULT_CA_HOME="$LE_CONFIG_HOME/ca"
  1877. if [ -z "$LE_TEMP_DIR" ]; then
  1878. LE_TEMP_DIR="$LE_CONFIG_HOME/tmp"
  1879. fi
  1880. }
  1881. #server
  1882. _initAPI() {
  1883. _api_server="${1:-$ACME_DIRECTORY}"
  1884. _debug "_init api for server: $_api_server"
  1885. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1886. response=$(_get "$_api_server")
  1887. if [ "$?" != "0" ]; then
  1888. _debug2 "response" "$response"
  1889. _err "Can not init api."
  1890. return 1
  1891. fi
  1892. _debug2 "response" "$response"
  1893. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'key-change" *: *"[^"]*"' | cut -d '"' -f 3)
  1894. if [ -z "$ACME_KEY_CHANGE" ]; then
  1895. ACME_KEY_CHANGE=$(echo "$response" | _egrep_o 'keyChange" *: *"[^"]*"' | cut -d '"' -f 3)
  1896. fi
  1897. export ACME_KEY_CHANGE
  1898. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'new-authz" *: *"[^"]*"' | cut -d '"' -f 3)
  1899. if [ -z "$ACME_NEW_AUTHZ" ]; then
  1900. ACME_NEW_AUTHZ=$(echo "$response" | _egrep_o 'newAuthz" *: *"[^"]*"' | cut -d '"' -f 3)
  1901. fi
  1902. export ACME_NEW_AUTHZ
  1903. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  1904. ACME_NEW_ORDER_RES="new-cert"
  1905. if [ -z "$ACME_NEW_ORDER" ]; then
  1906. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'new-order" *: *"[^"]*"' | cut -d '"' -f 3)
  1907. ACME_NEW_ORDER_RES="new-order"
  1908. if [ -z "$ACME_NEW_ORDER" ]; then
  1909. ACME_NEW_ORDER=$(echo "$response" | _egrep_o 'newOrder" *: *"[^"]*"' | cut -d '"' -f 3)
  1910. fi
  1911. fi
  1912. export ACME_NEW_ORDER
  1913. export ACME_NEW_ORDER_RES
  1914. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-reg" *: *"[^"]*"' | cut -d '"' -f 3)
  1915. ACME_NEW_ACCOUNT_RES="new-reg"
  1916. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1917. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'new-account" *: *"[^"]*"' | cut -d '"' -f 3)
  1918. ACME_NEW_ACCOUNT_RES="new-account"
  1919. if [ -z "$ACME_NEW_ACCOUNT" ]; then
  1920. ACME_NEW_ACCOUNT=$(echo "$response" | _egrep_o 'newAccount" *: *"[^"]*"' | cut -d '"' -f 3)
  1921. if [ "$ACME_NEW_ACCOUNT" ]; then
  1922. export ACME_VERSION=2
  1923. fi
  1924. fi
  1925. fi
  1926. export ACME_NEW_ACCOUNT
  1927. export ACME_NEW_ACCOUNT_RES
  1928. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revoke-cert" *: *"[^"]*"' | cut -d '"' -f 3)
  1929. if [ -z "$ACME_REVOKE_CERT" ]; then
  1930. ACME_REVOKE_CERT=$(echo "$response" | _egrep_o 'revokeCert" *: *"[^"]*"' | cut -d '"' -f 3)
  1931. fi
  1932. export ACME_REVOKE_CERT
  1933. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'new-nonce" *: *"[^"]*"' | cut -d '"' -f 3)
  1934. if [ -z "$ACME_NEW_NONCE" ]; then
  1935. ACME_NEW_NONCE=$(echo "$response" | _egrep_o 'newNonce" *: *"[^"]*"' | cut -d '"' -f 3)
  1936. fi
  1937. export ACME_NEW_NONCE
  1938. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'terms-of-service" *: *"[^"]*"' | cut -d '"' -f 3)
  1939. if [ -z "$ACME_AGREEMENT" ]; then
  1940. ACME_AGREEMENT=$(echo "$response" | _egrep_o 'termsOfService" *: *"[^"]*"' | cut -d '"' -f 3)
  1941. fi
  1942. export ACME_AGREEMENT
  1943. _debug "ACME_KEY_CHANGE" "$ACME_KEY_CHANGE"
  1944. _debug "ACME_NEW_AUTHZ" "$ACME_NEW_AUTHZ"
  1945. _debug "ACME_NEW_ORDER" "$ACME_NEW_ORDER"
  1946. _debug "ACME_NEW_ACCOUNT" "$ACME_NEW_ACCOUNT"
  1947. _debug "ACME_REVOKE_CERT" "$ACME_REVOKE_CERT"
  1948. _debug "ACME_AGREEMENT" "$ACME_AGREEMENT"
  1949. _debug "ACME_NEW_NONCE" "$ACME_NEW_NONCE"
  1950. _debug "ACME_VERSION" "$ACME_VERSION"
  1951. fi
  1952. }
  1953. #[domain] [keylength or isEcc flag]
  1954. _initpath() {
  1955. __initHome
  1956. if [ -f "$ACCOUNT_CONF_PATH" ]; then
  1957. . "$ACCOUNT_CONF_PATH"
  1958. fi
  1959. if [ "$IN_CRON" ]; then
  1960. if [ ! "$_USER_PATH_EXPORTED" ]; then
  1961. _USER_PATH_EXPORTED=1
  1962. export PATH="$USER_PATH:$PATH"
  1963. fi
  1964. fi
  1965. if [ -z "$CA_HOME" ]; then
  1966. CA_HOME="$DEFAULT_CA_HOME"
  1967. fi
  1968. if [ "$ACME_VERSION" = "2" ]; then
  1969. DEFAULT_CA="$LETSENCRYPT_CA_V2"
  1970. DEFAULT_STAGING_CA="$LETSENCRYPT_STAGING_CA_V2"
  1971. fi
  1972. if [ -z "$ACME_DIRECTORY" ]; then
  1973. if [ -z "$STAGE" ]; then
  1974. ACME_DIRECTORY="$DEFAULT_CA"
  1975. else
  1976. ACME_DIRECTORY="$DEFAULT_STAGING_CA"
  1977. _info "Using stage ACME_DIRECTORY: $ACME_DIRECTORY"
  1978. fi
  1979. fi
  1980. _debug2 ACME_DIRECTORY "$ACME_DIRECTORY"
  1981. _ACME_SERVER_HOST="$(echo "$ACME_DIRECTORY" | cut -d : -f 2 | tr -s / | cut -d / -f 2)"
  1982. _debug2 "_ACME_SERVER_HOST" "$_ACME_SERVER_HOST"
  1983. CA_DIR="$CA_HOME/$_ACME_SERVER_HOST"
  1984. _DEFAULT_CA_CONF="$CA_DIR/ca.conf"
  1985. if [ -z "$CA_CONF" ]; then
  1986. CA_CONF="$_DEFAULT_CA_CONF"
  1987. fi
  1988. _debug3 CA_CONF "$CA_CONF"
  1989. if [ -f "$CA_CONF" ]; then
  1990. . "$CA_CONF"
  1991. fi
  1992. if [ -z "$ACME_DIR" ]; then
  1993. ACME_DIR="/home/.acme"
  1994. fi
  1995. if [ -z "$APACHE_CONF_BACKUP_DIR" ]; then
  1996. APACHE_CONF_BACKUP_DIR="$LE_CONFIG_HOME"
  1997. fi
  1998. if [ -z "$USER_AGENT" ]; then
  1999. USER_AGENT="$DEFAULT_USER_AGENT"
  2000. fi
  2001. if [ -z "$HTTP_HEADER" ]; then
  2002. HTTP_HEADER="$LE_CONFIG_HOME/http.header"
  2003. fi
  2004. _OLD_ACCOUNT_KEY="$LE_WORKING_DIR/account.key"
  2005. _OLD_ACCOUNT_JSON="$LE_WORKING_DIR/account.json"
  2006. _DEFAULT_ACCOUNT_KEY_PATH="$CA_DIR/account.key"
  2007. _DEFAULT_ACCOUNT_JSON_PATH="$CA_DIR/account.json"
  2008. if [ -z "$ACCOUNT_KEY_PATH" ]; then
  2009. ACCOUNT_KEY_PATH="$_DEFAULT_ACCOUNT_KEY_PATH"
  2010. fi
  2011. if [ -z "$ACCOUNT_JSON_PATH" ]; then
  2012. ACCOUNT_JSON_PATH="$_DEFAULT_ACCOUNT_JSON_PATH"
  2013. fi
  2014. _DEFAULT_CERT_HOME="$LE_CONFIG_HOME"
  2015. if [ -z "$CERT_HOME" ]; then
  2016. CERT_HOME="$_DEFAULT_CERT_HOME"
  2017. fi
  2018. if [ -z "$ACME_OPENSSL_BIN" ] || [ ! -f "$ACME_OPENSSL_BIN" ] || [ ! -x "$ACME_OPENSSL_BIN" ]; then
  2019. ACME_OPENSSL_BIN="$DEFAULT_OPENSSL_BIN"
  2020. fi
  2021. if [ -z "$1" ]; then
  2022. return 0
  2023. fi
  2024. domain="$1"
  2025. _ilength="$2"
  2026. if [ -z "$DOMAIN_PATH" ]; then
  2027. domainhome="$CERT_HOME/$domain"
  2028. domainhomeecc="$CERT_HOME/$domain$ECC_SUFFIX"
  2029. DOMAIN_PATH="$domainhome"
  2030. if _isEccKey "$_ilength"; then
  2031. DOMAIN_PATH="$domainhomeecc"
  2032. else
  2033. if [ ! -d "$domainhome" ] && [ -d "$domainhomeecc" ]; then
  2034. _info "The domain '$domain' seems to have a ECC cert already, please add '$(__red "--ecc")' parameter if you want to use that cert."
  2035. fi
  2036. fi
  2037. _debug DOMAIN_PATH "$DOMAIN_PATH"
  2038. fi
  2039. if [ -z "$DOMAIN_BACKUP_PATH" ]; then
  2040. DOMAIN_BACKUP_PATH="$DOMAIN_PATH/backup"
  2041. fi
  2042. if [ -z "$DOMAIN_CONF" ]; then
  2043. DOMAIN_CONF="$DOMAIN_PATH/$domain.conf"
  2044. fi
  2045. if [ -z "$DOMAIN_SSL_CONF" ]; then
  2046. DOMAIN_SSL_CONF="$DOMAIN_PATH/$domain.csr.conf"
  2047. fi
  2048. if [ -z "$CSR_PATH" ]; then
  2049. CSR_PATH="$DOMAIN_PATH/$domain.csr"
  2050. fi
  2051. if [ -z "$CERT_KEY_PATH" ]; then
  2052. CERT_KEY_PATH="$DOMAIN_PATH/$domain.key"
  2053. fi
  2054. if [ -z "$CERT_PATH" ]; then
  2055. CERT_PATH="$DOMAIN_PATH/$domain.cer"
  2056. fi
  2057. if [ -z "$CA_CERT_PATH" ]; then
  2058. CA_CERT_PATH="$DOMAIN_PATH/ca.cer"
  2059. fi
  2060. if [ -z "$CERT_FULLCHAIN_PATH" ]; then
  2061. CERT_FULLCHAIN_PATH="$DOMAIN_PATH/fullchain.cer"
  2062. fi
  2063. if [ -z "$CERT_PFX_PATH" ]; then
  2064. CERT_PFX_PATH="$DOMAIN_PATH/$domain.pfx"
  2065. fi
  2066. if [ -z "$CERT_PKCS8_PATH" ]; then
  2067. CERT_PKCS8_PATH="$DOMAIN_PATH/$domain.pkcs8"
  2068. fi
  2069. if [ -z "$TLS_CONF" ]; then
  2070. TLS_CONF="$DOMAIN_PATH/tls.validation.conf"
  2071. fi
  2072. if [ -z "$TLS_CERT" ]; then
  2073. TLS_CERT="$DOMAIN_PATH/tls.validation.cert"
  2074. fi
  2075. if [ -z "$TLS_KEY" ]; then
  2076. TLS_KEY="$DOMAIN_PATH/tls.validation.key"
  2077. fi
  2078. if [ -z "$TLS_CSR" ]; then
  2079. TLS_CSR="$DOMAIN_PATH/tls.validation.csr"
  2080. fi
  2081. }
  2082. _exec() {
  2083. if [ -z "$_EXEC_TEMP_ERR" ]; then
  2084. _EXEC_TEMP_ERR="$(_mktemp)"
  2085. fi
  2086. if [ "$_EXEC_TEMP_ERR" ]; then
  2087. eval "$@ 2>>$_EXEC_TEMP_ERR"
  2088. else
  2089. eval "$@"
  2090. fi
  2091. }
  2092. _exec_err() {
  2093. [ "$_EXEC_TEMP_ERR" ] && _err "$(cat "$_EXEC_TEMP_ERR")" && echo "" >"$_EXEC_TEMP_ERR"
  2094. }
  2095. _apachePath() {
  2096. _APACHECTL="apachectl"
  2097. if ! _exists apachectl; then
  2098. if _exists apache2ctl; then
  2099. _APACHECTL="apache2ctl"
  2100. else
  2101. _err "'apachectl not found. It seems that apache is not installed, or you are not root user.'"
  2102. _err "Please use webroot mode to try again."
  2103. return 1
  2104. fi
  2105. fi
  2106. if ! _exec $_APACHECTL -V >/dev/null; then
  2107. _exec_err
  2108. return 1
  2109. fi
  2110. if [ "$APACHE_HTTPD_CONF" ]; then
  2111. _saveaccountconf APACHE_HTTPD_CONF "$APACHE_HTTPD_CONF"
  2112. httpdconf="$APACHE_HTTPD_CONF"
  2113. httpdconfname="$(basename "$httpdconfname")"
  2114. else
  2115. httpdconfname="$($_APACHECTL -V | grep SERVER_CONFIG_FILE= | cut -d = -f 2 | tr -d '"')"
  2116. _debug httpdconfname "$httpdconfname"
  2117. if [ -z "$httpdconfname" ]; then
  2118. _err "Can not read apache config file."
  2119. return 1
  2120. fi
  2121. if _startswith "$httpdconfname" '/'; then
  2122. httpdconf="$httpdconfname"
  2123. httpdconfname="$(basename "$httpdconfname")"
  2124. else
  2125. httpdroot="$($_APACHECTL -V | grep HTTPD_ROOT= | cut -d = -f 2 | tr -d '"')"
  2126. _debug httpdroot "$httpdroot"
  2127. httpdconf="$httpdroot/$httpdconfname"
  2128. httpdconfname="$(basename "$httpdconfname")"
  2129. fi
  2130. fi
  2131. _debug httpdconf "$httpdconf"
  2132. _debug httpdconfname "$httpdconfname"
  2133. if [ ! -f "$httpdconf" ]; then
  2134. _err "Apache Config file not found" "$httpdconf"
  2135. return 1
  2136. fi
  2137. return 0
  2138. }
  2139. _restoreApache() {
  2140. if [ -z "$usingApache" ]; then
  2141. return 0
  2142. fi
  2143. _initpath
  2144. if ! _apachePath; then
  2145. return 1
  2146. fi
  2147. if [ ! -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname" ]; then
  2148. _debug "No config file to restore."
  2149. return 0
  2150. fi
  2151. cat "$APACHE_CONF_BACKUP_DIR/$httpdconfname" >"$httpdconf"
  2152. _debug "Restored: $httpdconf."
  2153. if ! _exec $_APACHECTL -t; then
  2154. _exec_err
  2155. _err "Sorry, restore apache config error, please contact me."
  2156. return 1
  2157. fi
  2158. _debug "Restored successfully."
  2159. rm -f "$APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2160. return 0
  2161. }
  2162. _setApache() {
  2163. _initpath
  2164. if ! _apachePath; then
  2165. return 1
  2166. fi
  2167. #test the conf first
  2168. _info "Checking if there is an error in the apache config file before starting."
  2169. if ! _exec "$_APACHECTL" -t >/dev/null; then
  2170. _exec_err
  2171. _err "The apache config file has error, please fix it first, then try again."
  2172. _err "Don't worry, there is nothing changed to your system."
  2173. return 1
  2174. else
  2175. _info "OK"
  2176. fi
  2177. #backup the conf
  2178. _debug "Backup apache config file" "$httpdconf"
  2179. if ! cp "$httpdconf" "$APACHE_CONF_BACKUP_DIR/"; then
  2180. _err "Can not backup apache config file, so abort. Don't worry, the apache config is not changed."
  2181. _err "This might be a bug of $PROJECT_NAME , please report issue: $PROJECT"
  2182. return 1
  2183. fi
  2184. _info "JFYI, Config file $httpdconf is backuped to $APACHE_CONF_BACKUP_DIR/$httpdconfname"
  2185. _info "In case there is an error that can not be restored automatically, you may try restore it yourself."
  2186. _info "The backup file will be deleted on success, just forget it."
  2187. #add alias
  2188. apacheVer="$($_APACHECTL -V | grep "Server version:" | cut -d : -f 2 | cut -d " " -f 2 | cut -d '/' -f 2)"
  2189. _debug "apacheVer" "$apacheVer"
  2190. apacheMajer="$(echo "$apacheVer" | cut -d . -f 1)"
  2191. apacheMinor="$(echo "$apacheVer" | cut -d . -f 2)"
  2192. if [ "$apacheVer" ] && [ "$apacheMajer$apacheMinor" -ge "24" ]; then
  2193. echo "
  2194. Alias /.well-known/acme-challenge $ACME_DIR
  2195. <Directory $ACME_DIR >
  2196. Require all granted
  2197. </Directory>
  2198. " >>"$httpdconf"
  2199. else
  2200. echo "
  2201. Alias /.well-known/acme-challenge $ACME_DIR
  2202. <Directory $ACME_DIR >
  2203. Order allow,deny
  2204. Allow from all
  2205. </Directory>
  2206. " >>"$httpdconf"
  2207. fi
  2208. _msg="$($_APACHECTL -t 2>&1)"
  2209. if [ "$?" != "0" ]; then
  2210. _err "Sorry, apache config error"
  2211. if _restoreApache; then
  2212. _err "The apache config file is restored."
  2213. else
  2214. _err "Sorry, The apache config file can not be restored, please report bug."
  2215. fi
  2216. return 1
  2217. fi
  2218. if [ ! -d "$ACME_DIR" ]; then
  2219. mkdir -p "$ACME_DIR"
  2220. chmod 755 "$ACME_DIR"
  2221. fi
  2222. if ! _exec "$_APACHECTL" graceful; then
  2223. _exec_err
  2224. _err "$_APACHECTL graceful error, please contact me."
  2225. _restoreApache
  2226. return 1
  2227. fi
  2228. usingApache="1"
  2229. return 0
  2230. }
  2231. #find the real nginx conf file
  2232. #backup
  2233. #set the nginx conf
  2234. #returns the real nginx conf file
  2235. _setNginx() {
  2236. _d="$1"
  2237. _croot="$2"
  2238. _thumbpt="$3"
  2239. if ! _exists "nginx"; then
  2240. _err "nginx command is not found."
  2241. return 1
  2242. fi
  2243. FOUND_REAL_NGINX_CONF=""
  2244. FOUND_REAL_NGINX_CONF_LN=""
  2245. BACKUP_NGINX_CONF=""
  2246. _debug _croot "$_croot"
  2247. _start_f="$(echo "$_croot" | cut -d : -f 2)"
  2248. _debug _start_f "$_start_f"
  2249. if [ -z "$_start_f" ]; then
  2250. _debug "find start conf from nginx command"
  2251. if [ -z "$NGINX_CONF" ]; then
  2252. NGINX_CONF="$(nginx -V 2>&1 | _egrep_o "--conf-path=[^ ]* " | tr -d " ")"
  2253. _debug NGINX_CONF "$NGINX_CONF"
  2254. NGINX_CONF="$(echo "$NGINX_CONF" | cut -d = -f 2)"
  2255. _debug NGINX_CONF "$NGINX_CONF"
  2256. if [ ! -f "$NGINX_CONF" ]; then
  2257. _err "'$NGINX_CONF' doesn't exist."
  2258. NGINX_CONF=""
  2259. return 1
  2260. fi
  2261. _debug "Found nginx conf file:$NGINX_CONF"
  2262. fi
  2263. _start_f="$NGINX_CONF"
  2264. fi
  2265. _debug "Start detect nginx conf for $_d from:$_start_f"
  2266. if ! _checkConf "$_d" "$_start_f"; then
  2267. _err "Can not find conf file for domain $d"
  2268. return 1
  2269. fi
  2270. _info "Found conf file: $FOUND_REAL_NGINX_CONF"
  2271. _ln=$FOUND_REAL_NGINX_CONF_LN
  2272. _debug "_ln" "$_ln"
  2273. _lnn=$(_math $_ln + 1)
  2274. _debug _lnn "$_lnn"
  2275. _start_tag="$(sed -n "$_lnn,${_lnn}p" "$FOUND_REAL_NGINX_CONF")"
  2276. _debug "_start_tag" "$_start_tag"
  2277. if [ "$_start_tag" = "$NGINX_START" ]; then
  2278. _info "The domain $_d is already configured, skip"
  2279. FOUND_REAL_NGINX_CONF=""
  2280. return 0
  2281. fi
  2282. mkdir -p "$DOMAIN_BACKUP_PATH"
  2283. _backup_conf="$DOMAIN_BACKUP_PATH/$_d.nginx.conf"
  2284. _debug _backup_conf "$_backup_conf"
  2285. BACKUP_NGINX_CONF="$_backup_conf"
  2286. _info "Backup $FOUND_REAL_NGINX_CONF to $_backup_conf"
  2287. if ! cp "$FOUND_REAL_NGINX_CONF" "$_backup_conf"; then
  2288. _err "backup error."
  2289. FOUND_REAL_NGINX_CONF=""
  2290. return 1
  2291. fi
  2292. _info "Check the nginx conf before setting up."
  2293. if ! _exec "nginx -t" >/dev/null; then
  2294. _exec_err
  2295. return 1
  2296. fi
  2297. _info "OK, Set up nginx config file"
  2298. if ! sed -n "1,${_ln}p" "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"; then
  2299. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2300. _err "write nginx conf error, but don't worry, the file is restored to the original version."
  2301. return 1
  2302. fi
  2303. echo "$NGINX_START
  2304. location ~ \"^/\.well-known/acme-challenge/([-_a-zA-Z0-9]+)\$\" {
  2305. default_type text/plain;
  2306. return 200 \"\$1.$_thumbpt\";
  2307. }
  2308. #NGINX_START
  2309. " >>"$FOUND_REAL_NGINX_CONF"
  2310. if ! sed -n "${_lnn},99999p" "$_backup_conf" >>"$FOUND_REAL_NGINX_CONF"; then
  2311. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2312. _err "write nginx conf error, but don't worry, the file is restored."
  2313. return 1
  2314. fi
  2315. _debug3 "Modified config:$(cat $FOUND_REAL_NGINX_CONF)"
  2316. _info "nginx conf is done, let's check it again."
  2317. if ! _exec "nginx -t" >/dev/null; then
  2318. _exec_err
  2319. _err "It seems that nginx conf was broken, let's restore."
  2320. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2321. return 1
  2322. fi
  2323. _info "Reload nginx"
  2324. if ! _exec "nginx -s reload" >/dev/null; then
  2325. _exec_err
  2326. _err "It seems that nginx reload error, let's restore."
  2327. cat "$_backup_conf" >"$FOUND_REAL_NGINX_CONF"
  2328. return 1
  2329. fi
  2330. return 0
  2331. }
  2332. #d , conf
  2333. _checkConf() {
  2334. _d="$1"
  2335. _c_file="$2"
  2336. _debug "Start _checkConf from:$_c_file"
  2337. if [ ! -f "$2" ] && ! echo "$2" | grep '*$' >/dev/null && echo "$2" | grep '*' >/dev/null; then
  2338. _debug "wildcard"
  2339. for _w_f in $2; do
  2340. if [ -f "$_w_f" ] && _checkConf "$1" "$_w_f"; then
  2341. return 0
  2342. fi
  2343. done
  2344. #not found
  2345. return 1
  2346. elif [ -f "$2" ]; then
  2347. _debug "single"
  2348. if _isRealNginxConf "$1" "$2"; then
  2349. _debug "$2 is found."
  2350. FOUND_REAL_NGINX_CONF="$2"
  2351. return 0
  2352. fi
  2353. if cat "$2" | tr "\t" " " | grep "^ *include *.*;" >/dev/null; then
  2354. _debug "Try include files"
  2355. for included in $(cat "$2" | tr "\t" " " | grep "^ *include *.*;" | sed "s/include //" | tr -d " ;"); do
  2356. _debug "check included $included"
  2357. if _checkConf "$1" "$included"; then
  2358. return 0
  2359. fi
  2360. done
  2361. fi
  2362. return 1
  2363. else
  2364. _debug "$2 not found."
  2365. return 1
  2366. fi
  2367. return 1
  2368. }
  2369. #d , conf
  2370. _isRealNginxConf() {
  2371. _debug "_isRealNginxConf $1 $2"
  2372. if [ -f "$2" ]; then
  2373. for _fln in $(tr "\t" ' ' <"$2" | grep -n "^ *server_name.* $1" | cut -d : -f 1); do
  2374. _debug _fln "$_fln"
  2375. if [ "$_fln" ]; then
  2376. _start=$(tr "\t" ' ' <"$2" | _head_n "$_fln" | grep -n "^ *server *{" | _tail_n 1)
  2377. _debug "_start" "$_start"
  2378. _start_n=$(echo "$_start" | cut -d : -f 1)
  2379. _start_nn=$(_math $_start_n + 1)
  2380. _debug "_start_n" "$_start_n"
  2381. _debug "_start_nn" "$_start_nn"
  2382. _left="$(sed -n "${_start_nn},99999p" "$2")"
  2383. _debug2 _left "$_left"
  2384. if echo "$_left" | tr "\t" ' ' | grep -n "^ *server *{" >/dev/null; then
  2385. _end=$(echo "$_left" | tr "\t" ' ' | grep -n "^ *server *{" | _head_n 1)
  2386. _debug "_end" "$_end"
  2387. _end_n=$(echo "$_end" | cut -d : -f 1)
  2388. _debug "_end_n" "$_end_n"
  2389. _seg_n=$(echo "$_left" | sed -n "1,${_end_n}p")
  2390. else
  2391. _seg_n="$_left"
  2392. fi
  2393. _debug "_seg_n" "$_seg_n"
  2394. if [ "$(echo "$_seg_n" | _egrep_o "^ *ssl *on *;")" ] \
  2395. || [ "$(echo "$_seg_n" | _egrep_o "listen .* ssl[ |;]")" ]; then
  2396. _debug "ssl on, skip"
  2397. else
  2398. FOUND_REAL_NGINX_CONF_LN=$_fln
  2399. _debug3 "found FOUND_REAL_NGINX_CONF_LN" "$FOUND_REAL_NGINX_CONF_LN"
  2400. return 0
  2401. fi
  2402. fi
  2403. done
  2404. fi
  2405. return 1
  2406. }
  2407. #restore all the nginx conf
  2408. _restoreNginx() {
  2409. if [ -z "$NGINX_RESTORE_VLIST" ]; then
  2410. _debug "No need to restore nginx, skip."
  2411. return
  2412. fi
  2413. _debug "_restoreNginx"
  2414. _debug "NGINX_RESTORE_VLIST" "$NGINX_RESTORE_VLIST"
  2415. for ng_entry in $(echo "$NGINX_RESTORE_VLIST" | tr "$dvsep" ' '); do
  2416. _debug "ng_entry" "$ng_entry"
  2417. _nd=$(echo "$ng_entry" | cut -d "$sep" -f 1)
  2418. _ngconf=$(echo "$ng_entry" | cut -d "$sep" -f 2)
  2419. _ngbackupconf=$(echo "$ng_entry" | cut -d "$sep" -f 3)
  2420. _info "Restoring from $_ngbackupconf to $_ngconf"
  2421. cat "$_ngbackupconf" >"$_ngconf"
  2422. done
  2423. _info "Reload nginx"
  2424. if ! _exec "nginx -s reload" >/dev/null; then
  2425. _exec_err
  2426. _err "It seems that nginx reload error, please report bug."
  2427. return 1
  2428. fi
  2429. return 0
  2430. }
  2431. _clearup() {
  2432. _stopserver "$serverproc"
  2433. serverproc=""
  2434. _restoreApache
  2435. _restoreNginx
  2436. _clearupdns
  2437. if [ -z "$DEBUG" ]; then
  2438. rm -f "$TLS_CONF"
  2439. rm -f "$TLS_CERT"
  2440. rm -f "$TLS_KEY"
  2441. rm -f "$TLS_CSR"
  2442. fi
  2443. }
  2444. _clearupdns() {
  2445. _debug "_clearupdns"
  2446. if [ "$dnsadded" != 1 ] || [ -z "$vlist" ]; then
  2447. _debug "skip dns."
  2448. return
  2449. fi
  2450. ventries=$(echo "$vlist" | tr ',' ' ')
  2451. for ventry in $ventries; do
  2452. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2453. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2454. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2455. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2456. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  2457. _debug txt "$txt"
  2458. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  2459. _debug "$d is already verified, skip $vtype."
  2460. continue
  2461. fi
  2462. if [ "$vtype" != "$VTYPE_DNS" ]; then
  2463. _info "Skip $d for $vtype"
  2464. continue
  2465. fi
  2466. d_api="$(_findHook "$d" dnsapi "$_currentRoot")"
  2467. _debug d_api "$d_api"
  2468. if [ -z "$d_api" ]; then
  2469. _info "Not Found domain api file: $d_api"
  2470. continue
  2471. fi
  2472. (
  2473. if ! . "$d_api"; then
  2474. _err "Load file $d_api error. Please check your api file and try again."
  2475. return 1
  2476. fi
  2477. rmcommand="${_currentRoot}_rm"
  2478. if ! _exists "$rmcommand"; then
  2479. _err "It seems that your api file doesn't define $rmcommand"
  2480. return 1
  2481. fi
  2482. _dns_root_d="$d"
  2483. if _startswith "$_dns_root_d" "*."; then
  2484. _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
  2485. fi
  2486. txtdomain="_acme-challenge.$_dns_root_d"
  2487. if ! $rmcommand "$txtdomain" "$txt"; then
  2488. _err "Error removing txt for domain:$txtdomain"
  2489. return 1
  2490. fi
  2491. )
  2492. done
  2493. }
  2494. # webroot removelevel tokenfile
  2495. _clearupwebbroot() {
  2496. __webroot="$1"
  2497. if [ -z "$__webroot" ]; then
  2498. _debug "no webroot specified, skip"
  2499. return 0
  2500. fi
  2501. _rmpath=""
  2502. if [ "$2" = '1' ]; then
  2503. _rmpath="$__webroot/.well-known"
  2504. elif [ "$2" = '2' ]; then
  2505. _rmpath="$__webroot/.well-known/acme-challenge"
  2506. elif [ "$2" = '3' ]; then
  2507. _rmpath="$__webroot/.well-known/acme-challenge/$3"
  2508. else
  2509. _debug "Skip for removelevel:$2"
  2510. fi
  2511. if [ "$_rmpath" ]; then
  2512. if [ "$DEBUG" ]; then
  2513. _debug "Debugging, skip removing: $_rmpath"
  2514. else
  2515. rm -rf "$_rmpath"
  2516. fi
  2517. fi
  2518. return 0
  2519. }
  2520. _on_before_issue() {
  2521. _chk_web_roots="$1"
  2522. _chk_main_domain="$2"
  2523. _chk_alt_domains="$3"
  2524. _chk_pre_hook="$4"
  2525. _chk_local_addr="$5"
  2526. _debug _on_before_issue
  2527. #run pre hook
  2528. if [ "$_chk_pre_hook" ]; then
  2529. _info "Run pre hook:'$_chk_pre_hook'"
  2530. if ! (
  2531. cd "$DOMAIN_PATH" && eval "$_chk_pre_hook"
  2532. ); then
  2533. _err "Error when run pre hook."
  2534. return 1
  2535. fi
  2536. fi
  2537. if _hasfield "$_chk_web_roots" "$NO_VALUE"; then
  2538. if ! _exists "socat"; then
  2539. _err "Please install socat tools first."
  2540. return 1
  2541. fi
  2542. fi
  2543. _debug Le_LocalAddress "$_chk_local_addr"
  2544. alldomains=$(echo "$_chk_main_domain,$_chk_alt_domains" | tr ',' ' ')
  2545. _index=1
  2546. _currentRoot=""
  2547. _addrIndex=1
  2548. for d in $alldomains; do
  2549. _debug "Check for domain" "$d"
  2550. _currentRoot="$(_getfield "$_chk_web_roots" $_index)"
  2551. _debug "_currentRoot" "$_currentRoot"
  2552. _index=$(_math $_index + 1)
  2553. _checkport=""
  2554. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  2555. _info "Standalone mode."
  2556. if [ -z "$Le_HTTPPort" ]; then
  2557. Le_HTTPPort=80
  2558. else
  2559. _savedomainconf "Le_HTTPPort" "$Le_HTTPPort"
  2560. fi
  2561. _checkport="$Le_HTTPPort"
  2562. elif [ "$_currentRoot" = "$W_TLS" ]; then
  2563. _info "Standalone tls mode."
  2564. if [ -z "$Le_TLSPort" ]; then
  2565. Le_TLSPort=443
  2566. else
  2567. _savedomainconf "Le_TLSPort" "$Le_TLSPort"
  2568. fi
  2569. _checkport="$Le_TLSPort"
  2570. fi
  2571. if [ "$_checkport" ]; then
  2572. _debug _checkport "$_checkport"
  2573. _checkaddr="$(_getfield "$_chk_local_addr" $_addrIndex)"
  2574. _debug _checkaddr "$_checkaddr"
  2575. _addrIndex="$(_math $_addrIndex + 1)"
  2576. _netprc="$(_ss "$_checkport" | grep "$_checkport")"
  2577. netprc="$(echo "$_netprc" | grep "$_checkaddr")"
  2578. if [ -z "$netprc" ]; then
  2579. netprc="$(echo "$_netprc" | grep "$LOCAL_ANY_ADDRESS")"
  2580. fi
  2581. if [ "$netprc" ]; then
  2582. _err "$netprc"
  2583. _err "tcp port $_checkport is already used by $(echo "$netprc" | cut -d : -f 4)"
  2584. _err "Please stop it first"
  2585. return 1
  2586. fi
  2587. fi
  2588. done
  2589. if _hasfield "$_chk_web_roots" "apache"; then
  2590. if ! _setApache; then
  2591. _err "set up apache error. Report error to me."
  2592. return 1
  2593. fi
  2594. else
  2595. usingApache=""
  2596. fi
  2597. }
  2598. _on_issue_err() {
  2599. _chk_post_hook="$1"
  2600. _chk_vlist="$2"
  2601. _debug _on_issue_err
  2602. _cleardomainconf "Le_OrderFinalize"
  2603. if [ "$LOG_FILE" ]; then
  2604. _err "Please check log file for more details: $LOG_FILE"
  2605. else
  2606. _err "Please add '--debug' or '--log' to check more details."
  2607. _err "See: $_DEBUG_WIKI"
  2608. fi
  2609. #run the post hook
  2610. if [ "$_chk_post_hook" ]; then
  2611. _info "Run post hook:'$_chk_post_hook'"
  2612. if ! (
  2613. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2614. ); then
  2615. _err "Error when run post hook."
  2616. return 1
  2617. fi
  2618. fi
  2619. #trigger the validation to flush the pending authz
  2620. _debug2 "_chk_vlist" "$_chk_vlist"
  2621. if [ "$_chk_vlist" ]; then
  2622. (
  2623. _debug2 "start to deactivate authz"
  2624. ventries=$(echo "$_chk_vlist" | tr "$dvsep" ' ')
  2625. for ventry in $ventries; do
  2626. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  2627. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  2628. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  2629. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  2630. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  2631. __trigger_validation "$uri" "$keyauthorization"
  2632. done
  2633. )
  2634. fi
  2635. if [ "$IS_RENEW" = "1" ] && _hasfield "$Le_Webroot" "dns"; then
  2636. _err "$_DNS_MANUAL_ERR"
  2637. fi
  2638. if [ "$DEBUG" ] && [ "$DEBUG" -gt "0" ]; then
  2639. _debug "$(_dlg_versions)"
  2640. fi
  2641. }
  2642. _on_issue_success() {
  2643. _chk_post_hook="$1"
  2644. _chk_renew_hook="$2"
  2645. _debug _on_issue_success
  2646. #run the post hook
  2647. if [ "$_chk_post_hook" ]; then
  2648. _info "Run post hook:'$_chk_post_hook'"
  2649. if ! (
  2650. cd "$DOMAIN_PATH" && eval "$_chk_post_hook"
  2651. ); then
  2652. _err "Error when run post hook."
  2653. return 1
  2654. fi
  2655. fi
  2656. #run renew hook
  2657. if [ "$IS_RENEW" ] && [ "$_chk_renew_hook" ]; then
  2658. _info "Run renew hook:'$_chk_renew_hook'"
  2659. if ! (
  2660. cd "$DOMAIN_PATH" && eval "$_chk_renew_hook"
  2661. ); then
  2662. _err "Error when run renew hook."
  2663. return 1
  2664. fi
  2665. fi
  2666. if _hasfield "$Le_Webroot" "dns"; then
  2667. _err "$_DNS_MANUAL_WARN"
  2668. fi
  2669. }
  2670. updateaccount() {
  2671. _initpath
  2672. _regAccount
  2673. }
  2674. registeraccount() {
  2675. _reg_length="$1"
  2676. _initpath
  2677. _regAccount "$_reg_length"
  2678. }
  2679. __calcAccountKeyHash() {
  2680. [ -f "$ACCOUNT_KEY_PATH" ] && _digest sha256 <"$ACCOUNT_KEY_PATH"
  2681. }
  2682. __calc_account_thumbprint() {
  2683. printf "%s" "$jwk" | tr -d ' ' | _digest "sha256" | _url_replace
  2684. }
  2685. #keylength
  2686. _regAccount() {
  2687. _initpath
  2688. _reg_length="$1"
  2689. _debug3 _regAccount "$_regAccount"
  2690. _initAPI
  2691. mkdir -p "$CA_DIR"
  2692. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2693. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2694. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2695. fi
  2696. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2697. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2698. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2699. fi
  2700. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2701. if ! _create_account_key "$_reg_length"; then
  2702. _err "Create account key error."
  2703. return 1
  2704. fi
  2705. fi
  2706. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2707. return 1
  2708. fi
  2709. if [ "$ACME_VERSION" = "2" ]; then
  2710. regjson='{"termsOfServiceAgreed": true}'
  2711. if [ "$ACCOUNT_EMAIL" ]; then
  2712. regjson='{"contact": ["mailto: '$ACCOUNT_EMAIL'"], "termsOfServiceAgreed": true}'
  2713. fi
  2714. else
  2715. _reg_res="$ACME_NEW_ACCOUNT_RES"
  2716. regjson='{"resource": "'$_reg_res'", "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2717. if [ "$ACCOUNT_EMAIL" ]; then
  2718. regjson='{"resource": "'$_reg_res'", "contact": ["mailto: '$ACCOUNT_EMAIL'"], "terms-of-service-agreed": true, "agreement": "'$ACME_AGREEMENT'"}'
  2719. fi
  2720. fi
  2721. _info "Registering account"
  2722. if ! _send_signed_request "${ACME_NEW_ACCOUNT}" "$regjson"; then
  2723. _err "Register account Error: $response"
  2724. return 1
  2725. fi
  2726. if [ "$code" = "" ] || [ "$code" = '201' ]; then
  2727. echo "$response" >"$ACCOUNT_JSON_PATH"
  2728. _info "Registered"
  2729. elif [ "$code" = '409' ]; then
  2730. _info "Already registered"
  2731. else
  2732. _err "Register account Error: $response"
  2733. return 1
  2734. fi
  2735. _accUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  2736. _debug "_accUri" "$_accUri"
  2737. _savecaconf "ACCOUNT_URL" "$_accUri"
  2738. export ACCOUNT_URL="$ACCOUNT_URL"
  2739. CA_KEY_HASH="$(__calcAccountKeyHash)"
  2740. _debug "Calc CA_KEY_HASH" "$CA_KEY_HASH"
  2741. _savecaconf CA_KEY_HASH "$CA_KEY_HASH"
  2742. if [ "$code" = '403' ]; then
  2743. _err "It seems that the account key is already deactivated, please use a new account key."
  2744. return 1
  2745. fi
  2746. ACCOUNT_THUMBPRINT="$(__calc_account_thumbprint)"
  2747. _info "ACCOUNT_THUMBPRINT" "$ACCOUNT_THUMBPRINT"
  2748. }
  2749. #Implement deactivate account
  2750. deactivateaccount() {
  2751. _initpath
  2752. if [ ! -f "$ACCOUNT_KEY_PATH" ] && [ -f "$_OLD_ACCOUNT_KEY" ]; then
  2753. _info "mv $_OLD_ACCOUNT_KEY to $ACCOUNT_KEY_PATH"
  2754. mv "$_OLD_ACCOUNT_KEY" "$ACCOUNT_KEY_PATH"
  2755. fi
  2756. if [ ! -f "$ACCOUNT_JSON_PATH" ] && [ -f "$_OLD_ACCOUNT_JSON" ]; then
  2757. _info "mv $_OLD_ACCOUNT_JSON to $ACCOUNT_JSON_PATH"
  2758. mv "$_OLD_ACCOUNT_JSON" "$ACCOUNT_JSON_PATH"
  2759. fi
  2760. if [ ! -f "$ACCOUNT_KEY_PATH" ]; then
  2761. _err "Account key is not found at: $ACCOUNT_KEY_PATH"
  2762. return 1
  2763. fi
  2764. _accUri=$(_readcaconf "ACCOUNT_URL")
  2765. _debug _accUri "$_accUri"
  2766. if [ -z "$_accUri" ]; then
  2767. _err "The account url is empty, please run '--update-account' first to update the account info first,"
  2768. _err "Then try again."
  2769. return 1
  2770. fi
  2771. if ! _calcjwk "$ACCOUNT_KEY_PATH"; then
  2772. return 1
  2773. fi
  2774. _initAPI
  2775. if [ "$ACME_VERSION" = "2" ]; then
  2776. _djson="{\"status\":\"deactivated\"}"
  2777. else
  2778. _djson="{\"resource\": \"reg\", \"status\":\"deactivated\"}"
  2779. fi
  2780. if _send_signed_request "$_accUri" "$_djson" && _contains "$response" '"deactivated"'; then
  2781. _info "Deactivate account success for $_accUri."
  2782. _accid=$(echo "$response" | _egrep_o "\"id\" *: *[^,]*," | cut -d : -f 2 | tr -d ' ,')
  2783. elif [ "$code" = "403" ]; then
  2784. _info "The account is already deactivated."
  2785. _accid=$(_getfield "$_accUri" "999" "/")
  2786. else
  2787. _err "Deactivate: account failed for $_accUri."
  2788. return 1
  2789. fi
  2790. _debug "Account id: $_accid"
  2791. if [ "$_accid" ]; then
  2792. _deactivated_account_path="$CA_DIR/deactivated/$_accid"
  2793. _debug _deactivated_account_path "$_deactivated_account_path"
  2794. if mkdir -p "$_deactivated_account_path"; then
  2795. _info "Moving deactivated account info to $_deactivated_account_path/"
  2796. mv "$CA_CONF" "$_deactivated_account_path/"
  2797. mv "$ACCOUNT_JSON_PATH" "$_deactivated_account_path/"
  2798. mv "$ACCOUNT_KEY_PATH" "$_deactivated_account_path/"
  2799. else
  2800. _err "Can not create dir: $_deactivated_account_path, try to remove the deactivated account key."
  2801. rm -f "$CA_CONF"
  2802. rm -f "$ACCOUNT_JSON_PATH"
  2803. rm -f "$ACCOUNT_KEY_PATH"
  2804. fi
  2805. fi
  2806. }
  2807. # domain folder file
  2808. _findHook() {
  2809. _hookdomain="$1"
  2810. _hookcat="$2"
  2811. _hookname="$3"
  2812. if [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname" ]; then
  2813. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname"
  2814. elif [ -f "$_SCRIPT_HOME/$_hookcat/$_hookname.sh" ]; then
  2815. d_api="$_SCRIPT_HOME/$_hookcat/$_hookname.sh"
  2816. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname" ]; then
  2817. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname"
  2818. elif [ -f "$LE_WORKING_DIR/$_hookdomain/$_hookname.sh" ]; then
  2819. d_api="$LE_WORKING_DIR/$_hookdomain/$_hookname.sh"
  2820. elif [ -f "$LE_WORKING_DIR/$_hookname" ]; then
  2821. d_api="$LE_WORKING_DIR/$_hookname"
  2822. elif [ -f "$LE_WORKING_DIR/$_hookname.sh" ]; then
  2823. d_api="$LE_WORKING_DIR/$_hookname.sh"
  2824. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname" ]; then
  2825. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname"
  2826. elif [ -f "$LE_WORKING_DIR/$_hookcat/$_hookname.sh" ]; then
  2827. d_api="$LE_WORKING_DIR/$_hookcat/$_hookname.sh"
  2828. fi
  2829. printf "%s" "$d_api"
  2830. }
  2831. #domain
  2832. __get_domain_new_authz() {
  2833. _gdnd="$1"
  2834. _info "Getting new-authz for domain" "$_gdnd"
  2835. _initAPI
  2836. _Max_new_authz_retry_times=5
  2837. _authz_i=0
  2838. while [ "$_authz_i" -lt "$_Max_new_authz_retry_times" ]; do
  2839. _debug "Try new-authz for the $_authz_i time."
  2840. if ! _send_signed_request "${ACME_NEW_AUTHZ}" "{\"resource\": \"new-authz\", \"identifier\": {\"type\": \"dns\", \"value\": \"$(_idn "$_gdnd")\"}}"; then
  2841. _err "Can not get domain new authz."
  2842. return 1
  2843. fi
  2844. if _contains "$response" "No registration exists matching provided key"; then
  2845. _err "It seems there is an error, but it's recovered now, please try again."
  2846. _err "If you see this message for a second time, please report bug: $(__green "$PROJECT")"
  2847. _clearcaconf "CA_KEY_HASH"
  2848. break
  2849. fi
  2850. if ! _contains "$response" "An error occurred while processing your request"; then
  2851. _info "The new-authz request is ok."
  2852. break
  2853. fi
  2854. _authz_i="$(_math "$_authz_i" + 1)"
  2855. _info "The server is busy, Sleep $_authz_i to retry."
  2856. _sleep "$_authz_i"
  2857. done
  2858. if [ "$_authz_i" = "$_Max_new_authz_retry_times" ]; then
  2859. _err "new-authz retry reach the max $_Max_new_authz_retry_times times."
  2860. fi
  2861. if [ ! -z "$code" ] && [ ! "$code" = '201' ]; then
  2862. _err "new-authz error: $response"
  2863. return 1
  2864. fi
  2865. }
  2866. #uri keyAuthorization
  2867. __trigger_validation() {
  2868. _debug2 "tigger domain validation."
  2869. _t_url="$1"
  2870. _debug2 _t_url "$_t_url"
  2871. _t_key_authz="$2"
  2872. _debug2 _t_key_authz "$_t_key_authz"
  2873. if [ "$ACME_VERSION" = "2" ]; then
  2874. _send_signed_request "$_t_url" "{\"keyAuthorization\": \"$_t_key_authz\"}"
  2875. else
  2876. _send_signed_request "$_t_url" "{\"resource\": \"challenge\", \"keyAuthorization\": \"$_t_key_authz\"}"
  2877. fi
  2878. }
  2879. #webroot, domain domainlist keylength
  2880. issue() {
  2881. if [ -z "$2" ]; then
  2882. _usage "Usage: $PROJECT_ENTRY --issue -d a.com -w /path/to/webroot/a.com/ "
  2883. return 1
  2884. fi
  2885. if [ -z "$1" ]; then
  2886. _usage "Please specify at least one validation method: '--webroot', '--standalone', '--apache', '--nginx' or '--dns' etc."
  2887. return 1
  2888. fi
  2889. _web_roots="$1"
  2890. _main_domain="$2"
  2891. _alt_domains="$3"
  2892. if _startswith "$_main_domain" "*."; then
  2893. _err "The first domain can not be wildcard, '$_main_domain' is a wildcard domain."
  2894. return 1
  2895. fi
  2896. if _contains "$_main_domain" ","; then
  2897. _main_domain=$(echo "$2,$3" | cut -d , -f 1)
  2898. _alt_domains=$(echo "$2,$3" | cut -d , -f 2- | sed "s/,${NO_VALUE}$//")
  2899. fi
  2900. _key_length="$4"
  2901. _real_cert="$5"
  2902. _real_key="$6"
  2903. _real_ca="$7"
  2904. _reload_cmd="$8"
  2905. _real_fullchain="$9"
  2906. _pre_hook="${10}"
  2907. _post_hook="${11}"
  2908. _renew_hook="${12}"
  2909. _local_addr="${13}"
  2910. #remove these later.
  2911. if [ "$_web_roots" = "dns-cf" ]; then
  2912. _web_roots="dns_cf"
  2913. fi
  2914. if [ "$_web_roots" = "dns-dp" ]; then
  2915. _web_roots="dns_dp"
  2916. fi
  2917. if [ "$_web_roots" = "dns-cx" ]; then
  2918. _web_roots="dns_cx"
  2919. fi
  2920. if [ ! "$IS_RENEW" ]; then
  2921. _initpath "$_main_domain" "$_key_length"
  2922. mkdir -p "$DOMAIN_PATH"
  2923. fi
  2924. _debug "Using ACME_DIRECTORY: $ACME_DIRECTORY"
  2925. _initAPI
  2926. if [ -f "$DOMAIN_CONF" ]; then
  2927. Le_NextRenewTime=$(_readdomainconf Le_NextRenewTime)
  2928. _debug Le_NextRenewTime "$Le_NextRenewTime"
  2929. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  2930. _saved_domain=$(_readdomainconf Le_Domain)
  2931. _debug _saved_domain "$_saved_domain"
  2932. _saved_alt=$(_readdomainconf Le_Alt)
  2933. _debug _saved_alt "$_saved_alt"
  2934. if [ "$_saved_domain,$_saved_alt" = "$_main_domain,$_alt_domains" ]; then
  2935. _info "Domains not changed."
  2936. _info "Skip, Next renewal time is: $(__green "$(_readdomainconf Le_NextRenewTimeStr)")"
  2937. _info "Add '$(__red '--force')' to force to renew."
  2938. return $RENEW_SKIP
  2939. else
  2940. _info "Domains have changed."
  2941. fi
  2942. fi
  2943. fi
  2944. _savedomainconf "Le_Domain" "$_main_domain"
  2945. _savedomainconf "Le_Alt" "$_alt_domains"
  2946. _savedomainconf "Le_Webroot" "$_web_roots"
  2947. _savedomainconf "Le_PreHook" "$_pre_hook"
  2948. _savedomainconf "Le_PostHook" "$_post_hook"
  2949. _savedomainconf "Le_RenewHook" "$_renew_hook"
  2950. if [ "$_local_addr" ]; then
  2951. _savedomainconf "Le_LocalAddress" "$_local_addr"
  2952. else
  2953. _cleardomainconf "Le_LocalAddress"
  2954. fi
  2955. Le_API="$ACME_DIRECTORY"
  2956. _savedomainconf "Le_API" "$Le_API"
  2957. if [ "$_alt_domains" = "$NO_VALUE" ]; then
  2958. _alt_domains=""
  2959. fi
  2960. if [ "$_key_length" = "$NO_VALUE" ]; then
  2961. _key_length=""
  2962. fi
  2963. if ! _on_before_issue "$_web_roots" "$_main_domain" "$_alt_domains" "$_pre_hook" "$_local_addr"; then
  2964. _err "_on_before_issue."
  2965. return 1
  2966. fi
  2967. _saved_account_key_hash="$(_readcaconf "CA_KEY_HASH")"
  2968. _debug2 _saved_account_key_hash "$_saved_account_key_hash"
  2969. if [ -z "$_saved_account_key_hash" ] || [ "$_saved_account_key_hash" != "$(__calcAccountKeyHash)" ]; then
  2970. if ! _regAccount "$_accountkeylength"; then
  2971. _on_issue_err "$_post_hook"
  2972. return 1
  2973. fi
  2974. else
  2975. _debug "_saved_account_key_hash is not changed, skip register account."
  2976. fi
  2977. if [ -f "$CSR_PATH" ] && [ ! -f "$CERT_KEY_PATH" ]; then
  2978. _info "Signing from existing CSR."
  2979. else
  2980. _key=$(_readdomainconf Le_Keylength)
  2981. _debug "Read key length:$_key"
  2982. if [ ! -f "$CERT_KEY_PATH" ] || [ "$_key_length" != "$_key" ] || [ "$Le_ForceNewDomainKey" = "1" ]; then
  2983. if ! createDomainKey "$_main_domain" "$_key_length"; then
  2984. _err "Create domain key error."
  2985. _clearup
  2986. _on_issue_err "$_post_hook"
  2987. return 1
  2988. fi
  2989. fi
  2990. if ! _createcsr "$_main_domain" "$_alt_domains" "$CERT_KEY_PATH" "$CSR_PATH" "$DOMAIN_SSL_CONF"; then
  2991. _err "Create CSR error."
  2992. _clearup
  2993. _on_issue_err "$_post_hook"
  2994. return 1
  2995. fi
  2996. fi
  2997. _savedomainconf "Le_Keylength" "$_key_length"
  2998. vlist="$Le_Vlist"
  2999. _info "Getting domain auth token for each domain"
  3000. sep='#'
  3001. dvsep=','
  3002. if [ -z "$vlist" ]; then
  3003. if [ "$ACME_VERSION" = "2" ]; then
  3004. #make new order request
  3005. _identifiers="{\"type\":\"dns\",\"value\":\"$_main_domain\"}"
  3006. for d in $(echo "$_alt_domains" | tr ',' ' '); do
  3007. #todo: check wildcard ?
  3008. if [ "$d" ]; then
  3009. _identifiers="$_identifiers,{\"type\":\"dns\",\"value\":\"$d\"}"
  3010. fi
  3011. done
  3012. _debug2 _identifiers "$_identifiers"
  3013. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  3014. _err "Create new order error."
  3015. _clearup
  3016. _on_issue_err "$_post_hook"
  3017. return 1
  3018. fi
  3019. Le_OrderFinalize="$(echo "$response" | tr -d '\r\n' | _egrep_o '"finalize" *: *"[^"]*"' | cut -d '"' -f 4)"
  3020. _debug Le_OrderFinalize "$Le_OrderFinalize"
  3021. if [ -z "$Le_OrderFinalize" ]; then
  3022. _err "Le_OrderFinalize not found."
  3023. _clearup
  3024. _on_issue_err "$_post_hook"
  3025. return 1
  3026. fi
  3027. #for dns manual mode
  3028. _savedomainconf "Le_OrderFinalize" "$Le_OrderFinalize"
  3029. _authorizations_seg="$(echo "$response" | tr -d '\r\n' | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  3030. _debug2 _authorizations_seg "$_authorizations_seg"
  3031. if [ -z "$_authorizations_seg" ]; then
  3032. _err "_authorizations_seg not found."
  3033. _clearup
  3034. _on_issue_err "$_post_hook"
  3035. return 1
  3036. fi
  3037. #domain and authz map
  3038. _authorizations_map=""
  3039. for _authz_url in $(echo "$_authorizations_seg" | tr ',' ' '); do
  3040. _debug2 "_authz_url" "$_authz_url"
  3041. if ! response="$(_get "$_authz_url")"; then
  3042. _err "get to authz error."
  3043. _clearup
  3044. _on_issue_err "$_post_hook"
  3045. return 1
  3046. fi
  3047. response="$(echo "$response" | _normalizeJson)"
  3048. _debug2 response "$response"
  3049. _d="$(echo "$response" | _egrep_o '"value" *: *"[^"]*"' | cut -d : -f 2 | tr -d ' "')"
  3050. if _contains "$response" "\"wildcard\" *: *true"; then
  3051. _d="*.$_d"
  3052. fi
  3053. _debug2 _d "$_d"
  3054. _authorizations_map="$_d,$response
  3055. $_authorizations_map"
  3056. done
  3057. _debug2 _authorizations_map "$_authorizations_map"
  3058. fi
  3059. alldomains=$(echo "$_main_domain,$_alt_domains" | tr ',' ' ')
  3060. _index=0
  3061. _currentRoot=""
  3062. for d in $alldomains; do
  3063. _info "Getting webroot for domain" "$d"
  3064. _index=$(_math $_index + 1)
  3065. _w="$(echo $_web_roots | cut -d , -f $_index)"
  3066. _debug _w "$_w"
  3067. if [ "$_w" ]; then
  3068. _currentRoot="$_w"
  3069. fi
  3070. _debug "_currentRoot" "$_currentRoot"
  3071. vtype="$VTYPE_HTTP"
  3072. #todo, v2 wildcard force to use dns
  3073. if _startswith "$_currentRoot" "dns"; then
  3074. vtype="$VTYPE_DNS"
  3075. fi
  3076. if [ "$_currentRoot" = "$W_TLS" ]; then
  3077. if [ "$ACME_VERSION" = "2" ]; then
  3078. vtype="$VTYPE_TLS2"
  3079. else
  3080. vtype="$VTYPE_TLS"
  3081. fi
  3082. fi
  3083. if [ "$ACME_VERSION" = "2" ]; then
  3084. response="$(echo "$_authorizations_map" | grep "^$d," | sed "s/$d,//")"
  3085. _debug2 "response" "$response"
  3086. if [ -z "$response" ]; then
  3087. _err "get to authz error."
  3088. _clearup
  3089. _on_issue_err "$_post_hook"
  3090. return 1
  3091. fi
  3092. else
  3093. if ! __get_domain_new_authz "$d"; then
  3094. _clearup
  3095. _on_issue_err "$_post_hook"
  3096. return 1
  3097. fi
  3098. fi
  3099. if [ -z "$thumbprint" ]; then
  3100. thumbprint="$(__calc_account_thumbprint)"
  3101. fi
  3102. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  3103. _debug entry "$entry"
  3104. if [ -z "$entry" ]; then
  3105. _err "Error, can not get domain token $d"
  3106. _clearup
  3107. _on_issue_err "$_post_hook"
  3108. return 1
  3109. fi
  3110. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  3111. _debug token "$token"
  3112. if [ "$ACME_VERSION" = "2" ]; then
  3113. uri="$(printf "%s\n" "$entry" | _egrep_o '"url":"[^"]*' | cut -d '"' -f 4 | _head_n 1)"
  3114. else
  3115. uri="$(printf "%s\n" "$entry" | _egrep_o '"uri":"[^"]*' | cut -d '"' -f 4)"
  3116. fi
  3117. _debug uri "$uri"
  3118. keyauthorization="$token.$thumbprint"
  3119. _debug keyauthorization "$keyauthorization"
  3120. if printf "%s" "$response" | grep '"status":"valid"' >/dev/null 2>&1; then
  3121. _debug "$d is already verified."
  3122. keyauthorization="$STATE_VERIFIED"
  3123. _debug keyauthorization "$keyauthorization"
  3124. fi
  3125. dvlist="$d$sep$keyauthorization$sep$uri$sep$vtype$sep$_currentRoot"
  3126. _debug dvlist "$dvlist"
  3127. vlist="$vlist$dvlist$dvsep"
  3128. done
  3129. _debug vlist "$vlist"
  3130. #add entry
  3131. dnsadded=""
  3132. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3133. for ventry in $ventries; do
  3134. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3135. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3136. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3137. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3138. _debug d "$d"
  3139. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3140. _debug "$d is already verified, skip $vtype."
  3141. continue
  3142. fi
  3143. if [ "$vtype" = "$VTYPE_DNS" ]; then
  3144. dnsadded='0'
  3145. _dns_root_d="$d"
  3146. if _startswith "$_dns_root_d" "*."; then
  3147. _dns_root_d="$(echo "$_dns_root_d" | sed 's/*.//')"
  3148. fi
  3149. txtdomain="_acme-challenge.$_dns_root_d"
  3150. _debug txtdomain "$txtdomain"
  3151. txt="$(printf "%s" "$keyauthorization" | _digest "sha256" | _url_replace)"
  3152. _debug txt "$txt"
  3153. d_api="$(_findHook "$_dns_root_d" dnsapi "$_currentRoot")"
  3154. _debug d_api "$d_api"
  3155. if [ "$d_api" ]; then
  3156. _info "Found domain api file: $d_api"
  3157. else
  3158. _info "$(__red "Add the following TXT record:")"
  3159. _info "$(__red "Domain: '$(__green "$txtdomain")'")"
  3160. _info "$(__red "TXT value: '$(__green "$txt")'")"
  3161. _info "$(__red "Please be aware that you prepend _acme-challenge. before your domain")"
  3162. _info "$(__red "so the resulting subdomain will be: $txtdomain")"
  3163. continue
  3164. fi
  3165. (
  3166. if ! . "$d_api"; then
  3167. _err "Load file $d_api error. Please check your api file and try again."
  3168. return 1
  3169. fi
  3170. addcommand="${_currentRoot}_add"
  3171. if ! _exists "$addcommand"; then
  3172. _err "It seems that your api file is not correct, it must have a function named: $addcommand"
  3173. return 1
  3174. fi
  3175. if ! $addcommand "$txtdomain" "$txt"; then
  3176. _err "Error add txt for domain:$txtdomain"
  3177. return 1
  3178. fi
  3179. )
  3180. if [ "$?" != "0" ]; then
  3181. _clearup
  3182. _on_issue_err "$_post_hook" "$vlist"
  3183. return 1
  3184. fi
  3185. dnsadded='1'
  3186. fi
  3187. done
  3188. if [ "$dnsadded" = '0' ]; then
  3189. _savedomainconf "Le_Vlist" "$vlist"
  3190. _debug "Dns record not added yet, so, save to $DOMAIN_CONF and exit."
  3191. _err "Please add the TXT records to the domains, and retry again."
  3192. _clearup
  3193. _on_issue_err "$_post_hook"
  3194. return 1
  3195. fi
  3196. fi
  3197. if [ "$dnsadded" = '1' ]; then
  3198. if [ -z "$Le_DNSSleep" ]; then
  3199. Le_DNSSleep="$DEFAULT_DNS_SLEEP"
  3200. else
  3201. _savedomainconf "Le_DNSSleep" "$Le_DNSSleep"
  3202. fi
  3203. _info "Sleep $(__green $Le_DNSSleep) seconds for the txt records to take effect"
  3204. _sleep "$Le_DNSSleep"
  3205. fi
  3206. NGINX_RESTORE_VLIST=""
  3207. _debug "ok, let's start to verify"
  3208. _ncIndex=1
  3209. ventries=$(echo "$vlist" | tr "$dvsep" ' ')
  3210. for ventry in $ventries; do
  3211. d=$(echo "$ventry" | cut -d "$sep" -f 1)
  3212. keyauthorization=$(echo "$ventry" | cut -d "$sep" -f 2)
  3213. uri=$(echo "$ventry" | cut -d "$sep" -f 3)
  3214. vtype=$(echo "$ventry" | cut -d "$sep" -f 4)
  3215. _currentRoot=$(echo "$ventry" | cut -d "$sep" -f 5)
  3216. if [ "$keyauthorization" = "$STATE_VERIFIED" ]; then
  3217. _info "$d is already verified, skip $vtype."
  3218. continue
  3219. fi
  3220. _info "Verifying:$d"
  3221. _debug "d" "$d"
  3222. _debug "keyauthorization" "$keyauthorization"
  3223. _debug "uri" "$uri"
  3224. removelevel=""
  3225. token="$(printf "%s" "$keyauthorization" | cut -d '.' -f 1)"
  3226. _debug "_currentRoot" "$_currentRoot"
  3227. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3228. if [ "$_currentRoot" = "$NO_VALUE" ]; then
  3229. _info "Standalone mode server"
  3230. _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
  3231. _ncIndex="$(_math $_ncIndex + 1)"
  3232. _startserver "$keyauthorization" "$_ncaddr"
  3233. if [ "$?" != "0" ]; then
  3234. _clearup
  3235. _on_issue_err "$_post_hook" "$vlist"
  3236. return 1
  3237. fi
  3238. sleep 1
  3239. _debug serverproc "$serverproc"
  3240. elif [ "$_currentRoot" = "$MODE_STATELESS" ]; then
  3241. _info "Stateless mode for domain:$d"
  3242. _sleep 1
  3243. elif _startswith "$_currentRoot" "$NGINX"; then
  3244. _info "Nginx mode for domain:$d"
  3245. #set up nginx server
  3246. FOUND_REAL_NGINX_CONF=""
  3247. BACKUP_NGINX_CONF=""
  3248. if ! _setNginx "$d" "$_currentRoot" "$thumbprint"; then
  3249. _clearup
  3250. _on_issue_err "$_post_hook" "$vlist"
  3251. return 1
  3252. fi
  3253. if [ "$FOUND_REAL_NGINX_CONF" ]; then
  3254. _realConf="$FOUND_REAL_NGINX_CONF"
  3255. _backup="$BACKUP_NGINX_CONF"
  3256. _debug _realConf "$_realConf"
  3257. NGINX_RESTORE_VLIST="$d$sep$_realConf$sep$_backup$dvsep$NGINX_RESTORE_VLIST"
  3258. fi
  3259. _sleep 1
  3260. else
  3261. if [ "$_currentRoot" = "apache" ]; then
  3262. wellknown_path="$ACME_DIR"
  3263. else
  3264. wellknown_path="$_currentRoot/.well-known/acme-challenge"
  3265. if [ ! -d "$_currentRoot/.well-known" ]; then
  3266. removelevel='1'
  3267. elif [ ! -d "$_currentRoot/.well-known/acme-challenge" ]; then
  3268. removelevel='2'
  3269. else
  3270. removelevel='3'
  3271. fi
  3272. fi
  3273. _debug wellknown_path "$wellknown_path"
  3274. _debug "writing token:$token to $wellknown_path/$token"
  3275. mkdir -p "$wellknown_path"
  3276. if ! printf "%s" "$keyauthorization" >"$wellknown_path/$token"; then
  3277. _err "$d:Can not write token to file : $wellknown_path/$token"
  3278. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3279. _clearup
  3280. _on_issue_err "$_post_hook" "$vlist"
  3281. return 1
  3282. fi
  3283. if [ ! "$usingApache" ]; then
  3284. if webroot_owner=$(_stat "$_currentRoot"); then
  3285. _debug "Changing owner/group of .well-known to $webroot_owner"
  3286. if ! _exec "chown -R \"$webroot_owner\" \"$_currentRoot/.well-known\""; then
  3287. _debug "$(cat "$_EXEC_TEMP_ERR")"
  3288. _exec_err >/dev/null 2>&1
  3289. fi
  3290. else
  3291. _debug "not changing owner/group of webroot"
  3292. fi
  3293. fi
  3294. fi
  3295. elif [ "$vtype" = "$VTYPE_TLS" ]; then
  3296. #create A
  3297. #_hash_A="$(printf "%s" $token | _digest "sha256" "hex" )"
  3298. #_debug2 _hash_A "$_hash_A"
  3299. #_x="$(echo $_hash_A | cut -c 1-32)"
  3300. #_debug2 _x "$_x"
  3301. #_y="$(echo $_hash_A | cut -c 33-64)"
  3302. #_debug2 _y "$_y"
  3303. #_SAN_A="$_x.$_y.token.acme.invalid"
  3304. #_debug2 _SAN_A "$_SAN_A"
  3305. #create B
  3306. _hash_B="$(printf "%s" "$keyauthorization" | _digest "sha256" "hex")"
  3307. _debug2 _hash_B "$_hash_B"
  3308. _x="$(echo "$_hash_B" | cut -c 1-32)"
  3309. _debug2 _x "$_x"
  3310. _y="$(echo "$_hash_B" | cut -c 33-64)"
  3311. _debug2 _y "$_y"
  3312. #_SAN_B="$_x.$_y.ka.acme.invalid"
  3313. _SAN_B="$_x.$_y.acme.invalid"
  3314. _debug2 _SAN_B "$_SAN_B"
  3315. _ncaddr="$(_getfield "$_local_addr" "$_ncIndex")"
  3316. _ncIndex="$(_math "$_ncIndex" + 1)"
  3317. if ! _starttlsserver "$_SAN_B" "$_SAN_A" "$Le_TLSPort" "$keyauthorization" "$_ncaddr"; then
  3318. _err "Start tls server error."
  3319. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3320. _clearup
  3321. _on_issue_err "$_post_hook" "$vlist"
  3322. return 1
  3323. fi
  3324. fi
  3325. if ! __trigger_validation "$uri" "$keyauthorization"; then
  3326. _err "$d:Can not get challenge: $response"
  3327. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3328. _clearup
  3329. _on_issue_err "$_post_hook" "$vlist"
  3330. return 1
  3331. fi
  3332. if [ "$code" ] && [ "$code" != '202' ]; then
  3333. if [ "$ACME_VERSION" = "2" ] && [ "$code" = '200' ]; then
  3334. _debug "trigger validation code: $code"
  3335. else
  3336. _err "$d:Challenge error: $response"
  3337. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3338. _clearup
  3339. _on_issue_err "$_post_hook" "$vlist"
  3340. return 1
  3341. fi
  3342. fi
  3343. waittimes=0
  3344. if [ -z "$MAX_RETRY_TIMES" ]; then
  3345. MAX_RETRY_TIMES=30
  3346. fi
  3347. while true; do
  3348. waittimes=$(_math "$waittimes" + 1)
  3349. if [ "$waittimes" -ge "$MAX_RETRY_TIMES" ]; then
  3350. _err "$d:Timeout"
  3351. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3352. _clearup
  3353. _on_issue_err "$_post_hook" "$vlist"
  3354. return 1
  3355. fi
  3356. _debug "sleep 2 secs to verify"
  3357. sleep 2
  3358. _debug "checking"
  3359. response="$(_get "$uri")"
  3360. if [ "$?" != "0" ]; then
  3361. _err "$d:Verify error:$response"
  3362. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3363. _clearup
  3364. _on_issue_err "$_post_hook" "$vlist"
  3365. return 1
  3366. fi
  3367. _debug2 original "$response"
  3368. response="$(echo "$response" | _normalizeJson)"
  3369. _debug2 response "$response"
  3370. status=$(echo "$response" | _egrep_o '"status":"[^"]*' | cut -d : -f 2 | tr -d '"')
  3371. if [ "$status" = "valid" ]; then
  3372. _info "$(__green Success)"
  3373. _stopserver "$serverproc"
  3374. serverproc=""
  3375. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3376. break
  3377. fi
  3378. if [ "$status" = "invalid" ]; then
  3379. error="$(echo "$response" | tr -d "\r\n" | _egrep_o '"error":\{[^\}]*')"
  3380. _debug2 error "$error"
  3381. errordetail="$(echo "$error" | _egrep_o '"detail": *"[^"]*' | cut -d '"' -f 4)"
  3382. _debug2 errordetail "$errordetail"
  3383. if [ "$errordetail" ]; then
  3384. _err "$d:Verify error:$errordetail"
  3385. else
  3386. _err "$d:Verify error:$error"
  3387. fi
  3388. if [ "$DEBUG" ]; then
  3389. if [ "$vtype" = "$VTYPE_HTTP" ]; then
  3390. _debug "Debug: get token url."
  3391. _get "http://$d/.well-known/acme-challenge/$token" "" 1
  3392. fi
  3393. fi
  3394. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3395. _clearup
  3396. _on_issue_err "$_post_hook" "$vlist"
  3397. return 1
  3398. fi
  3399. if [ "$status" = "pending" ]; then
  3400. _info "Pending"
  3401. else
  3402. _err "$d:Verify error:$response"
  3403. _clearupwebbroot "$_currentRoot" "$removelevel" "$token"
  3404. _clearup
  3405. _on_issue_err "$_post_hook" "$vlist"
  3406. return 1
  3407. fi
  3408. done
  3409. done
  3410. _clearup
  3411. _info "Verify finished, start to sign."
  3412. der="$(_getfile "${CSR_PATH}" "${BEGIN_CSR}" "${END_CSR}" | tr -d "\r\n" | _url_replace)"
  3413. if [ "$ACME_VERSION" = "2" ]; then
  3414. if ! _send_signed_request "${Le_OrderFinalize}" "{\"csr\": \"$der\"}"; then
  3415. _err "Sign failed."
  3416. _on_issue_err "$_post_hook"
  3417. return 1
  3418. fi
  3419. if [ "$code" != "200" ]; then
  3420. _err "Sign failed, code is not 200."
  3421. _on_issue_err "$_post_hook"
  3422. return 1
  3423. fi
  3424. Le_LinkCert="$(echo "$response" | tr -d '\r\n' | _egrep_o '"certificate" *: *"[^"]*"' | cut -d '"' -f 4)"
  3425. if ! _get "$Le_LinkCert" >"$CERT_PATH"; then
  3426. _err "Sign failed, code is not 200."
  3427. _on_issue_err "$_post_hook"
  3428. return 1
  3429. fi
  3430. else
  3431. if ! _send_signed_request "${ACME_NEW_ORDER}" "{\"resource\": \"$ACME_NEW_ORDER_RES\", \"csr\": \"$der\"}" "needbase64"; then
  3432. _err "Sign failed."
  3433. _on_issue_err "$_post_hook"
  3434. return 1
  3435. fi
  3436. _rcert="$response"
  3437. Le_LinkCert="$(grep -i '^Location.*$' "$HTTP_HEADER" | _head_n 1 | tr -d "\r\n" | cut -d " " -f 2)"
  3438. echo "$BEGIN_CERT" >"$CERT_PATH"
  3439. #if ! _get "$Le_LinkCert" | _base64 "multiline" >> "$CERT_PATH" ; then
  3440. # _debug "Get cert failed. Let's try last response."
  3441. # printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >> "$CERT_PATH"
  3442. #fi
  3443. if ! printf -- "%s" "$_rcert" | _dbase64 "multiline" | _base64 "multiline" >>"$CERT_PATH"; then
  3444. _debug "Try cert link."
  3445. _get "$Le_LinkCert" | _base64 "multiline" >>"$CERT_PATH"
  3446. fi
  3447. echo "$END_CERT" >>"$CERT_PATH"
  3448. fi
  3449. _debug "Le_LinkCert" "$Le_LinkCert"
  3450. _savedomainconf "Le_LinkCert" "$Le_LinkCert"
  3451. if [ "$Le_LinkCert" ]; then
  3452. _info "$(__green "Cert success.")"
  3453. cat "$CERT_PATH"
  3454. _info "Your cert is in $(__green " $CERT_PATH ")"
  3455. if [ -f "$CERT_KEY_PATH" ]; then
  3456. _info "Your cert key is in $(__green " $CERT_KEY_PATH ")"
  3457. fi
  3458. cp "$CERT_PATH" "$CERT_FULLCHAIN_PATH"
  3459. if [ ! "$USER_PATH" ] || [ ! "$IN_CRON" ]; then
  3460. USER_PATH="$PATH"
  3461. _saveaccountconf "USER_PATH" "$USER_PATH"
  3462. fi
  3463. fi
  3464. if [ -z "$Le_LinkCert" ]; then
  3465. response="$(echo "$response" | _dbase64 "multiline" | _normalizeJson)"
  3466. _err "Sign failed: $(echo "$response" | _egrep_o '"detail":"[^"]*"')"
  3467. _on_issue_err "$_post_hook"
  3468. return 1
  3469. fi
  3470. _cleardomainconf "Le_Vlist"
  3471. Le_LinkIssuer=$(grep -i '^Link' "$HTTP_HEADER" | _head_n 1 | cut -d " " -f 2 | cut -d ';' -f 1 | tr -d '<>')
  3472. if [ "$Le_LinkIssuer" ]; then
  3473. if ! _contains "$Le_LinkIssuer" ":"; then
  3474. _info "$(__red "Relative issuer link found.")"
  3475. Le_LinkIssuer="$_ACME_SERVER_HOST$Le_LinkIssuer"
  3476. fi
  3477. _debug Le_LinkIssuer "$Le_LinkIssuer"
  3478. _savedomainconf "Le_LinkIssuer" "$Le_LinkIssuer"
  3479. _link_issuer_retry=0
  3480. _MAX_ISSUER_RETRY=5
  3481. while [ "$_link_issuer_retry" -lt "$_MAX_ISSUER_RETRY" ]; do
  3482. _debug _link_issuer_retry "$_link_issuer_retry"
  3483. if [ "$ACME_VERSION" = "2" ]; then
  3484. if _get "$Le_LinkIssuer" >"$CA_CERT_PATH"; then
  3485. break
  3486. fi
  3487. else
  3488. if _get "$Le_LinkIssuer" >"$CA_CERT_PATH.der"; then
  3489. echo "$BEGIN_CERT" >"$CA_CERT_PATH"
  3490. _base64 "multiline" <"$CA_CERT_PATH.der" >>"$CA_CERT_PATH"
  3491. echo "$END_CERT" >>"$CA_CERT_PATH"
  3492. _info "The intermediate CA cert is in $(__green " $CA_CERT_PATH ")"
  3493. cat "$CA_CERT_PATH" >>"$CERT_FULLCHAIN_PATH"
  3494. _info "And the full chain certs is there: $(__green " $CERT_FULLCHAIN_PATH ")"
  3495. rm -f "$CA_CERT_PATH.der"
  3496. break
  3497. fi
  3498. fi
  3499. _link_issuer_retry=$(_math $_link_issuer_retry + 1)
  3500. _sleep "$_link_issuer_retry"
  3501. done
  3502. if [ "$_link_issuer_retry" = "$_MAX_ISSUER_RETRY" ]; then
  3503. _err "Max retry for issuer ca cert is reached."
  3504. fi
  3505. else
  3506. _debug "No Le_LinkIssuer header found."
  3507. fi
  3508. Le_CertCreateTime=$(_time)
  3509. _savedomainconf "Le_CertCreateTime" "$Le_CertCreateTime"
  3510. Le_CertCreateTimeStr=$(date -u)
  3511. _savedomainconf "Le_CertCreateTimeStr" "$Le_CertCreateTimeStr"
  3512. if [ -z "$Le_RenewalDays" ] || [ "$Le_RenewalDays" -lt "0" ] || [ "$Le_RenewalDays" -gt "$MAX_RENEW" ]; then
  3513. Le_RenewalDays="$MAX_RENEW"
  3514. else
  3515. _savedomainconf "Le_RenewalDays" "$Le_RenewalDays"
  3516. fi
  3517. if [ "$CA_BUNDLE" ]; then
  3518. _saveaccountconf CA_BUNDLE "$CA_BUNDLE"
  3519. else
  3520. _clearaccountconf "CA_BUNDLE"
  3521. fi
  3522. if [ "$CA_PATH" ]; then
  3523. _saveaccountconf CA_PATH "$CA_PATH"
  3524. else
  3525. _clearaccountconf "CA_PATH"
  3526. fi
  3527. if [ "$HTTPS_INSECURE" ]; then
  3528. _saveaccountconf HTTPS_INSECURE "$HTTPS_INSECURE"
  3529. else
  3530. _clearaccountconf "HTTPS_INSECURE"
  3531. fi
  3532. if [ "$Le_Listen_V4" ]; then
  3533. _savedomainconf "Le_Listen_V4" "$Le_Listen_V4"
  3534. _cleardomainconf Le_Listen_V6
  3535. elif [ "$Le_Listen_V6" ]; then
  3536. _savedomainconf "Le_Listen_V6" "$Le_Listen_V6"
  3537. _cleardomainconf Le_Listen_V4
  3538. fi
  3539. if [ "$Le_ForceNewDomainKey" = "1" ]; then
  3540. _savedomainconf "Le_ForceNewDomainKey" "$Le_ForceNewDomainKey"
  3541. else
  3542. _cleardomainconf Le_ForceNewDomainKey
  3543. fi
  3544. Le_NextRenewTime=$(_math "$Le_CertCreateTime" + "$Le_RenewalDays" \* 24 \* 60 \* 60)
  3545. Le_NextRenewTimeStr=$(_time2str "$Le_NextRenewTime")
  3546. _savedomainconf "Le_NextRenewTimeStr" "$Le_NextRenewTimeStr"
  3547. Le_NextRenewTime=$(_math "$Le_NextRenewTime" - 86400)
  3548. _savedomainconf "Le_NextRenewTime" "$Le_NextRenewTime"
  3549. if ! _on_issue_success "$_post_hook" "$_renew_hook"; then
  3550. _err "Call hook error."
  3551. return 1
  3552. fi
  3553. if [ "$_real_cert$_real_key$_real_ca$_reload_cmd$_real_fullchain" ]; then
  3554. _savedomainconf "Le_RealCertPath" "$_real_cert"
  3555. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  3556. _savedomainconf "Le_RealKeyPath" "$_real_key"
  3557. _savedomainconf "Le_ReloadCmd" "$_reload_cmd"
  3558. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  3559. _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"
  3560. fi
  3561. }
  3562. #domain [isEcc]
  3563. renew() {
  3564. Le_Domain="$1"
  3565. if [ -z "$Le_Domain" ]; then
  3566. _usage "Usage: $PROJECT_ENTRY --renew -d domain.com [--ecc]"
  3567. return 1
  3568. fi
  3569. _isEcc="$2"
  3570. _initpath "$Le_Domain" "$_isEcc"
  3571. _info "$(__green "Renew: '$Le_Domain'")"
  3572. if [ ! -f "$DOMAIN_CONF" ]; then
  3573. _info "'$Le_Domain' is not a issued domain, skip."
  3574. return 0
  3575. fi
  3576. if [ "$Le_RenewalDays" ]; then
  3577. _savedomainconf Le_RenewalDays "$Le_RenewalDays"
  3578. fi
  3579. . "$DOMAIN_CONF"
  3580. if [ "$Le_API" ]; then
  3581. if [ "$_OLD_CA_HOST" = "$Le_API" ]; then
  3582. export Le_API="$DEFAULT_CA"
  3583. _savedomainconf Le_API "$Le_API"
  3584. fi
  3585. if [ "$_OLD_STAGE_CA_HOST" = "$Le_API" ]; then
  3586. export Le_API="$DEFAULT_STAGING_CA"
  3587. _savedomainconf Le_API "$Le_API"
  3588. fi
  3589. export ACME_DIRECTORY="$Le_API"
  3590. #reload ca configs
  3591. ACCOUNT_KEY_PATH=""
  3592. ACCOUNT_JSON_PATH=""
  3593. CA_CONF=""
  3594. _debug3 "initpath again."
  3595. _initpath "$Le_Domain" "$_isEcc"
  3596. fi
  3597. if [ -z "$FORCE" ] && [ "$Le_NextRenewTime" ] && [ "$(_time)" -lt "$Le_NextRenewTime" ]; then
  3598. _info "Skip, Next renewal time is: $(__green "$Le_NextRenewTimeStr")"
  3599. _info "Add '$(__red '--force')' to force to renew."
  3600. return "$RENEW_SKIP"
  3601. fi
  3602. if [ "$IN_CRON" = "1" ] && [ -z "$Le_CertCreateTime" ]; then
  3603. _info "Skip invalid cert for: $Le_Domain"
  3604. return 0
  3605. fi
  3606. IS_RENEW="1"
  3607. 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"
  3608. res="$?"
  3609. if [ "$res" != "0" ]; then
  3610. return "$res"
  3611. fi
  3612. if [ "$Le_DeployHook" ]; then
  3613. _deploy "$Le_Domain" "$Le_DeployHook"
  3614. res="$?"
  3615. fi
  3616. IS_RENEW=""
  3617. return "$res"
  3618. }
  3619. #renewAll [stopRenewOnError]
  3620. renewAll() {
  3621. _initpath
  3622. _stopRenewOnError="$1"
  3623. _debug "_stopRenewOnError" "$_stopRenewOnError"
  3624. _ret="0"
  3625. for di in "${CERT_HOME}"/*.*/; do
  3626. _debug di "$di"
  3627. if ! [ -d "$di" ]; then
  3628. _debug "Not directory, skip: $di"
  3629. continue
  3630. fi
  3631. d=$(basename "$di")
  3632. _debug d "$d"
  3633. (
  3634. if _endswith "$d" "$ECC_SUFFIX"; then
  3635. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  3636. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  3637. fi
  3638. renew "$d" "$_isEcc"
  3639. )
  3640. rc="$?"
  3641. _debug "Return code: $rc"
  3642. if [ "$rc" != "0" ]; then
  3643. if [ "$rc" = "$RENEW_SKIP" ]; then
  3644. _info "Skipped $d"
  3645. elif [ "$_stopRenewOnError" ]; then
  3646. _err "Error renew $d, stop now."
  3647. return "$rc"
  3648. else
  3649. _ret="$rc"
  3650. _err "Error renew $d."
  3651. fi
  3652. fi
  3653. done
  3654. return "$_ret"
  3655. }
  3656. #csr webroot
  3657. signcsr() {
  3658. _csrfile="$1"
  3659. _csrW="$2"
  3660. if [ -z "$_csrfile" ] || [ -z "$_csrW" ]; then
  3661. _usage "Usage: $PROJECT_ENTRY --signcsr --csr mycsr.csr -w /path/to/webroot/a.com/ "
  3662. return 1
  3663. fi
  3664. _initpath
  3665. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  3666. if [ "$?" != "0" ]; then
  3667. _err "Can not read subject from csr: $_csrfile"
  3668. return 1
  3669. fi
  3670. _debug _csrsubj "$_csrsubj"
  3671. if _contains "$_csrsubj" ' ' || ! _contains "$_csrsubj" '.'; then
  3672. _info "It seems that the subject: $_csrsubj is not a valid domain name. Drop it."
  3673. _csrsubj=""
  3674. fi
  3675. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  3676. if [ "$?" != "0" ]; then
  3677. _err "Can not read domain list from csr: $_csrfile"
  3678. return 1
  3679. fi
  3680. _debug "_csrdomainlist" "$_csrdomainlist"
  3681. if [ -z "$_csrsubj" ]; then
  3682. _csrsubj="$(_getfield "$_csrdomainlist" 1)"
  3683. _debug _csrsubj "$_csrsubj"
  3684. _csrdomainlist="$(echo "$_csrdomainlist" | cut -d , -f 2-)"
  3685. _debug "_csrdomainlist" "$_csrdomainlist"
  3686. fi
  3687. if [ -z "$_csrsubj" ]; then
  3688. _err "Can not read subject from csr: $_csrfile"
  3689. return 1
  3690. fi
  3691. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  3692. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  3693. _err "Can not read key length from csr: $_csrfile"
  3694. return 1
  3695. fi
  3696. _initpath "$_csrsubj" "$_csrkeylength"
  3697. mkdir -p "$DOMAIN_PATH"
  3698. _info "Copy csr to: $CSR_PATH"
  3699. cp "$_csrfile" "$CSR_PATH"
  3700. issue "$_csrW" "$_csrsubj" "$_csrdomainlist" "$_csrkeylength"
  3701. }
  3702. showcsr() {
  3703. _csrfile="$1"
  3704. _csrd="$2"
  3705. if [ -z "$_csrfile" ] && [ -z "$_csrd" ]; then
  3706. _usage "Usage: $PROJECT_ENTRY --showcsr --csr mycsr.csr"
  3707. return 1
  3708. fi
  3709. _initpath
  3710. _csrsubj=$(_readSubjectFromCSR "$_csrfile")
  3711. if [ "$?" != "0" ] || [ -z "$_csrsubj" ]; then
  3712. _err "Can not read subject from csr: $_csrfile"
  3713. return 1
  3714. fi
  3715. _info "Subject=$_csrsubj"
  3716. _csrdomainlist=$(_readSubjectAltNamesFromCSR "$_csrfile")
  3717. if [ "$?" != "0" ]; then
  3718. _err "Can not read domain list from csr: $_csrfile"
  3719. return 1
  3720. fi
  3721. _debug "_csrdomainlist" "$_csrdomainlist"
  3722. _info "SubjectAltNames=$_csrdomainlist"
  3723. _csrkeylength=$(_readKeyLengthFromCSR "$_csrfile")
  3724. if [ "$?" != "0" ] || [ -z "$_csrkeylength" ]; then
  3725. _err "Can not read key length from csr: $_csrfile"
  3726. return 1
  3727. fi
  3728. _info "KeyLength=$_csrkeylength"
  3729. }
  3730. list() {
  3731. _raw="$1"
  3732. _initpath
  3733. _sep="|"
  3734. if [ "$_raw" ]; then
  3735. printf "%s\n" "Main_Domain${_sep}KeyLength${_sep}SAN_Domains${_sep}Created${_sep}Renew"
  3736. for di in "${CERT_HOME}"/*.*/; do
  3737. if ! [ -d "$di" ]; then
  3738. _debug "Not directory, skip: $di"
  3739. continue
  3740. fi
  3741. d=$(basename "$di")
  3742. _debug d "$d"
  3743. (
  3744. if _endswith "$d" "$ECC_SUFFIX"; then
  3745. _isEcc=$(echo "$d" | cut -d "$ECC_SEP" -f 2)
  3746. d=$(echo "$d" | cut -d "$ECC_SEP" -f 1)
  3747. fi
  3748. _initpath "$d" "$_isEcc"
  3749. if [ -f "$DOMAIN_CONF" ]; then
  3750. . "$DOMAIN_CONF"
  3751. printf "%s\n" "$Le_Domain${_sep}\"$Le_Keylength\"${_sep}$Le_Alt${_sep}$Le_CertCreateTimeStr${_sep}$Le_NextRenewTimeStr"
  3752. fi
  3753. )
  3754. done
  3755. else
  3756. if _exists column; then
  3757. list "raw" | column -t -s "$_sep"
  3758. else
  3759. list "raw" | tr "$_sep" '\t'
  3760. fi
  3761. fi
  3762. }
  3763. _deploy() {
  3764. _d="$1"
  3765. _hooks="$2"
  3766. for _d_api in $(echo "$_hooks" | tr ',' " "); do
  3767. _deployApi="$(_findHook "$_d" deploy "$_d_api")"
  3768. if [ -z "$_deployApi" ]; then
  3769. _err "The deploy hook $_d_api is not found."
  3770. return 1
  3771. fi
  3772. _debug _deployApi "$_deployApi"
  3773. if ! (
  3774. if ! . "$_deployApi"; then
  3775. _err "Load file $_deployApi error. Please check your api file and try again."
  3776. return 1
  3777. fi
  3778. d_command="${_d_api}_deploy"
  3779. if ! _exists "$d_command"; then
  3780. _err "It seems that your api file is not correct, it must have a function named: $d_command"
  3781. return 1
  3782. fi
  3783. if ! $d_command "$_d" "$CERT_KEY_PATH" "$CERT_PATH" "$CA_CERT_PATH" "$CERT_FULLCHAIN_PATH"; then
  3784. _err "Error deploy for domain:$_d"
  3785. return 1
  3786. fi
  3787. ); then
  3788. _err "Deploy error."
  3789. return 1
  3790. else
  3791. _info "$(__green Success)"
  3792. fi
  3793. done
  3794. }
  3795. #domain hooks
  3796. deploy() {
  3797. _d="$1"
  3798. _hooks="$2"
  3799. _isEcc="$3"
  3800. if [ -z "$_hooks" ]; then
  3801. _usage "Usage: $PROJECT_ENTRY --deploy -d domain.com --deploy-hook cpanel [--ecc] "
  3802. return 1
  3803. fi
  3804. _initpath "$_d" "$_isEcc"
  3805. if [ ! -d "$DOMAIN_PATH" ]; then
  3806. _err "Domain is not valid:'$_d'"
  3807. return 1
  3808. fi
  3809. . "$DOMAIN_CONF"
  3810. _savedomainconf Le_DeployHook "$_hooks"
  3811. _deploy "$_d" "$_hooks"
  3812. }
  3813. installcert() {
  3814. _main_domain="$1"
  3815. if [ -z "$_main_domain" ]; then
  3816. _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]"
  3817. return 1
  3818. fi
  3819. _real_cert="$2"
  3820. _real_key="$3"
  3821. _real_ca="$4"
  3822. _reload_cmd="$5"
  3823. _real_fullchain="$6"
  3824. _isEcc="$7"
  3825. _initpath "$_main_domain" "$_isEcc"
  3826. if [ ! -d "$DOMAIN_PATH" ]; then
  3827. _err "Domain is not valid:'$_main_domain'"
  3828. return 1
  3829. fi
  3830. _savedomainconf "Le_RealCertPath" "$_real_cert"
  3831. _savedomainconf "Le_RealCACertPath" "$_real_ca"
  3832. _savedomainconf "Le_RealKeyPath" "$_real_key"
  3833. _savedomainconf "Le_ReloadCmd" "$_reload_cmd"
  3834. _savedomainconf "Le_RealFullChainPath" "$_real_fullchain"
  3835. _installcert "$_main_domain" "$_real_cert" "$_real_key" "$_real_ca" "$_real_fullchain" "$_reload_cmd"
  3836. }
  3837. #domain cert key ca fullchain reloadcmd backup-prefix
  3838. _installcert() {
  3839. _main_domain="$1"
  3840. _real_cert="$2"
  3841. _real_key="$3"
  3842. _real_ca="$4"
  3843. _real_fullchain="$5"
  3844. _reload_cmd="$6"
  3845. _backup_prefix="$7"
  3846. if [ "$_real_cert" = "$NO_VALUE" ]; then
  3847. _real_cert=""
  3848. fi
  3849. if [ "$_real_key" = "$NO_VALUE" ]; then
  3850. _real_key=""
  3851. fi
  3852. if [ "$_real_ca" = "$NO_VALUE" ]; then
  3853. _real_ca=""
  3854. fi
  3855. if [ "$_reload_cmd" = "$NO_VALUE" ]; then
  3856. _reload_cmd=""
  3857. fi
  3858. if [ "$_real_fullchain" = "$NO_VALUE" ]; then
  3859. _real_fullchain=""
  3860. fi
  3861. _backup_path="$DOMAIN_BACKUP_PATH/$_backup_prefix"
  3862. mkdir -p "$_backup_path"
  3863. if [ "$_real_cert" ]; then
  3864. _info "Installing cert to:$_real_cert"
  3865. if [ -f "$_real_cert" ] && [ ! "$IS_RENEW" ]; then
  3866. cp "$_real_cert" "$_backup_path/cert.bak"
  3867. fi
  3868. cat "$CERT_PATH" >"$_real_cert"
  3869. fi
  3870. if [ "$_real_ca" ]; then
  3871. _info "Installing CA to:$_real_ca"
  3872. if [ "$_real_ca" = "$_real_cert" ]; then
  3873. echo "" >>"$_real_ca"
  3874. cat "$CA_CERT_PATH" >>"$_real_ca"
  3875. else
  3876. if [ -f "$_real_ca" ] && [ ! "$IS_RENEW" ]; then
  3877. cp "$_real_ca" "$_backup_path/ca.bak"
  3878. fi
  3879. cat "$CA_CERT_PATH" >"$_real_ca"
  3880. fi
  3881. fi
  3882. if [ "$_real_key" ]; then
  3883. _info "Installing key to:$_real_key"
  3884. if [ -f "$_real_key" ] && [ ! "$IS_RENEW" ]; then
  3885. cp "$_real_key" "$_backup_path/key.bak"
  3886. fi
  3887. if [ -f "$_real_key" ]; then
  3888. cat "$CERT_KEY_PATH" >"$_real_key"
  3889. else
  3890. cat "$CERT_KEY_PATH" >"$_real_key"
  3891. chmod 700 "$_real_key"
  3892. fi
  3893. fi
  3894. if [ "$_real_fullchain" ]; then
  3895. _info "Installing full chain to:$_real_fullchain"
  3896. if [ -f "$_real_fullchain" ] && [ ! "$IS_RENEW" ]; then
  3897. cp "$_real_fullchain" "$_backup_path/fullchain.bak"
  3898. fi
  3899. cat "$CERT_FULLCHAIN_PATH" >"$_real_fullchain"
  3900. fi
  3901. if [ "$_reload_cmd" ]; then
  3902. _info "Run reload cmd: $_reload_cmd"
  3903. if (
  3904. export CERT_PATH
  3905. export CERT_KEY_PATH
  3906. export CA_CERT_PATH
  3907. export CERT_FULLCHAIN_PATH
  3908. export Le_Domain
  3909. cd "$DOMAIN_PATH" && eval "$_reload_cmd"
  3910. ); then
  3911. _info "$(__green "Reload success")"
  3912. else
  3913. _err "Reload error for :$Le_Domain"
  3914. fi
  3915. fi
  3916. }
  3917. #confighome
  3918. installcronjob() {
  3919. _c_home="$1"
  3920. _initpath
  3921. _CRONTAB="crontab"
  3922. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  3923. _CRONTAB="fcrontab"
  3924. fi
  3925. if ! _exists "$_CRONTAB"; then
  3926. _err "crontab/fcrontab doesn't exist, so, we can not install cron jobs."
  3927. _err "All your certs will not be renewed automatically."
  3928. _err "You must add your own cron job to call '$PROJECT_ENTRY --cron' everyday."
  3929. return 1
  3930. fi
  3931. _info "Installing cron job"
  3932. if ! $_CRONTAB -l | grep "$PROJECT_ENTRY --cron"; then
  3933. if [ -f "$LE_WORKING_DIR/$PROJECT_ENTRY" ]; then
  3934. lesh="\"$LE_WORKING_DIR\"/$PROJECT_ENTRY"
  3935. else
  3936. _err "Can not install cronjob, $PROJECT_ENTRY not found."
  3937. return 1
  3938. fi
  3939. if [ "$_c_home" ]; then
  3940. _c_entry="--config-home \"$_c_home\" "
  3941. fi
  3942. _t=$(_time)
  3943. random_minute=$(_math $_t % 60)
  3944. if _exists uname && uname -a | grep SunOS >/dev/null; then
  3945. $_CRONTAB -l | {
  3946. cat
  3947. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  3948. } | $_CRONTAB --
  3949. else
  3950. $_CRONTAB -l | {
  3951. cat
  3952. echo "$random_minute 0 * * * $lesh --cron --home \"$LE_WORKING_DIR\" $_c_entry> /dev/null"
  3953. } | $_CRONTAB -
  3954. fi
  3955. fi
  3956. if [ "$?" != "0" ]; then
  3957. _err "Install cron job failed. You need to manually renew your certs."
  3958. _err "Or you can add cronjob by yourself:"
  3959. _err "$lesh --cron --home \"$LE_WORKING_DIR\" > /dev/null"
  3960. return 1
  3961. fi
  3962. }
  3963. uninstallcronjob() {
  3964. _CRONTAB="crontab"
  3965. if ! _exists "$_CRONTAB" && _exists "fcrontab"; then
  3966. _CRONTAB="fcrontab"
  3967. fi
  3968. if ! _exists "$_CRONTAB"; then
  3969. return
  3970. fi
  3971. _info "Removing cron job"
  3972. cr="$($_CRONTAB -l | grep "$PROJECT_ENTRY --cron")"
  3973. if [ "$cr" ]; then
  3974. if _exists uname && uname -a | grep solaris >/dev/null; then
  3975. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB --
  3976. else
  3977. $_CRONTAB -l | sed "/$PROJECT_ENTRY --cron/d" | $_CRONTAB -
  3978. fi
  3979. LE_WORKING_DIR="$(echo "$cr" | cut -d ' ' -f 9 | tr -d '"')"
  3980. _info LE_WORKING_DIR "$LE_WORKING_DIR"
  3981. if _contains "$cr" "--config-home"; then
  3982. LE_CONFIG_HOME="$(echo "$cr" | cut -d ' ' -f 11 | tr -d '"')"
  3983. _debug LE_CONFIG_HOME "$LE_CONFIG_HOME"
  3984. fi
  3985. fi
  3986. _initpath
  3987. }
  3988. revoke() {
  3989. Le_Domain="$1"
  3990. if [ -z "$Le_Domain" ]; then
  3991. _usage "Usage: $PROJECT_ENTRY --revoke -d domain.com [--ecc]"
  3992. return 1
  3993. fi
  3994. _isEcc="$2"
  3995. _initpath "$Le_Domain" "$_isEcc"
  3996. if [ ! -f "$DOMAIN_CONF" ]; then
  3997. _err "$Le_Domain is not a issued domain, skip."
  3998. return 1
  3999. fi
  4000. if [ ! -f "$CERT_PATH" ]; then
  4001. _err "Cert for $Le_Domain $CERT_PATH is not found, skip."
  4002. return 1
  4003. fi
  4004. cert="$(_getfile "${CERT_PATH}" "${BEGIN_CERT}" "${END_CERT}" | tr -d "\r\n" | _url_replace)"
  4005. if [ -z "$cert" ]; then
  4006. _err "Cert for $Le_Domain is empty found, skip."
  4007. return 1
  4008. fi
  4009. _initAPI
  4010. if [ "$ACME_VERSION" = "2" ]; then
  4011. data="{\"certificate\": \"$cert\"}"
  4012. else
  4013. data="{\"resource\": \"revoke-cert\", \"certificate\": \"$cert\"}"
  4014. fi
  4015. uri="${ACME_REVOKE_CERT}"
  4016. if [ -f "$CERT_KEY_PATH" ]; then
  4017. _info "Try domain key first."
  4018. if _send_signed_request "$uri" "$data" "" "$CERT_KEY_PATH"; then
  4019. if [ -z "$response" ]; then
  4020. _info "Revoke success."
  4021. rm -f "$CERT_PATH"
  4022. return 0
  4023. else
  4024. _err "Revoke error by domain key."
  4025. _err "$response"
  4026. fi
  4027. fi
  4028. else
  4029. _info "Domain key file doesn't exists."
  4030. fi
  4031. _info "Try account key."
  4032. if _send_signed_request "$uri" "$data" "" "$ACCOUNT_KEY_PATH"; then
  4033. if [ -z "$response" ]; then
  4034. _info "Revoke success."
  4035. rm -f "$CERT_PATH"
  4036. return 0
  4037. else
  4038. _err "Revoke error."
  4039. _debug "$response"
  4040. fi
  4041. fi
  4042. return 1
  4043. }
  4044. #domain ecc
  4045. remove() {
  4046. Le_Domain="$1"
  4047. if [ -z "$Le_Domain" ]; then
  4048. _usage "Usage: $PROJECT_ENTRY --remove -d domain.com [--ecc]"
  4049. return 1
  4050. fi
  4051. _isEcc="$2"
  4052. _initpath "$Le_Domain" "$_isEcc"
  4053. _removed_conf="$DOMAIN_CONF.removed"
  4054. if [ ! -f "$DOMAIN_CONF" ]; then
  4055. if [ -f "$_removed_conf" ]; then
  4056. _err "$Le_Domain is already removed, You can remove the folder by yourself: $DOMAIN_PATH"
  4057. else
  4058. _err "$Le_Domain is not a issued domain, skip."
  4059. fi
  4060. return 1
  4061. fi
  4062. if mv "$DOMAIN_CONF" "$_removed_conf"; then
  4063. _info "$Le_Domain is removed, the key and cert files are in $(__green $DOMAIN_PATH)"
  4064. _info "You can remove them by yourself."
  4065. return 0
  4066. else
  4067. _err "Remove $Le_Domain failed."
  4068. return 1
  4069. fi
  4070. }
  4071. #domain vtype
  4072. _deactivate() {
  4073. _d_domain="$1"
  4074. _d_type="$2"
  4075. _initpath
  4076. if [ "$ACME_VERSION" = "2" ]; then
  4077. _identifiers="{\"type\":\"dns\",\"value\":\"$_d_domain\"}"
  4078. if ! _send_signed_request "$ACME_NEW_ORDER" "{\"identifiers\": [$_identifiers]}"; then
  4079. _err "Can not get domain new order."
  4080. return 1
  4081. fi
  4082. _authorizations_seg="$(echo "$response" | tr -d '\r\n' | _egrep_o '"authorizations" *: *\[[^\]*\]' | cut -d '[' -f 2 | tr -d ']' | tr -d '"')"
  4083. _debug2 _authorizations_seg "$_authorizations_seg"
  4084. if [ -z "$_authorizations_seg" ]; then
  4085. _err "_authorizations_seg not found."
  4086. _clearup
  4087. _on_issue_err "$_post_hook"
  4088. return 1
  4089. fi
  4090. authzUri="$_authorizations_seg"
  4091. _debug2 "authzUri" "$authzUri"
  4092. if ! response="$(_get "$authzUri")"; then
  4093. _err "get to authz error."
  4094. _clearup
  4095. _on_issue_err "$_post_hook"
  4096. return 1
  4097. fi
  4098. response="$(echo "$response" | _normalizeJson)"
  4099. _debug2 response "$response"
  4100. _URL_NAME="url"
  4101. else
  4102. if ! __get_domain_new_authz "$_d_domain"; then
  4103. _err "Can not get domain new authz token."
  4104. return 1
  4105. fi
  4106. authzUri="$(echo "$responseHeaders" | grep "^Location:" | _head_n 1 | cut -d ' ' -f 2 | tr -d "\r\n")"
  4107. _debug "authzUri" "$authzUri"
  4108. if [ "$code" ] && [ ! "$code" = '201' ]; then
  4109. _err "new-authz error: $response"
  4110. return 1
  4111. fi
  4112. _URL_NAME="uri"
  4113. fi
  4114. entries="$(echo "$response" | _egrep_o "{ *\"type\":\"[^\"]*\", *\"status\": *\"valid\", *\"$_URL_NAME\"[^}]*")"
  4115. if [ -z "$entries" ]; then
  4116. _info "No valid entries found."
  4117. if [ -z "$thumbprint" ]; then
  4118. thumbprint="$(__calc_account_thumbprint)"
  4119. fi
  4120. _debug "Trigger validation."
  4121. vtype="$VTYPE_DNS"
  4122. entry="$(printf "%s\n" "$response" | _egrep_o '[^\{]*"type":"'$vtype'"[^\}]*')"
  4123. _debug entry "$entry"
  4124. if [ -z "$entry" ]; then
  4125. _err "Error, can not get domain token $d"
  4126. return 1
  4127. fi
  4128. token="$(printf "%s\n" "$entry" | _egrep_o '"token":"[^"]*' | cut -d : -f 2 | tr -d '"')"
  4129. _debug token "$token"
  4130. uri="$(printf "%s\n" "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  4131. _debug uri "$uri"
  4132. keyauthorization="$token.$thumbprint"
  4133. _debug keyauthorization "$keyauthorization"
  4134. __trigger_validation "$uri" "$keyauthorization"
  4135. fi
  4136. _d_i=0
  4137. _d_max_retry=$(echo "$entries" | wc -l)
  4138. while [ "$_d_i" -lt "$_d_max_retry" ]; do
  4139. _info "Deactivate: $_d_domain"
  4140. _d_i="$(_math $_d_i + 1)"
  4141. entry="$(echo "$entries" | sed -n "${_d_i}p")"
  4142. _debug entry "$entry"
  4143. if [ -z "$entry" ]; then
  4144. _info "No more valid entry found."
  4145. break
  4146. fi
  4147. _vtype="$(printf "%s\n" "$entry" | _egrep_o '"type": *"[^"]*"' | cut -d : -f 2 | tr -d '"')"
  4148. _debug _vtype "$_vtype"
  4149. _info "Found $_vtype"
  4150. uri="$(printf "%s\n" "$entry" | _egrep_o "\"$_URL_NAME\":\"[^\"]*" | cut -d : -f 2,3 | tr -d '"')"
  4151. _debug uri "$uri"
  4152. if [ "$_d_type" ] && [ "$_d_type" != "$_vtype" ]; then
  4153. _info "Skip $_vtype"
  4154. continue
  4155. fi
  4156. _info "Deactivate: $_vtype"
  4157. if [ "$ACME_VERSION" = "2" ]; then
  4158. _djson="{\"status\":\"deactivated\"}"
  4159. else
  4160. _djson="{\"resource\": \"authz\", \"status\":\"deactivated\"}"
  4161. fi
  4162. if _send_signed_request "$authzUri" "$_djson" && _contains "$response" '"deactivated"'; then
  4163. _info "Deactivate: $_vtype success."
  4164. else
  4165. _err "Can not deactivate $_vtype."
  4166. break
  4167. fi
  4168. done
  4169. _debug "$_d_i"
  4170. if [ "$_d_i" -eq "$_d_max_retry" ]; then
  4171. _info "Deactivated success!"
  4172. else
  4173. _err "Deactivate failed."
  4174. fi
  4175. }
  4176. deactivate() {
  4177. _d_domain_list="$1"
  4178. _d_type="$2"
  4179. _initpath
  4180. _initAPI
  4181. _debug _d_domain_list "$_d_domain_list"
  4182. if [ -z "$(echo $_d_domain_list | cut -d , -f 1)" ]; then
  4183. _usage "Usage: $PROJECT_ENTRY --deactivate -d domain.com [-d domain.com]"
  4184. return 1
  4185. fi
  4186. for _d_dm in $(echo "$_d_domain_list" | tr ',' ' '); do
  4187. if [ -z "$_d_dm" ] || [ "$_d_dm" = "$NO_VALUE" ]; then
  4188. continue
  4189. fi
  4190. if ! _deactivate "$_d_dm" "$_d_type"; then
  4191. return 1
  4192. fi
  4193. done
  4194. }
  4195. # Detect profile file if not specified as environment variable
  4196. _detect_profile() {
  4197. if [ -n "$PROFILE" -a -f "$PROFILE" ]; then
  4198. echo "$PROFILE"
  4199. return
  4200. fi
  4201. DETECTED_PROFILE=''
  4202. SHELLTYPE="$(basename "/$SHELL")"
  4203. if [ "$SHELLTYPE" = "bash" ]; then
  4204. if [ -f "$HOME/.bashrc" ]; then
  4205. DETECTED_PROFILE="$HOME/.bashrc"
  4206. elif [ -f "$HOME/.bash_profile" ]; then
  4207. DETECTED_PROFILE="$HOME/.bash_profile"
  4208. fi
  4209. elif [ "$SHELLTYPE" = "zsh" ]; then
  4210. DETECTED_PROFILE="$HOME/.zshrc"
  4211. fi
  4212. if [ -z "$DETECTED_PROFILE" ]; then
  4213. if [ -f "$HOME/.profile" ]; then
  4214. DETECTED_PROFILE="$HOME/.profile"
  4215. elif [ -f "$HOME/.bashrc" ]; then
  4216. DETECTED_PROFILE="$HOME/.bashrc"
  4217. elif [ -f "$HOME/.bash_profile" ]; then
  4218. DETECTED_PROFILE="$HOME/.bash_profile"
  4219. elif [ -f "$HOME/.zshrc" ]; then
  4220. DETECTED_PROFILE="$HOME/.zshrc"
  4221. fi
  4222. fi
  4223. echo "$DETECTED_PROFILE"
  4224. }
  4225. _initconf() {
  4226. _initpath
  4227. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  4228. echo "
  4229. #LOG_FILE=\"$DEFAULT_LOG_FILE\"
  4230. #LOG_LEVEL=1
  4231. #AUTO_UPGRADE=\"1\"
  4232. #NO_TIMESTAMP=1
  4233. " >"$ACCOUNT_CONF_PATH"
  4234. fi
  4235. }
  4236. # nocron
  4237. _precheck() {
  4238. _nocron="$1"
  4239. if ! _exists "curl" && ! _exists "wget"; then
  4240. _err "Please install curl or wget first, we need to access http resources."
  4241. return 1
  4242. fi
  4243. if [ -z "$_nocron" ]; then
  4244. if ! _exists "crontab" && ! _exists "fcrontab"; then
  4245. _err "It is recommended to install crontab first. try to install 'cron, crontab, crontabs or vixie-cron'."
  4246. _err "We need to set cron job to renew the certs automatically."
  4247. _err "Otherwise, your certs will not be able to be renewed automatically."
  4248. if [ -z "$FORCE" ]; then
  4249. _err "Please add '--force' and try install again to go without crontab."
  4250. _err "./$PROJECT_ENTRY --install --force"
  4251. return 1
  4252. fi
  4253. fi
  4254. fi
  4255. if ! _exists "${ACME_OPENSSL_BIN:-openssl}"; then
  4256. _err "Please install openssl first. ACME_OPENSSL_BIN=$ACME_OPENSSL_BIN"
  4257. _err "We need openssl to generate keys."
  4258. return 1
  4259. fi
  4260. if ! _exists "socat"; then
  4261. _err "It is recommended to install socat first."
  4262. _err "We use socat for standalone server if you use standalone mode."
  4263. _err "If you don't use standalone mode, just ignore this warning."
  4264. fi
  4265. return 0
  4266. }
  4267. _setShebang() {
  4268. _file="$1"
  4269. _shebang="$2"
  4270. if [ -z "$_shebang" ]; then
  4271. _usage "Usage: file shebang"
  4272. return 1
  4273. fi
  4274. cp "$_file" "$_file.tmp"
  4275. echo "$_shebang" >"$_file"
  4276. sed -n 2,99999p "$_file.tmp" >>"$_file"
  4277. rm -f "$_file.tmp"
  4278. }
  4279. #confighome
  4280. _installalias() {
  4281. _c_home="$1"
  4282. _initpath
  4283. _envfile="$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  4284. if [ "$_upgrading" ] && [ "$_upgrading" = "1" ]; then
  4285. echo "$(cat "$_envfile")" | sed "s|^LE_WORKING_DIR.*$||" >"$_envfile"
  4286. echo "$(cat "$_envfile")" | sed "s|^alias le.*$||" >"$_envfile"
  4287. echo "$(cat "$_envfile")" | sed "s|^alias le.sh.*$||" >"$_envfile"
  4288. fi
  4289. if [ "$_c_home" ]; then
  4290. _c_entry=" --config-home '$_c_home'"
  4291. fi
  4292. _setopt "$_envfile" "export LE_WORKING_DIR" "=" "\"$LE_WORKING_DIR\""
  4293. if [ "$_c_home" ]; then
  4294. _setopt "$_envfile" "export LE_CONFIG_HOME" "=" "\"$LE_CONFIG_HOME\""
  4295. else
  4296. _sed_i "/^export LE_CONFIG_HOME/d" "$_envfile"
  4297. fi
  4298. _setopt "$_envfile" "alias $PROJECT_ENTRY" "=" "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4299. _profile="$(_detect_profile)"
  4300. if [ "$_profile" ]; then
  4301. _debug "Found profile: $_profile"
  4302. _info "Installing alias to '$_profile'"
  4303. _setopt "$_profile" ". \"$_envfile\""
  4304. _info "OK, Close and reopen your terminal to start using $PROJECT_NAME"
  4305. else
  4306. _info "No profile is found, you will need to go into $LE_WORKING_DIR to use $PROJECT_NAME"
  4307. fi
  4308. #for csh
  4309. _cshfile="$LE_WORKING_DIR/$PROJECT_ENTRY.csh"
  4310. _csh_profile="$HOME/.cshrc"
  4311. if [ -f "$_csh_profile" ]; then
  4312. _info "Installing alias to '$_csh_profile'"
  4313. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  4314. if [ "$_c_home" ]; then
  4315. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  4316. else
  4317. _sed_i "/^setenv LE_CONFIG_HOME/d" "$_cshfile"
  4318. fi
  4319. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4320. _setopt "$_csh_profile" "source \"$_cshfile\""
  4321. fi
  4322. #for tcsh
  4323. _tcsh_profile="$HOME/.tcshrc"
  4324. if [ -f "$_tcsh_profile" ]; then
  4325. _info "Installing alias to '$_tcsh_profile'"
  4326. _setopt "$_cshfile" "setenv LE_WORKING_DIR" " " "\"$LE_WORKING_DIR\""
  4327. if [ "$_c_home" ]; then
  4328. _setopt "$_cshfile" "setenv LE_CONFIG_HOME" " " "\"$LE_CONFIG_HOME\""
  4329. fi
  4330. _setopt "$_cshfile" "alias $PROJECT_ENTRY" " " "\"$LE_WORKING_DIR/$PROJECT_ENTRY$_c_entry\""
  4331. _setopt "$_tcsh_profile" "source \"$_cshfile\""
  4332. fi
  4333. }
  4334. # nocron confighome
  4335. install() {
  4336. if [ -z "$LE_WORKING_DIR" ]; then
  4337. LE_WORKING_DIR="$DEFAULT_INSTALL_HOME"
  4338. fi
  4339. _nocron="$1"
  4340. _c_home="$2"
  4341. if ! _initpath; then
  4342. _err "Install failed."
  4343. return 1
  4344. fi
  4345. if [ "$_nocron" ]; then
  4346. _debug "Skip install cron job"
  4347. fi
  4348. if [ "$IN_CRON" != "1" ]; then
  4349. if ! _precheck "$_nocron"; then
  4350. _err "Pre-check failed, can not install."
  4351. return 1
  4352. fi
  4353. fi
  4354. if [ -z "$_c_home" ] && [ "$LE_CONFIG_HOME" != "$LE_WORKING_DIR" ]; then
  4355. _info "Using config home: $LE_CONFIG_HOME"
  4356. _c_home="$LE_CONFIG_HOME"
  4357. fi
  4358. #convert from le
  4359. if [ -d "$HOME/.le" ]; then
  4360. for envfile in "le.env" "le.sh.env"; do
  4361. if [ -f "$HOME/.le/$envfile" ]; then
  4362. if grep "le.sh" "$HOME/.le/$envfile" >/dev/null; then
  4363. _upgrading="1"
  4364. _info "You are upgrading from le.sh"
  4365. _info "Renaming \"$HOME/.le\" to $LE_WORKING_DIR"
  4366. mv "$HOME/.le" "$LE_WORKING_DIR"
  4367. mv "$LE_WORKING_DIR/$envfile" "$LE_WORKING_DIR/$PROJECT_ENTRY.env"
  4368. break
  4369. fi
  4370. fi
  4371. done
  4372. fi
  4373. _info "Installing to $LE_WORKING_DIR"
  4374. if [ ! -d "$LE_WORKING_DIR" ]; then
  4375. if ! mkdir -p "$LE_WORKING_DIR"; then
  4376. _err "Can not create working dir: $LE_WORKING_DIR"
  4377. return 1
  4378. fi
  4379. chmod 700 "$LE_WORKING_DIR"
  4380. fi
  4381. if [ ! -d "$LE_CONFIG_HOME" ]; then
  4382. if ! mkdir -p "$LE_CONFIG_HOME"; then
  4383. _err "Can not create config dir: $LE_CONFIG_HOME"
  4384. return 1
  4385. fi
  4386. chmod 700 "$LE_CONFIG_HOME"
  4387. fi
  4388. cp "$PROJECT_ENTRY" "$LE_WORKING_DIR/" && chmod +x "$LE_WORKING_DIR/$PROJECT_ENTRY"
  4389. if [ "$?" != "0" ]; then
  4390. _err "Install failed, can not copy $PROJECT_ENTRY"
  4391. return 1
  4392. fi
  4393. _info "Installed to $LE_WORKING_DIR/$PROJECT_ENTRY"
  4394. if [ "$IN_CRON" != "1" ]; then
  4395. _installalias "$_c_home"
  4396. fi
  4397. for subf in $_SUB_FOLDERS; do
  4398. if [ -d "$subf" ]; then
  4399. mkdir -p "$LE_WORKING_DIR/$subf"
  4400. cp "$subf"/* "$LE_WORKING_DIR"/"$subf"/
  4401. fi
  4402. done
  4403. if [ ! -f "$ACCOUNT_CONF_PATH" ]; then
  4404. _initconf
  4405. fi
  4406. if [ "$_DEFAULT_ACCOUNT_CONF_PATH" != "$ACCOUNT_CONF_PATH" ]; then
  4407. _setopt "$_DEFAULT_ACCOUNT_CONF_PATH" "ACCOUNT_CONF_PATH" "=" "\"$ACCOUNT_CONF_PATH\""
  4408. fi
  4409. if [ "$_DEFAULT_CERT_HOME" != "$CERT_HOME" ]; then
  4410. _saveaccountconf "CERT_HOME" "$CERT_HOME"
  4411. fi
  4412. if [ "$_DEFAULT_ACCOUNT_KEY_PATH" != "$ACCOUNT_KEY_PATH" ]; then
  4413. _saveaccountconf "ACCOUNT_KEY_PATH" "$ACCOUNT_KEY_PATH"
  4414. fi
  4415. if [ -z "$_nocron" ]; then
  4416. installcronjob "$_c_home"
  4417. fi
  4418. if [ -z "$NO_DETECT_SH" ]; then
  4419. #Modify shebang
  4420. if _exists bash; then
  4421. _info "Good, bash is found, so change the shebang to use bash as preferred."
  4422. _shebang='#!'"$(env bash -c "command -v bash")"
  4423. _setShebang "$LE_WORKING_DIR/$PROJECT_ENTRY" "$_shebang"
  4424. for subf in $_SUB_FOLDERS; do
  4425. if [ -d "$LE_WORKING_DIR/$subf" ]; then
  4426. for _apifile in "$LE_WORKING_DIR/$subf/"*.sh; do
  4427. _setShebang "$_apifile" "$_shebang"
  4428. done
  4429. fi
  4430. done
  4431. fi
  4432. fi
  4433. _info OK
  4434. }
  4435. # nocron
  4436. uninstall() {
  4437. _nocron="$1"
  4438. if [ -z "$_nocron" ]; then
  4439. uninstallcronjob
  4440. fi
  4441. _initpath
  4442. _uninstallalias
  4443. rm -f "$LE_WORKING_DIR/$PROJECT_ENTRY"
  4444. _info "The keys and certs are in \"$(__green "$LE_CONFIG_HOME")\", you can remove them by yourself."
  4445. }
  4446. _uninstallalias() {
  4447. _initpath
  4448. _profile="$(_detect_profile)"
  4449. if [ "$_profile" ]; then
  4450. _info "Uninstalling alias from: '$_profile'"
  4451. text="$(cat "$_profile")"
  4452. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.env\"$||" >"$_profile"
  4453. fi
  4454. _csh_profile="$HOME/.cshrc"
  4455. if [ -f "$_csh_profile" ]; then
  4456. _info "Uninstalling alias from: '$_csh_profile'"
  4457. text="$(cat "$_csh_profile")"
  4458. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_csh_profile"
  4459. fi
  4460. _tcsh_profile="$HOME/.tcshrc"
  4461. if [ -f "$_tcsh_profile" ]; then
  4462. _info "Uninstalling alias from: '$_csh_profile'"
  4463. text="$(cat "$_tcsh_profile")"
  4464. echo "$text" | sed "s|^.*\"$LE_WORKING_DIR/$PROJECT_NAME.csh\"$||" >"$_tcsh_profile"
  4465. fi
  4466. }
  4467. cron() {
  4468. export IN_CRON=1
  4469. _initpath
  4470. _info "$(__green "===Starting cron===")"
  4471. if [ "$AUTO_UPGRADE" = "1" ]; then
  4472. export LE_WORKING_DIR
  4473. (
  4474. if ! upgrade; then
  4475. _err "Cron:Upgrade failed!"
  4476. return 1
  4477. fi
  4478. )
  4479. . "$LE_WORKING_DIR/$PROJECT_ENTRY" >/dev/null
  4480. if [ -t 1 ]; then
  4481. __INTERACTIVE="1"
  4482. fi
  4483. _info "Auto upgraded to: $VER"
  4484. fi
  4485. renewAll
  4486. _ret="$?"
  4487. IN_CRON=""
  4488. _info "$(__green "===End cron===")"
  4489. exit $_ret
  4490. }
  4491. version() {
  4492. echo "$PROJECT"
  4493. echo "v$VER"
  4494. }
  4495. showhelp() {
  4496. _initpath
  4497. version
  4498. echo "Usage: $PROJECT_ENTRY command ...[parameters]....
  4499. Commands:
  4500. --help, -h Show this help message.
  4501. --version, -v Show version info.
  4502. --install Install $PROJECT_NAME to your system.
  4503. --uninstall Uninstall $PROJECT_NAME, and uninstall the cron job.
  4504. --upgrade Upgrade $PROJECT_NAME to the latest code from $PROJECT.
  4505. --issue Issue a cert.
  4506. --signcsr Issue a cert from an existing csr.
  4507. --deploy Deploy the cert to your server.
  4508. --install-cert Install the issued cert to apache/nginx or any other server.
  4509. --renew, -r Renew a cert.
  4510. --renew-all Renew all the certs.
  4511. --revoke Revoke a cert.
  4512. --remove Remove the cert from $PROJECT
  4513. --list List all the certs.
  4514. --showcsr Show the content of a csr.
  4515. --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.
  4516. --uninstall-cronjob Uninstall the cron job. The 'uninstall' command can do this automatically.
  4517. --cron Run cron job to renew all the certs.
  4518. --toPkcs Export the certificate and key to a pfx file.
  4519. --toPkcs8 Convert to pkcs8 format.
  4520. --update-account Update account info.
  4521. --register-account Register account key.
  4522. --deactivate-account Deactivate the account.
  4523. --create-account-key Create an account private key, professional use.
  4524. --create-domain-key Create an domain private key, professional use.
  4525. --createCSR, -ccsr Create CSR , professional use.
  4526. --deactivate Deactivate the domain authz, professional use.
  4527. Parameters:
  4528. --domain, -d domain.tld Specifies a domain, used to issue, renew or revoke etc.
  4529. --force, -f Used to force to install or force to renew a cert immediately.
  4530. --staging, --test Use staging server, just for test.
  4531. --debug Output debug info.
  4532. --output-insecure Output all the sensitive messages. By default all the credentials/sensitive messages are hidden from the output/debug/log for secure.
  4533. --webroot, -w /path/to/webroot Specifies the web root folder for web root mode.
  4534. --standalone Use standalone mode.
  4535. --stateless Use stateless mode, see: $_STATELESS_WIKI
  4536. --tls Use standalone tls mode.
  4537. --apache Use apache mode.
  4538. --dns [dns_cf|dns_dp|dns_cx|/path/to/api/file] Use dns mode or dns api.
  4539. --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.
  4540. --keylength, -k [2048] Specifies the domain key length: 2048, 3072, 4096, 8192 or ec-256, ec-384.
  4541. --accountkeylength, -ak [2048] Specifies the account key length.
  4542. --log [/path/to/logfile] Specifies the log file. The default is: \"$DEFAULT_LOG_FILE\" if you don't give a file path here.
  4543. --log-level 1|2 Specifies the log level, default is 1.
  4544. --syslog [0|3|6|7] Syslog level, 0: disable syslog, 3: error, 6: info, 7: debug.
  4545. These parameters are to install the cert to nginx/apache or anyother server after issue/renew a cert:
  4546. --cert-file After issue/renew, the cert will be copied to this path.
  4547. --key-file After issue/renew, the key will be copied to this path.
  4548. --ca-file After issue/renew, the intermediate cert will be copied to this path.
  4549. --fullchain-file After issue/renew, the fullchain cert will be copied to this path.
  4550. --reloadcmd \"service nginx reload\" After issue/renew, it's used to reload the server.
  4551. --server SERVER ACME Directory Resource URI. (default: https://acme-v01.api.letsencrypt.org/directory)
  4552. --accountconf Specifies a customized account config file.
  4553. --home Specifies the home dir for $PROJECT_NAME .
  4554. --cert-home Specifies the home dir to save all the certs, only valid for '--install' command.
  4555. --config-home Specifies the home dir to save all the configurations.
  4556. --useragent Specifies the user agent string. it will be saved for future use too.
  4557. --accountemail Specifies the account email for registering, Only valid for the '--install' command.
  4558. --accountkey Specifies the account key path, Only valid for the '--install' command.
  4559. --days Specifies the days to renew the cert when using '--issue' command. The max value is $MAX_RENEW days.
  4560. --httpport Specifies the standalone listening port. Only valid if the server is behind a reverse proxy or load balancer.
  4561. --tlsport Specifies the standalone tls listening port. Only valid if the server is behind a reverse proxy or load balancer.
  4562. --local-address Specifies the standalone/tls server listening address, in case you have multiple ip addresses.
  4563. --listraw Only used for '--list' command, list the certs in raw format.
  4564. --stopRenewOnError, -se Only valid for '--renew-all' command. Stop if one cert has error in renewal.
  4565. --insecure Do not check the server certificate, in some devices, the api server's certificate may not be trusted.
  4566. --ca-bundle Specifies the path to the CA certificate bundle to verify api server's certificate.
  4567. --ca-path Specifies directory containing CA certificates in PEM format, used by wget or curl.
  4568. --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.
  4569. --no-color Do not output color text.
  4570. --ecc Specifies to use the ECC cert. Valid for '--install-cert', '--renew', '--revoke', '--toPkcs' and '--createCSR'
  4571. --csr Specifies the input csr.
  4572. --pre-hook Command to be run before obtaining any certificates.
  4573. --post-hook Command to be run after attempting to obtain/renew certificates. No matter the obtain/renew is success or failed.
  4574. --renew-hook Command to be run once for each successfully renewed certificate.
  4575. --deploy-hook The hook file to deploy cert
  4576. --ocsp-must-staple, --ocsp Generate ocsp must Staple extension.
  4577. --always-force-new-domain-key Generate new domain key when renewal. Otherwise, the domain key is not changed by default.
  4578. --auto-upgrade [0|1] Valid for '--upgrade' command, indicating whether to upgrade automatically in future.
  4579. --listen-v4 Force standalone/tls server to listen at ipv4.
  4580. --listen-v6 Force standalone/tls server to listen at ipv6.
  4581. --openssl-bin Specifies a custom openssl bin location.
  4582. --use-wget Force to use wget, if you have both curl and wget installed.
  4583. "
  4584. }
  4585. # nocron
  4586. _installOnline() {
  4587. _info "Installing from online archive."
  4588. _nocron="$1"
  4589. if [ ! "$BRANCH" ]; then
  4590. BRANCH="master"
  4591. fi
  4592. target="$PROJECT/archive/$BRANCH.tar.gz"
  4593. _info "Downloading $target"
  4594. localname="$BRANCH.tar.gz"
  4595. if ! _get "$target" >$localname; then
  4596. _err "Download error."
  4597. return 1
  4598. fi
  4599. (
  4600. _info "Extracting $localname"
  4601. if ! (tar xzf $localname || gtar xzf $localname); then
  4602. _err "Extraction error."
  4603. exit 1
  4604. fi
  4605. cd "$PROJECT_NAME-$BRANCH"
  4606. chmod +x $PROJECT_ENTRY
  4607. if ./$PROJECT_ENTRY install "$_nocron"; then
  4608. _info "Install success!"
  4609. fi
  4610. cd ..
  4611. rm -rf "$PROJECT_NAME-$BRANCH"
  4612. rm -f "$localname"
  4613. )
  4614. }
  4615. upgrade() {
  4616. if (
  4617. _initpath
  4618. export LE_WORKING_DIR
  4619. cd "$LE_WORKING_DIR"
  4620. _installOnline "nocron"
  4621. ); then
  4622. _info "Upgrade success!"
  4623. exit 0
  4624. else
  4625. _err "Upgrade failed!"
  4626. exit 1
  4627. fi
  4628. }
  4629. _processAccountConf() {
  4630. if [ "$_useragent" ]; then
  4631. _saveaccountconf "USER_AGENT" "$_useragent"
  4632. elif [ "$USER_AGENT" ] && [ "$USER_AGENT" != "$DEFAULT_USER_AGENT" ]; then
  4633. _saveaccountconf "USER_AGENT" "$USER_AGENT"
  4634. fi
  4635. if [ "$_accountemail" ]; then
  4636. _saveaccountconf "ACCOUNT_EMAIL" "$_accountemail"
  4637. elif [ "$ACCOUNT_EMAIL" ] && [ "$ACCOUNT_EMAIL" != "$DEFAULT_ACCOUNT_EMAIL" ]; then
  4638. _saveaccountconf "ACCOUNT_EMAIL" "$ACCOUNT_EMAIL"
  4639. fi
  4640. if [ "$_openssl_bin" ]; then
  4641. _saveaccountconf "ACME_OPENSSL_BIN" "$_openssl_bin"
  4642. elif [ "$ACME_OPENSSL_BIN" ] && [ "$ACME_OPENSSL_BIN" != "$DEFAULT_OPENSSL_BIN" ]; then
  4643. _saveaccountconf "ACME_OPENSSL_BIN" "$ACME_OPENSSL_BIN"
  4644. fi
  4645. if [ "$_auto_upgrade" ]; then
  4646. _saveaccountconf "AUTO_UPGRADE" "$_auto_upgrade"
  4647. elif [ "$AUTO_UPGRADE" ]; then
  4648. _saveaccountconf "AUTO_UPGRADE" "$AUTO_UPGRADE"
  4649. fi
  4650. if [ "$_use_wget" ]; then
  4651. _saveaccountconf "ACME_USE_WGET" "$_use_wget"
  4652. elif [ "$ACME_USE_WGET" ]; then
  4653. _saveaccountconf "ACME_USE_WGET" "$ACME_USE_WGET"
  4654. fi
  4655. }
  4656. _process() {
  4657. _CMD=""
  4658. _domain=""
  4659. _altdomains="$NO_VALUE"
  4660. _webroot=""
  4661. _keylength=""
  4662. _accountkeylength=""
  4663. _cert_file=""
  4664. _key_file=""
  4665. _ca_file=""
  4666. _fullchain_file=""
  4667. _reloadcmd=""
  4668. _password=""
  4669. _accountconf=""
  4670. _useragent=""
  4671. _accountemail=""
  4672. _accountkey=""
  4673. _certhome=""
  4674. _confighome=""
  4675. _httpport=""
  4676. _tlsport=""
  4677. _dnssleep=""
  4678. _listraw=""
  4679. _stopRenewOnError=""
  4680. #_insecure=""
  4681. _ca_bundle=""
  4682. _ca_path=""
  4683. _nocron=""
  4684. _ecc=""
  4685. _csr=""
  4686. _pre_hook=""
  4687. _post_hook=""
  4688. _renew_hook=""
  4689. _deploy_hook=""
  4690. _logfile=""
  4691. _log=""
  4692. _local_address=""
  4693. _log_level=""
  4694. _auto_upgrade=""
  4695. _listen_v4=""
  4696. _listen_v6=""
  4697. _openssl_bin=""
  4698. _syslog=""
  4699. _use_wget=""
  4700. _server=""
  4701. while [ ${#} -gt 0 ]; do
  4702. case "${1}" in
  4703. --help | -h)
  4704. showhelp
  4705. return
  4706. ;;
  4707. --version | -v)
  4708. version
  4709. return
  4710. ;;
  4711. --install)
  4712. _CMD="install"
  4713. ;;
  4714. --uninstall)
  4715. _CMD="uninstall"
  4716. ;;
  4717. --upgrade)
  4718. _CMD="upgrade"
  4719. ;;
  4720. --issue)
  4721. _CMD="issue"
  4722. ;;
  4723. --deploy)
  4724. _CMD="deploy"
  4725. ;;
  4726. --signcsr)
  4727. _CMD="signcsr"
  4728. ;;
  4729. --showcsr)
  4730. _CMD="showcsr"
  4731. ;;
  4732. --installcert | -i | --install-cert)
  4733. _CMD="installcert"
  4734. ;;
  4735. --renew | -r)
  4736. _CMD="renew"
  4737. ;;
  4738. --renewAll | --renewall | --renew-all)
  4739. _CMD="renewAll"
  4740. ;;
  4741. --revoke)
  4742. _CMD="revoke"
  4743. ;;
  4744. --remove)
  4745. _CMD="remove"
  4746. ;;
  4747. --list)
  4748. _CMD="list"
  4749. ;;
  4750. --installcronjob | --install-cronjob)
  4751. _CMD="installcronjob"
  4752. ;;
  4753. --uninstallcronjob | --uninstall-cronjob)
  4754. _CMD="uninstallcronjob"
  4755. ;;
  4756. --cron)
  4757. _CMD="cron"
  4758. ;;
  4759. --toPkcs)
  4760. _CMD="toPkcs"
  4761. ;;
  4762. --toPkcs8)
  4763. _CMD="toPkcs8"
  4764. ;;
  4765. --createAccountKey | --createaccountkey | -cak | --create-account-key)
  4766. _CMD="createAccountKey"
  4767. ;;
  4768. --createDomainKey | --createdomainkey | -cdk | --create-domain-key)
  4769. _CMD="createDomainKey"
  4770. ;;
  4771. --createCSR | --createcsr | -ccr)
  4772. _CMD="createCSR"
  4773. ;;
  4774. --deactivate)
  4775. _CMD="deactivate"
  4776. ;;
  4777. --updateaccount | --update-account)
  4778. _CMD="updateaccount"
  4779. ;;
  4780. --registeraccount | --register-account)
  4781. _CMD="registeraccount"
  4782. ;;
  4783. --deactivate-account)
  4784. _CMD="deactivateaccount"
  4785. ;;
  4786. --domain | -d)
  4787. _dvalue="$2"
  4788. if [ "$_dvalue" ]; then
  4789. if _startswith "$_dvalue" "-"; then
  4790. _err "'$_dvalue' is not a valid domain for parameter '$1'"
  4791. return 1
  4792. fi
  4793. if _is_idn "$_dvalue" && ! _exists idn; then
  4794. _err "It seems that $_dvalue is an IDN( Internationalized Domain Names), please install 'idn' command first."
  4795. return 1
  4796. fi
  4797. if [ -z "$_domain" ]; then
  4798. _domain="$_dvalue"
  4799. else
  4800. if _startswith "$_dvalue" "*."; then
  4801. _debug "Wildcard domain"
  4802. export ACME_VERSION=2
  4803. fi
  4804. if [ "$_altdomains" = "$NO_VALUE" ]; then
  4805. _altdomains="$_dvalue"
  4806. else
  4807. _altdomains="$_altdomains,$_dvalue"
  4808. fi
  4809. fi
  4810. fi
  4811. shift
  4812. ;;
  4813. --force | -f)
  4814. FORCE="1"
  4815. ;;
  4816. --staging | --test)
  4817. STAGE="1"
  4818. ;;
  4819. --server)
  4820. ACME_DIRECTORY="$2"
  4821. _server="$ACME_DIRECTORY"
  4822. export ACME_DIRECTORY
  4823. shift
  4824. ;;
  4825. --debug)
  4826. if [ -z "$2" ] || _startswith "$2" "-"; then
  4827. DEBUG="$DEBUG_LEVEL_DEFAULT"
  4828. else
  4829. DEBUG="$2"
  4830. shift
  4831. fi
  4832. ;;
  4833. --output-insecure)
  4834. export OUTPUT_INSECURE=1
  4835. ;;
  4836. --webroot | -w)
  4837. wvalue="$2"
  4838. if [ -z "$_webroot" ]; then
  4839. _webroot="$wvalue"
  4840. else
  4841. _webroot="$_webroot,$wvalue"
  4842. fi
  4843. shift
  4844. ;;
  4845. --standalone)
  4846. wvalue="$NO_VALUE"
  4847. if [ -z "$_webroot" ]; then
  4848. _webroot="$wvalue"
  4849. else
  4850. _webroot="$_webroot,$wvalue"
  4851. fi
  4852. ;;
  4853. --stateless)
  4854. wvalue="$MODE_STATELESS"
  4855. if [ -z "$_webroot" ]; then
  4856. _webroot="$wvalue"
  4857. else
  4858. _webroot="$_webroot,$wvalue"
  4859. fi
  4860. ;;
  4861. --local-address)
  4862. lvalue="$2"
  4863. _local_address="$_local_address$lvalue,"
  4864. shift
  4865. ;;
  4866. --apache)
  4867. wvalue="apache"
  4868. if [ -z "$_webroot" ]; then
  4869. _webroot="$wvalue"
  4870. else
  4871. _webroot="$_webroot,$wvalue"
  4872. fi
  4873. ;;
  4874. --nginx)
  4875. wvalue="$NGINX"
  4876. if [ -z "$_webroot" ]; then
  4877. _webroot="$wvalue"
  4878. else
  4879. _webroot="$_webroot,$wvalue"
  4880. fi
  4881. ;;
  4882. --tls)
  4883. wvalue="$W_TLS"
  4884. if [ -z "$_webroot" ]; then
  4885. _webroot="$wvalue"
  4886. else
  4887. _webroot="$_webroot,$wvalue"
  4888. fi
  4889. ;;
  4890. --dns)
  4891. wvalue="dns"
  4892. if [ "$2" ] && ! _startswith "$2" "-"; then
  4893. wvalue="$2"
  4894. shift
  4895. fi
  4896. if [ -z "$_webroot" ]; then
  4897. _webroot="$wvalue"
  4898. else
  4899. _webroot="$_webroot,$wvalue"
  4900. fi
  4901. ;;
  4902. --dnssleep)
  4903. _dnssleep="$2"
  4904. Le_DNSSleep="$_dnssleep"
  4905. shift
  4906. ;;
  4907. --keylength | -k)
  4908. _keylength="$2"
  4909. shift
  4910. ;;
  4911. --accountkeylength | -ak)
  4912. _accountkeylength="$2"
  4913. shift
  4914. ;;
  4915. --cert-file | --certpath)
  4916. _cert_file="$2"
  4917. shift
  4918. ;;
  4919. --key-file | --keypath)
  4920. _key_file="$2"
  4921. shift
  4922. ;;
  4923. --ca-file | --capath)
  4924. _ca_file="$2"
  4925. shift
  4926. ;;
  4927. --fullchain-file | --fullchainpath)
  4928. _fullchain_file="$2"
  4929. shift
  4930. ;;
  4931. --reloadcmd | --reloadCmd)
  4932. _reloadcmd="$2"
  4933. shift
  4934. ;;
  4935. --password)
  4936. _password="$2"
  4937. shift
  4938. ;;
  4939. --accountconf)
  4940. _accountconf="$2"
  4941. ACCOUNT_CONF_PATH="$_accountconf"
  4942. shift
  4943. ;;
  4944. --home)
  4945. LE_WORKING_DIR="$2"
  4946. shift
  4947. ;;
  4948. --certhome | --cert-home)
  4949. _certhome="$2"
  4950. CERT_HOME="$_certhome"
  4951. shift
  4952. ;;
  4953. --config-home)
  4954. _confighome="$2"
  4955. LE_CONFIG_HOME="$_confighome"
  4956. shift
  4957. ;;
  4958. --useragent)
  4959. _useragent="$2"
  4960. USER_AGENT="$_useragent"
  4961. shift
  4962. ;;
  4963. --accountemail)
  4964. _accountemail="$2"
  4965. ACCOUNT_EMAIL="$_accountemail"
  4966. shift
  4967. ;;
  4968. --accountkey)
  4969. _accountkey="$2"
  4970. ACCOUNT_KEY_PATH="$_accountkey"
  4971. shift
  4972. ;;
  4973. --days)
  4974. _days="$2"
  4975. Le_RenewalDays="$_days"
  4976. shift
  4977. ;;
  4978. --httpport)
  4979. _httpport="$2"
  4980. Le_HTTPPort="$_httpport"
  4981. shift
  4982. ;;
  4983. --tlsport)
  4984. _tlsport="$2"
  4985. Le_TLSPort="$_tlsport"
  4986. shift
  4987. ;;
  4988. --listraw)
  4989. _listraw="raw"
  4990. ;;
  4991. --stopRenewOnError | --stoprenewonerror | -se)
  4992. _stopRenewOnError="1"
  4993. ;;
  4994. --insecure)
  4995. #_insecure="1"
  4996. HTTPS_INSECURE="1"
  4997. ;;
  4998. --ca-bundle)
  4999. _ca_bundle="$(_readlink -f "$2")"
  5000. CA_BUNDLE="$_ca_bundle"
  5001. shift
  5002. ;;
  5003. --ca-path)
  5004. _ca_path="$2"
  5005. CA_PATH="$_ca_path"
  5006. shift
  5007. ;;
  5008. --nocron)
  5009. _nocron="1"
  5010. ;;
  5011. --no-color)
  5012. export ACME_NO_COLOR=1
  5013. ;;
  5014. --ecc)
  5015. _ecc="isEcc"
  5016. ;;
  5017. --csr)
  5018. _csr="$2"
  5019. shift
  5020. ;;
  5021. --pre-hook)
  5022. _pre_hook="$2"
  5023. shift
  5024. ;;
  5025. --post-hook)
  5026. _post_hook="$2"
  5027. shift
  5028. ;;
  5029. --renew-hook)
  5030. _renew_hook="$2"
  5031. shift
  5032. ;;
  5033. --deploy-hook)
  5034. if [ -z "$2" ] || _startswith "$2" "-"; then
  5035. _usage "Please specify a value for '--deploy-hook'"
  5036. return 1
  5037. fi
  5038. _deploy_hook="$_deploy_hook$2,"
  5039. shift
  5040. ;;
  5041. --ocsp-must-staple | --ocsp)
  5042. Le_OCSP_Staple="1"
  5043. ;;
  5044. --always-force-new-domain-key)
  5045. if [ -z "$2" ] || _startswith "$2" "-"; then
  5046. Le_ForceNewDomainKey=1
  5047. else
  5048. Le_ForceNewDomainKey="$2"
  5049. shift
  5050. fi
  5051. ;;
  5052. --log | --logfile)
  5053. _log="1"
  5054. _logfile="$2"
  5055. if _startswith "$_logfile" '-'; then
  5056. _logfile=""
  5057. else
  5058. shift
  5059. fi
  5060. LOG_FILE="$_logfile"
  5061. if [ -z "$LOG_LEVEL" ]; then
  5062. LOG_LEVEL="$DEFAULT_LOG_LEVEL"
  5063. fi
  5064. ;;
  5065. --log-level)
  5066. _log_level="$2"
  5067. LOG_LEVEL="$_log_level"
  5068. shift
  5069. ;;
  5070. --syslog)
  5071. if ! _startswith "$2" '-'; then
  5072. _syslog="$2"
  5073. shift
  5074. fi
  5075. if [ -z "$_syslog" ]; then
  5076. _syslog="$SYSLOG_LEVEL_DEFAULT"
  5077. fi
  5078. ;;
  5079. --auto-upgrade)
  5080. _auto_upgrade="$2"
  5081. if [ -z "$_auto_upgrade" ] || _startswith "$_auto_upgrade" '-'; then
  5082. _auto_upgrade="1"
  5083. else
  5084. shift
  5085. fi
  5086. AUTO_UPGRADE="$_auto_upgrade"
  5087. ;;
  5088. --listen-v4)
  5089. _listen_v4="1"
  5090. Le_Listen_V4="$_listen_v4"
  5091. ;;
  5092. --listen-v6)
  5093. _listen_v6="1"
  5094. Le_Listen_V6="$_listen_v6"
  5095. ;;
  5096. --openssl-bin)
  5097. _openssl_bin="$2"
  5098. ACME_OPENSSL_BIN="$_openssl_bin"
  5099. shift
  5100. ;;
  5101. --use-wget)
  5102. _use_wget="1"
  5103. ACME_USE_WGET="1"
  5104. ;;
  5105. *)
  5106. _err "Unknown parameter : $1"
  5107. return 1
  5108. ;;
  5109. esac
  5110. shift 1
  5111. done
  5112. if [ "${_CMD}" != "install" ]; then
  5113. __initHome
  5114. if [ "$_log" ]; then
  5115. if [ -z "$_logfile" ]; then
  5116. _logfile="$DEFAULT_LOG_FILE"
  5117. fi
  5118. fi
  5119. if [ "$_logfile" ]; then
  5120. _saveaccountconf "LOG_FILE" "$_logfile"
  5121. LOG_FILE="$_logfile"
  5122. fi
  5123. if [ "$_log_level" ]; then
  5124. _saveaccountconf "LOG_LEVEL" "$_log_level"
  5125. LOG_LEVEL="$_log_level"
  5126. fi
  5127. if [ "$_syslog" ]; then
  5128. if _exists logger; then
  5129. if [ "$_syslog" = "0" ]; then
  5130. _clearaccountconf "SYS_LOG"
  5131. else
  5132. _saveaccountconf "SYS_LOG" "$_syslog"
  5133. fi
  5134. SYS_LOG="$_syslog"
  5135. else
  5136. _err "The 'logger' command is not found, can not enable syslog."
  5137. _clearaccountconf "SYS_LOG"
  5138. SYS_LOG=""
  5139. fi
  5140. fi
  5141. _processAccountConf
  5142. fi
  5143. _debug2 LE_WORKING_DIR "$LE_WORKING_DIR"
  5144. if [ "$DEBUG" ]; then
  5145. version
  5146. if [ "$_server" ]; then
  5147. _debug "Using server: $_server"
  5148. fi
  5149. fi
  5150. case "${_CMD}" in
  5151. install) install "$_nocron" "$_confighome" ;;
  5152. uninstall) uninstall "$_nocron" ;;
  5153. upgrade) upgrade ;;
  5154. issue)
  5155. issue "$_webroot" "$_domain" "$_altdomains" "$_keylength" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_pre_hook" "$_post_hook" "$_renew_hook" "$_local_address"
  5156. ;;
  5157. deploy)
  5158. deploy "$_domain" "$_deploy_hook" "$_ecc"
  5159. ;;
  5160. signcsr)
  5161. signcsr "$_csr" "$_webroot"
  5162. ;;
  5163. showcsr)
  5164. showcsr "$_csr" "$_domain"
  5165. ;;
  5166. installcert)
  5167. installcert "$_domain" "$_cert_file" "$_key_file" "$_ca_file" "$_reloadcmd" "$_fullchain_file" "$_ecc"
  5168. ;;
  5169. renew)
  5170. renew "$_domain" "$_ecc"
  5171. ;;
  5172. renewAll)
  5173. renewAll "$_stopRenewOnError"
  5174. ;;
  5175. revoke)
  5176. revoke "$_domain" "$_ecc"
  5177. ;;
  5178. remove)
  5179. remove "$_domain" "$_ecc"
  5180. ;;
  5181. deactivate)
  5182. deactivate "$_domain,$_altdomains"
  5183. ;;
  5184. registeraccount)
  5185. registeraccount "$_accountkeylength"
  5186. ;;
  5187. updateaccount)
  5188. updateaccount
  5189. ;;
  5190. deactivateaccount)
  5191. deactivateaccount
  5192. ;;
  5193. list)
  5194. list "$_listraw"
  5195. ;;
  5196. installcronjob) installcronjob "$_confighome" ;;
  5197. uninstallcronjob) uninstallcronjob ;;
  5198. cron) cron ;;
  5199. toPkcs)
  5200. toPkcs "$_domain" "$_password" "$_ecc"
  5201. ;;
  5202. toPkcs8)
  5203. toPkcs8 "$_domain" "$_ecc"
  5204. ;;
  5205. createAccountKey)
  5206. createAccountKey "$_accountkeylength"
  5207. ;;
  5208. createDomainKey)
  5209. createDomainKey "$_domain" "$_keylength"
  5210. ;;
  5211. createCSR)
  5212. createCSR "$_domain" "$_altdomains" "$_ecc"
  5213. ;;
  5214. *)
  5215. if [ "$_CMD" ]; then
  5216. _err "Invalid command: $_CMD"
  5217. fi
  5218. showhelp
  5219. return 1
  5220. ;;
  5221. esac
  5222. _ret="$?"
  5223. if [ "$_ret" != "0" ]; then
  5224. return $_ret
  5225. fi
  5226. if [ "${_CMD}" = "install" ]; then
  5227. if [ "$_log" ]; then
  5228. if [ -z "$LOG_FILE" ]; then
  5229. LOG_FILE="$DEFAULT_LOG_FILE"
  5230. fi
  5231. _saveaccountconf "LOG_FILE" "$LOG_FILE"
  5232. fi
  5233. if [ "$_log_level" ]; then
  5234. _saveaccountconf "LOG_LEVEL" "$_log_level"
  5235. fi
  5236. if [ "$_syslog" ]; then
  5237. if _exists logger; then
  5238. if [ "$_syslog" = "0" ]; then
  5239. _clearaccountconf "SYS_LOG"
  5240. else
  5241. _saveaccountconf "SYS_LOG" "$_syslog"
  5242. fi
  5243. else
  5244. _err "The 'logger' command is not found, can not enable syslog."
  5245. _clearaccountconf "SYS_LOG"
  5246. SYS_LOG=""
  5247. fi
  5248. fi
  5249. _processAccountConf
  5250. fi
  5251. }
  5252. if [ "$INSTALLONLINE" ]; then
  5253. INSTALLONLINE=""
  5254. _installOnline
  5255. exit
  5256. fi
  5257. main() {
  5258. [ -z "$1" ] && showhelp && return
  5259. if _startswith "$1" '-'; then _process "$@"; else "$@"; fi
  5260. }
  5261. main "$@"