From 45e6d61cbbe0dde786055360af71eeeeb6ca6695 Mon Sep 17 00:00:00 2001 From: Simon Sudarushkin <68971770+simonether@users.noreply.github.com> Date: Mon, 5 Oct 2026 02:22:21 +0500 Subject: [PATCH] caddytls: add not matcher for TLS handshakes (#8138) (cherry picked from commit 8507b63cf03a7a0d90b2084f3aafbcc1d8e60a7b) --- modules/caddytls/matchers.go | 113 ++++++++++++++++++++++++ modules/caddytls/matchers_test.go | 139 ++++++++++++++++++++++++++++++ 2 files changed, 252 insertions(+) diff --git a/modules/caddytls/matchers.go b/modules/caddytls/matchers.go index 466292e41..d0cf30d8b 100644 --- a/modules/caddytls/matchers.go +++ b/modules/caddytls/matchers.go @@ -17,6 +17,7 @@ package caddytls import ( "context" "crypto/tls" + "encoding/json" "fmt" "net" "net/netip" @@ -40,6 +41,7 @@ func init() { caddy.RegisterModule(MatchServerNameRE{}) caddy.RegisterModule(MatchRemoteIP{}) caddy.RegisterModule(MatchLocalIP{}) + caddy.RegisterModule(MatchNot{}) } // MatchServerName matches based on SNI. Names in @@ -538,21 +540,132 @@ func (m *MatchLocalIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { return nil } +// MatchNot matches a TLS handshake by negating the results of its +// matcher sets. A single "not" matcher takes one or more matcher sets. +// Each matcher set is OR'ed; in other words, if any matcher set returns +// true, the final result of the "not" matcher is false. Individual +// matchers within a set work the same (i.e. different matchers in +// the same set are AND'ed). +// +// NOTE: The generated docs which describe the structure of this +// module are wrong because of how this type unmarshals JSON in a +// custom way. The correct structure is: +// +// ```json +// [{}, {}] +// ``` +// +// where each of the array elements is a matcher set, i.e. an +// object keyed by matcher name. +type MatchNot struct { + MatcherSetsRaw []caddy.ModuleMap `json:"-" caddy:"namespace=tls.handshake_match"` + + matcherSets [][]ConnectionMatcher +} + +// CaddyModule returns the Caddy module information. +func (MatchNot) CaddyModule() caddy.ModuleInfo { + return caddy.ModuleInfo{ + ID: "tls.handshake_match.not", + New: func() caddy.Module { return new(MatchNot) }, + } +} + +// UnmarshalJSON satisfies json.Unmarshaler. It puts the JSON +// bytes directly into m's MatcherSetsRaw field. +func (m *MatchNot) UnmarshalJSON(data []byte) error { + return json.Unmarshal(data, &m.MatcherSetsRaw) +} + +// MarshalJSON satisfies json.Marshaler by marshaling +// m's raw matcher sets. +func (m MatchNot) MarshalJSON() ([]byte, error) { + return json.Marshal(m.MatcherSetsRaw) +} + +// Provision loads the matcher modules to be negated. +func (m *MatchNot) Provision(ctx caddy.Context) error { + matcherSets, err := ctx.LoadModule(m, "MatcherSetsRaw") + if err != nil { + return fmt.Errorf("loading matcher sets: %v", err) + } + for _, modMap := range matcherSets.([]map[string]any) { + var ms []ConnectionMatcher + for _, modIface := range modMap { + cm, ok := modIface.(ConnectionMatcher) + if !ok { + return fmt.Errorf("module is not a TLS handshake matcher: %T", modIface) + } + ms = append(ms, cm) + } + m.matcherSets = append(m.matcherSets, ms) + } + return nil +} + +// Match returns true if hello does not match any of m's +// matcher sets. +func (m MatchNot) Match(hello *tls.ClientHelloInfo) bool { +setLoop: + for _, ms := range m.matcherSets { + for _, matcher := range ms { + if !matcher.Match(hello) { + continue setLoop + } + } + return false + } + return true +} + +// UnmarshalCaddyfile sets up the MatchNot from Caddyfile tokens. Syntax: +// +// not [] +// not { +// [] +// } +func (m *MatchNot) UnmarshalCaddyfile(d *caddyfile.Dispenser) error { + // iterate to merge multiple matchers into one + for d.Next() { + wrapper := d.Val() + + matcherSet, err := ParseCaddyfileNestedMatcherSet(d) + if err != nil { + return err + } + + // At least one matcher must be provided + if len(matcherSet) == 0 { + return d.Errf("malformed TLS handshake matcher '%s': no matchers to negate", wrapper) + } + + m.MatcherSetsRaw = append(m.MatcherSetsRaw, matcherSet) + } + + return nil +} + // Interface guards var ( _ ConnectionMatcher = (*MatchLocalIP)(nil) + _ ConnectionMatcher = (*MatchNot)(nil) _ ConnectionMatcher = (*MatchRemoteIP)(nil) _ ConnectionMatcher = (*MatchServerName)(nil) _ ConnectionMatcher = (*MatchServerNameRE)(nil) _ caddy.Provisioner = (*MatchLocalIP)(nil) + _ caddy.Provisioner = (*MatchNot)(nil) _ caddy.Provisioner = (*MatchRemoteIP)(nil) _ caddy.Provisioner = (*MatchServerNameRE)(nil) _ caddyfile.Unmarshaler = (*MatchLocalIP)(nil) + _ caddyfile.Unmarshaler = (*MatchNot)(nil) _ caddyfile.Unmarshaler = (*MatchRemoteIP)(nil) _ caddyfile.Unmarshaler = (*MatchServerName)(nil) _ caddyfile.Unmarshaler = (*MatchServerNameRE)(nil) + + _ json.Marshaler = (*MatchNot)(nil) + _ json.Unmarshaler = (*MatchNot)(nil) ) var wordRE = regexp.MustCompile(`\w+`) diff --git a/modules/caddytls/matchers_test.go b/modules/caddytls/matchers_test.go index 8b597b188..09fbc55e6 100644 --- a/modules/caddytls/matchers_test.go +++ b/modules/caddytls/matchers_test.go @@ -17,10 +17,12 @@ package caddytls import ( "context" "crypto/tls" + "encoding/json" "net" "testing" "github.com/caddyserver/caddy/v2" + "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile" ) func TestServerNameMatcher(t *testing.T) { @@ -302,6 +304,143 @@ func TestLocalIPMatcher(t *testing.T) { } } +func TestNotMatcher(t *testing.T) { + ctx, cancel := caddy.NewContext(caddy.Context{Context: context.Background()}) + defer cancel() + + for i, tc := range []struct { + config string + serverName string + input string + expect bool + }{ + { + config: `[]`, + input: "10.1.2.3:12345", + expect: true, + }, + { + config: `[{"local_ip": {"ranges": ["10.1.2.3"]}}]`, + input: "10.1.2.3:12345", + expect: false, + }, + { + config: `[{"local_ip": {"ranges": ["10.1.2.3"]}}]`, + input: "10.2.3.4:12345", + expect: true, + }, + { + config: `[{"remote_ip": {"ranges": ["10.0.0.0/8"]}, "sni": ["example.com"]}]`, + serverName: "example.com", + input: "10.1.2.3:12345", + expect: false, + }, + { + config: `[{"remote_ip": {"ranges": ["10.0.0.0/8"]}, "sni": ["example.com"]}]`, + serverName: "example.net", + input: "10.1.2.3:12345", + expect: true, + }, + { + config: `[{"remote_ip": {"ranges": ["10.0.0.0/8"]}}, {"sni": ["example.com"]}]`, + serverName: "example.com", + input: "192.168.1.1:12345", + expect: false, + }, + { + config: `[{"remote_ip": {"ranges": ["10.0.0.0/8"]}}, {"sni": ["example.com"]}]`, + serverName: "example.net", + input: "192.168.1.1:12345", + expect: true, + }, + { + config: `[{"not": [{"remote_ip": {"ranges": ["10.0.0.0/8"]}}]}]`, + input: "10.1.2.3:12345", + expect: true, + }, + } { + var matcher MatchNot + if err := json.Unmarshal([]byte(tc.config), &matcher); err != nil { + t.Fatalf("Test %d: unmarshaling config: %v", i, err) + } + if err := matcher.Provision(ctx); err != nil { + t.Fatalf("Test %d: Provision failed: %v", i, err) + } + + addr := testAddr(tc.input) + chi := &tls.ClientHelloInfo{ServerName: tc.serverName, Conn: testConn{addr: addr}} + + actual := matcher.Match(chi) + if actual != tc.expect { + t.Errorf("Test %d: Expected %t but got %t (config=%s input=%s serverName=%s)", + i, tc.expect, actual, tc.config, tc.input, tc.serverName) + } + } +} + +func TestNotMatcherUnmarshalCaddyfile(t *testing.T) { + for i, tc := range []struct { + input string + expect string + wantErr bool + }{ + { + input: `not local_ip 10.1.2.3`, + expect: `[{"local_ip":{"ranges":["10.1.2.3"]}}]`, + }, + { + input: `not { + remote_ip 10.0.0.0/8 + sni example.com + }`, + expect: `[{"remote_ip":{"ranges":["10.0.0.0/8"]},"sni":["example.com"]}]`, + }, + { + input: `not sni example.com + not remote_ip 10.0.0.0/8`, + expect: `[{"sni":["example.com"]},{"remote_ip":{"ranges":["10.0.0.0/8"]}}]`, + }, + { + input: `not not sni example.com`, + expect: `[{"not":[{"sni":["example.com"]}]}]`, + }, + { + input: `not`, + wantErr: true, + }, + { + input: `not { + }`, + wantErr: true, + }, + { + input: `not foo`, + wantErr: true, + }, + } { + var matcher MatchNot + err := matcher.UnmarshalCaddyfile(caddyfile.NewTestDispenser(tc.input)) + if tc.wantErr { + if err == nil { + t.Errorf("Test %d: expected error but got none", i) + } + continue + } + if err != nil { + t.Errorf("Test %d: unexpected error: %v", i, err) + continue + } + + actual, err := json.Marshal(matcher) + if err != nil { + t.Fatalf("Test %d: marshaling matcher: %v", i, err) + } + if string(actual) != tc.expect { + t.Errorf("Test %d: expected %s, got %s", i, tc.expect, actual) + } + } +} + type testConn struct { *net.TCPConn addr testAddr