acme.sh 144 KB

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