acme.sh 130 KB

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