-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathenricher.go
91 lines (76 loc) · 1.9 KB
/
enricher.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
package main
import (
"fmt"
"io"
"github.com/corazawaf/coraza/v2"
"github.com/corazawaf/coraza/v2/seclang"
"github.com/oschwald/geoip2-golang"
)
type enricher struct {
waf *coraza.Waf
geoDB *geoip2.Reader
}
func newEnricher(opts ...enricherFunc) (ercr *enricher, err error) {
ercr = &enricher{}
for _, opt := range opts {
if err = opt(ercr); err != nil {
return nil, err
}
}
return
}
type enricherFunc func(*enricher) error
func enricherFuncNOOP(*enricher) error { return nil }
func enricherWithOptionalGeoIP(dbpath string) enricherFunc {
db, err := geoip2.Open(dbpath)
if err != nil {
return enricherFuncNOOP
}
return func(ercr *enricher) error {
ercr.geoDB = db
return nil
}
}
func enricherWithCRS(rules ...string) enricherFunc {
return func(ercr *enricher) error {
waf := coraza.NewWaf()
parser, _ := seclang.NewParser(waf)
for _, f := range rules {
if err := parser.FromFile(f); err != nil {
return fmt.Errorf("error reading rules file from %s: %w", f, err)
}
}
ercr.waf = waf
return nil
}
}
func (ercr *enricher) newEnrichment(record io.Reader) (erc *enrichment) {
erc = &enrichment{
ercr: ercr,
msg: newHTTPRecordedMessage(record),
secs: []subEnricher{
&mimeEnricher{req: newWritableMimeReader(), res: newWritableMimeReader()},
&uaEnricher{},
},
}
if ercr.waf != nil {
erc.secs = append(erc.secs, &crsSubEnricher{tx: ercr.waf.NewTransaction()})
}
if ercr.geoDB != nil {
erc.secs = append(erc.secs, &geoipEnricher{ercr.geoDB})
}
return
}
func (ercr *enricher) EnrichRecord(record io.Reader) (erc *enrichment, err error) {
erc = ercr.newEnrichment(record)
if err = erc.processRequest(); err != nil {
return nil, fmt.Errorf("error parsing request: %w", err)
}
if err = erc.processResponse(); err != nil {
return nil, fmt.Errorf("error parsing response: %w", err)
}
return
}
func (ercr *enricher) Close() error {
return ercr.geoDB.Close()
}