-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathnotWindows.go
More file actions
682 lines (582 loc) · 14.9 KB
/
Copy pathnotWindows.go
File metadata and controls
682 lines (582 loc) · 14.9 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
//go:build !windows
package osctrl
import (
"time"
"log"
"context"
"os/exec"
"bytes"
"io"
"syscall"
"fmt"
"os"
"errors"
"path/filepath"
"strings"
"runtime"
"bufio"
"encoding/json"
"strconv"
"github.com/shuffle/shuffle-shared"
)
func RunCommandString(command string, timeout time.Duration, onStream StreamFn) (string, error) {
if debug {
log.Printf("[DEBUG] Running command (timeout: %#v): '%s'", timeout, command)
}
ctx, cancel := context.WithTimeout(context.Background(), timeout)
defer cancel()
cmd := exec.CommandContext(ctx, "sh", "-c", command)
stdout, _ := cmd.StdoutPipe()
stderr, _ := cmd.StderrPipe()
if err := cmd.Start(); err != nil {
return "", err
}
var out bytes.Buffer
stream := func(r io.ReadCloser) {
buf := make([]byte, 32*1024)
for {
n, err := r.Read(buf)
if n > 0 {
out.Write(buf[:n])
if onStream != nil {
onStream(string(buf[:n]))
}
}
if err != nil {
return
}
}
}
go stream(stdout)
go stream(stderr)
// IMPORTANT: wait in separate goroutine
waitCh := make(chan error, 1)
go func() {
waitCh <- cmd.Wait()
}()
select {
case err := <-waitCh:
return out.String(), err
case <-ctx.Done():
_ = syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
return out.String(), errors.New(fmt.Sprintf("process timeout after %s", timeout))
}
}
func IsElevated() bool {
return os.Geteuid() == 0
}
// EDR and Telemetry Functions
// NewAuditLogCollector creates a new audit log collector for the current platform
func NewAuditLogCollector(config shuffle.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 shuffle.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 errors.New(fmt.Sprintf("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 := shuffle.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 = &shuffle.ProcessInfo{
PID: int32(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 := shuffle.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 = &shuffle.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 := shuffle.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 = &shuffle.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 := shuffle.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 = &shuffle.ProcessInfo{
PID: int32(pidInt),
}
if comm, ok := journalData["_COMM"].(string); ok {
entry.ProcessInfo.ProcessName = comm
}
if cmdline, ok := journalData["_CMDLINE"].(string); ok {
entry.ProcessInfo.CommandLine = cmdline
}
}
// User information
if uid, ok := journalData["_UID"].(string); ok {
entry.UserInfo = &shuffle.UserInfo{
UserID: uid,
}
}
// Apply filters
if c.shouldFilterLog(&entry) {
return
}
select {
case c.LogChannel <- entry:
default:
// Channel full, drop the log
}
}
// tailLogFile monitors a log file for new entries
func (c *AuditLogCollector) tailLogFile(ctx context.Context, filepath string, source string) {
file, err := os.Open(filepath)
if err != nil {
log.Printf("[ERROR] Failed to open log file %s: %v", filepath, err)
return
}
defer file.Close()
// Seek to end of file
file.Seek(0, 2)
scanner := bufio.NewScanner(file)
for {
select {
case <-ctx.Done():
return
case <-c.StopChan:
return
default:
if scanner.Scan() {
line := scanner.Text()
entry := shuffle.AuditLogEntry{
Timestamp: time.Now(),
Platform: c.Platform,
Source: source,
Message: line,
RawData: line,
}
// Apply filters
if c.shouldFilterLog(&entry) {
continue
}
select {
case c.LogChannel <- entry:
default:
// Channel full, drop the log
}
} else {
// No new data, sleep briefly
time.Sleep(100 * time.Millisecond)
}
}
}
}
func (c *AuditLogCollector) processTelemetryLogs(ctx context.Context) {
buffer := make([]shuffle.AuditLogEntry, 0, c.Config.BufferSize)
ticker := time.NewTicker(c.Config.FlushInterval)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
c.flushLogs(buffer)
return
case <-c.StopChan:
c.flushLogs(buffer)
return
case entry := <-c.LogChannel:
buffer = append(buffer, entry)
if len(buffer) >= c.Config.BufferSize {
c.flushLogs(buffer)
buffer = buffer[:0]
}
case <-ticker.C:
if len(buffer) > 0 {
c.flushLogs(buffer)
buffer = buffer[:0]
}
}
}
}
// flushLogs outputs collected logs (for now just printing)
func (c *AuditLogCollector) flushLogs(logs []shuffle.AuditLogEntry) {
c.mu.Lock()
defer c.mu.Unlock()
for _, log := range logs {
// For now, just print the logs
fmt.Printf("[AUDIT] %s | %s | %s | %s\n",
log.Timestamp.Format(time.RFC3339),
log.Platform,
log.EventType,
log.Message)
}
}
func (c *AuditLogCollector) shouldFilterLog(entry *shuffle.AuditLogEntry) bool {
for _, filter := range c.Config.Filters {
switch filter.Type {
case "event_type":
if len(filter.Include) > 0 {
included := false
for _, inc := range filter.Include {
if strings.Contains(entry.EventType, inc) {
included = true
break
}
}
if !included {
return true
}
}
for _, exc := range filter.Exclude {
if strings.Contains(entry.EventType, exc) {
return true
}
}
case "message":
if len(filter.Include) > 0 {
included := false
for _, inc := range filter.Include {
if strings.Contains(entry.Message, inc) {
included = true
break
}
}
if !included {
return true
}
}
for _, exc := range filter.Exclude {
if strings.Contains(entry.Message, exc) {
return true
}
}
}
}
return false
}
// isJournalAvailable checks if systemd journal is available
func (c *AuditLogCollector) IsJournalAvailable() bool {
cmd := exec.Command("which", "journalctl")
err := cmd.Run()
return err == nil
}
// priorityToLevel converts systemd priority to log level
func (c *AuditLogCollector) priorityToLevel(priority string) string {
switch priority {
case "0", "1", "2", "3":
return "ERROR"
case "4":
return "WARNING"
case "5", "6":
return "INFO"
case "7":
return "DEBUG"
default:
return "INFO"
}
}