From 5b13c65a82a395e81260983ac6684a589600bc2b Mon Sep 17 00:00:00 2001 From: vnxme <46669194+vnxme@users.noreply.github.com> Date: Fri, 24 Jan 2025 10:28:26 +0300 Subject: [PATCH] caddytls: Fix sni_regexp matcher --- modules/caddytls/matchers.go | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/modules/caddytls/matchers.go b/modules/caddytls/matchers.go index a74d6ea80..eb466ea34 100644 --- a/modules/caddytls/matchers.go +++ b/modules/caddytls/matchers.go @@ -15,6 +15,7 @@ package caddytls import ( + "context" "crypto/tls" "fmt" "net" @@ -224,13 +225,26 @@ func (MatchServerNameRE) CaddyModule() caddy.ModuleInfo { // Match matches hello based on SNI using a regular expression. func (m MatchServerNameRE) Match(hello *tls.ClientHelloInfo) bool { - repl := caddy.NewReplacer() + var repl *caddy.Replacer // caddytls.TestServerNameMatcher calls this function without any context if ctx := hello.Context(); ctx != nil { // In some situations the existing context may have no replacer if replAny := ctx.Value(caddy.ReplacerCtxKey); replAny != nil { repl = replAny.(*caddy.Replacer) } + } else if mayHaveContext, ok := hello.Conn.(interface{ GetContext() context.Context }); ok { + // layer4.Connection implements GetContext() to pass its context here, + // since hello.Context() returns nil + if ctx = mayHaveContext.GetContext(); ctx != nil { + // In some situations the existing context may have no replacer + if replAny := ctx.Value(caddy.ReplacerCtxKey); replAny != nil { + repl = replAny.(*caddy.Replacer) + } + } + } + + if repl == nil { + repl = caddy.NewReplacer() } return m.MatchRegexp.Match(hello.ServerName, repl)