acme.sh 129 KB

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