acme.sh 190 KB

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