forked from evilsocket/opensnitch
/
loader.go
303 lines (256 loc) · 6.65 KB
/
loader.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
package rule
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"time"
"github.com/gustavo-iniguez-goya/opensnitch/daemon/conman"
"github.com/gustavo-iniguez-goya/opensnitch/daemon/core"
"github.com/gustavo-iniguez-goya/opensnitch/daemon/log"
"github.com/fsnotify/fsnotify"
)
// Loader is the object that holds the rules loaded from disk, as well as the
// rules watcher.
type Loader struct {
sync.RWMutex
path string
rules map[string]*Rule
rulesKeys []string
watcher *fsnotify.Watcher
liveReload bool
liveReloadRunning bool
}
// NewLoader loads rules from disk, and watches for changes made to the rules files
// on disk.
func NewLoader(liveReload bool) (*Loader, error) {
watcher, err := fsnotify.NewWatcher()
if err != nil {
return nil, err
}
return &Loader{
path: "",
rules: make(map[string]*Rule),
liveReload: liveReload,
watcher: watcher,
liveReloadRunning: false,
}, nil
}
// NumRules returns he number of loaded rules.
func (l *Loader) NumRules() int {
l.RLock()
defer l.RUnlock()
return len(l.rules)
}
// Load loads rules files from disk.
func (l *Loader) Load(path string) error {
if core.Exists(path) == false {
return fmt.Errorf("Path '%s' does not exist", path)
}
expr := filepath.Join(path, "*.json")
matches, err := filepath.Glob(expr)
if err != nil {
return fmt.Errorf("Error globbing '%s': %s", expr, err)
}
l.Lock()
defer l.Unlock()
l.path = path
if len(l.rules) == 0 {
l.rules = make(map[string]*Rule)
}
diskRules := make(map[string]string)
for _, fileName := range matches {
log.Debug("Reading rule from %s", fileName)
raw, err := ioutil.ReadFile(fileName)
if err != nil {
return fmt.Errorf("Error while reading %s: %s", fileName, err)
}
var r Rule
err = json.Unmarshal(raw, &r)
if err != nil {
log.Error("Error parsing rule from %s: %s", fileName, err)
continue
}
r.Operator.Compile()
diskRules[r.Name] = r.Name
log.Debug("Loaded rule from %s: %s", fileName, r.String())
l.rules[r.Name] = &r
}
for ruleName, inMemoryRule := range l.rules {
if _, ok := diskRules[ruleName]; ok == false {
if inMemoryRule.Duration == Always {
log.Debug("Rule deleted from disk, updating rules list: %s", ruleName)
delete(l.rules, ruleName)
}
}
}
l.sortRules()
if l.liveReload && l.liveReloadRunning == false {
go l.liveReloadWorker()
}
return nil
}
func (l *Loader) liveReloadWorker() {
l.liveReloadRunning = true
log.Debug("Rules watcher started on path %s ...", l.path)
if err := l.watcher.Add(l.path); err != nil {
log.Error("Could not watch path: %s", err)
l.liveReloadRunning = false
return
}
for {
select {
case event := <-l.watcher.Events:
// a new rule json file has been created or updated
if (event.Op&fsnotify.Write == fsnotify.Write) || (event.Op&fsnotify.Remove == fsnotify.Remove) {
if strings.HasSuffix(event.Name, ".json") {
log.Important("Ruleset changed due to %s, reloading ...", path.Base(event.Name))
if err := l.Reload(); err != nil {
log.Error("%s", err)
}
}
}
case err := <-l.watcher.Errors:
log.Error("File system watcher error: %s", err)
}
}
}
// Reload reloads the rules from disk.
func (l *Loader) Reload() error {
return l.Load(l.path)
}
// GetAll returns the loaded rules.
func (l *Loader) GetAll() map[string]*Rule {
l.RLock()
defer l.RUnlock()
return l.rules
}
func (l *Loader) isUniqueName(name string) bool {
_, found := l.rules[name]
return !found
}
func (l *Loader) setUniqueName(rule *Rule) {
l.Lock()
defer l.Unlock()
idx := 1
base := rule.Name
for l.isUniqueName(rule.Name) == false {
idx++
rule.Name = fmt.Sprintf("%s-%d", base, idx)
}
}
func (l *Loader) sortRules() {
l.rulesKeys = make([]string, 0, len(l.rules))
for k := range l.rules {
l.rulesKeys = append(l.rulesKeys, k)
}
sort.Strings(l.rulesKeys)
}
func (l *Loader) addUserRule(rule *Rule) {
if rule.Duration == Once {
return
}
l.setUniqueName(rule)
l.replaceUserRule(rule)
}
func (l *Loader) replaceUserRule(rule *Rule) {
l.Lock()
if rule.Operator.Type == List {
if err := json.Unmarshal([]byte(rule.Operator.Data), &rule.Operator.List); err != nil {
log.Error("Error loading rule of type list: %s", err)
}
}
l.rules[rule.Name] = rule
l.sortRules()
l.Unlock()
if rule.Duration == Restart || rule.Duration == Always {
return
}
tTime, err := time.ParseDuration(string(rule.Duration))
if err != nil {
return
}
time.AfterFunc(tTime, func() {
l.Lock()
delete(l.rules, rule.Name)
l.sortRules()
l.Unlock()
})
}
// Add adds a rule to the list of rules, and optionally saves it to disk.
func (l *Loader) Add(rule *Rule, saveToDisk bool) error {
l.addUserRule(rule)
if saveToDisk {
fileName := filepath.Join(l.path, fmt.Sprintf("%s.json", rule.Name))
return l.Save(rule, fileName)
}
return nil
}
// Replace adds a rule to the list of rules, and optionally saves it to disk.
func (l *Loader) Replace(rule *Rule, saveToDisk bool) error {
l.replaceUserRule(rule)
if saveToDisk {
l.Lock()
defer l.Unlock()
fileName := filepath.Join(l.path, fmt.Sprintf("%s.json", rule.Name))
return l.Save(rule, fileName)
}
return nil
}
// Save a rule to disk.
func (l *Loader) Save(rule *Rule, path string) error {
rule.Updated = time.Now()
raw, err := json.MarshalIndent(rule, "", " ")
if err != nil {
return fmt.Errorf("Error while saving rule %s to %s: %s", rule, path, err)
}
if err = ioutil.WriteFile(path, raw, 0644); err != nil {
return fmt.Errorf("Error while saving rule %s to %s: %s", rule, path, err)
}
return nil
}
// Delete deletes a rule from the list.
// If the duration is Always (i.e: saved on disk), it'll attempt to delete
// it from disk.
func (l *Loader) Delete(ruleName string) error {
l.Lock()
defer l.Unlock()
rule := l.rules[ruleName]
if rule == nil {
return nil
}
delete(l.rules, ruleName)
l.sortRules()
if rule.Duration != Always {
return nil
}
log.Info("Delete() rule: %s", rule)
path := fmt.Sprint(l.path, "/", ruleName, ".json")
return os.Remove(path)
}
// FindFirstMatch will try match the connection against the existing rule set.
func (l *Loader) FindFirstMatch(con *conman.Connection) (match *Rule) {
l.RLock()
defer l.RUnlock()
for _, idx := range l.rulesKeys {
rule, _ := l.rules[idx]
if rule.Enabled == false {
continue
}
if rule.Match(con) {
// We have a match.
// Save the rule in order to don't ask the user to take action,
// and keep iterating until a Deny or a Priority rule appears.
match = rule
if rule.Action == Deny || rule.Precedence == true {
return rule
}
}
}
return match
}