-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
600 lines (523 loc) · 16 KB
/
main.go
File metadata and controls
600 lines (523 loc) · 16 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
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
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
package main
import (
"crypto/subtle"
"encoding/json"
"fmt"
"log"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"sync/atomic"
"time"
"unicode"
"gopkg.in/yaml.v3"
)
// ---------------------------------------------------------------------------
// Policy types
// ---------------------------------------------------------------------------
type Policy struct {
Version int `yaml:"version"`
Defaults PolicyDefaults `yaml:"defaults"`
Tools ToolsPolicy `yaml:"tools"`
}
type PolicyDefaults struct {
Network struct {
RuntimeEgress string `yaml:"runtime_egress"`
} `yaml:"network"`
Logging struct {
StoreRawPrompts bool `yaml:"store_raw_prompts"`
StoreRawResponses bool `yaml:"store_raw_responses"`
} `yaml:"logging"`
}
type ToolsPolicy struct {
Default string `yaml:"default"`
Allow []ToolEntry `yaml:"allow"`
Deny []ToolEntry `yaml:"deny"`
RateLimit RateConfig `yaml:"rate_limit"`
}
type ToolEntry struct {
Name string `yaml:"name"`
PathsAllowlist []string `yaml:"paths_allowlist"`
PathsDenylist []string `yaml:"paths_denylist"`
ArgsBlacklist []string `yaml:"args_blocklist"`
MaxArgLength int `yaml:"max_arg_length"`
}
type RateConfig struct {
RequestsPerMinute int `yaml:"requests_per_minute"`
BurstSize int `yaml:"burst_size"`
}
// ---------------------------------------------------------------------------
// Request / response
// ---------------------------------------------------------------------------
type ToolCallRequest struct {
Tool string `json:"tool"`
Params map[string]string `json:"params"`
}
type ToolCallResponse struct {
Allowed bool `json:"allowed"`
Reason string `json:"reason,omitempty"`
}
// ---------------------------------------------------------------------------
// Globals
// ---------------------------------------------------------------------------
var (
policyMu sync.RWMutex
policy Policy
auditFile *os.File
auditMu sync.Mutex
auditPath string
// Rate limiting: simple sliding window counter
rateMu sync.Mutex
rateCounter int64
rateWindow time.Time
// Stats
totalRequests atomic.Int64
deniedRequests atomic.Int64
)
var serviceToken string // loaded at startup; empty = dev mode (no auth)
const (
defaultMaxArgLength = 4096
defaultRequestsPerMin = 120
defaultBurstSize = 20
maxRequestBodySize = 64 * 1024 // 64 KB
)
// loadServiceToken reads the service-to-service auth token from disk.
// If the file does not exist, token auth is disabled (dev/test mode).
func loadServiceToken() {
tokenPath := os.Getenv("SERVICE_TOKEN_PATH")
if tokenPath == "" {
tokenPath = "/run/secure-ai/service-token"
}
data, err := os.ReadFile(tokenPath)
if err != nil {
log.Printf("warning: service token not loaded (%v) — running in dev mode (no token auth)", err)
return
}
serviceToken = strings.TrimSpace(string(data))
if serviceToken == "" {
log.Printf("warning: service token file is empty — running in dev mode (no token auth)")
return
}
log.Printf("service token loaded from %s", tokenPath)
}
// requireServiceToken wraps a handler to enforce Bearer token auth on mutating endpoints.
// If no token was loaded at startup (dev mode), all requests pass through.
func requireServiceToken(next http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if serviceToken == "" {
next(w, r)
return
}
auth := r.Header.Get("Authorization")
if !strings.HasPrefix(auth, "Bearer ") {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]string{"error": "forbidden: invalid service token"})
return
}
token := strings.TrimPrefix(auth, "Bearer ")
if subtle.ConstantTimeCompare([]byte(token), []byte(serviceToken)) != 1 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusForbidden)
json.NewEncoder(w).Encode(map[string]string{"error": "forbidden: invalid service token"})
return
}
next(w, r)
}
}
// ---------------------------------------------------------------------------
// Policy loading
// ---------------------------------------------------------------------------
func policyFilePath() string {
p := os.Getenv("POLICY_PATH")
if p == "" {
p = "/etc/secure-ai/policy/policy.yaml"
}
return p
}
func loadPolicy() error {
data, err := os.ReadFile(policyFilePath())
if err != nil {
return err
}
var p Policy
if err := yaml.Unmarshal(data, &p); err != nil {
return err
}
policyMu.Lock()
policy = p
policyMu.Unlock()
log.Printf("policy loaded: default=%s allow=%d deny=%d",
p.Tools.Default, len(p.Tools.Allow), len(p.Tools.Deny))
return nil
}
func getPolicy() Policy {
policyMu.RLock()
defer policyMu.RUnlock()
return policy
}
// ---------------------------------------------------------------------------
// Audit logging (structured JSONL)
// ---------------------------------------------------------------------------
type AuditEntry struct {
Timestamp string `json:"timestamp"`
Tool string `json:"tool"`
Params map[string]string `json:"params,omitempty"`
Allowed bool `json:"allowed"`
Reason string `json:"reason,omitempty"`
}
func initAuditLog() {
auditPath = os.Getenv("AUDIT_LOG_PATH")
if auditPath == "" {
auditPath = "/var/lib/secure-ai/logs/tool-firewall-audit.jsonl"
}
dir := filepath.Dir(auditPath)
if err := os.MkdirAll(dir, 0750); err != nil {
log.Printf("warning: cannot create audit log dir %s: %v", dir, err)
return
}
f, err := os.OpenFile(auditPath, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0640)
if err != nil {
log.Printf("warning: cannot open audit log %s: %v", auditPath, err)
return
}
auditFile = f
}
func writeAudit(entry AuditEntry) {
if auditFile == nil {
return
}
entry.Timestamp = time.Now().UTC().Format(time.RFC3339)
data, err := json.Marshal(entry)
if err != nil {
return
}
auditMu.Lock()
defer auditMu.Unlock()
auditFile.Write(append(data, '\n'))
}
// ---------------------------------------------------------------------------
// Rate limiting
// ---------------------------------------------------------------------------
func checkRateLimit(pol Policy) bool {
rpm := pol.Tools.RateLimit.RequestsPerMinute
if rpm <= 0 {
rpm = defaultRequestsPerMin
}
rateMu.Lock()
defer rateMu.Unlock()
now := time.Now()
if now.Sub(rateWindow) > time.Minute {
rateCounter = 0
rateWindow = now
}
rateCounter++
return rateCounter <= int64(rpm)
}
// ---------------------------------------------------------------------------
// Path security
// ---------------------------------------------------------------------------
// cleanAndResolvePath canonicalizes a path, catching traversal attempts.
func cleanAndResolvePath(raw string) (string, error) {
if raw == "" {
return "", nil
}
// Reject null bytes (path injection via null terminator)
if strings.ContainsRune(raw, 0) {
return "", fmt.Errorf("path contains null byte")
}
decoded, err := decodePath(raw)
if err != nil {
return "", err
}
if containsUnicodePathConfusable(decoded) {
return "", fmt.Errorf("path contains unicode path confusable")
}
cleaned := filepath.Clean(decoded)
// Resolve to absolute to catch ../../../etc/shadow style attacks
abs, err := filepath.Abs(cleaned)
if err != nil {
return "", fmt.Errorf("cannot resolve path: %w", err)
}
return resolvePath(abs)
}
func decodePath(raw string) (string, error) {
decoded := raw
for i := 0; i < 3; i++ {
next, err := url.PathUnescape(decoded)
if err != nil {
return "", fmt.Errorf("path contains invalid percent-encoding")
}
if next == decoded {
return decoded, nil
}
if strings.ContainsRune(next, 0) {
return "", fmt.Errorf("path contains null byte")
}
decoded = next
}
return "", fmt.Errorf("path is percent-encoded too deeply")
}
func containsUnicodePathConfusable(raw string) bool {
for _, r := range raw {
switch r {
case '\u2044', '\u2215', '\u2216', '\u29f8', '\uff0e', '\uff0f', '\uff3c', '\ufffd':
return true
}
if unicode.Is(unicode.Mn, r) || unicode.Is(unicode.Me, r) {
return true
}
}
return false
}
func resolvePath(abs string) (string, error) {
cursor := abs
var suffix []string
for {
resolved, err := filepath.EvalSymlinks(cursor)
if err == nil {
for i := len(suffix) - 1; i >= 0; i-- {
resolved = filepath.Join(resolved, suffix[i])
}
return filepath.Clean(resolved), nil
}
if !os.IsNotExist(err) {
return "", fmt.Errorf("cannot resolve path: %w", err)
}
parent := filepath.Dir(cursor)
if parent == cursor {
return filepath.Clean(abs), nil
}
suffix = append(suffix, filepath.Base(cursor))
cursor = parent
}
}
func normalizeMatchPath(raw string) string {
clean := filepath.Clean(raw)
slash := filepath.ToSlash(clean)
if vol := filepath.VolumeName(clean); vol != "" {
slash = strings.ToLower(filepath.ToSlash(vol)) + strings.TrimPrefix(slash, vol)
}
return slash
}
func pathMatchCandidates(raw string) []string {
norm := normalizeMatchPath(raw)
candidates := []string{norm}
if vol := filepath.VolumeName(filepath.Clean(raw)); vol != "" {
volNorm := strings.ToLower(filepath.ToSlash(vol))
trimmed := strings.TrimPrefix(norm, volNorm)
if trimmed != "" {
candidates = append(candidates, trimmed)
}
}
return candidates
}
func hasPathPrefix(path, prefix string) bool {
prefixNorm := normalizeMatchPath(prefix)
for _, candidate := range pathMatchCandidates(path) {
if candidate == prefixNorm || strings.HasPrefix(candidate, prefixNorm+"/") {
return true
}
}
return false
}
// matchesGlob checks if a path matches an allowlist pattern.
// Supports trailing ** for recursive match (prefix match) and exact prefix match.
func matchesGlob(path, pattern string) bool {
if strings.HasSuffix(pattern, "/**") {
prefix := strings.TrimSuffix(pattern, "/**")
prefix = filepath.Clean(prefix)
return hasPathPrefix(path, prefix)
}
if strings.HasSuffix(pattern, "**") {
prefix := strings.TrimSuffix(pattern, "**")
prefix = filepath.Clean(prefix)
return hasPathPrefix(path, prefix)
}
return hasPathPrefix(path, pattern)
}
// ---------------------------------------------------------------------------
// Argument validation
// ---------------------------------------------------------------------------
func validateArgs(params map[string]string, entry ToolEntry) (bool, string) {
maxLen := entry.MaxArgLength
if maxLen <= 0 {
maxLen = defaultMaxArgLength
}
for key, val := range params {
// Length check
if len(val) > maxLen {
return false, fmt.Sprintf("argument %q exceeds max length (%d > %d)", key, len(val), maxLen)
}
// Blocked argument patterns (e.g., shell injection attempts)
for _, blocked := range entry.ArgsBlacklist {
if strings.Contains(strings.ToLower(val), strings.ToLower(blocked)) {
return false, fmt.Sprintf("argument %q contains blocked pattern %q", key, blocked)
}
}
}
return true, ""
}
// ---------------------------------------------------------------------------
// Core evaluation
// ---------------------------------------------------------------------------
// checkPathConstraints validates path parameters against allowlist/denylist rules.
func checkPathConstraints(params map[string]string, entry ToolEntry) (bool, string) {
path, ok := params["path"]
if !ok || path == "" {
return true, ""
}
resolved, err := cleanAndResolvePath(path)
if err != nil {
return false, "invalid path: " + err.Error()
}
for _, denied := range entry.PathsDenylist {
if matchesGlob(resolved, denied) {
return false, "path matches denylist"
}
}
if len(entry.PathsAllowlist) > 0 {
for _, pattern := range entry.PathsAllowlist {
if matchesGlob(resolved, pattern) {
return true, ""
}
}
return false, "path not in allowlist"
}
return true, ""
}
func evaluateTool(req ToolCallRequest) ToolCallResponse {
pol := getPolicy()
// Rate limit check
if !checkRateLimit(pol) {
return ToolCallResponse{Allowed: false, Reason: "rate limit exceeded"}
}
// Check deny list first (deny always wins)
for _, denied := range pol.Tools.Deny {
if denied.Name == req.Tool {
return ToolCallResponse{Allowed: false, Reason: "tool is explicitly denied"}
}
}
// Default deny mode
if pol.Tools.Default != "allow" {
var matched *ToolEntry
for i, allowed := range pol.Tools.Allow {
if allowed.Name == req.Tool {
matched = &pol.Tools.Allow[i]
break
}
}
if matched == nil {
return ToolCallResponse{Allowed: false, Reason: "tool not in allowlist"}
}
if ok, reason := validateArgs(req.Params, *matched); !ok {
return ToolCallResponse{Allowed: false, Reason: reason}
}
if ok, reason := checkPathConstraints(req.Params, *matched); !ok {
return ToolCallResponse{Allowed: false, Reason: reason}
}
return ToolCallResponse{Allowed: true}
}
// Default allow mode (not recommended, but supported)
return ToolCallResponse{Allowed: true}
}
// ---------------------------------------------------------------------------
// HTTP handlers
// ---------------------------------------------------------------------------
func handleEvaluate(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
r.Body = http.MaxBytesReader(w, r.Body, maxRequestBodySize)
var req ToolCallRequest
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, "invalid request body", http.StatusBadRequest)
return
}
totalRequests.Add(1)
resp := evaluateTool(req)
if !resp.Allowed {
deniedRequests.Add(1)
}
// Structured logging
log.Printf("tool-firewall: tool=%s allowed=%t reason=%q", req.Tool, resp.Allowed, resp.Reason)
// Audit log
writeAudit(AuditEntry{
Tool: req.Tool,
Params: req.Params,
Allowed: resp.Allowed,
Reason: resp.Reason,
})
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(resp)
}
func handleHealth(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"status": "ok",
"total_requests": totalRequests.Load(),
"denied_requests": deniedRequests.Load(),
})
}
func handleReload(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
if err := loadPolicy(); err != nil {
log.Printf("policy reload failed: %v", err)
w.WriteHeader(http.StatusInternalServerError)
json.NewEncoder(w).Encode(map[string]string{"error": err.Error()})
return
}
log.Printf("policy reloaded successfully")
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]string{"status": "reloaded"})
}
func handleStats(w http.ResponseWriter, r *http.Request) {
pol := getPolicy()
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(map[string]interface{}{
"default_action": pol.Tools.Default,
"allowed_tools": len(pol.Tools.Allow),
"denied_tools": len(pol.Tools.Deny),
"total_requests": totalRequests.Load(),
"denied_requests": deniedRequests.Load(),
})
}
// ---------------------------------------------------------------------------
// Main
// ---------------------------------------------------------------------------
func main() {
if err := loadPolicy(); err != nil {
log.Fatalf("failed to load policy: %v", err)
}
initAuditLog()
loadServiceToken()
bind := os.Getenv("BIND_ADDR")
if bind == "" {
bind = "127.0.0.1:8475"
}
mux := http.NewServeMux()
// Read-only endpoints — no auth required
mux.HandleFunc("/health", handleHealth)
mux.HandleFunc("/v1/evaluate", handleEvaluate)
mux.HandleFunc("/v1/stats", handleStats)
// Mutating endpoints — require service token
mux.HandleFunc("/v1/reload", requireServiceToken(handleReload))
log.Printf("agent-tool-firewall listening on %s", bind)
server := &http.Server{
Addr: bind,
Handler: mux,
ReadTimeout: 10 * time.Second,
WriteTimeout: 10 * time.Second,
IdleTimeout: 60 * time.Second,
}
if err := server.ListenAndServe(); err != nil {
log.Fatalf("server error: %v", err)
}
}