Debian Codegraph @

modules/logging/filters.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 logging
16
17 import (
18 "crypto/sha256"
19 "errors"
20 "fmt"
21 "net"
22 "net/http"
23 "net/url"
24 "regexp"
25 "strconv"
26 "strings"
27
28 "go.uber.org/zap/zapcore"
29
30 "github.com/caddyserver/caddy/v2"
31 "github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
32 "github.com/caddyserver/caddy/v2/internal"
33 )
34
35 func init() {
36 caddy.RegisterModule(DeleteFilter{})
37 caddy.RegisterModule(HashFilter{})
38 caddy.RegisterModule(ReplaceFilter{})
39 caddy.RegisterModule(IPMaskFilter{})
40 caddy.RegisterModule(QueryFilter{})
41 caddy.RegisterModule(CookieFilter{})
42 caddy.RegisterModule(RegexpFilter{})
43 caddy.RegisterModule(RenameFilter{})
44 caddy.RegisterModule(MultiRegexpFilter{})
45 }
46
47 // LogFieldFilter can filter (or manipulate)
48 // a field in a log entry.
49 type LogFieldFilter interface {
50 Filter(zapcore.Field) zapcore.Field
51 }
52
53 // DeleteFilter is a Caddy log field filter that
54 // deletes the field.
55 type DeleteFilter struct{}
56
57 // CaddyModule returns the Caddy module information.
58 func (DeleteFilter) CaddyModule() caddy.ModuleInfo {
59 return caddy.ModuleInfo{
60 ID: "caddy.logging.encoders.filter.delete",
61 New: func() caddy.Module { return new(DeleteFilter) },
62 }
63 }
64
65 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
66 func (DeleteFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
67 return nil
68 }
69
70 // Filter filters the input field.
71 func (DeleteFilter) Filter(in zapcore.Field) zapcore.Field {
72 in.Type = zapcore.SkipType
73 return in
74 }
75
76 // hash returns the first 4 bytes of the SHA-256 hash of the given data as hexadecimal
77 func hash(s string) string {
78 return fmt.Sprintf("%.4x", sha256.Sum256([]byte(s)))
79 }
80
81 // HashFilter is a Caddy log field filter that
82 // replaces the field with the initial 4 bytes
83 // of the SHA-256 hash of the content. Operates
84 // on string fields, or on arrays of strings
85 // where each string is hashed.
86 type HashFilter struct{}
87
88 // CaddyModule returns the Caddy module information.
89 func (HashFilter) CaddyModule() caddy.ModuleInfo {
90 return caddy.ModuleInfo{
91 ID: "caddy.logging.encoders.filter.hash",
92 New: func() caddy.Module { return new(HashFilter) },
93 }
94 }
95
96 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
97 func (f *HashFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
98 return nil
99 }
100
101 // Filter filters the input field with the replacement value.
102 func (f *HashFilter) Filter(in zapcore.Field) zapcore.Field {
103 if array, ok := in.Interface.(internal.LoggableStringArray); ok {
104 newArray := make(internal.LoggableStringArray, len(array))
105 for i, s := range array {
106 newArray[i] = hash(s)
107 }
108 in.Interface = newArray
109 } else {
110 in.String = hash(in.String)
111 }
112
113 return in
114 }
115
116 // ReplaceFilter is a Caddy log field filter that
117 // replaces the field with the indicated string.
118 type ReplaceFilter struct {
119 Value string `json:"value,omitempty"`
120 }
121
122 // CaddyModule returns the Caddy module information.
123 func (ReplaceFilter) CaddyModule() caddy.ModuleInfo {
124 return caddy.ModuleInfo{
125 ID: "caddy.logging.encoders.filter.replace",
126 New: func() caddy.Module { return new(ReplaceFilter) },
127 }
128 }
129
130 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
131 func (f *ReplaceFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
132 d.Next() // consume filter name
133 if d.NextArg() {
134 f.Value = d.Val()
135 }
136 return nil
137 }
138
139 // Filter filters the input field with the replacement value.
140 func (f *ReplaceFilter) Filter(in zapcore.Field) zapcore.Field {
141 in.Type = zapcore.StringType
142 in.String = f.Value
143 return in
144 }
145
146 // IPMaskFilter is a Caddy log field filter that
147 // masks IP addresses in a string, or in an array
148 // of strings. The string may be a comma separated
149 // list of IP addresses, where all of the values
150 // will be masked.
151 type IPMaskFilter struct {
152 // The IPv4 mask, as a subnet size CIDR.
153 IPv4MaskRaw int `json:"ipv4_cidr,omitempty"`
154
155 // The IPv6 mask, as a subnet size CIDR.
156 IPv6MaskRaw int `json:"ipv6_cidr,omitempty"`
157
158 v4Mask net.IPMask
159 v6Mask net.IPMask
160 }
161
162 // CaddyModule returns the Caddy module information.
163 func (IPMaskFilter) CaddyModule() caddy.ModuleInfo {
164 return caddy.ModuleInfo{
165 ID: "caddy.logging.encoders.filter.ip_mask",
166 New: func() caddy.Module { return new(IPMaskFilter) },
167 }
168 }
169
170 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
171 func (m *IPMaskFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
172 d.Next() // consume filter name
173
174 args := d.RemainingArgs()
175 if len(args) > 2 {
176 return d.Errf("too many arguments")
177 }
178 if len(args) > 0 {
179 val, err := strconv.Atoi(args[0])
180 if err != nil {
181 return d.Errf("error parsing %s: %v", args[0], err)
182 }
183 m.IPv4MaskRaw = val
184
185 if len(args) > 1 {
186 val, err := strconv.Atoi(args[1])
187 if err != nil {
188 return d.Errf("error parsing %s: %v", args[1], err)
189 }
190 m.IPv6MaskRaw = val
191 }
192 }
193
194 for d.NextBlock(0) {
195 switch d.Val() {
196 case "ipv4":
197 if !d.NextArg() {
198 return d.ArgErr()
199 }
200 val, err := strconv.Atoi(d.Val())
201 if err != nil {
202 return d.Errf("error parsing %s: %v", d.Val(), err)
203 }
204 m.IPv4MaskRaw = val
205
206 case "ipv6":
207 if !d.NextArg() {
208 return d.ArgErr()
209 }
210 val, err := strconv.Atoi(d.Val())
211 if err != nil {
212 return d.Errf("error parsing %s: %v", d.Val(), err)
213 }
214 m.IPv6MaskRaw = val
215
216 default:
217 return d.Errf("unrecognized subdirective %s", d.Val())
218 }
219 }
220 return nil
221 }
222
223 // Provision parses m's IP masks, from integers.
224 func (m *IPMaskFilter) Provision(ctx caddy.Context) error {
225 parseRawToMask := func(rawField int, bitLen int) net.IPMask {
226 if rawField == 0 {
227 return nil
228 }
229
230 // we assume the int is a subnet size CIDR
231 // e.g. "16" being equivalent to masking the last
232 // two bytes of an ipv4 address, like "255.255.0.0"
233 return net.CIDRMask(rawField, bitLen)
234 }
235
236 m.v4Mask = parseRawToMask(m.IPv4MaskRaw, 32)
237 m.v6Mask = parseRawToMask(m.IPv6MaskRaw, 128)
238
239 return nil
240 }
241
242 // Filter filters the input field.
243 func (m IPMaskFilter) Filter(in zapcore.Field) zapcore.Field {
244 if array, ok := in.Interface.(internal.LoggableStringArray); ok {
245 newArray := make(internal.LoggableStringArray, len(array))
246 for i, s := range array {
247 newArray[i] = m.mask(s)
248 }
249 in.Interface = newArray
250 } else {
251 in.String = m.mask(in.String)
252 }
253
254 return in
255 }
256
257 func (m IPMaskFilter) mask(s string) string {
258 parts := make([]string, 0)
259 for value := range strings.SplitSeq(s, ",") {
260 value = strings.TrimSpace(value)
261 host, port, err := net.SplitHostPort(value)
262 if err != nil {
263 host = value // assume whole thing was IP address
264 }
265 ipAddr := net.ParseIP(host)
266 if ipAddr == nil {
267 parts = append(parts, value)
268 continue
269 }
270 mask := m.v4Mask
271 if ipAddr.To4() == nil {
272 mask = m.v6Mask
273 }
274 masked := ipAddr.Mask(mask)
275 if port == "" {
276 parts = append(parts, masked.String())
277 continue
278 }
279
280 parts = append(parts, net.JoinHostPort(masked.String(), port))
281 }
282 return strings.Join(parts, ", ")
283 }
284
285 type filterAction string
286
287 const (
288 // Replace value(s).
289 replaceAction filterAction = "replace"
290
291 // Hash value(s).
292 hashAction filterAction = "hash"
293
294 // Delete.
295 deleteAction filterAction = "delete"
296 )
297
298 func (a filterAction) IsValid() error {
299 switch a {
300 case replaceAction, deleteAction, hashAction:
301 return nil
302 }
303
304 return errors.New("invalid action type")
305 }
306
307 type queryFilterAction struct {
308 // `replace` to replace the value(s) associated with the parameter(s), `hash` to replace them with the 4 initial bytes of the SHA-256 of their content or `delete` to remove them entirely.
309 Type filterAction `json:"type"`
310
311 // The name of the query parameter.
312 Parameter string `json:"parameter"`
313
314 // The value to use as replacement if the action is `replace`.
315 Value string `json:"value,omitempty"`
316 }
317
318 // QueryFilter is a Caddy log field filter that filters
319 // query parameters from a URL.
320 //
321 // This filter updates the logged URL string to remove, replace or hash
322 // query parameters containing sensitive data. For instance, it can be
323 // used to redact any kind of secrets which were passed as query parameters,
324 // such as OAuth access tokens, session IDs, magic link tokens, etc.
325 type QueryFilter struct {
326 // A list of actions to apply to the query parameters of the URL.
327 Actions []queryFilterAction `json:"actions"`
328 }
329
330 // Validate checks that action types are correct.
331 func (f *QueryFilter) Validate() error {
332 for _, a := range f.Actions {
333 if err := a.Type.IsValid(); err != nil {
334 return err
335 }
336 }
337
338 return nil
339 }
340
341 // CaddyModule returns the Caddy module information.
342 func (QueryFilter) CaddyModule() caddy.ModuleInfo {
343 return caddy.ModuleInfo{
344 ID: "caddy.logging.encoders.filter.query",
345 New: func() caddy.Module { return new(QueryFilter) },
346 }
347 }
348
349 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
350 func (m *QueryFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
351 d.Next() // consume filter name
352 for d.NextBlock(0) {
353 qfa := queryFilterAction{}
354 switch d.Val() {
355 case "replace":
356 if !d.NextArg() {
357 return d.ArgErr()
358 }
359
360 qfa.Type = replaceAction
361 qfa.Parameter = d.Val()
362
363 if !d.NextArg() {
364 return d.ArgErr()
365 }
366 qfa.Value = d.Val()
367
368 case "hash":
369 if !d.NextArg() {
370 return d.ArgErr()
371 }
372
373 qfa.Type = hashAction
374 qfa.Parameter = d.Val()
375
376 case "delete":
377 if !d.NextArg() {
378 return d.ArgErr()
379 }
380
381 qfa.Type = deleteAction
382 qfa.Parameter = d.Val()
383
384 default:
385 return d.Errf("unrecognized subdirective %s", d.Val())
386 }
387
388 m.Actions = append(m.Actions, qfa)
389 }
390 return nil
391 }
392
393 // Filter filters the input field.
394 func (m QueryFilter) Filter(in zapcore.Field) zapcore.Field {
395 if array, ok := in.Interface.(internal.LoggableStringArray); ok {
396 newArray := make(internal.LoggableStringArray, len(array))
397 for i, s := range array {
398 newArray[i] = m.processQueryString(s)
399 }
400 in.Interface = newArray
401 } else {
402 in.String = m.processQueryString(in.String)
403 }
404
405 return in
406 }
407
408 func (m QueryFilter) processQueryString(s string) string {
409 u, err := url.Parse(s)
410 if err != nil {
411 return s
412 }
413
414 q := u.Query()
415 for _, a := range m.Actions {
416 switch a.Type {
417 case replaceAction:
418 for i := range q[a.Parameter] {
419 q[a.Parameter][i] = a.Value
420 }
421
422 case hashAction:
423 for i := range q[a.Parameter] {
424 q[a.Parameter][i] = hash(a.Value)
425 }
426
427 case deleteAction:
428 q.Del(a.Parameter)
429 }
430 }
431
432 u.RawQuery = q.Encode()
433 return u.String()
434 }
435
436 type cookieFilterAction struct {
437 // `replace` to replace the value of the cookie, `hash` to replace it with the 4 initial bytes of the SHA-256 of its content or `delete` to remove it entirely.
438 Type filterAction `json:"type"`
439
440 // The name of the cookie.
441 Name string `json:"name"`
442
443 // The value to use as replacement if the action is `replace`.
444 Value string `json:"value,omitempty"`
445 }
446
447 // CookieFilter is a Caddy log field filter that filters
448 // cookies.
449 //
450 // This filter updates the logged HTTP header string
451 // to remove, replace or hash cookies containing sensitive data. For instance,
452 // it can be used to redact any kind of secrets, such as session IDs.
453 //
454 // If several actions are configured for the same cookie name, only the first
455 // will be applied.
456 type CookieFilter struct {
457 // A list of actions to apply to the cookies.
458 Actions []cookieFilterAction `json:"actions"`
459 }
460
461 // Validate checks that action types are correct.
462 func (f *CookieFilter) Validate() error {
463 for _, a := range f.Actions {
464 if err := a.Type.IsValid(); err != nil {
465 return err
466 }
467 }
468
469 return nil
470 }
471
472 // CaddyModule returns the Caddy module information.
473 func (CookieFilter) CaddyModule() caddy.ModuleInfo {
474 return caddy.ModuleInfo{
475 ID: "caddy.logging.encoders.filter.cookie",
476 New: func() caddy.Module { return new(CookieFilter) },
477 }
478 }
479
480 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
481 func (m *CookieFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
482 d.Next() // consume filter name
483 for d.NextBlock(0) {
484 cfa := cookieFilterAction{}
485 switch d.Val() {
486 case "replace":
487 if !d.NextArg() {
488 return d.ArgErr()
489 }
490
491 cfa.Type = replaceAction
492 cfa.Name = d.Val()
493
494 if !d.NextArg() {
495 return d.ArgErr()
496 }
497 cfa.Value = d.Val()
498
499 case "hash":
500 if !d.NextArg() {
501 return d.ArgErr()
502 }
503
504 cfa.Type = hashAction
505 cfa.Name = d.Val()
506
507 case "delete":
508 if !d.NextArg() {
509 return d.ArgErr()
510 }
511
512 cfa.Type = deleteAction
513 cfa.Name = d.Val()
514
515 default:
516 return d.Errf("unrecognized subdirective %s", d.Val())
517 }
518
519 m.Actions = append(m.Actions, cfa)
520 }
521 return nil
522 }
523
524 // Filter filters the input field.
525 func (m CookieFilter) Filter(in zapcore.Field) zapcore.Field {
526 cookiesSlice, ok := in.Interface.(internal.LoggableStringArray)
527 if !ok {
528 return in
529 }
530
531 // using a dummy Request to make use of the Cookies() function to parse it
532 originRequest := http.Request{Header: http.Header{"Cookie": cookiesSlice}}
533 cookies := originRequest.Cookies()
534 transformedRequest := http.Request{Header: make(http.Header)}
535
536 OUTER:
537 for _, c := range cookies {
538 for _, a := range m.Actions {
539 if c.Name != a.Name {
540 continue
541 }
542
543 switch a.Type {
544 case replaceAction:
545 c.Value = a.Value
546 transformedRequest.AddCookie(c)
547 continue OUTER
548
549 case hashAction:
550 c.Value = hash(c.Value)
551 transformedRequest.AddCookie(c)
552 continue OUTER
553
554 case deleteAction:
555 continue OUTER
556 }
557 }
558
559 transformedRequest.AddCookie(c)
560 }
561
562 in.Interface = internal.LoggableStringArray(transformedRequest.Header["Cookie"])
563
564 return in
565 }
566
567 // RegexpFilter is a Caddy log field filter that
568 // replaces the field matching the provided regexp
569 // with the indicated string. If the field is an
570 // array of strings, each of them will have the
571 // regexp replacement applied.
572 type RegexpFilter struct {
573 // The regular expression pattern defining what to replace.
574 RawRegexp string `json:"regexp,omitempty"`
575
576 // The value to use as replacement
577 Value string `json:"value,omitempty"`
578
579 regexp *regexp.Regexp
580 }
581
582 // CaddyModule returns the Caddy module information.
583 func (RegexpFilter) CaddyModule() caddy.ModuleInfo {
584 return caddy.ModuleInfo{
585 ID: "caddy.logging.encoders.filter.regexp",
586 New: func() caddy.Module { return new(RegexpFilter) },
587 }
588 }
589
590 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
591 func (f *RegexpFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
592 d.Next() // consume filter name
593 if d.NextArg() {
594 f.RawRegexp = d.Val()
595 }
596 if d.NextArg() {
597 f.Value = d.Val()
598 }
599 return nil
600 }
601
602 // Provision compiles m's regexp.
603 func (m *RegexpFilter) Provision(ctx caddy.Context) error {
604 r, err := regexp.Compile(m.RawRegexp)
605 if err != nil {
606 return err
607 }
608
609 m.regexp = r
610
611 return nil
612 }
613
614 // Filter filters the input field with the replacement value if it matches the regexp.
615 func (f *RegexpFilter) Filter(in zapcore.Field) zapcore.Field {
616 if array, ok := in.Interface.(internal.LoggableStringArray); ok {
617 newArray := make(internal.LoggableStringArray, len(array))
618 for i, s := range array {
619 newArray[i] = f.regexp.ReplaceAllString(s, f.Value)
620 }
621 in.Interface = newArray
622 } else {
623 in.String = f.regexp.ReplaceAllString(in.String, f.Value)
624 }
625
626 return in
627 }
628
629 // regexpFilterOperation represents a single regexp operation
630 // within a MultiRegexpFilter.
631 type regexpFilterOperation struct {
632 // The regular expression pattern defining what to replace.
633 RawRegexp string `json:"regexp,omitempty"`
634
635 // The value to use as replacement
636 Value string `json:"value,omitempty"`
637
638 regexp *regexp.Regexp
639 }
640
641 // MultiRegexpFilter is a Caddy log field filter that
642 // can apply multiple regular expression replacements to
643 // the same field. This filter processes operations in the
644 // order they are defined, applying each regexp replacement
645 // sequentially to the result of the previous operation.
646 //
647 // This allows users to define multiple regexp filters for
648 // the same field without them overwriting each other.
649 //
650 // Security considerations:
651 // - Uses Go's regexp package (RE2 engine) which is safe from ReDoS attacks
652 // - Validates all patterns during provisioning
653 // - Limits the maximum number of operations to prevent resource exhaustion
654 // - Sanitizes input to prevent injection attacks
655 type MultiRegexpFilter struct {
656 // A list of regexp operations to apply in sequence.
657 // Maximum of 50 operations allowed for security and performance.
658 Operations []regexpFilterOperation `json:"operations"`
659 }
660
661 // Security constants
662 const (
663 maxRegexpOperations = 50 // Maximum operations to prevent resource exhaustion
664 maxPatternLength = 1000 // Maximum pattern length to prevent abuse
665 )
666
667 // CaddyModule returns the Caddy module information.
668 func (MultiRegexpFilter) CaddyModule() caddy.ModuleInfo {
669 return caddy.ModuleInfo{
670 ID: "caddy.logging.encoders.filter.multi_regexp",
671 New: func() caddy.Module { return new(MultiRegexpFilter) },
672 }
673 }
674
675 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
676 // Syntax:
677 //
678 // multi_regexp {
679 // regexp <pattern> <replacement>
680 // regexp <pattern> <replacement>
681 // ...
682 // }
683 func (f *MultiRegexpFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
684 d.Next() // consume filter name
685 for d.NextBlock(0) {
686 switch d.Val() {
687 case "regexp":
688 // Security check: limit number of operations
689 if len(f.Operations) >= maxRegexpOperations {
690 return d.Errf("too many regexp operations (maximum %d allowed)", maxRegexpOperations)
691 }
692
693 op := regexpFilterOperation{}
694 if !d.NextArg() {
695 return d.ArgErr()
696 }
697 op.RawRegexp = d.Val()
698
699 // Security validation: check pattern length
700 if len(op.RawRegexp) > maxPatternLength {
701 return d.Errf("regexp pattern too long (maximum %d characters)", maxPatternLength)
702 }
703
704 // Security validation: basic pattern validation
705 if op.RawRegexp == "" {
706 return d.Errf("regexp pattern cannot be empty")
707 }
708
709 if !d.NextArg() {
710 return d.ArgErr()
711 }
712 op.Value = d.Val()
713 f.Operations = append(f.Operations, op)
714 default:
715 return d.Errf("unrecognized subdirective %s", d.Val())
716 }
717 }
718
719 // Security check: ensure at least one operation is defined
720 if len(f.Operations) == 0 {
721 return d.Err("multi_regexp filter requires at least one regexp operation")
722 }
723
724 return nil
725 }
726
727 // Provision compiles all regexp patterns with security validation.
728 func (f *MultiRegexpFilter) Provision(ctx caddy.Context) error {
729 // Security check: validate operation count
730 if len(f.Operations) > maxRegexpOperations {
731 return fmt.Errorf("too many regexp operations: %d (maximum %d allowed)", len(f.Operations), maxRegexpOperations)
732 }
733
734 if len(f.Operations) == 0 {
735 return fmt.Errorf("multi_regexp filter requires at least one operation")
736 }
737
738 for i := range f.Operations {
739 // Security validation: pattern length check
740 if len(f.Operations[i].RawRegexp) > maxPatternLength {
741 return fmt.Errorf("regexp pattern %d too long: %d characters (maximum %d)", i, len(f.Operations[i].RawRegexp), maxPatternLength)
742 }
743
744 // Security validation: empty pattern check
745 if f.Operations[i].RawRegexp == "" {
746 return fmt.Errorf("regexp pattern %d cannot be empty", i)
747 }
748
749 // Compile and validate the pattern (uses RE2 engine - safe from ReDoS)
750 r, err := regexp.Compile(f.Operations[i].RawRegexp)
751 if err != nil {
752 return fmt.Errorf("compiling regexp pattern %d (%s): %v", i, f.Operations[i].RawRegexp, err)
753 }
754 f.Operations[i].regexp = r
755 }
756 return nil
757 }
758
759 // Validate ensures the filter is properly configured with security checks.
760 func (f *MultiRegexpFilter) Validate() error {
761 if len(f.Operations) == 0 {
762 return fmt.Errorf("multi_regexp filter requires at least one operation")
763 }
764
765 if len(f.Operations) > maxRegexpOperations {
766 return fmt.Errorf("too many regexp operations: %d (maximum %d allowed)", len(f.Operations), maxRegexpOperations)
767 }
768
769 for i, op := range f.Operations {
770 if op.RawRegexp == "" {
771 return fmt.Errorf("regexp pattern %d cannot be empty", i)
772 }
773 if len(op.RawRegexp) > maxPatternLength {
774 return fmt.Errorf("regexp pattern %d too long: %d characters (maximum %d)", i, len(op.RawRegexp), maxPatternLength)
775 }
776 if op.regexp == nil {
777 return fmt.Errorf("regexp pattern %d not compiled (call Provision first)", i)
778 }
779 }
780 return nil
781 }
782
783 // Filter applies all regexp operations sequentially to the input field.
784 // Input is sanitized and validated for security.
785 func (f *MultiRegexpFilter) Filter(in zapcore.Field) zapcore.Field {
786 if array, ok := in.Interface.(internal.LoggableStringArray); ok {
787 newArray := make(internal.LoggableStringArray, len(array))
788 for i, s := range array {
789 newArray[i] = f.processString(s)
790 }
791 in.Interface = newArray
792 } else {
793 in.String = f.processString(in.String)
794 }
795
796 return in
797 }
798
799 // processString applies all regexp operations to a single string with input validation.
800 func (f *MultiRegexpFilter) processString(s string) string {
801 // Security: validate input string length to prevent resource exhaustion
802 const maxInputLength = 1000000 // 1MB max input size
803 if len(s) > maxInputLength {
804 // Log warning but continue processing (truncated)
805 s = s[:maxInputLength]
806 }
807
808 result := s
809 for _, op := range f.Operations {
810 // Each regexp operation is applied sequentially
811 // Using RE2 engine which is safe from ReDoS attacks
812 result = op.regexp.ReplaceAllString(result, op.Value)
813
814 // Ensure result doesn't exceed max length after each operation
815 if len(result) > maxInputLength {
816 result = result[:maxInputLength]
817 }
818 }
819 return result
820 }
821
822 // AddOperation adds a single regexp operation to the filter with validation.
823 // This is used when merging multiple RegexpFilter instances.
824 func (f *MultiRegexpFilter) AddOperation(rawRegexp, value string) error {
825 // Security checks
826 if len(f.Operations) >= maxRegexpOperations {
827 return fmt.Errorf("cannot add operation: maximum %d operations allowed", maxRegexpOperations)
828 }
829
830 if rawRegexp == "" {
831 return fmt.Errorf("regexp pattern cannot be empty")
832 }
833
834 if len(rawRegexp) > maxPatternLength {
835 return fmt.Errorf("regexp pattern too long: %d characters (maximum %d)", len(rawRegexp), maxPatternLength)
836 }
837
838 f.Operations = append(f.Operations, regexpFilterOperation{
839 RawRegexp: rawRegexp,
840 Value: value,
841 })
842 return nil
843 }
844
845 // RenameFilter is a Caddy log field filter that
846 // renames the field's key with the indicated name.
847 type RenameFilter struct {
848 Name string `json:"name,omitempty"`
849 }
850
851 // CaddyModule returns the Caddy module information.
852 func (RenameFilter) CaddyModule() caddy.ModuleInfo {
853 return caddy.ModuleInfo{
854 ID: "caddy.logging.encoders.filter.rename",
855 New: func() caddy.Module { return new(RenameFilter) },
856 }
857 }
858
859 // UnmarshalCaddyfile sets up the module from Caddyfile tokens.
860 func (f *RenameFilter) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
861 d.Next() // consume filter name
862 if d.NextArg() {
863 f.Name = d.Val()
864 }
865 return nil
866 }
867
868 // Filter renames the input field with the replacement name.
869 func (f *RenameFilter) Filter(in zapcore.Field) zapcore.Field {
870 in.Key = f.Name
871 return in
872 }
873
874 // Interface guards
875 var (
876 _ LogFieldFilter = (*DeleteFilter)(nil)
877 _ LogFieldFilter = (*HashFilter)(nil)
878 _ LogFieldFilter = (*ReplaceFilter)(nil)
879 _ LogFieldFilter = (*IPMaskFilter)(nil)
880 _ LogFieldFilter = (*QueryFilter)(nil)
881 _ LogFieldFilter = (*CookieFilter)(nil)
882 _ LogFieldFilter = (*RegexpFilter)(nil)
883 _ LogFieldFilter = (*RenameFilter)(nil)
884 _ LogFieldFilter = (*MultiRegexpFilter)(nil)
885
886 _ caddyfile.Unmarshaler = (*DeleteFilter)(nil)
887 _ caddyfile.Unmarshaler = (*HashFilter)(nil)
888 _ caddyfile.Unmarshaler = (*ReplaceFilter)(nil)
889 _ caddyfile.Unmarshaler = (*IPMaskFilter)(nil)
890 _ caddyfile.Unmarshaler = (*QueryFilter)(nil)
891 _ caddyfile.Unmarshaler = (*CookieFilter)(nil)
892 _ caddyfile.Unmarshaler = (*RegexpFilter)(nil)
893 _ caddyfile.Unmarshaler = (*RenameFilter)(nil)
894 _ caddyfile.Unmarshaler = (*MultiRegexpFilter)(nil)
895
896 _ caddy.Provisioner = (*IPMaskFilter)(nil)
897 _ caddy.Provisioner = (*RegexpFilter)(nil)
898 _ caddy.Provisioner = (*MultiRegexpFilter)(nil)
899
900 _ caddy.Validator = (*QueryFilter)(nil)
901 _ caddy.Validator = (*MultiRegexpFilter)(nil)
902 )