-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathtypes.go
More file actions
203 lines (169 loc) · 6.24 KB
/
types.go
File metadata and controls
203 lines (169 loc) · 6.24 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
package caddywaf
import (
"regexp"
"sync"
"time"
"github.com/oschwald/maxminddb-golang"
"github.com/phemmer/go-iptrie"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
)
// Package caddywaf is a Caddy module providing web application firewall functionality.
// ==================== Constants and Globals ====================
var (
_ caddy.Module = (*Middleware)(nil)
_ caddy.Provisioner = (*Middleware)(nil)
_ caddyhttp.MiddlewareHandler = (*Middleware)(nil)
_ caddyfile.Unmarshaler = (*Middleware)(nil)
_ caddy.Validator = (*Middleware)(nil)
)
// Define custom types for rule hits
type (
RuleID string
HitCount int
)
// RuleCache caches compiled regex patterns for rules.
type RuleCache struct {
mu sync.RWMutex
rules map[string]*regexp.Regexp
}
// CountryAccessFilter struct
type CountryAccessFilter struct {
Enabled bool `json:"enabled"`
CountryList []string `json:"country_list"`
GeoIPDBPath string `json:"geoip_db_path"`
geoIP *maxminddb.Reader `json:"-"` // Explicitly mark as not serialized
}
// ASNAccessFilter struct
type ASNAccessFilter struct {
Enabled bool `json:"enabled"`
BlockedASNs []string `json:"blocked_asns"`
GeoIPDBPath string `json:"geoip_db_path"`
geoIP *maxminddb.Reader `json:"-"` // Explicitly mark as not serialized
}
// GeoIPRecord struct
type GeoIPRecord struct {
Country struct {
ISOCode string `maxminddb:"iso_code"`
} `maxminddb:"country"`
}
// ASNRecord struct
type ASNRecord struct {
AutonomousSystemOrganization string `maxminddb:"autonomous_system_organization"`
AutonomousSystemNumber uint `maxminddb:"autonomous_system_number"`
}
// Rule struct
type Rule struct {
ID string `json:"id"`
Phase int `json:"phase"`
Pattern string `json:"pattern"`
Targets []string `json:"targets"`
Severity string `json:"severity"` // Used for logging only
Score int `json:"score"`
Action string `json:"mode"` // CRITICAL FIX: This should map to the "mode" field in JSON
Description string `json:"description"`
regex *regexp.Regexp
Priority int // New field for rule priority
}
// CustomBlockResponse struct
type CustomBlockResponse struct {
StatusCode int
Headers map[string]string
Body string
}
// WAFState struct
type WAFState struct {
TotalScore int
Blocked bool
StatusCode int
ResponseWritten bool
}
// Middleware is the main WAF middleware struct that implements Caddy's
// Module, Provisioner, Validator, and MiddlewareHandler interfaces.
//
// It provides comprehensive web application firewall functionality including:
// - Rule-based request filtering
// - IP and DNS blacklisting
// - Geographic access control
// - Rate limiting
// - Anomaly detection
// - Custom response handling
// - Real-time metrics and monitoring
//
// The middleware can be configured via Caddyfile or JSON and integrates
// seamlessly into Caddy's request processing pipeline.
type Middleware struct {
mu sync.RWMutex
RuleFiles []string `json:"rule_files"`
IPBlacklistFile string `json:"ip_blacklist_file"`
DNSBlacklistFile string `json:"dns_blacklist_file"`
AnomalyThreshold int `json:"anomaly_threshold"`
CountryBlacklist CountryAccessFilter `json:"country_blacklist"`
CountryWhitelist CountryAccessFilter `json:"country_whitelist"`
BlockASNs ASNAccessFilter `json:"block_asns"`
Rules map[int][]Rule `json:"-"`
ipBlacklist *iptrie.Trie `json:"-"`
dnsBlacklist map[string]struct{} `json:"-"` // Changed to map[string]struct{}
logger *zap.Logger
LogSeverity string `json:"log_severity,omitempty"`
LogJSON bool `json:"log_json,omitempty"`
logLevel zapcore.Level
isShuttingDown bool
geoIPCacheTTL time.Duration
geoIPLookupFallbackBehavior string
CustomResponses map[int]CustomBlockResponse `json:"custom_responses,omitempty"`
LogFilePath string
LogBuffer int `json:"log_buffer,omitempty"` // Add the LogBuffer field
RedactSensitiveData bool `json:"redact_sensitive_data,omitempty"`
MaxRequestBodySize int64 `json:"max_request_body_size,omitempty"`
GeoIPFailOpen bool `json:"geoip_fail_open,omitempty"`
ruleHits sync.Map `json:"-"`
MetricsEndpoint string `json:"metrics_endpoint,omitempty"`
configLoader *ConfigLoader
blacklistLoader *BlacklistLoader
geoIPHandler *GeoIPHandler
requestValueExtractor *RequestValueExtractor
RateLimit RateLimit
rateLimiter *RateLimiter
totalRequests int64
blockedRequests int64
allowedRequests int64
ruleHitsByPhase map[int]int64
geoIPStats map[string]int64 // Key: country code, Value: count
muMetrics sync.RWMutex // Mutex for metrics synchronization
rateLimiterBlockedRequests int64 // Add rate limiter blocked requests metric
muRateLimiterMetrics sync.RWMutex // Mutex to protect rate limiter metrics
geoIPBlocked int
Tor TorConfig `json:"tor,omitempty"`
logChan chan LogEntry // Buffered channel for log entries
logDone chan struct{} // Signal to stop the logging worker
ruleCache *RuleCache // New field for RuleCache
IPBlacklistBlockCount int64 `json:"ip_blacklist_hits"`
muIPBlacklistMetrics sync.Mutex
DNSBlacklistBlockCount int64 `json:"dns_blacklist_hits"`
muDNSBlacklistMetrics sync.Mutex
}
// ==================== Constructors (New functions) ====================
// NewRuleCache creates a new RuleCache.
func NewRuleCache() *RuleCache {
return &RuleCache{
rules: make(map[string]*regexp.Regexp),
}
}
// ==================== RuleCache Methods ====================
// Get retrieves a compiled regex pattern from the cache.
func (rc *RuleCache) Get(ruleID string) (*regexp.Regexp, bool) {
rc.mu.RLock()
defer rc.mu.RUnlock()
regex, exists := rc.rules[ruleID]
return regex, exists
}
// Set stores a compiled regex pattern in the cache.
func (rc *RuleCache) Set(ruleID string, regex *regexp.Regexp) {
rc.mu.Lock()
defer rc.mu.Unlock()
rc.rules[ruleID] = regex
}