-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathnixSpecific.go
More file actions
2042 lines (1720 loc) · 43.4 KB
/
nixSpecific.go
File metadata and controls
2042 lines (1720 loc) · 43.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
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
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//go:build !windows
package shuffle
import (
"os"
"os/exec"
"strings"
"strconv"
"regexp"
"encoding/json"
"time"
"context"
"bytes"
"io"
"fmt"
"log"
"bufio"
"path/filepath"
"syscall"
"runtime"
)
func IsElevated() bool {
return os.Geteuid() == 0
}
func parsePmsetDisplaySleep(out []byte) int {
lines := strings.Split(string(out), "\n")
for _, line := range lines {
line = strings.TrimSpace(line)
if strings.HasPrefix(line, "displaysleep") {
fields := strings.Fields(line)
if len(fields) >= 2 {
mins := parseInt(fields[1])
return mins * 60
}
}
}
return 0
}
func willLockWithin15MinMac() bool {
idleSec := getMacIdleTimeSeconds()
if idleSec <= 0 {
return false
}
lockEnabled := isMacScreenLockEnabled()
// must both be true
//return lockEnabled && idleSec <= 900
return lockEnabled && idleSec <= 10800
}
func getMacIdleTimeSeconds() int {
// try currentHost (more reliable than system-wide)
out, err := exec.Command(
"defaults",
"-currentHost",
"read",
"com.apple.screensaver",
"idleTime",
).Output()
if err == nil {
if v := parseInt(strings.TrimSpace(string(out))); v > 0 {
return v
}
}
// fallback: system-wide pmset
out, err = exec.Command("pmset", "-g", "custom").Output()
if err == nil {
return parsePmsetDisplaySleep(out)
}
return 0
}
func isMacScreenLockEnabled() bool {
out, err := exec.Command(
"defaults",
"read",
"com.apple.screensaver",
"askForPassword",
).Output()
if err != nil {
// missing key → assume enabled in managed/security contexts
return true
}
return strings.TrimSpace(string(out)) == "1"
}
func getAutoLockTimeout() int {
out, err := exec.Command(
"gsettings",
"get",
"org.gnome.desktop.session",
"idle-delay",
).Output()
if err == nil {
s := strings.TrimSpace(string(out))
s = strings.Trim(s, "uint32()")
if v, err := strconv.Atoi(s); err == nil {
return v / 60
}
}
return tryKDETimeout()
}
func tryKDETimeout() int {
data, err := os.ReadFile(os.ExpandEnv("$HOME/.config/kscreenlockerrc"))
if err != nil {
return -1
}
re := regexp.MustCompile(`Timeout=(\d+)`)
m := re.FindSubmatch(data)
if len(m) != 2 {
return -1
}
v, err := strconv.Atoi(string(m[1]))
if err != nil {
return -1
}
return v
}
func getDesktop() string {
// most reliable first
v := os.Getenv("XDG_CURRENT_DESKTOP")
if v != "" {
return strings.ToLower(v)
}
v = os.Getenv("DESKTOP_SESSION")
if v != "" {
return strings.ToLower(v)
}
v = os.Getenv("GDMSESSION")
return strings.ToLower(v)
}
func isGNOME() bool {
d := getDesktop()
return strings.Contains(d, "gnome")
}
func isKDE() bool {
d := getDesktop()
return strings.Contains(d, "kde") ||
strings.Contains(d, "plasma")
}
func getAutoLockTimeoutNix() int {
switch {
case isGNOME():
return getAutoLockTimeout()
case isKDE():
return tryKDETimeout()
default:
return getAutoLockTimeout()
}
}
func getScreenPolicyUnix() bool {
// 15 minutes check
lockTimeout := getAutoLockTimeoutNix()
if lockTimeout > 0 && lockTimeout <= 15 {
return true
}
return false
}
func IsAutomaticScreenlockEnabled() bool {
switch runtime.GOOS {
case "windows":
return false
case "darwin":
return willLockWithin15MinMac()
default: // linux, macOS, etc.
return getScreenPolicyUnix()
}
}
func isEncryptedMac() bool {
out, err := exec.Command("fdesetup", "status").Output()
if err != nil {
return false
}
s := strings.ToLower(string(out))
return strings.Contains(s, "filevault is on")
}
func isEncryptedLinux() bool {
out, err := exec.Command("lsblk", "-o", "NAME,TYPE").Output()
if err != nil {
return false
}
s := string(out)
// look for crypt mapping (LUKS/dm-crypt)
return strings.Contains(s, "crypt")
}
func IsDiskEncrypted() bool {
switch runtime.GOOS {
case "windows":
return false
case "darwin":
return isEncryptedMac()
default:
return isEncryptedLinux()
}
}
func cleanSerial(s string) string {
return strings.TrimSpace(s)
}
func getProfileMac() string {
out, err := exec.Command("system_profiler", "SPHardwareDataType").Output()
if err == nil {
return string(out)
}
return "failed to locate (macos)"
}
func getSerialLinux() string {
paths := []string{
"/sys/class/dmi/id/product_serial",
"/sys/class/dmi/id/board_serial",
}
for _, p := range paths {
if data, err := os.ReadFile(p); err == nil {
s := cleanSerial(string(data))
if isValidSerial(s) {
return s
}
}
}
// fallback (requires root on many systems)
out, err := exec.Command("dmidecode", "-s", "system-serial-number").Output()
if err == nil {
s := cleanSerial(string(out))
if isValidSerial(s) {
return s
}
}
return "failed to locate"
}
func GetProfiler() string {
switch runtime.GOOS {
case "windows":
return ""
case "darwin":
return getProfileMac()
default:
return getSerialLinux()
}
}
func listRPM() []Software {
out, err := exec.Command(
"rpm",
"-qa",
"--queryformat",
"%{NAME} %{VERSION}-%{RELEASE}\n",
).Output()
if err != nil {
return nil
}
var result []Software
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 {
result = append(result, Software{
Name: fields[0],
Version: fields[1],
})
}
}
return result
}
func listDpkg() []Software {
out, err := exec.Command(
"dpkg-query",
"-W",
"-f=${Package} ${Version}\n",
).Output()
if err != nil {
return nil
}
var result []Software
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 {
result = append(result, Software{
Name: fields[0],
Version: fields[1],
})
}
}
return result
}
func listPacman() []Software {
out, err := exec.Command(
"pacman",
"-Q",
).Output()
if err != nil {
return nil
}
var result []Software
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 {
result = append(result, Software{
Name: fields[0],
Version: fields[1],
})
}
}
return result
}
func listYay() []Software {
out, err := exec.Command(
"yay",
"-Q",
).Output()
if err != nil {
return nil
}
var result []Software
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 {
result = append(result, Software{
Name: fields[0],
Version: fields[1],
})
}
}
return result
}
func listAPK() []Software {
out, err := exec.Command(
"apk",
"info",
"-v",
).Output()
if err != nil {
return nil
}
var result []Software
for _, line := range strings.Split(string(out), "\n") {
line = strings.TrimSpace(line)
if line == "" {
continue
}
// split on last "-" because names can contain hyphens
i := strings.LastIndex(line, "-")
if i <= 0 || i == len(line)-1 {
continue
}
result = append(result, Software{
Name: line[:i],
Version: line[i+1:],
})
}
return result
}
func listLinuxSoftware() []Software {
// dpkg (Debian/Ubuntu)
found := []Software{}
if _, err := exec.LookPath("dpkg-query"); err == nil {
found = listDpkg()
if len(found) > 0 {
return found
}
}
// rpm (RHEL/Fedora)
if _, err := exec.LookPath("rpm"); err == nil {
found = listRPM()
if len(found) > 0 {
return found
}
}
if _, err := exec.LookPath("pacman"); err == nil {
found = listPacman()
if len(found) > 0 {
return found
}
}
if _, err := exec.LookPath("yay"); err == nil {
found = listYay()
if len(found) > 0 {
return found
}
}
if _, err := exec.LookPath("apk"); err == nil {
found = listAPK()
if len(found) > 0 {
return found
}
}
// fallback
return []Software{}
}
func listBrew() []Software {
out, err := exec.Command("brew", "list", "--versions").Output()
if err != nil {
return nil
}
var result []Software
for _, line := range strings.Split(string(out), "\n") {
fields := strings.Fields(line)
if len(fields) >= 2 {
result = append(result, Software{
Name: fields[0],
Version: fields[1],
})
}
}
return result
}
func GetLinuxSoftware() (Software, error) {
file, err := os.Open("/etc/os-release")
if err != nil {
return Software{}, err
}
defer file.Close()
var name, version, codename string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := scanner.Text()
parts := strings.SplitN(line, "=", 2)
if len(parts) != 2 {
continue
}
key := parts[0]
value := strings.Trim(parts[1], `"`)
switch key {
case "NAME":
name = value
case "VERSION_ID":
version = value
case "VERSION_CODENAME":
codename = value
}
}
if err := scanner.Err(); err != nil {
return Software{}, err
}
fullName := name
if version != "" {
fullName = fmt.Sprintf("%s %s", name, version)
}
if codename != "" {
fullName = fmt.Sprintf("%s (%s)", fullName, codename)
}
return Software{
Name: fullName,
Version: version,
}, nil
}
func FindSystemVersionMacOS() Software {
get := func(flag string) (string, error) {
out, err := exec.Command("sw_vers", flag).Output()
if err != nil {
return "", err
}
return strings.TrimSpace(string(out)), nil
}
productName, err := get("-productName")
if err != nil {
return Software{}
}
version, err := get("-productVersion")
if err != nil {
return Software{}
}
build, err := get("-buildVersion")
if err != nil {
return Software{}
}
return Software{
Name: fmt.Sprintf("%s %s (%s)", productName, version, build),
Version: version,
}
}
func ListInstalledSoftware() []Software {
switch runtime.GOOS {
case "windows":
return []Software{}
case "darwin":
systemInfo := FindSystemVersionMacOS()
systemApps := listMacSoftware()
homebrew := listBrew()
allSoftware := []Software{systemInfo}
allSoftware = append(allSoftware, systemApps...)
allSoftware = append(allSoftware, homebrew...)
return allSoftware
default:
allSoftware := []Software{}
defaultSoftware, err := GetLinuxSoftware()
if err != nil {
log.Printf("[WARNING] Failed to get Linux distribution info: %v", err)
} else {
allSoftware = append(allSoftware, defaultSoftware)
}
return append(allSoftware, listLinuxSoftware()...)
}
}
// EDR and Telemetry Functions
// NewAuditLogCollector creates a new audit log collector for the current platform
func NewAuditLogCollector(config TelemetryConfig) (*AuditLogCollector, error) {
platform := runtime.GOOS
if config.BufferSize == 0 {
config.BufferSize = 1000
}
if config.FlushInterval == 0 {
config.FlushInterval = 10 * time.Second
}
collector := &AuditLogCollector{
Config: config,
Platform: platform,
LogChannel: make(chan AuditLogEntry, config.BufferSize),
StopChan: make(chan bool),
}
return collector, nil
}
func (c *AuditLogCollector) LogCollectorStart(ctx context.Context) error {
if !c.Config.Enabled {
return nil
}
auditLogEnabled := false
for _, mode := range c.Config.Modes {
if mode == "audit_log" {
auditLogEnabled = true
break
}
}
if !auditLogEnabled {
return nil
}
log.Printf("[INFO] Starting audit log collector for platform: %s", c.Platform)
switch c.Platform {
case "linux":
go c.collectLinuxAuditLogs(ctx)
case "darwin":
go c.collectMacOSAuditLogs(ctx)
default:
return fmt.Errorf("unsupported platform: %s", c.Platform)
}
go c.processTelemetryLogs(ctx)
return nil
}
// Stop stops the audit log collection
func (c *AuditLogCollector) Stop() {
log.Printf("[INFO] Stopping audit log collector")
close(c.StopChan)
}
// collectLinuxAuditLogs collects audit logs on Linux systems
func (c *AuditLogCollector) collectLinuxAuditLogs(ctx context.Context) {
// Check for auditd logs
auditLogPath := "/var/log/audit/audit.log"
syslogPath := "/var/log/syslog"
journalAvailable := c.isJournalAvailable()
// Use journalctl if available
if journalAvailable {
go c.collectJournalLogs(ctx)
}
// Monitor audit.log if it exists
if _, err := os.Stat(auditLogPath); err == nil {
go c.tailLogFile(ctx, auditLogPath, "auditd")
}
// Monitor syslog
if _, err := os.Stat(syslogPath); err == nil {
go c.tailLogFile(ctx, syslogPath, "syslog")
}
}
func (c *AuditLogCollector) collectMacOSAuditLogs(ctx context.Context) {
go c.collectMacOSSecurityLogs(ctx)
}
// collectMacOSSecurityLogs collects all security-relevant logs with one predicate
func (c *AuditLogCollector) collectMacOSSecurityLogs(ctx context.Context) {
log.Printf("[INFO] Starting macOS security log collection")
predicate := `(subsystem == "com.apple.opendirectoryd" && category == "auth") ||
process == "login" ||
process == "sshd" ||
process == "sudo" ||
process == "su"`
cmd := exec.Command("log", "stream",
"--predicate", predicate,
"--info", "--debug",
"--style", "json")
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Printf("[ERROR] Failed to create stdout pipe for security log stream: %v", err)
return
}
if err := cmd.Start(); err != nil {
log.Printf("[ERROR] Failed to start security log stream: %v", err)
return
}
log.Printf("[INFO] Successfully started security log stream")
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
select {
case <-ctx.Done():
cmd.Process.Kill()
return
case <-c.StopChan:
cmd.Process.Kill()
return
default:
line := scanner.Text()
if line != "" {
c.parseMacOSLogEntry(line)
}
}
}
if err := scanner.Err(); err != nil {
log.Printf("[ERROR] Error reading security log stream: %v", err)
}
}
func (c *AuditLogCollector) parseMacOSLogEntry(line string) {
// First, let's see what we're actually getting
log.Printf("[DEBUG] Raw log line: %s", line)
var logData map[string]interface{}
if err := json.Unmarshal([]byte(line), &logData); err != nil {
log.Printf("[ERROR] Failed to parse JSON: %v", err)
// If JSON parsing fails, treat it as plain text
c.parseSimpleMacOSLogEntry(line)
return
}
log.Printf("[DEBUG] Parsed JSON log entry: %v", logData)
entry := AuditLogEntry{
Timestamp: time.Now(),
Platform: "darwin",
RawData: line,
Metadata: logData,
}
if eventType, ok := logData["eventType"].(string); ok {
entry.EventType = eventType
}
if eventMessage, ok := logData["eventMessage"].(string); ok {
entry.Message = eventMessage
}
if processID, ok := logData["processID"].(float64); ok {
entry.ProcessInfo = &ProcessInfo{
PID: int(processID),
}
if processImagePath, ok := logData["processImagePath"].(string); ok {
entry.ProcessInfo.ProcessName = filepath.Base(processImagePath)
}
}
if c.shouldFilterLog(&entry) {
return
}
select {
case c.LogChannel <- entry:
default:
// log.Printf("[WARNING] Log channel full, dropping log entry")
}
}
func (c *AuditLogCollector) parseSimpleMacOSLogEntry(line string) {
// this just looks for keywords in the log line
// not sure how reliable this is, but it's a start lol
lowerLine := strings.ToLower(line)
isSecurityRelevant := strings.Contains(lowerLine, "login") ||
strings.Contains(lowerLine, "auth") ||
strings.Contains(lowerLine, "sudo") ||
strings.Contains(lowerLine, "password") ||
strings.Contains(lowerLine, "session") ||
strings.Contains(lowerLine, "security") ||
strings.Contains(lowerLine, "loginwindow") ||
strings.Contains(lowerLine, "securityd")
if !isSecurityRelevant {
return
}
entry := AuditLogEntry{
Timestamp: time.Now(),
Platform: "darwin",
Source: "unified_log",
Message: line,
RawData: line,
EventType: "security",
}
// Basic process extraction from log format
if strings.Contains(line, ": ") {
parts := strings.Split(line, ": ")
if len(parts) > 1 {
processField := parts[0]
if strings.Contains(processField, "[") {
procParts := strings.Split(processField, "[")
if len(procParts) > 0 {
entry.ProcessInfo = &ProcessInfo{
ProcessName: strings.TrimSpace(procParts[0]),
}
}
}
}
}
if c.shouldFilterLog(&entry) {
return
}
select {
case c.LogChannel <- entry:
default:
// Channel full, drop the log
}
}
// collectMacOSAuthLogs monitors auth.log and system authentication events
func (c *AuditLogCollector) collectMacOSAuthLogs(ctx context.Context) {
log.Printf("[INFO] Starting macOS auth log collection")
// Just monitor some basic log files that might exist
logPaths := []string{
"/var/log/auth.log",
"/var/log/system.log",
"/var/log/secure.log",
}
for _, logPath := range logPaths {
if _, err := os.Stat(logPath); err == nil {
log.Printf("[INFO] Monitoring log file: %s", logPath)
go c.tailLogFile(ctx, logPath, filepath.Base(logPath))
}
}
}
// collectMacOSBSMaudit collects from macOS BSM audit system
func (c *AuditLogCollector) collectMacOSBSMaudit(ctx context.Context) {
// Check if audit is enabled
cmd := exec.Command("sudo", "audit", "-s")
if err := cmd.Run(); err != nil {
log.Printf("[WARNING] BSM audit not available or not enabled: %v", err)
return
}
// Monitor current audit trail
auditDir := "/var/audit"
if _, err := os.Stat(auditDir); err != nil {
log.Printf("[WARNING] Audit directory not accessible: %v", err)
return
}
// Use praudit to read audit records in real-time
cmd = exec.Command("sudo", "praudit", "-l")
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Printf("[ERROR] Failed to create stdout pipe for praudit: %v", err)
return
}
if err := cmd.Start(); err != nil {
log.Printf("[ERROR] Failed to start praudit: %v", err)
return
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
select {
case <-ctx.Done():
cmd.Process.Kill()
return
case <-c.StopChan:
cmd.Process.Kill()
return
default:
line := scanner.Text()
c.parseBSMAuditEntry(line)
}
}
}
// parseBSMAuditEntry parses BSM audit entries
func (c *AuditLogCollector) parseBSMAuditEntry(line string) {
entry := AuditLogEntry{
Timestamp: time.Now(),
Platform: "darwin",
Source: "bsm_audit",
Message: line,
RawData: line,
EventType: "audit",
}
// Extract process info if available (basic parsing)
if strings.Contains(line, "process") {
// This is a simplified parser - BSM audit format is complex
fields := strings.Fields(line)
for i, field := range fields {
if field == "process" && i+1 < len(fields) {
entry.ProcessInfo = &ProcessInfo{
ProcessName: fields[i+1],
}
break
}
}
}
if c.shouldFilterLog(&entry) {
return
}
select {
case c.LogChannel <- entry:
default:
// Channel full, drop the log
}
}
func (c *AuditLogCollector) collectJournalLogs(ctx context.Context) {
cmd := exec.Command("journalctl", "-f", "-o", "json", "--since", "now")
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Printf("[ERROR] Failed to create stdout pipe for journalctl: %v", err)
return
}
if err := cmd.Start(); err != nil {
log.Printf("[ERROR] Failed to start journalctl: %v", err)
return
}
scanner := bufio.NewScanner(stdout)
for scanner.Scan() {
select {
case <-ctx.Done():
cmd.Process.Kill()
return
case <-c.StopChan:
cmd.Process.Kill()
return
default:
line := scanner.Text()
c.parseJournalEntry(line)
}
}
if err := scanner.Err(); err != nil {
log.Printf("[ERROR] Error reading journalctl: %v", err)
}
}
// parseJournalEntry parses a systemd journal entry
func (c *AuditLogCollector) parseJournalEntry(line string) {
var journalData map[string]interface{}
if err := json.Unmarshal([]byte(line), &journalData); err != nil {
return
}
entry := AuditLogEntry{
Timestamp: time.Now(),
Platform: "linux",
Source: "journal",
RawData: line,
Metadata: journalData,
}
// Extract standard journal fields
if priority, ok := journalData["PRIORITY"].(string); ok {
entry.Level = c.priorityToLevel(priority)
}
if message, ok := journalData["MESSAGE"].(string); ok {
entry.Message = message
}
if syslogID, ok := journalData["SYSLOG_IDENTIFIER"].(string); ok {
entry.EventType = syslogID
}
// Process information
if pid, ok := journalData["_PID"].(string); ok {
pidInt, _ := strconv.Atoi(pid)
entry.ProcessInfo = &ProcessInfo{
PID: pidInt,