-
-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathcaddywaf.go
548 lines (469 loc) · 17.1 KB
/
caddywaf.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
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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
package caddywaf
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"strings"
"sync"
"github.com/caddyserver/caddy/v2"
"github.com/caddyserver/caddy/v2/caddyconfig/caddyfile"
"github.com/caddyserver/caddy/v2/caddyconfig/httpcaddyfile"
"github.com/caddyserver/caddy/v2/modules/caddyhttp"
"github.com/oschwald/maxminddb-golang"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/fsnotify/fsnotify"
)
// ==================== Constants and Globals ====================
var (
_ caddy.Provisioner = (*Middleware)(nil)
_ caddyhttp.MiddlewareHandler = (*Middleware)(nil)
_ caddyfile.Unmarshaler = (*Middleware)(nil)
_ caddy.Validator = (*Middleware)(nil)
)
// Add or update the version constant as needed
const wafVersion = "v0.0.1" // update this value to the new release version when tagging
// ==================== Initialization and Setup ====================
func init() {
caddy.RegisterModule(&Middleware{}) // Changed from Middleware{} to &Middleware{}
httpcaddyfile.RegisterHandlerDirective("waf", parseCaddyfile)
}
func (*Middleware) CaddyModule() caddy.ModuleInfo {
return caddy.ModuleInfo{
ID: "http.handlers.waf",
New: func() caddy.Module { return &Middleware{} },
}
}
func parseCaddyfile(h httpcaddyfile.Helper) (caddyhttp.MiddlewareHandler, error) {
logger := zap.L().Named("caddyfile_parser")
logger.Info("Starting to parse Caddyfile", zap.String("file", h.Dispenser.File()))
var m Middleware
err := m.UnmarshalCaddyfile(h.Dispenser)
if err != nil {
return nil, fmt.Errorf("caddyfile parse error: %w", err)
}
logger.Info("Successfully parsed Caddyfile", zap.String("file", h.Dispenser.File()))
return &m, nil
}
// ==================== Middleware Lifecycle Methods ====================
func (m *Middleware) Provision(ctx caddy.Context) error {
m.logger = ctx.Logger(m)
m.ruleCache = NewRuleCache() // Initialize RuleCache
// Set default log severity if not provided
if m.LogSeverity == "" {
m.LogSeverity = "info"
}
// Set default log file path if not provided
if m.LogFilePath == "" {
m.LogFilePath = "log.json"
}
// Parse log severity level
var logLevel zapcore.Level
switch strings.ToLower(m.LogSeverity) {
case "debug":
logLevel = zapcore.DebugLevel
case "warn":
logLevel = zapcore.WarnLevel
case "error":
logLevel = zapcore.ErrorLevel
default:
logLevel = zapcore.InfoLevel
}
// Configure console logging
consoleCfg := zap.NewProductionConfig()
consoleCfg.EncoderConfig.EncodeTime = caddyTimeEncoder
consoleCfg.EncoderConfig.EncodeLevel = zapcore.CapitalColorLevelEncoder
consoleEncoder := zapcore.NewConsoleEncoder(consoleCfg.EncoderConfig)
consoleSync := zapcore.AddSync(os.Stdout)
// Configure file logging
fileCfg := zap.NewProductionConfig()
fileCfg.EncoderConfig.EncodeTime = caddyTimeEncoder
fileCfg.EncoderConfig.EncodeLevel = zapcore.CapitalLevelEncoder
fileEncoder := zapcore.NewJSONEncoder(fileCfg.EncoderConfig)
fileSync, err := os.OpenFile(m.LogFilePath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
if err != nil {
m.logger.Warn("Failed to open log file, logging only to console", zap.String("path", m.LogFilePath), zap.Error(err))
m.logger = zap.New(zapcore.NewCore(consoleEncoder, consoleSync, logLevel))
return nil
}
// Create a multi-core logger for both console and file
core := zapcore.NewTee(
zapcore.NewCore(consoleEncoder, consoleSync, logLevel),
zapcore.NewCore(fileEncoder, zapcore.AddSync(fileSync), zap.DebugLevel),
)
m.logger = zap.New(core)
m.logger.Info("Provisioning WAF middleware",
zap.String("log_level", m.LogSeverity),
zap.String("log_path", m.LogFilePath),
zap.Bool("log_json", m.LogJSON),
zap.Int("anomaly_threshold", m.AnomalyThreshold),
)
// Start the asynchronous logging worker
m.StartLogWorker()
// Provision Tor blocking
if err := m.Tor.Provision(ctx); err != nil {
return err
}
// Initialize rule hits map
m.ruleHits = sync.Map{}
// Log the current version of the middleware
m.logVersion()
// Start file watchers for rule files and blacklist files
// Context cancellation could be added in the future to gracefully stop watchers.
m.startFileWatcher(m.RuleFiles)
m.startFileWatcher([]string{m.IPBlacklistFile, m.DNSBlacklistFile})
// Configure rate limiting
if m.RateLimit.Requests > 0 {
if m.RateLimit.Window <= 0 || m.RateLimit.CleanupInterval <= 0 {
return fmt.Errorf("invalid rate limit configuration: requests, window, and cleanup_interval must be greater than zero")
}
m.logger.Info("Rate limit configuration",
zap.Int("requests", m.RateLimit.Requests),
zap.Duration("window", m.RateLimit.Window),
zap.Duration("cleanup_interval", m.RateLimit.CleanupInterval),
zap.Strings("paths", m.RateLimit.Paths),
zap.Bool("match_all_paths", m.RateLimit.MatchAllPaths),
)
var err error
m.rateLimiter, err = NewRateLimiter(m.RateLimit)
if err != nil {
return fmt.Errorf("failed to create rate limiter: %w", err)
}
m.rateLimiter.startCleanup()
} else {
m.logger.Info("Rate limiting is disabled")
}
// Initialize GeoIP stats
m.geoIPStats = make(map[string]int64)
// Configure GeoIP-based country blocking/whitelisting
if m.CountryBlock.Enabled || m.CountryWhitelist.Enabled {
geoIPPath := m.CountryBlock.GeoIPDBPath
if m.CountryWhitelist.Enabled && m.CountryWhitelist.GeoIPDBPath != "" {
geoIPPath = m.CountryWhitelist.GeoIPDBPath
}
if !fileExists(geoIPPath) {
m.logger.Warn("GeoIP database not found. Country blocking/whitelisting will be disabled", zap.String("path", geoIPPath))
} else {
reader, err := maxminddb.Open(geoIPPath)
if err != nil {
m.logger.Error("Failed to load GeoIP database", zap.String("path", geoIPPath), zap.Error(err))
} else {
m.logger.Info("GeoIP database loaded successfully", zap.String("path", geoIPPath))
if m.CountryBlock.Enabled {
m.CountryBlock.geoIP = reader
}
if m.CountryWhitelist.Enabled {
m.CountryWhitelist.geoIP = reader
}
}
}
}
// Initialize config and blacklist loaders
m.configLoader = NewConfigLoader(m.logger)
m.blacklistLoader = NewBlacklistLoader(m.logger)
m.geoIPHandler = NewGeoIPHandler(m.logger)
m.requestValueExtractor = NewRequestValueExtractor(m.logger, m.RedactSensitiveData)
// Configure GeoIP handler
m.geoIPHandler.WithGeoIPCache(m.geoIPCacheTTL)
m.geoIPHandler.WithGeoIPLookupFallbackBehavior(m.geoIPLookupFallbackBehavior)
// Load configuration from Caddyfile
dispenser := caddyfile.NewDispenser([]caddyfile.Token{})
err = m.configLoader.UnmarshalCaddyfile(dispenser, m)
if err != nil {
return fmt.Errorf("failed to load config: %w", err)
}
// Load IP blacklist
if m.IPBlacklistFile != "" {
m.ipBlacklist = NewCIDRTrie()
err = m.loadIPBlacklist(m.IPBlacklistFile, m.ipBlacklist)
if err != nil {
return fmt.Errorf("failed to load IP blacklist: %w", err)
}
}
// Load DNS blacklist
if m.DNSBlacklistFile != "" {
m.dnsBlacklist = make(map[string]struct{})
err = m.loadDNSBlacklist(m.DNSBlacklistFile, m.dnsBlacklist)
if err != nil {
return fmt.Errorf("failed to load DNS blacklist: %w", err)
}
}
// Load WAF rules - calling the new external loadRules function
if len(m.RuleFiles) > 0 { // Modified condition to check for rule files before loading
if err := m.loadRules(m.RuleFiles); err != nil {
return fmt.Errorf("failed to load rules: %w", err)
}
} else {
m.logger.Warn("No rule files specified, WAF will run without rules.") // Log a warning instead of error
}
m.logger.Info("WAF middleware provisioned successfully")
return nil
}
func (m *Middleware) Shutdown(ctx context.Context) error {
m.logger.Info("Starting WAF middleware shutdown procedures")
m.isShuttingDown = true
// Stop the rate limiter cleanup
if m.rateLimiter != nil {
m.logger.Debug("Signaling rate limiter cleanup to stop...")
m.rateLimiter.signalStopCleanup()
m.logger.Debug("Rate limiter cleanup signaled.")
} else {
m.logger.Debug("Rate limiter is nil, no cleanup signaling needed.")
}
// Stop the asynchronous logging worker
m.logger.Debug("Stopping logging worker...")
m.StopLogWorker()
m.logger.Debug("Logging worker stopped.")
var firstError error
var errorOccurred bool
// Close GeoIP databases
if m.CountryBlock.geoIP != nil {
m.logger.Debug("Closing country block GeoIP database...")
if err := m.CountryBlock.geoIP.Close(); err != nil {
m.logger.Error("Error encountered while closing country block GeoIP database", zap.Error(err))
if !errorOccurred {
firstError = fmt.Errorf("error closing country block GeoIP: %w", err)
errorOccurred = true
}
} else {
m.logger.Debug("Country block GeoIP database closed successfully.")
}
m.CountryBlock.geoIP = nil
} else {
m.logger.Debug("Country block GeoIP database was not open, skipping close.")
}
if m.CountryWhitelist.geoIP != nil {
m.logger.Debug("Closing country whitelist GeoIP database...")
if err := m.CountryWhitelist.geoIP.Close(); err != nil {
m.logger.Error("Error encountered while closing country whitelist GeoIP database", zap.Error(err))
if firstError == nil {
firstError = fmt.Errorf("error closing country whitelist GeoIP: %w", err)
}
} else {
m.logger.Debug("Country whitelist GeoIP database closed successfully.")
}
m.CountryWhitelist.geoIP = nil
} else {
m.logger.Debug("Country whitelist GeoIP database was not open, skipping close.")
}
// Log rule hit statistics
m.logger.Info("Rule Hit Statistics:")
m.ruleHits.Range(func(key, value interface{}) bool {
ruleID, ok := key.(RuleID)
if !ok {
m.logger.Error("Invalid type for rule ID in ruleHits map", zap.Any("key", key))
return true
}
hitCount, ok := value.(HitCount)
if !ok {
m.logger.Error("Invalid type for hit count in ruleHits map", zap.Any("value", value))
return true
}
m.logger.Info("Rule Hit",
zap.String("rule_id", string(ruleID)),
zap.Int("hits", int(hitCount)),
)
return true
})
m.logger.Info("WAF middleware shutdown procedures completed")
return firstError
}
// ==================== Helper Functions ====================
func (m *Middleware) logVersion() {
// Updated to use wafVersion constant
m.logger.Info("WAF middleware version", zap.String("version", wafVersion))
}
func (m *Middleware) startFileWatcher(filePaths []string) {
for _, path := range filePaths {
// Skip watching if the file doesn't exist
if _, err := os.Stat(path); os.IsNotExist(err) {
m.logger.Warn("Skipping file watch, file does not exist",
zap.String("file", path),
)
continue
}
// Note: In future, a context may be used here for cancellation.
go func(file string) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
m.logger.Error("Failed to start file watcher", zap.Error(err))
return
}
defer watcher.Close()
err = watcher.Add(file)
if err != nil {
m.logger.Error("Failed to watch file", zap.String("file", file), zap.Error(err))
return
}
for {
select {
case event := <-watcher.Events:
if event.Op&fsnotify.Write == fsnotify.Write {
m.logger.Info("Detected configuration change. Reloading...", zap.String("file", file))
if strings.Contains(file, "rule") {
if err := m.ReloadRules(); err != nil {
m.logger.Error("Failed to reload rules after change", zap.String("file", file), zap.Error(err))
} else {
m.logger.Info("Rules reloaded successfully", zap.String("file", file))
}
} else {
err := m.ReloadConfig()
if err != nil {
m.logger.Error("Failed to reload config after change", zap.Error(err))
} else {
m.logger.Info("Configuration reloaded successfully")
}
}
}
case err := <-watcher.Errors:
m.logger.Error("File watcher error", zap.Error(err))
}
}
}(path)
}
}
func (m *Middleware) ReloadRules() error {
m.mu.Lock()
defer m.mu.Unlock()
m.logger.Info("Reloading WAF rules")
// Call the external loadRules function
if err := m.loadRules(m.RuleFiles); err != nil {
m.logger.Error("Failed to reload rules", zap.Error(err))
return fmt.Errorf("failed to reload rules: %v", err)
}
m.logger.Info("WAF rules reloaded successfully")
return nil
}
func (m *Middleware) ReloadConfig() error {
m.mu.Lock()
defer m.mu.Unlock()
m.logger.Info("Reloading WAF configuration")
if m.IPBlacklistFile != "" {
newIPBlacklist := NewCIDRTrie()
if err := m.loadIPBlacklist(m.IPBlacklistFile, newIPBlacklist); err != nil {
m.logger.Error("Failed to reload IP blacklist", zap.String("file", m.IPBlacklistFile), zap.Error(err))
return fmt.Errorf("failed to reload IP blacklist: %v", err)
}
m.ipBlacklist = newIPBlacklist
}
if m.DNSBlacklistFile != "" {
newDNSBlacklist := make(map[string]struct{})
if err := m.loadDNSBlacklist(m.DNSBlacklistFile, newDNSBlacklist); err != nil {
m.logger.Error("Failed to reload DNS blacklist", zap.String("file", m.DNSBlacklistFile), zap.Error(err))
return fmt.Errorf("failed to reload DNS blacklist: %v", err)
}
m.dnsBlacklist = newDNSBlacklist
}
// Call the external loadRules function
if err := m.loadRules(m.RuleFiles); err != nil {
m.logger.Error("Failed to reload rules", zap.Error(err))
return fmt.Errorf("failed to reload rules: %v", err)
}
m.logger.Info("WAF configuration reloaded successfully")
return nil
}
func (m *Middleware) loadIPBlacklist(path string, blacklistMap *CIDRTrie) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
m.logger.Warn("Skipping IP blacklist load, file does not exist", zap.String("file", path))
return nil
}
blacklist := make(map[string]struct{})
err := m.blacklistLoader.LoadIPBlacklistFromFile(path, blacklist)
if err != nil {
return fmt.Errorf("failed to load IP blacklist: %w", err)
}
// Convert the map to CIDRTrie
for ip := range blacklist {
blacklistMap.Insert(ip)
}
return nil
}
func (m *Middleware) loadDNSBlacklist(path string, blacklistMap map[string]struct{}) error {
if _, err := os.Stat(path); os.IsNotExist(err) {
m.logger.Warn("Skipping DNS blacklist load, file does not exist", zap.String("file", path))
return nil
}
err := m.blacklistLoader.LoadDNSBlacklistFromFile(path, blacklistMap)
if err != nil {
return fmt.Errorf("failed to load DNS blacklist: %w", err)
}
return nil
}
// ==================== Metrics and Statistics ====================
func (m *Middleware) getRuleHitStats() map[string]int {
stats := make(map[string]int)
m.ruleHits.Range(func(key, value interface{}) bool {
ruleID, ok := key.(RuleID)
if !ok {
m.logger.Error("Invalid type for rule ID in ruleHits map", zap.Any("key", key))
return true // Continue iteration
}
hitCount, ok := value.(HitCount)
if !ok {
m.logger.Error("Invalid type for hit count in ruleHits map", zap.Any("value", value))
return true // Continue iteration
}
stats[string(ruleID)] = int(hitCount)
return true
})
return stats
}
func (m *Middleware) handleMetricsRequest(w http.ResponseWriter, r *http.Request) error {
m.logger.Debug("Handling metrics request", zap.String("path", r.URL.Path))
w.Header().Set("Content-Type", "application/json")
// Get rate limiter metrics
var rateLimiterTotalRequests int64
var rateLimiterBlockedRequests int64
if m.rateLimiter != nil {
rateLimiterTotalRequests = m.rateLimiter.GetTotalRequests()
rateLimiterBlockedRequests = m.rateLimiter.GetBlockedRequests()
}
// Collect rule hits using getRuleHitStats
ruleHits := m.getRuleHitStats()
// Collect all metrics
metrics := map[string]interface{}{
"total_requests": m.totalRequests,
"blocked_requests": m.blockedRequests,
"allowed_requests": m.allowedRequests,
"rule_hits": ruleHits,
"rule_hits_by_phase": m.ruleHitsByPhase, // Include rule hits by phase
"geoip_blocked": m.geoIPBlocked, // Add the new geoIPBlocked metric
"ip_blacklist_hits": m.IPBlacklistBlockCount, // Add IP blacklist hits metric
"dns_blacklist_hits": m.DNSBlacklistBlockCount, // Add DNS blacklist hits metric
"rate_limiter_requests": rateLimiterTotalRequests, // Add rate limiter total requests
"rate_limiter_blocked_requests": rateLimiterBlockedRequests, // Add rate limiter blocked requests
"version": wafVersion,
}
jsonMetrics, err := json.Marshal(metrics)
if err != nil {
m.logger.Error("Failed to marshal metrics to JSON", zap.Error(err))
w.WriteHeader(http.StatusInternalServerError)
return fmt.Errorf("failed to marshal metrics to JSON: %v", err)
}
_, err = w.Write(jsonMetrics)
if err != nil {
m.logger.Error("Failed to write metrics response", zap.Error(err))
return fmt.Errorf("failed to write metrics response: %v", err)
}
return nil
}
// ==================== Utility Functions ====================
func (m *Middleware) extractValue(target string, r *http.Request, w http.ResponseWriter) (string, error) {
return m.requestValueExtractor.ExtractValue(target, r, w)
}
// ==================== Unimplemented Functions ====================
func (m *Middleware) UnmarshalCaddyfile(d *caddyfile.Dispenser) error {
if m.configLoader == nil {
m.configLoader = NewConfigLoader(m.logger)
}
return m.configLoader.UnmarshalCaddyfile(d, m)
}
// Validate implements caddy.Validator.
func (m *Middleware) Validate() error {
if m.logLevel == 0 {
m.logLevel = zapcore.InfoLevel // Default log level
}
return nil
}