-
Notifications
You must be signed in to change notification settings - Fork 69
/
auparse.go
578 lines (492 loc) · 15.1 KB
/
auparse.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
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
// Licensed to Elasticsearch B.V. under one or more contributor
// license agreements. See the NOTICE file distributed with
// this work for additional information regarding copyright
// ownership. Elasticsearch B.V. licenses this file to you under
// the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package auparse
import (
"bytes"
"fmt"
"regexp"
"strconv"
"strings"
"time"
"github.com/pkg/errors"
)
//go:generate sh -c "go run mk_audit_msg_types.go && gofmt -s -w zaudit_msg_types.go"
//go:generate sh -c "perl mk_audit_syscalls.pl > zaudit_syscalls.go && gofmt -s -w zaudit_syscalls.go"
//go:generate perl mk_audit_arches.pl
//go:generate go run mk_audit_exit_codes.go
const (
typeToken = "type="
msgToken = "msg="
)
var (
// errInvalidAuditHeader means some part of the audit header was invalid.
errInvalidAuditHeader = errors.New("invalid audit message header")
// errParseFailure indicates a generic failure to parse.
errParseFailure = errors.New("failed to parse audit message")
)
// AuditMessage represents a single audit message.
type AuditMessage struct {
RecordType AuditMessageType // Record type from netlink header.
Timestamp time.Time // Timestamp parsed from payload in netlink message.
Sequence uint32 // Sequence parsed from payload.
RawData string // Raw message as a string.
fields map[string]*field
offset int // offset is the index into RawData where the header ends and message begins.
data map[string]string // The key value pairs parsed from the message.
tags []string // The keys associated with the event (e.g. the values set in rules with -F key=exec).
error error // Error that occurred while parsing.
}
type field struct {
orig string // Original field value parse from message (including quotes).
value string // Parsed and enriched value.
}
func newField(orig string) *field { return &field{orig: orig, value: orig} }
func (f *field) Orig() string { return f.orig }
func (f *field) Value() string { return f.value }
func (f *field) Set(value string) { f.value = value }
// Data returns the key-value pairs that are contained in the audit message.
// This information is parsed from the raw message text the first time this
// method is called, all future invocations return the stored result. A nil
// map may be returned error is non-nil. A non-nil error is returned if there
// was a failure parsing or enriching the data.
func (m *AuditMessage) Data() (map[string]string, error) {
if m.data != nil || m.error != nil {
return m.data, m.error
}
if m.offset < 0 {
m.error = errors.New("message has no data content")
return nil, m.error
}
message, err := normalizeAuditMessage(m.RecordType, m.RawData[m.offset:])
if err != nil {
m.error = err
return nil, m.error
}
m.fields = map[string]*field{}
defer func() { m.fields = nil }()
extractKeyValuePairs(message, m.fields)
if err = enrichData(m); err != nil {
m.error = err
return nil, m.error
}
m.data = make(map[string]string, len(m.fields))
for k, f := range m.fields {
m.data[k] = f.Value()
}
return m.data, m.error
}
func (m *AuditMessage) Tags() ([]string, error) {
_, err := m.Data()
return m.tags, err
}
// ToMapStr returns a new map containing the parsed key value pairs, the
// record_type, @timestamp, and sequence. The parsed key value pairs have
// a lower precedence than the well-known keys and will not override them.
// If an error occurred while parsing the message then an error key will be
// present.
func (m *AuditMessage) ToMapStr() map[string]interface{} {
// Ensure event has been parsed.
data, err := m.Data()
out := make(map[string]interface{}, len(data)+5)
for k, v := range data {
out[k] = v
}
out["record_type"] = m.RecordType.String()
out["@timestamp"] = m.Timestamp.UTC().String()
out["sequence"] = strconv.FormatUint(uint64(m.Sequence), 10)
out["raw_msg"] = m.RawData
if len(m.tags) > 0 {
out["tags"] = m.tags
}
if err != nil {
out["error"] = err.Error()
}
return out
}
// ParseLogLine parses an audit message as logged by the Linux audit daemon.
// It expects logs line that begin with the message type. For example,
// "type=SYSCALL msg=audit(1488862769.030:19469538)". A non-nil error is
// returned if it fails to parse the message header (type, timestamp, sequence).
func ParseLogLine(line string) (*AuditMessage, error) {
msgIndex := strings.Index(line, msgToken)
if msgIndex == -1 {
return nil, errInvalidAuditHeader
}
// Verify type=XXX is before msg=
if msgIndex < len(typeToken)+1 {
return nil, errInvalidAuditHeader
}
// Convert the type to a number (i.e. type=SYSCALL -> 1300).
typName := line[len(typeToken) : msgIndex-1]
typ, err := GetAuditMessageType(typName)
if err != nil {
return nil, err
}
msg := line[msgIndex+len(msgToken):]
return Parse(typ, msg)
}
// Parse parses an audit message in the format it was received from the kernel.
// It expects a message type, which is the message type value from the netlink
// header, and a message, which is raw data from the netlink message. The
// message should begin the the audit header that contains the timestamp and
// sequence number -- "audit(1488862769.030:19469538)".
//
// A non-nil error is returned if it fails to parse the message header
// (timestamp, sequence).
func Parse(typ AuditMessageType, message string) (*AuditMessage, error) {
message = strings.TrimSpace(message)
timestamp, seq, end, err := parseAuditHeader([]byte(message))
if err != nil {
return nil, err
}
msg := &AuditMessage{
RecordType: typ,
Timestamp: timestamp,
Sequence: seq,
offset: indexOfMessage(message[end:]),
RawData: message,
}
return msg, nil
}
// parseAuditHeader parses the timestamp and sequence number from the audit
// message header that has the form of "audit(1490137971.011:50406):".
func parseAuditHeader(line []byte) (time.Time, uint32, int, error) {
// Find tokens.
start := bytes.IndexRune(line, '(')
if start == -1 {
return time.Time{}, 0, 0, errInvalidAuditHeader
}
dot := bytes.IndexRune(line[start:], '.')
if dot == -1 {
return time.Time{}, 0, 0, errInvalidAuditHeader
}
dot += start
sep := bytes.IndexRune(line[dot:], ':')
if sep == -1 {
return time.Time{}, 0, 0, errInvalidAuditHeader
}
sep += dot
end := bytes.IndexRune(line[sep:], ')')
if end == -1 {
return time.Time{}, 0, 0, errInvalidAuditHeader
}
end += sep
// Parse timestamp.
sec, err := strconv.ParseInt(string(line[start+1:dot]), 10, 64)
if err != nil {
return time.Time{}, 0, 0, errInvalidAuditHeader
}
msec, err := strconv.ParseInt(string(line[dot+1:sep]), 10, 64)
if err != nil {
return time.Time{}, 0, 0, errInvalidAuditHeader
}
tm := time.Unix(sec, msec*int64(time.Millisecond)).UTC()
// Parse sequence.
sequence, err := strconv.ParseUint(string(line[sep+1:end]), 10, 32)
if err != nil {
return time.Time{}, 0, 0, errInvalidAuditHeader
}
return tm, uint32(sequence), end, nil
}
func indexOfMessage(msg string) int {
return strings.IndexFunc(msg, func(r rune) bool {
switch r {
case ':', ' ':
return true
default:
return false
}
})
}
// Key/Value Parsing Helpers
var (
// kvRegex is the regular expression used to match quoted and unquoted key
// value pairs.
kvRegex = regexp.MustCompile(`([a-z0-9_-]+)=((?:[^"'\s]+)|'(?:\\'|[^'])*'|"(?:\\"|[^"])*")`)
// avcMessageRegex matches the beginning of SELinux AVC messages to parse
// the seresult and seperms parameters.
// Example: "avc: denied { read } for "
selinuxAVCMessageRegex = regexp.MustCompile(`avc:\s+(\w+)\s+\{\s*(.*)\s*\}\s+for\s+`)
)
// normalizeAuditMessage fixes some of the peculiarities of certain audit
// messages in order to make them parsable as key-value pairs.
func normalizeAuditMessage(typ AuditMessageType, msg string) (string, error) {
switch typ {
case AUDIT_AVC:
i := selinuxAVCMessageRegex.FindStringSubmatchIndex(msg)
if i == nil {
// It's a different type of AVC (e.g. AppArmor) and doesn't require
// normalization to make it parsable.
return msg, nil
}
// This selinux AVC regex match should return three pairs.
if len(i) != 3*2 {
return "", errParseFailure
}
perms := strings.Fields(msg[i[4]:i[5]])
msg = fmt.Sprintf("seresult=%v seperms=%v %v", msg[i[2]:i[3]], strings.Join(perms, ","), msg[i[1]:])
case AUDIT_LOGIN:
msg = strings.Replace(msg, "old ", "old_", 2)
msg = strings.Replace(msg, "new ", "new_", 2)
case AUDIT_CRED_DISP, AUDIT_USER_START, AUDIT_USER_END:
msg = strings.Replace(msg, " (hostname=", " hostname=", 2)
msg = strings.TrimRight(msg, ")'")
}
return msg, nil
}
func extractKeyValuePairs(msg string, data map[string]*field) {
matches := kvRegex.FindAllStringSubmatch(msg, -1)
for _, m := range matches {
key := m[1]
f := newField(m[2])
f.Set(trimQuotesAndSpace(m[2]))
// Drop fields with useless values.
switch f.Value() {
case "", "?", "?,", "(null)":
continue
}
if key == "msg" {
extractKeyValuePairs(f.Value(), data)
} else {
data[key] = f
}
}
}
func trimQuotesAndSpace(v string) string { return strings.Trim(v, `'" `) }
// Enrichment after KV parsing
func enrichData(msg *AuditMessage) error {
normalizeUnsetID("auid", msg.fields)
normalizeUnsetID("ses", msg.fields)
// Many different message types can have subj field so check them all.
parseSELinuxContext("subj", msg.fields)
// Normalize success/res to result.
result(msg.fields)
// Convert exit codes to named POSIX exit codes.
exit(msg.fields)
// Normalize keys that are of the form key="key=user_command".
auditRuleKey(msg)
hexDecode("cwd", msg.fields)
switch msg.RecordType {
case AUDIT_SYSCALL:
if err := arch(msg.fields); err != nil {
return err
}
if err := syscall(msg.fields); err != nil {
return err
}
if err := hexDecode("exe", msg.fields); err != nil {
return err
}
case AUDIT_SOCKADDR:
if err := saddr(msg.fields); err != nil {
return err
}
case AUDIT_PROCTITLE:
if err := hexDecode("proctitle", msg.fields); err != nil {
return err
}
case AUDIT_USER_CMD:
if err := hexDecode("cmd", msg.fields); err != nil {
return err
}
case AUDIT_TTY, AUDIT_USER_TTY:
if err := hexDecode("data", msg.fields); err != nil {
return err
}
case AUDIT_EXECVE:
if err := execveArgs(msg.fields); err != nil {
return err
}
case AUDIT_PATH:
parseSELinuxContext("obj", msg.fields)
hexDecode("name", msg.fields)
case AUDIT_USER_LOGIN:
// acct only exists in failed logins.
hexDecode("acct", msg.fields)
}
return nil
}
func arch(data map[string]*field) error {
field, found := data["arch"]
if !found {
return errors.New("arch key not found")
}
arch, err := strconv.ParseInt(field.Value(), 16, 64)
if err != nil {
return errors.Wrap(err, "failed to parse arch")
}
field.Set(AuditArch(arch).String())
return nil
}
func syscall(data map[string]*field) error {
field, found := data["syscall"]
if !found {
return errors.New("syscall key not found")
}
syscall, err := strconv.Atoi(field.Value())
if err != nil {
return errors.Wrap(err, "failed to parse syscall")
}
arch, found := data["arch"]
if !found {
return errors.New("arch key not found so syscall cannot be translated to a name")
}
if name, found := AuditSyscalls[arch.Value()][syscall]; found {
field.Set(name)
}
return nil
}
func saddr(data map[string]*field) error {
field, found := data["saddr"]
if !found {
return errors.New("saddr key not found")
}
saddrData, err := parseSockaddr(field.Value())
if err != nil {
return errors.Wrap(err, "failed to parse saddr")
}
delete(data, "saddr")
for k, v := range saddrData {
data[k] = newField(v)
}
return nil
}
func normalizeUnsetID(key string, data map[string]*field) {
field, found := data[key]
if !found {
return
}
switch field.Value() {
case "4294967295", "-1":
field.Set("unset")
}
}
func hexDecode(key string, data map[string]*field) error {
field, found := data[key]
if !found {
return errors.Errorf("%v key not found", key)
}
// Use the original value that may or may not contain a leading quote.
decodedStrings, err := hexToStrings(field.Orig())
if err != nil {
// Field is not in hex. Ignore.
return nil
}
if len(decodedStrings) > 0 {
field.Set(strings.Join(decodedStrings, " "))
}
return nil
}
func execveArgs(data map[string]*field) error {
argc, found := data["argc"]
if !found {
return errors.New("argc key not found")
}
count, err := strconv.ParseUint(argc.Value(), 10, 32)
if err != nil {
return errors.Wrapf(err, "failed to convert argc='%v' to number", argc)
}
for i := 0; i < int(count); i++ {
key := "a" + strconv.Itoa(i)
arg, found := data[key]
if !found {
return errors.Errorf("failed to find arg %v", key)
}
if ascii, err := hexToString(arg.Orig()); err == nil {
arg.Set(ascii)
}
}
return nil
}
// parseSELinuxContext parses a SELinux security context of the form
// 'user:role:domain:level:category'.
func parseSELinuxContext(key string, data map[string]*field) error {
field, found := data[key]
if !found {
return errors.Errorf("%v key not found", key)
}
keys := []string{"_user", "_role", "_domain", "_level", "_category"}
contextParts := strings.SplitN(field.Value(), ":", len(keys))
if len(contextParts) == 0 {
return errors.Errorf("failed to split SELinux context field %v", key)
}
delete(data, key)
for i, part := range contextParts {
data[key+keys[i]] = newField(part)
}
return nil
}
func result(data map[string]*field) error {
// Syscall messages use "success". Other messages use "res".
field, found := data["success"]
if !found {
field, found = data["res"]
if !found {
return errors.New("success and res key not found")
}
delete(data, "res")
} else {
delete(data, "success")
}
switch v := strings.ToLower(field.Value()); {
case v == "yes", v == "1", strings.HasPrefix(v, "suc"):
data["result"] = newField("success")
default:
data["result"] = newField("fail")
}
return nil
}
func auditRuleKey(msg *AuditMessage) {
field, found := msg.fields["key"]
if !found {
return
}
delete(msg.fields, "key")
// Handle hex encoded data (e.g. key=28696E7).
if decodedData, err := decodeUppercaseHexString(field.Orig()); err == nil {
keys := strings.Split(string(decodedData), string([]byte{0x01}))
msg.tags = keys
return
}
parts := strings.SplitN(field.Value(), "=", 2)
if len(parts) == 1 {
// Handle key="net".
msg.tags = parts
} else if len(parts) == 2 {
// Handle key="key=net".
msg.tags = parts[1:]
}
}
func exit(data map[string]*field) error {
field, found := data["exit"]
if !found {
return errors.New("exit key not found")
}
exitCode, err := strconv.Atoi(field.Value())
if err != nil {
return errors.Wrap(err, "failed to parse exit")
}
if exitCode >= 0 {
return nil
}
name, found := AuditErrnoToName[-1*exitCode]
if !found {
return nil
}
field.Set(name)
return nil
}