-
Notifications
You must be signed in to change notification settings - Fork 75
Expand file tree
/
Copy pathrule_store.go
More file actions
467 lines (409 loc) · 10.4 KB
/
Copy pathrule_store.go
File metadata and controls
467 lines (409 loc) · 10.4 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
package usecase
import (
"encoding/json"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"time"
)
type RuleListFilter struct {
Page int // 0-based
Size int
Name string // case-insensitive partial on rule name
Search string // case-insensitive partial on rule name (general text)
Active *bool // enabled state
SystemOwner *bool // system overlay membership
Categories []string // any-of
Adversaries []string // any-of
Techniques []string // any-of
DataTypes []string // any-of (rule must reference at least one)
Confidentiality []int // any-of
Integrity []int // any-of
Availability []int // any-of
InitDate time.Time // Modified >= InitDate (when non-zero)
EndDate time.Time // Modified <= EndDate (when non-zero)
}
type RuleStore struct {
systemDir string
userDir string
mu sync.RWMutex
rules []*StoredRule // load order (system first, then user)
index map[string]*StoredRule // relPath -> rule
}
func NewRuleStore(systemDir, userDir string) *RuleStore {
return &RuleStore{
systemDir: systemDir,
userDir: userDir,
index: make(map[string]*StoredRule),
}
}
// Load (re)reads both overlays into memory, replacing the current contents.
func (s *RuleStore) Load() error {
rules := make([]*StoredRule, 0, 256)
index := make(map[string]*StoredRule, 256)
for _, ov := range []struct {
dir string
system bool
}{
{s.systemDir, true},
{s.userDir, false},
} {
loaded, err := loadOverlay(ov.dir, ov.system)
if err != nil {
return err
}
for _, sr := range loaded {
if prev, ok := index[sr.RelPath]; ok {
// User overlay overrides a system rule with the same relPath.
*prev = *sr
continue
}
index[sr.RelPath] = sr
rules = append(rules, sr)
}
}
s.mu.Lock()
s.rules = rules
s.index = index
s.mu.Unlock()
return nil
}
// loadOverlay walks one overlay directory and parses every rule file in it.
func loadOverlay(dir string, system bool) ([]*StoredRule, error) {
var out []*StoredRule
if _, err := os.Stat(dir); os.IsNotExist(err) {
return out, nil
}
err := filepath.WalkDir(dir, func(path string, d os.DirEntry, err error) error {
if err != nil {
return err
}
if d.IsDir() {
return nil
}
enabled := true
logical := path
if strings.HasSuffix(path, DisabledSuffix) {
enabled = false
logical = strings.TrimSuffix(path, DisabledSuffix)
}
if !strings.HasSuffix(logical, RuleFileExt) {
return nil // ignore non-rule files
}
rule, rerr := readRuleFile(path)
if rerr != nil {
return nil // skip unparsable files rather than failing the whole load
}
rel, rerr := filepath.Rel(dir, logical)
if rerr != nil {
return nil
}
var mod time.Time
if info, ierr := d.Info(); ierr == nil {
mod = info.ModTime()
}
out = append(out, &StoredRule{
Rule: rule,
RelPath: filepath.ToSlash(rel),
Modified: mod,
system: system,
enabled: enabled,
})
return nil
})
return out, err
}
// findByRelPath returns the rule for relPath or nil. Caller-facing reads use
// the read lock.
func (s *RuleStore) findByRelPath(relPath string) *StoredRule {
s.mu.RLock()
defer s.mu.RUnlock()
if sr, ok := s.index[relPath]; ok {
cp := *sr
return &cp
}
return nil
}
func (s *RuleStore) FindByName(name string) *StoredRule {
s.mu.RLock()
defer s.mu.RUnlock()
for _, sr := range s.rules {
if strings.EqualFold(sr.Name, name) {
cp := *sr
return &cp
}
}
return nil
}
func (s *RuleStore) CorrelationsByName(name string) (json.RawMessage, bool) {
sr := s.FindByName(name)
if sr == nil {
return nil, false
}
return anyToRaw(sr.Correlation), true
}
// List applies the filter, sorts by name and paginates. It returns the page
// plus the total match count (pre-pagination).
func (s *RuleStore) List(f RuleListFilter) ([]*StoredRule, int) {
s.mu.RLock()
matched := make([]*StoredRule, 0, len(s.rules))
for _, sr := range s.rules {
if ruleMatches(sr, f) {
cp := *sr
matched = append(matched, &cp)
}
}
s.mu.RUnlock()
sort.SliceStable(matched, func(i, j int) bool {
return strings.ToLower(matched[i].Name) < strings.ToLower(matched[j].Name)
})
total := len(matched)
if f.Size <= 0 {
return matched, total
}
start := f.Page * f.Size
if start >= total {
return []*StoredRule{}, total
}
end := start + f.Size
if end > total {
end = total
}
return matched[start:end], total
}
func ruleMatches(sr *StoredRule, f RuleListFilter) bool {
if f.Name != "" && !strings.Contains(strings.ToLower(sr.Name), strings.ToLower(f.Name)) {
return false
}
if f.Search != "" && !strings.Contains(strings.ToLower(sr.Name), strings.ToLower(f.Search)) {
return false
}
if f.Active != nil && sr.enabled != *f.Active {
return false
}
if f.SystemOwner != nil && sr.system != *f.SystemOwner {
return false
}
if len(f.Categories) > 0 && !containsStr(f.Categories, sr.Category) {
return false
}
if len(f.Adversaries) > 0 && !containsStr(f.Adversaries, sr.Adversary) {
return false
}
if len(f.Techniques) > 0 && !containsStr(f.Techniques, sr.Technique) {
return false
}
if len(f.Confidentiality) > 0 && !containsInt(f.Confidentiality, sr.Impact.Confidentiality) {
return false
}
if len(f.Integrity) > 0 && !containsInt(f.Integrity, sr.Impact.Integrity) {
return false
}
if len(f.Availability) > 0 && !containsInt(f.Availability, sr.Impact.Availability) {
return false
}
if len(f.DataTypes) > 0 && !anyStr(f.DataTypes, sr.DataTypes) {
return false
}
if !f.InitDate.IsZero() && sr.Modified.Before(f.InitDate) {
return false
}
if !f.EndDate.IsZero() && sr.Modified.After(f.EndDate) {
return false
}
return true
}
// Create writes a new rule into the user overlay. The relPath is derived from
// the rule name; a collision is reported as an error.
func (s *RuleStore) Create(rule Rule) (*StoredRule, error) {
relPath := slug(rule.Name) + RuleFileExt
s.mu.Lock()
defer s.mu.Unlock()
if _, exists := s.index[relPath]; exists {
return nil, os.ErrExist
}
abs := filepath.Join(s.userDir, relPath)
if err := writeRuleFile(abs, rule); err != nil {
return nil, err
}
sr := &StoredRule{
Rule: rule,
RelPath: relPath,
Modified: fileModTime(abs),
system: false,
enabled: true,
}
s.index[relPath] = sr
s.rules = append(s.rules, sr)
cp := *sr
return &cp, nil
}
// Update overwrites an existing user rule's content. System rules are
// read-only.
func (s *RuleStore) Update(relPath string, rule Rule) (*StoredRule, error) {
s.mu.Lock()
defer s.mu.Unlock()
sr, ok := s.index[relPath]
if !ok {
return nil, ErrRuleNotFound
}
if sr.system {
return nil, ErrSystemRuleContent
}
abs := s.absPath(sr)
if err := writeRuleFile(abs, rule); err != nil {
return nil, err
}
sr.Rule = rule
sr.Modified = fileModTime(abs)
cp := *sr
return &cp, nil
}
// Delete removes a user rule. System rules are read-only.
func (s *RuleStore) Delete(relPath string) error {
s.mu.Lock()
defer s.mu.Unlock()
sr, ok := s.index[relPath]
if !ok {
return ErrRuleNotFound
}
if sr.system {
return ErrSystemRuleContent
}
if err := removeRuleFile(s.absPath(sr)); err != nil {
return err
}
delete(s.index, relPath)
for i, r := range s.rules {
if r == sr {
s.rules = append(s.rules[:i], s.rules[i+1:]...)
break
}
}
return nil
}
// SetEnabled toggles a rule's enabled state by adding/removing the .disabled
// suffix on its file. Works for both system and user rules (disabling is the
// one mutation allowed on a system rule).
func (s *RuleStore) SetEnabled(relPath string, enabled bool) error {
s.mu.Lock()
defer s.mu.Unlock()
sr, ok := s.index[relPath]
if !ok {
return ErrRuleNotFound
}
if sr.enabled == enabled {
return nil
}
from := s.absPath(sr)
sr.enabled = enabled
to := s.absPath(sr)
if err := renameRuleFile(from, to); err != nil {
sr.enabled = !enabled // roll back the in-memory flag on failure
return err
}
return nil
}
// DistinctValues returns the distinct values of a rule property, optionally
// filtered to those containing `value` (case-insensitive). prop is a legacy
// column name (rule_name, rule_category, rule_technique, rule_adversary).
func (s *RuleStore) DistinctValues(prop, value string) []string {
pick := propPicker(prop)
if pick == nil {
return []string{}
}
s.mu.RLock()
defer s.mu.RUnlock()
seen := make(map[string]struct{})
out := make([]string, 0)
needle := strings.ToLower(value)
for _, sr := range s.rules {
v := pick(sr)
if v == "" {
continue
}
if needle != "" && !strings.Contains(strings.ToLower(v), needle) {
continue
}
if _, dup := seen[v]; dup {
continue
}
seen[v] = struct{}{}
out = append(out, v)
}
sort.Strings(out)
return out
}
func propPicker(prop string) func(*StoredRule) string {
switch prop {
case "rule_name":
return func(sr *StoredRule) string { return sr.Name }
case "rule_category":
return func(sr *StoredRule) string { return sr.Category }
case "rule_technique":
return func(sr *StoredRule) string { return sr.Technique }
case "rule_adversary":
return func(sr *StoredRule) string { return sr.Adversary }
default:
return nil
}
}
// absPath resolves a rule's on-disk path, including the .disabled suffix when
// the rule is disabled.
func (s *RuleStore) absPath(sr *StoredRule) string {
dir := s.userDir
if sr.system {
dir = s.systemDir
}
p := filepath.Join(dir, filepath.FromSlash(sr.RelPath))
if !sr.enabled {
p += DisabledSuffix
}
return p
}
// ── helpers ─────────────────────────────────────────────────────────────────
var slugNonAlnum = regexp.MustCompile(`[^a-z0-9]+`)
// slug turns a rule name into a filesystem-safe identifier.
func slug(name string) string {
s := strings.ToLower(strings.TrimSpace(name))
s = slugNonAlnum.ReplaceAllString(s, "-")
s = strings.Trim(s, "-")
if s == "" {
s = "rule"
}
return s
}
func fileModTime(path string) time.Time {
if info, err := os.Stat(path); err == nil {
return info.ModTime()
}
return time.Time{}
}
func containsStr(set []string, v string) bool {
for _, x := range set {
if x == v {
return true
}
}
return false
}
func containsInt(set []int, v int) bool {
for _, x := range set {
if x == v {
return true
}
}
return false
}
// anyStr reports whether any element of want is present in have.
func anyStr(want, have []string) bool {
for _, w := range want {
if containsStr(have, w) {
return true
}
}
return false
}