acme.sh 143 KB

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