forked from slackhq/go-audit
-
Notifications
You must be signed in to change notification settings - Fork 0
/
audit.go
422 lines (335 loc) · 9.87 KB
/
audit.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
package main
import (
"errors"
"flag"
"fmt"
"log"
"log/syslog"
"os"
"os/exec"
"os/signal"
"os/user"
"regexp"
"strconv"
"strings"
"syscall"
"github.com/spf13/viper"
)
var l = log.New(os.Stdout, "", 0)
var el = log.New(os.Stderr, "", 0)
type executor func(string, ...string) error
func lExec(s string, a ...string) error {
return exec.Command(s, a...).Run()
}
func loadRules(rulesFile string) (*viper.Viper, error) {
config := viper.New()
config.SetConfigFile(rulesFile)
if err := config.ReadInConfig(); err != nil {
return nil, err
}
return config, nil
}
func loadConfig(configFile string) (*viper.Viper, error) {
config := viper.New()
config.SetConfigFile(configFile)
config.SetDefault("events.min", 1300)
config.SetDefault("events.max", 1399)
config.SetDefault("message_tracking.enabled", true)
config.SetDefault("message_tracking.log_out_of_order", false)
config.SetDefault("message_tracking.max_out_of_order", 500)
config.SetDefault("output.syslog.enabled", false)
config.SetDefault("output.syslog.priority", int(syslog.LOG_LOCAL0|syslog.LOG_WARNING))
config.SetDefault("output.syslog.tag", "go-audit")
config.SetDefault("output.syslog.attempts", "3")
config.SetDefault("log.flags", 0)
if err := config.ReadInConfig(); err != nil {
return nil, err
}
l.SetFlags(config.GetInt("log.flags"))
el.SetFlags(config.GetInt("log.flags"))
return config, nil
}
func setRules(config *viper.Viper, e executor) error {
// Clear existing rules
if err := e("auditctl", "-D"); err != nil {
return fmt.Errorf("Failed to flush existing audit rules. Error: %s", err)
}
l.Println("Flushed existing audit rules")
// Add ours in
ruleSection := config.Get("rules")
rules := []Rule{}
rawRuleList, _ := ruleSection.([]interface{})
for _, rawItem := range rawRuleList {
itemMap, _ := rawItem.(map[interface{}]interface{})
rule := Rule{}
for key, value := range itemMap {
if value == "" {
continue
}
switch key {
case "rule":
ruleValue, _ := value.(string)
rule.rule = ruleValue
case "topic":
topicName, _ := value.(string)
rule.topic = topicName
}
}
if rule.rule == "" {
continue
}
if err := e("auditctl", strings.Fields(rule.rule)...); err != nil {
return fmt.Errorf("Failed to add rule #%d. Error: %s", len(rules)+1, err)
}
rules = append(rules, rule)
l.Printf("Added audit rule #%d\n", len(rules))
}
if len(rules) == 0 {
return errors.New("No audit rules found")
}
return nil
}
func createOutput(config *viper.Viper) (*AuditWriter, error) {
var writer *AuditWriter
var err error
i := 0
if config.GetBool("output.syslog.enabled") == true {
i++
writer, err = createSyslogOutput(config)
if err != nil {
return nil, err
}
}
if config.GetBool("output.file.enabled") == true {
i++
writer, err = createFileOutput(config)
if err != nil {
return nil, err
}
go handleLogRotation(config, writer)
}
if config.GetBool("output.stdout.enabled") == true {
i++
writer, err = createStdOutOutput(config)
if err != nil {
return nil, err
}
}
if i > 1 {
return nil, errors.New("Only one output can be enabled at a time")
}
if writer == nil {
return nil, errors.New("No outputs were configured")
}
return writer, nil
}
func createSyslogOutput(config *viper.Viper) (*AuditWriter, error) {
attempts := config.GetInt("output.syslog.attempts")
if attempts < 1 {
return nil, fmt.Errorf("Output attempts for syslog must be at least 1, %v provided", attempts)
}
syslogWriter, err := syslog.Dial(
config.GetString("output.syslog.network"),
config.GetString("output.syslog.address"),
syslog.Priority(config.GetInt("output.syslog.priority")),
config.GetString("output.syslog.tag"),
)
if err != nil {
return nil, fmt.Errorf("Failed to open syslog writer. Error: %v", err)
}
return NewAuditWriter(syslogWriter, attempts), nil
}
func createFileOutput(config *viper.Viper) (*AuditWriter, error) {
attempts := config.GetInt("output.file.attempts")
if attempts < 1 {
return nil, fmt.Errorf("Output attempts for file must be at least 1, %v provided", attempts)
}
mode := os.FileMode(config.GetInt("output.file.mode"))
if mode < 1 {
return nil, errors.New("Output file mode should be greater than 0000")
}
f, err := os.OpenFile(
config.GetString("output.file.path"),
os.O_APPEND|os.O_CREATE|os.O_WRONLY, mode,
)
if err != nil {
return nil, fmt.Errorf("Failed to open output file. Error: %s", err)
}
if err := f.Chmod(mode); err != nil {
return nil, fmt.Errorf("Failed to set file permissions. Error: %s", err)
}
uname := config.GetString("output.file.user")
u, err := user.Lookup(uname)
if err != nil {
return nil, fmt.Errorf("Could not find uid for user %s. Error: %s", uname, err)
}
gname := config.GetString("output.file.group")
g, err := user.LookupGroup(gname)
if err != nil {
return nil, fmt.Errorf("Could not find gid for group %s. Error: %s", gname, err)
}
uid, err := strconv.ParseInt(u.Uid, 10, 32)
if err != nil {
return nil, fmt.Errorf("Found uid could not be parsed. Error: %s", err)
}
gid, err := strconv.ParseInt(g.Gid, 10, 32)
if err != nil {
return nil, fmt.Errorf("Found gid could not be parsed. Error: %s", err)
}
if err = f.Chown(int(uid), int(gid)); err != nil {
return nil, fmt.Errorf("Could not chown output file. Error: %s", err)
}
return NewAuditWriter(f, attempts), nil
}
func handleLogRotation(config *viper.Viper, writer *AuditWriter) {
// Re-open our log file. This is triggered by a USR1 signal and is meant to be used upon log rotation
sigc := make(chan os.Signal, 1)
signal.Notify(sigc, syscall.SIGUSR1)
for range sigc {
newWriter, err := createFileOutput(config)
if err != nil {
el.Fatalln("Error re-opening log file. Exiting.")
}
oldFile := writer.w.(*os.File)
writer.w = newWriter.w
writer.e = newWriter.e
err = oldFile.Close()
if err != nil {
el.Printf("Error closing old log file: %+v\n", err)
}
}
}
func createStdOutOutput(config *viper.Viper) (*AuditWriter, error) {
attempts := config.GetInt("output.stdout.attempts")
if attempts < 1 {
return nil, fmt.Errorf("Output attempts for stdout must be at least 1, %v provided", attempts)
}
// l logger is no longer stdout
l.SetOutput(os.Stderr)
return NewAuditWriter(os.Stdout, attempts), nil
}
func createFilters(config *viper.Viper) ([]AuditFilter, error) {
var err error
var ok bool
fs := config.Get("filters")
filters := []AuditFilter{}
if fs == nil {
return filters, nil
}
ft, ok := fs.([]interface{})
if !ok {
return filters, fmt.Errorf("Could not parse filters object")
}
for i, f := range ft {
f2, ok := f.(map[interface{}]interface{})
if !ok {
return filters, fmt.Errorf("Could not parse filter %d; '%+v'", i+1, f)
}
af := AuditFilter{}
for k, v := range f2 {
switch k {
case "message_type":
if ev, ok := v.(string); ok {
fv, err := strconv.ParseUint(ev, 10, 64)
if err != nil {
return filters, fmt.Errorf("`message_type` in filter %d could not be parsed; Value: `%+v`; Error: %s", i+1, v, err)
}
af.messageType = uint16(fv)
} else if ev, ok := v.(int); ok {
af.messageType = uint16(ev)
} else {
return filters, fmt.Errorf("`message_type` in filter %d could not be parsed; Value: `%+v`", i+1, v)
}
case "regex":
re, ok := v.(string)
if !ok {
return filters, fmt.Errorf("`regex` in filter %d could not be parsed; Value: `%+v`", i+1, v)
}
if af.regex, err = regexp.Compile(re); err != nil {
return filters, fmt.Errorf("`regex` in filter %d could not be parsed; Value: `%+v`; Error: %s", i+1, v, err)
}
case "syscall":
if af.syscall, ok = v.(string); ok {
// All is good
} else if ev, ok := v.(int); ok {
af.syscall = strconv.Itoa(ev)
} else {
return filters, fmt.Errorf("`syscall` in filter %d could not be parsed; Value: `%+v`", i+1, v)
}
}
}
if af.regex == nil {
return filters, fmt.Errorf("Filter %d is missing the `regex` entry", i+1)
}
if af.syscall == "" {
return filters, fmt.Errorf("Filter %d is missing the `syscall` entry", i+1)
}
if af.messageType == 0 {
return filters, fmt.Errorf("Filter %d is missing the `message_type` entry", i+1)
}
filters = append(filters, af)
l.Printf("Ignoring syscall `%v` containing message type `%v` matching string `%s`\n", af.syscall, af.messageType, af.regex.String())
}
return filters, nil
}
func main() {
configFile := flag.String("config", "", "Config file location")
rulesFile := flag.String("rules-file", "", "Rules file location")
flag.Parse()
if *configFile == "" {
el.Println("A config file must be provided")
flag.Usage()
os.Exit(1)
}
if *rulesFile == "" {
el.Println("A rules file must be provided")
flag.Usage()
os.Exit(1)
}
config, err := loadConfig(*configFile)
if err != nil {
el.Fatal(err)
}
rules, err := loadRules(*rulesFile)
if err != nil {
el.Fatal(err)
}
// output needs to be created before anything that write to stdout
writer, err := createOutput(config)
if err != nil {
el.Fatal(err)
}
if err := setRules(rules, lExec); err != nil {
el.Fatal(err)
}
filters, err := createFilters(rules)
if err != nil {
el.Fatal(err)
}
nlClient, err := NewNetlinkClient(config.GetInt("socket_buffer.receive"))
if err != nil {
el.Fatal(err)
}
marshaller := NewAuditMarshaller(
writer,
uint16(config.GetInt("events.min")),
uint16(config.GetInt("events.max")),
config.GetBool("message_tracking.enabled"),
config.GetBool("message_tracking.log_out_of_order"),
config.GetInt("message_tracking.max_out_of_order"),
filters,
)
l.Printf("Started processing events in the range [%d, %d]\n", config.GetInt("events.min"), config.GetInt("events.max"))
//Main loop. Get data from netlink and send it to the json lib for processing
for {
msg, err := nlClient.Receive()
if err != nil {
el.Printf("Error during message receive: %+v\n", err)
continue
}
if msg == nil {
continue
}
marshaller.Consume(msg)
}
}