acme.sh 140 KB

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