acme.sh 160 KB

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