Debian Codegraph @

modules/caddytls/matchers.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddytls
16
17 import (
18 "context"
19 "crypto/tls"
20 "fmt"
21 "net"
22 "net/netip"
23 "regexp"
24 "slices"
25 "strconv"
26 "strings"
27
28 "github.com/caddyserver/certmagic"
29 "go.uber.org/zap"
30 "go.uber.org/zap/zapcore"
31 "golang.org/x/net/idna"
32
33 "github.com/caddyserver/caddy/v2"
34 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
35 "github.com/caddyserver/caddy/v2/internal"
36 )
37
38 func init() {
39 caddy.RegisterModule(MatchServerName{})
40 caddy.RegisterModule(MatchServerNameRE{})
41 caddy.RegisterModule(MatchRemoteIP{})
42 caddy.RegisterModule(MatchLocalIP{})
43 }
44
45 // MatchServerName matches based on SNI. Names in
46 // this list may use left-most-label wildcards,
47 // similar to wildcard certificates.
48 type MatchServerName []string
49
50 // CaddyModule returns the Caddy module information.
51 func (MatchServerName) CaddyModule() caddy.ModuleInfo {
52 return caddy.ModuleInfo{
53 ID: "tls.handshake_match.sni",
54 New: func() caddy.Module { return new(MatchServerName) },
55 }
56 }
57
58 // Match matches hello based on SNI.
59 func (m MatchServerName) Match(hello *tls.ClientHelloInfo) bool {
60 var repl *caddy.Replacer
61 // caddytls.TestServerNameMatcher calls this function without any context
62 if ctx := hello.Context(); ctx != nil {
63 // In some situations the existing context may have no replacer
64 if replAny := ctx.Value(caddy.ReplacerCtxKey); replAny != nil {
65 repl = replAny.(*caddy.Replacer)
66 }
67 }
68
69 if repl == nil {
70 repl = caddy.NewReplacer()
71 }
72
73 serverName := asciiServerNameForMatch(hello.ServerName)
74 for _, name := range m {
75 rs := asciiServerNameForMatch(repl.ReplaceAll(name, ""))
76 if certmagic.MatchWildcard(serverName, rs) {
77 return true
78 }
79 }
80 return false
81 }
82
83 func asciiServerNameForMatch(name string) string {
84 if name == "" {
85 return name
86 }
87
88 // Fast path: if the name is pure ASCII, skip idna.ToASCII.
89 // SNI values on the wire are always ASCII (RFC 6066), and most
90 // config patterns are also ASCII. For pure ASCII input, idna.ToASCII
91 // only validates and lowercases, which is equivalent to our fallback.
92 if isPureASCII(name) {
93 return strings.ToLower(name)
94 }
95
96 // Config can use Unicode IDNs.
97 ascii, err := idna.ToASCII(name)
98 if err == nil {
99 return strings.ToLower(ascii)
100 }
101
102 if !strings.Contains(name, "*") {
103 return strings.ToLower(name)
104 }
105
106 labels := strings.Split(name, ".")
107 for i, label := range labels {
108 if label == "" || label == "*" {
109 continue
110 }
111 ascii, err := idna.ToASCII(label)
112 if err != nil {
113 return strings.ToLower(name)
114 }
115 labels[i] = strings.ToLower(ascii)
116 }
117 return strings.Join(labels, ".")
118 }
119
120 func isPureASCII(s string) bool {
121 for i := 0; i < len(s); i++ {
122 if s[i] >= 0x80 {
123 return false
124 }
125 }
126 return true
127 }
128
129 // UnmarshalCaddyfile sets up the MatchServerName from Caddyfile tokens. Syntax:
130 //
131 // sni <domains...>
132 func (m *MatchServerName) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
133 for d.Next() {
134 wrapper := d.Val()
135
136 // At least one same-line option must be provided
137 if d.CountRemainingArgs() == 0 {
138 return d.ArgErr()
139 }
140
141 *m = append(*m, d.RemainingArgs()...)
142
143 // No blocks are supported
144 if d.NextBlock(d.Nesting()) {
145 return d.Errf("malformed TLS handshake matcher '%s': blocks are not supported", wrapper)
146 }
147 }
148
149 return nil
150 }
151
152 // MatchRegexp is an embeddable type for matching
153 // using regular expressions. It adds placeholders
154 // to the request's replacer. In fact, it is a copy of
155 // caddyhttp.MatchRegexp with a local replacer prefix
156 // and placeholders support in a regular expression pattern.
157 type MatchRegexp struct {
158 // A unique name for this regular expression. Optional,
159 // but useful to prevent overwriting captures from other
160 // regexp matchers.
161 Name string `json:"name,omitempty"`
162
163 // The regular expression to evaluate, in RE2 syntax,
164 // which is the same general syntax used by Go, Perl,
165 // and Python. For details, see
166 // [Go's regexp package](https://golang.org/pkg/regexp/).
167 // Captures are accessible via placeholders. Unnamed
168 // capture groups are exposed as their numeric, 1-based
169 // index, while named capture groups are available by
170 // the capture group name.
171 Pattern string `json:"pattern"`
172
173 compiled *regexp.Regexp
174 }
175
176 // Provision compiles the regular expression which may include placeholders.
177 func (mre *MatchRegexp) Provision(caddy.Context) error {
178 repl := caddy.NewReplacer()
179 re, err := regexp.Compile(repl.ReplaceAll(mre.Pattern, ""))
180 if err != nil {
181 return fmt.Errorf("compiling matcher regexp %s: %v", mre.Pattern, err)
182 }
183 mre.compiled = re
184 return nil
185 }
186
187 // Validate ensures mre is set up correctly.
188 func (mre *MatchRegexp) Validate() error {
189 if mre.Name != "" && !wordRE.MatchString(mre.Name) {
190 return fmt.Errorf("invalid regexp name (must contain only word characters): %s", mre.Name)
191 }
192 return nil
193 }
194
195 // Match returns true if input matches the compiled regular
196 // expression in m. It sets values on the replacer repl
197 // associated with capture groups, using the given scope
198 // (namespace).
199 func (mre *MatchRegexp) Match(input string, repl *caddy.Replacer) bool {
200 matches := mre.compiled.FindStringSubmatch(input)
201 if matches == nil {
202 return false
203 }
204
205 // save all capture groups, first by index
206 for i, match := range matches {
207 keySuffix := "." + strconv.Itoa(i)
208 if mre.Name != "" {
209 repl.Set(regexpPlaceholderPrefix+"."+mre.Name+keySuffix, match)
210 }
211 repl.Set(regexpPlaceholderPrefix+keySuffix, match)
212 }
213
214 // then by name
215 for i, name := range mre.compiled.SubexpNames() {
216 // skip the first element (the full match), and empty names
217 if i == 0 || name == "" {
218 continue
219 }
220
221 keySuffix := "." + name
222 if mre.Name != "" {
223 repl.Set(regexpPlaceholderPrefix+"."+mre.Name+keySuffix, matches[i])
224 }
225 repl.Set(regexpPlaceholderPrefix+keySuffix, matches[i])
226 }
227
228 return true
229 }
230
231 // UnmarshalCaddyfile implements caddyfile.Unmarshaler.
232 func (mre *MatchRegexp) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
233 // iterate to merge multiple matchers into one
234 for d.Next() {
235 // If this is the second iteration of the loop
236 // then there's more than one *_regexp matcher,
237 // and we would end up overwriting the old one
238 if mre.Pattern != "" {
239 return d.Err("regular expression can only be used once per named matcher")
240 }
241
242 args := d.RemainingArgs()
243 switch len(args) {
244 case 1:
245 mre.Pattern = args[0]
246 case 2:
247 mre.Name = args[0]
248 mre.Pattern = args[1]
249 default:
250 return d.ArgErr()
251 }
252
253 // Default to the named matcher's name, if no regexp name is provided.
254 // Note: it requires d.SetContext(caddyfile.MatcherNameCtxKey, value)
255 // called before this unmarshalling, otherwise it wouldn't work.
256 if mre.Name == "" {
257 mre.Name = d.GetContextString(caddyfile.MatcherNameCtxKey)
258 }
259
260 if d.NextBlock(0) {
261 return d.Err("malformed regexp matcher: blocks are not supported")
262 }
263 }
264 return nil
265 }
266
267 // MatchServerNameRE matches based on SNI using a regular expression.
268 type MatchServerNameRE struct{ MatchRegexp }
269
270 // CaddyModule returns the Caddy module information.
271 func (MatchServerNameRE) CaddyModule() caddy.ModuleInfo {
272 return caddy.ModuleInfo{
273 ID: "tls.handshake_match.sni_regexp",
274 New: func() caddy.Module { return new(MatchServerNameRE) },
275 }
276 }
277
278 // Match matches hello based on SNI using a regular expression.
279 func (m MatchServerNameRE) Match(hello *tls.ClientHelloInfo) bool {
280 // Note: caddytls.TestServerNameMatcher calls this function without any context
281 ctx := hello.Context()
282 if ctx == nil {
283 // layer4.Connection implements GetContext() to pass its context here,
284 // since hello.Context() returns nil
285 if mayHaveContext, ok := hello.Conn.(interface{ GetContext() context.Context }); ok {
286 ctx = mayHaveContext.GetContext()
287 }
288 }
289
290 var repl *caddy.Replacer
291 if ctx != nil {
292 // In some situations the existing context may have no replacer
293 if replAny := ctx.Value(caddy.ReplacerCtxKey); replAny != nil {
294 repl = replAny.(*caddy.Replacer)
295 }
296 }
297
298 if repl == nil {
299 repl = caddy.NewReplacer()
300 }
301
302 return m.MatchRegexp.Match(hello.ServerName, repl)
303 }
304
305 // MatchRemoteIP matches based on the remote IP of the
306 // connection. Specific IPs or CIDR ranges can be specified.
307 //
308 // Note that IPs can sometimes be spoofed, so do not rely
309 // on this as a replacement for actual authentication.
310 type MatchRemoteIP struct {
311 // The IPs or CIDR ranges to match.
312 Ranges []string `json:"ranges,omitempty"`
313
314 // The IPs or CIDR ranges to *NOT* match.
315 NotRanges []string `json:"not_ranges,omitempty"`
316
317 cidrs []netip.Prefix
318 notCidrs []netip.Prefix
319 logger *zap.Logger
320 }
321
322 // CaddyModule returns the Caddy module information.
323 func (MatchRemoteIP) CaddyModule() caddy.ModuleInfo {
324 return caddy.ModuleInfo{
325 ID: "tls.handshake_match.remote_ip",
326 New: func() caddy.Module { return new(MatchRemoteIP) },
327 }
328 }
329
330 // Provision parses m's IP ranges, either from IP or CIDR expressions.
331 func (m *MatchRemoteIP) Provision(ctx caddy.Context) error {
332 repl := caddy.NewReplacer()
333 m.logger = ctx.Logger()
334 for _, str := range m.Ranges {
335 rs := repl.ReplaceAll(str, "")
336 cidrs, err := m.parseIPRange(rs)
337 if err != nil {
338 return err
339 }
340 m.cidrs = append(m.cidrs, cidrs...)
341 }
342 for _, str := range m.NotRanges {
343 rs := repl.ReplaceAll(str, "")
344 cidrs, err := m.parseIPRange(rs)
345 if err != nil {
346 return err
347 }
348 m.notCidrs = append(m.notCidrs, cidrs...)
349 }
350 return nil
351 }
352
353 // Match matches hello based on the connection's remote IP.
354 func (m MatchRemoteIP) Match(hello *tls.ClientHelloInfo) bool {
355 remoteAddr := hello.Conn.RemoteAddr().String()
356 ipStr, _, err := net.SplitHostPort(remoteAddr)
357 if err != nil {
358 ipStr = remoteAddr // weird; maybe no port?
359 }
360 ipAddr, err := netip.ParseAddr(ipStr)
361 if err != nil {
362 if c := m.logger.Check(zapcore.ErrorLevel, "invalid client IP address"); c != nil {
363 c.Write(zap.String("ip", ipStr))
364 }
365 return false
366 }
367 return (len(m.cidrs) == 0 || m.matches(ipAddr, m.cidrs)) &&
368 (len(m.notCidrs) == 0 || !m.matches(ipAddr, m.notCidrs))
369 }
370
371 func (MatchRemoteIP) parseIPRange(str string) ([]netip.Prefix, error) {
372 var cidrs []netip.Prefix
373 if strings.Contains(str, "/") {
374 ipNet, err := netip.ParsePrefix(str)
375 if err != nil {
376 return nil, fmt.Errorf("parsing CIDR expression: %v", err)
377 }
378 cidrs = append(cidrs, ipNet)
379 } else {
380 ipAddr, err := netip.ParseAddr(str)
381 if err != nil {
382 return nil, fmt.Errorf("invalid IP address: '%s': %v", str, err)
383 }
384 ip := netip.PrefixFrom(ipAddr, ipAddr.BitLen())
385 cidrs = append(cidrs, ip)
386 }
387 return cidrs, nil
388 }
389
390 func (MatchRemoteIP) matches(ip netip.Addr, ranges []netip.Prefix) bool {
391 return slices.ContainsFunc(ranges, func(prefix netip.Prefix) bool {
392 return prefix.Contains(ip)
393 })
394 }
395
396 // UnmarshalCaddyfile sets up the MatchRemoteIP from Caddyfile tokens. Syntax:
397 //
398 // remote_ip <ranges...>
399 //
400 // Note: IPs and CIDRs prefixed with ! symbol are treated as not_ranges
401 func (m *MatchRemoteIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
402 for d.Next() {
403 wrapper := d.Val()
404
405 // At least one same-line option must be provided
406 if d.CountRemainingArgs() == 0 {
407 return d.ArgErr()
408 }
409
410 for d.NextArg() {
411 val := d.Val()
412 var exclamation bool
413 if len(val) > 1 && val[0] == '!' {
414 exclamation, val = true, val[1:]
415 }
416 ranges := []string{val}
417 if val == "private_ranges" {
418 ranges = internal.PrivateRangesCIDR()
419 }
420 if exclamation {
421 m.NotRanges = append(m.NotRanges, ranges...)
422 } else {
423 m.Ranges = append(m.Ranges, ranges...)
424 }
425 }
426
427 // No blocks are supported
428 if d.NextBlock(d.Nesting()) {
429 return d.Errf("malformed TLS handshake matcher '%s': blocks are not supported", wrapper)
430 }
431 }
432
433 return nil
434 }
435
436 // MatchLocalIP matches based on the IP address of the interface
437 // receiving the connection. Specific IPs or CIDR ranges can be specified.
438 type MatchLocalIP struct {
439 // The IPs or CIDR ranges to match.
440 Ranges []string `json:"ranges,omitempty"`
441
442 cidrs []netip.Prefix
443 logger *zap.Logger
444 }
445
446 // CaddyModule returns the Caddy module information.
447 func (MatchLocalIP) CaddyModule() caddy.ModuleInfo {
448 return caddy.ModuleInfo{
449 ID: "tls.handshake_match.local_ip",
450 New: func() caddy.Module { return new(MatchLocalIP) },
451 }
452 }
453
454 // Provision parses m's IP ranges, either from IP or CIDR expressions.
455 func (m *MatchLocalIP) Provision(ctx caddy.Context) error {
456 repl := caddy.NewReplacer()
457 m.logger = ctx.Logger()
458 for _, str := range m.Ranges {
459 rs := repl.ReplaceAll(str, "")
460 cidrs, err := m.parseIPRange(rs)
461 if err != nil {
462 return err
463 }
464 m.cidrs = append(m.cidrs, cidrs...)
465 }
466 return nil
467 }
468
469 // Match matches hello based on the connection's remote IP.
470 func (m MatchLocalIP) Match(hello *tls.ClientHelloInfo) bool {
471 localAddr := hello.Conn.LocalAddr().String()
472 ipStr, _, err := net.SplitHostPort(localAddr)
473 if err != nil {
474 ipStr = localAddr // weird; maybe no port?
475 }
476 ipAddr, err := netip.ParseAddr(ipStr)
477 if err != nil {
478 if c := m.logger.Check(zapcore.ErrorLevel, "invalid local IP address"); c != nil {
479 c.Write(zap.String("ip", ipStr))
480 }
481 return false
482 }
483 return (len(m.cidrs) == 0 || m.matches(ipAddr, m.cidrs))
484 }
485
486 func (MatchLocalIP) parseIPRange(str string) ([]netip.Prefix, error) {
487 var cidrs []netip.Prefix
488 if strings.Contains(str, "/") {
489 ipNet, err := netip.ParsePrefix(str)
490 if err != nil {
491 return nil, fmt.Errorf("parsing CIDR expression: %v", err)
492 }
493 cidrs = append(cidrs, ipNet)
494 } else {
495 ipAddr, err := netip.ParseAddr(str)
496 if err != nil {
497 return nil, fmt.Errorf("invalid IP address: '%s': %v", str, err)
498 }
499 ip := netip.PrefixFrom(ipAddr, ipAddr.BitLen())
500 cidrs = append(cidrs, ip)
501 }
502 return cidrs, nil
503 }
504
505 func (MatchLocalIP) matches(ip netip.Addr, ranges []netip.Prefix) bool {
506 return slices.ContainsFunc(ranges, func(prefix netip.Prefix) bool {
507 return prefix.Contains(ip)
508 })
509 }
510
511 // UnmarshalCaddyfile sets up the MatchLocalIP from Caddyfile tokens. Syntax:
512 //
513 // local_ip <ranges...>
514 func (m *MatchLocalIP) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
515 for d.Next() {
516 wrapper := d.Val()
517
518 // At least one same-line option must be provided
519 if d.CountRemainingArgs() == 0 {
520 return d.ArgErr()
521 }
522
523 for d.NextArg() {
524 val := d.Val()
525 if val == "private_ranges" {
526 m.Ranges = append(m.Ranges, internal.PrivateRangesCIDR()...)
527 continue
528 }
529 m.Ranges = append(m.Ranges, val)
530 }
531
532 // No blocks are supported
533 if d.NextBlock(d.Nesting()) {
534 return d.Errf("malformed TLS handshake matcher '%s': blocks are not supported", wrapper)
535 }
536 }
537
538 return nil
539 }
540
541 // Interface guards
542 var (
543 _ ConnectionMatcher = (*MatchLocalIP)(nil)
544 _ ConnectionMatcher = (*MatchRemoteIP)(nil)
545 _ ConnectionMatcher = (*MatchServerName)(nil)
546 _ ConnectionMatcher = (*MatchServerNameRE)(nil)
547
548 _ caddy.Provisioner = (*MatchLocalIP)(nil)
549 _ caddy.Provisioner = (*MatchRemoteIP)(nil)
550 _ caddy.Provisioner = (*MatchServerNameRE)(nil)
551
552 _ caddyfile.Unmarshaler = (*MatchLocalIP)(nil)
553 _ caddyfile.Unmarshaler = (*MatchRemoteIP)(nil)
554 _ caddyfile.Unmarshaler = (*MatchServerName)(nil)
555 _ caddyfile.Unmarshaler = (*MatchServerNameRE)(nil)
556 )
557
558 var wordRE = regexp.MustCompile(`\w+`)
559
560 const regexpPlaceholderPrefix = "tls.regexp"