-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain.go
More file actions
1593 lines (1409 loc) · 46.6 KB
/
main.go
File metadata and controls
1593 lines (1409 loc) · 46.6 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
// Package main implements the gitMDM agent that collects compliance data.
package main
import (
"bytes"
"context"
"crypto/sha256"
_ "embed"
"encoding/hex"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"log"
"math"
"net/http"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"runtime/debug"
"sort"
"strconv"
"strings"
"sync"
"syscall"
"time"
"github.com/codeGROOVE-dev/gitMDM/internal/analyzer"
"github.com/codeGROOVE-dev/gitMDM/internal/config"
"github.com/codeGROOVE-dev/gitMDM/internal/gitmdm"
"github.com/codeGROOVE-dev/retry"
"gopkg.in/yaml.v3"
)
const (
// Version of the agent.
version = "1.0.0"
// Command execution timeout.
commandTimeout = 10 * time.Second
// OS constants.
osWindows = "windows"
osDarwin = "darwin"
osLinux = "linux"
// Windows command constants.
wmicCmd = "wmic"
wmicGetArg = "get"
// Maximum output size to prevent memory exhaustion.
maxOutputSize = 92160 // 90KB limit (matching server)
// Maximum log output length for readability.
maxLogLength = 200
// Minimum parts required for IOPlatformUUID parsing.
minUUIDParts = 4
// Retry configuration - using exponential backoff with jitter up to 2 minutes total.
maxRetries = 7 // More attempts to handle transient failures
initialBackoff = 1 * time.Second
maxBackoff = 30 * time.Second // Per-retry max delay to fit within 2 minute total
// HTTP client timeout.
httpTimeout = 30 * time.Second
// Queue size for failed reports.
failedReportsQueueSize = 100
// Response body read limit for error messages.
maxResponseBodyBytes = 256
// Display constants for interactive mode.
maxDisplayLines = 5
maxVerboseLines = 20
// Status constants.
statusFail = "fail"
statusPass = "pass"
)
//go:embed checks.yaml
var checksConfig []byte
var (
server = flag.String("server", "", "Server URL (e.g., http://localhost:8080)")
join = flag.String("join", "", "Join key for registration (required when using --server)")
runCheck = flag.String("run", "", "Run a single check and exit (use 'all' to run all checks)")
listChecks = flag.Bool("list", false, "List available compliance checks")
interval = flag.Duration("interval", 20*time.Minute, "Polling interval")
debugMode = flag.Bool("debug", false, "Enable debug logging")
verbose = flag.Bool("verbose", false, "Show all check outputs, not just failures (with --run all)")
install = flag.Bool("install", false, "Install agent to run automatically at startup")
uninstall = flag.Bool("uninstall", false, "Uninstall agent and remove autostart")
signedBy = flag.String("signed-by", "github:t+github@stromberg.org",
"Comma-separated list of provider:identity pairs allowed to sign configs (e.g., github:username, google:email@example.com)")
skipSignatureCheck = flag.Bool("skip-signature-check", false, "Skip signature verification (INSECURE - for development only)")
quiet = false // Set to true to suppress INFO logs (used for interactive mode)
)
// Agent represents the gitMDM agent that collects compliance data.
type Agent struct {
config *config.Config
httpClient *http.Client
failedReports chan gitmdm.DeviceReport
serverURL string
joinKey string
hardwareID string
hostname string
user string
}
// normalizeServerURL ensures the server URL has a protocol and removes trailing slash.
func normalizeServerURL(url string) string {
// Add https:// if no protocol is specified
if !strings.HasPrefix(url, "http://") && !strings.HasPrefix(url, "https://") {
log.Printf("[INFO] No protocol specified for %s, using https://", url)
url = "https://" + url
}
// Remove trailing slash
return strings.TrimSuffix(url, "/")
}
// handleInstall handles the agent installation process.
func (a *Agent) handleInstall() error {
if *server == "" || *join == "" {
return errors.New("--server and --join flags are required for installation")
}
// Set up agent configuration for verification
a.serverURL = normalizeServerURL(*server)
a.joinKey = *join
// Verify server connection and join key by sending a test report
log.Println("Verifying server connection and join key...")
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
// Run checks and attempt to report to server
report := a.buildDeviceReport(ctx)
// Retry the verification with exponential backoff
if err := a.verifyServerConnection(ctx, report); err != nil {
cancel()
return fmt.Errorf("failed to verify server connection after %d attempts: %v\n"+
"Please check your --server and --join parameters", maxRetries+1, err)
}
log.Println("✓ Server connection verified successfully")
log.Printf("✓ Device registered as: %s (%s)", a.hostname, a.hardwareID)
// Now proceed with installation
allowedSigners := parseAllowedSigners(*signedBy)
if err := installAgent(*server, *join, allowedSigners); err != nil {
return fmt.Errorf("installation failed: %w", err)
}
log.Println("✓ Agent installed successfully and will run automatically at startup")
return nil
}
// verifyServerConnection verifies the server connection with retries.
func (a *Agent) verifyServerConnection(ctx context.Context, report gitmdm.DeviceReport) error {
var lastErr error
for attempt := 0; attempt <= maxRetries; attempt++ {
if attempt > 0 {
backoff := time.Duration(float64(initialBackoff) * math.Pow(2, float64(attempt-1)))
if backoff > maxBackoff {
backoff = maxBackoff
}
log.Printf("[INFO] Retrying verification (attempt %d/%d) after %v...", attempt, maxRetries, backoff)
select {
case <-time.After(backoff):
case <-ctx.Done():
return ctx.Err()
}
}
if err := a.sendReport(ctx, report); err != nil {
lastErr = err
log.Printf("[WARN] Verification attempt %d failed: %v", attempt+1, err)
continue
}
// Success!
return nil
}
return lastErr
}
// buildDeviceReport builds a complete device report.
func (a *Agent) buildDeviceReport(ctx context.Context) gitmdm.DeviceReport {
return gitmdm.DeviceReport{
HardwareID: a.hardwareID,
Hostname: a.hostname,
User: a.user,
Timestamp: time.Now(),
Checks: a.runAllChecks(ctx),
OS: a.osInfo(ctx),
Architecture: runtime.GOARCH, // Directly get architecture
Version: a.osVersion(ctx),
SystemUptime: a.systemUptime(ctx),
CPULoad: a.cpuLoad(ctx),
LoggedInUsers: a.loggedInUsers(ctx),
}
}
// configureServerConnection configures the server connection from flags or config file.
func (a *Agent) configureServerConnection() error {
// Try to load config file if server/join not provided via flags
if *server == "" || *join == "" {
cfg, err := loadConfig()
if err != nil {
// Config file doesn't exist or is invalid
if *server == "" {
return errors.New("server URL is required (use --server flag or install agent with --install)")
}
if *join == "" {
return errors.New("join key is required (use --join flag or install agent with --install)")
}
} else {
// Use config file values if flags not provided
if *server == "" {
*server = cfg.ServerURL
}
if *join == "" {
*join = cfg.JoinKey
}
}
}
a.serverURL = normalizeServerURL(*server)
a.joinKey = *join
return nil
}
// initializeAgent creates and initializes an Agent instance.
func initializeAgent() (*Agent, error) {
// First, verify the embedded checks.yaml is properly signed
switch {
case !*skipSignatureCheck:
if err := verifyEmbeddedConfig(); err != nil {
return nil, fmt.Errorf("configuration signature verification failed: %w", err)
}
case isDevelopmentMode():
log.Print("[INFO] Development mode: signature verification disabled (running via 'go run')")
default:
log.Print("[WARN] ⚠️ SIGNATURE VERIFICATION SKIPPED (--skip-signature-check flag)")
log.Print("[WARN] Running with UNVERIFIED configuration - this is INSECURE!")
}
var cfg config.Config
if err := yaml.Unmarshal(checksConfig, &cfg); err != nil {
return nil, fmt.Errorf("failed to parse checks config: %w", err)
}
// Get hostname directly
hostname, err := os.Hostname()
if err != nil {
hostname = "unknown"
}
// Get current user directly
user := os.Getenv("USER")
if user == "" {
user = os.Getenv("USERNAME")
}
if user == "" {
user = "unknown"
}
return &Agent{
config: &cfg,
hardwareID: hardwareID(context.Background()),
hostname: hostname,
user: user,
httpClient: &http.Client{
Timeout: httpTimeout,
},
failedReports: make(chan gitmdm.DeviceReport, failedReportsQueueSize),
}, nil
}
// setupLogging configures logging to both console and file.
func setupLogging() (*os.File, error) {
// Create log directory if it doesn't exist
homeDir, err := os.UserHomeDir()
if err != nil {
return nil, fmt.Errorf("failed to get home directory: %w", err)
}
logDir := filepath.Join(homeDir, ".gitmdm")
if err := os.MkdirAll(logDir, 0o750); err != nil {
return nil, fmt.Errorf("failed to create log directory: %w", err)
}
// Open log file for appending (only accessible by user)
logPath := filepath.Join(logDir, "agent.log")
logFile, err := os.OpenFile(logPath, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o600)
if err != nil {
return nil, fmt.Errorf("failed to open log file: %w", err)
}
// Set up multi-writer to log to both console and file
multiWriter := io.MultiWriter(os.Stderr, logFile)
log.SetOutput(multiWriter)
// Add timestamp to logs
log.SetFlags(log.Ldate | log.Ltime | log.Lmicroseconds)
return logFile, nil
}
// checkAndCreatePIDFile checks if another instance is running and creates a PID file.
// Returns true if we should continue running, false if another instance is active.
func checkAndCreatePIDFile() (exists bool, cleanup func()) {
homeDir, err := os.UserHomeDir()
if err != nil {
log.Printf("[WARN] Failed to get home directory for PID file: %v", err)
return true, func() {} // Continue without PID file
}
pidPath := filepath.Join(homeDir, ".gitmdm", "agent.pid")
// Check if PID file exists and if that process is still running
if pidData, err := os.ReadFile(pidPath); err == nil {
oldPID, err := strconv.Atoi(strings.TrimSpace(string(pidData)))
if err == nil {
// Check if process exists by sending signal 0
if process, err := os.FindProcess(oldPID); err == nil {
if err := process.Signal(syscall.Signal(0)); err == nil {
log.Printf("[INFO] Agent already running with PID %d, exiting", oldPID)
return false, func() {}
}
}
log.Printf("[INFO] Removing stale PID file for non-existent process %d", oldPID)
// Remove the stale PID file so we can create our own
if err := os.Remove(pidPath); err != nil && !os.IsNotExist(err) {
log.Printf("[WARN] Failed to remove stale PID file: %v", err)
}
}
}
// Write our PID atomically using O_EXCL to prevent race conditions
pid := os.Getpid()
pidFile, err := os.OpenFile(pidPath, os.O_CREATE|os.O_EXCL|os.O_WRONLY, 0o600)
if err != nil {
if os.IsExist(err) {
// Another process created the file between our check and now
// This is an actual race condition with another starting instance
log.Print("[INFO] Another agent instance is starting up, exiting")
return false, func() {}
}
log.Printf("[WARN] Failed to create PID file: %v", err)
return true, func() {} // Continue without PID file
}
if _, err := pidFile.WriteString(strconv.Itoa(pid)); err != nil {
_ = pidFile.Close() //nolint:errcheck // best effort cleanup
_ = os.Remove(pidPath) //nolint:errcheck // best effort cleanup
log.Printf("[WARN] Failed to write PID file: %v", err)
return true, func() {} // Continue without PID file
}
if err := pidFile.Close(); err != nil {
log.Printf("[WARN] Failed to close PID file: %v", err)
}
log.Printf("[INFO] Created PID file with PID %d", pid)
// Return cleanup function
cleanup = func() {
if err := os.Remove(pidPath); err != nil && !os.IsNotExist(err) {
log.Printf("[WARN] Failed to remove PID file: %v", err)
} else {
log.Print("[INFO] Removed PID file")
}
}
return true, cleanup
}
// isDevelopmentMode detects if the agent is running via "go run" instead of as a built binary.
func isDevelopmentMode() bool {
// When go run executes, it creates binaries in temp with specific patterns:
// /tmp/go-build####/b###/exe/binary-name
exePath, err := os.Executable()
if err != nil {
return false
}
// Resolve symlinks to get the real path
realPath, err := filepath.EvalSymlinks(exePath)
if err != nil {
realPath = exePath
}
// Check if path matches go run's pattern
// Must be in temp AND contain "go-build" AND have b### directory structure
return strings.Contains(realPath, filepath.Join(os.TempDir(), "go-build")) ||
strings.Contains(realPath, filepath.Join("/private"+os.TempDir(), "go-build")) // macOS symlink
}
func main() {
// Set up panic recovery first
defer func() {
if r := recover(); r != nil {
log.Printf("[PANIC] Agent crashed: %v\nStack trace:\n%s", r, debug.Stack())
os.Exit(1)
}
}()
flag.Parse()
// Auto-detect development mode
isDev := isDevelopmentMode()
if isDev && !*skipSignatureCheck {
// Automatically skip signature checks in development
*skipSignatureCheck = true
}
// Set up file logging (non-fatal if it fails)
var logFile *os.File
if lf, err := setupLogging(); err != nil {
log.Printf("[WARN] Failed to set up file logging: %v", err)
} else {
logFile = lf
defer func() {
if err := logFile.Close(); err != nil {
log.Printf("[WARN] Failed to close log file: %v", err)
}
}()
log.Printf("[INFO] Agent starting - version %s, PID %d", version, os.Getpid())
}
agent, err := initializeAgent()
if err != nil {
if logFile != nil {
_ = logFile.Close() //nolint:errcheck // Best effort before exiting
}
log.Fatal(err) //nolint:gocritic // exitAfterDefer - panic recovery needed
}
// Handle --list flag
if *listChecks {
agent.listAvailableChecks()
return
}
// Handle --install flag
if *install {
if err := agent.handleInstall(); err != nil {
log.Fatal(err)
}
return
}
// Handle --uninstall flag
if *uninstall {
if err := uninstallAgent(); err != nil {
log.Fatalf("Uninstallation failed: %v", err)
}
log.Println("Agent uninstalled successfully")
return
}
// Handle --run flag
if *runCheck != "" {
if *runCheck == "all" {
agent.runAllChecksInteractive()
} else {
// Security: Validate check name to prevent injection
if !gitmdm.IsValidCheckName(*runCheck) {
log.Fatal("Invalid check name - only alphanumeric and underscore allowed")
}
output := agent.runSingleCheck(*runCheck)
log.Print(output)
if !strings.HasSuffix(output, "\n") {
log.Print("\n")
}
}
return
}
// Configure server connection
if err := agent.configureServerConnection(); err != nil {
log.Printf("[ERROR] Failed to configure server connection: %v", err)
log.Print("[INFO] Agent will continue running in offline mode, collecting data locally")
// Continue in offline mode - we can still collect data even if server is not configured
agent.serverURL = ""
}
// Check PID file to avoid duplicate processes
shouldRun, cleanupPID := checkAndCreatePIDFile()
if !shouldRun {
return // Another instance is already running
}
defer cleanupPID()
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, os.Interrupt, syscall.SIGTERM)
ticker := time.NewTicker(*interval)
defer ticker.Stop()
log.Printf("[INFO] Agent started. Hardware ID: %s, Hostname: %s, User: %s", agent.hardwareID, agent.hostname, agent.user)
log.Printf("[INFO] Reporting to server: %s every %v", agent.serverURL, *interval)
log.Printf("[INFO] Retry configuration: max_retries=%d, initial_backoff=%v, max_backoff=%v", maxRetries, initialBackoff, maxBackoff)
// Start failed reports processor with panic recovery
go func() {
defer func() {
if r := recover(); r != nil {
log.Printf("[PANIC] Failed reports processor crashed: %v\nStack trace:\n%s", r, debug.Stack())
}
}()
agent.processFailedReports(ctx)
}()
// Initial report
log.Println("[INFO] Sending initial report to server")
agent.reportToServer(ctx)
log.Println("[INFO] Agent main loop started, waiting for next interval or shutdown signal")
for {
select {
case <-ticker.C:
log.Printf("[INFO] Interval elapsed (%v), sending report", *interval)
agent.reportToServer(ctx)
case sig := <-sigChan:
log.Printf("[INFO] Received signal %v, shutting down agent gracefully", sig)
return
case <-ctx.Done():
log.Println("[INFO] Context cancelled, shutting down agent")
return
}
}
}
func (a *Agent) reportToServer(ctx context.Context) {
start := time.Now()
report := a.buildDeviceReport(ctx)
if *debugMode {
log.Printf("[DEBUG] Generated report with %d checks in %v", len(report.Checks), time.Since(start))
}
// If no server configured (offline mode), just log the collection
if a.serverURL == "" {
log.Print("[INFO] Running in offline mode - data collected but not sent to server")
if *debugMode {
log.Printf("[DEBUG] Collected %d checks in offline mode", len(report.Checks))
}
return
}
retryCount := 0
err := retry.Do(func() error {
retryCount++
if retryCount > 1 {
log.Printf("[INFO] Retry attempt %d/%d for sending report", retryCount, maxRetries)
}
return a.sendReport(ctx, report)
}, retry.Attempts(maxRetries), retry.DelayType(retry.FullJitterBackoffDelay), retry.Delay(initialBackoff), retry.MaxDelay(maxBackoff))
if err != nil {
log.Printf("[ERROR] Failed to send report after %d attempts: %v", retryCount, err)
// Queue for later retry if queue not full
select {
case a.failedReports <- report:
log.Print("[INFO] Report queued for retry processing")
default:
log.Print("[WARN] Failed reports queue is full, dropping report")
}
return
}
// Log success, noting if retries were needed
if retryCount > 1 {
log.Printf("[INFO] Successfully reported to server after %d attempts (took %v)", retryCount, time.Since(start))
} else if *debugMode {
log.Printf("[DEBUG] Successfully reported to server in %v", time.Since(start))
}
}
func (a *Agent) sendReport(ctx context.Context, report gitmdm.DeviceReport) error {
data, err := json.Marshal(report)
if err != nil {
return fmt.Errorf("failed to marshal report: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, a.serverURL+"/api/v1/report", bytes.NewBuffer(data))
if err != nil {
return fmt.Errorf("failed to create request: %w", err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("X-Join-Key", a.joinKey)
resp, err := a.httpClient.Do(req)
if err != nil {
log.Printf("[ERROR] Failed to send report to %s: %v", a.serverURL, err)
return fmt.Errorf("failed to send request: %w", err)
}
defer func() {
if err := resp.Body.Close(); err != nil {
log.Printf("[WARN] Error closing response body: %v", err)
}
}()
// Log the HTTP response code
log.Printf("[INFO] Report sent to %s - Response: %d %s", a.serverURL, resp.StatusCode, resp.Status)
if resp.StatusCode != http.StatusOK {
// Read response body for debugging (limit to 256 bytes)
bodyBytes, err := io.ReadAll(io.LimitReader(resp.Body, maxResponseBodyBytes))
if err != nil {
log.Printf("[ERROR] Server returned %d but failed to read response body: %v", resp.StatusCode, err)
return fmt.Errorf("server returned status %d (failed to read body: %w)", resp.StatusCode, err)
}
errorMsg := string(bodyBytes)
log.Printf("[ERROR] Server returned %d: %s", resp.StatusCode, errorMsg)
return fmt.Errorf("server returned status %d: %s", resp.StatusCode, errorMsg)
}
return nil
}
func (a *Agent) processFailedReports(ctx context.Context) {
ticker := time.NewTicker(5 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
// Drain all queued reports
for {
select {
case report := <-a.failedReports:
a.retryFailedReport(ctx, report)
default:
goto drained
}
}
drained:
}
}
}
func (a *Agent) retryFailedReport(ctx context.Context, report gitmdm.DeviceReport) {
log.Printf("[INFO] Retrying failed report for device %s", report.HardwareID)
err := retry.Do(func() error {
return a.sendReport(ctx, report)
},
retry.Attempts(maxRetries),
retry.DelayType(retry.FullJitterBackoffDelay),
retry.Delay(initialBackoff),
retry.MaxDelay(maxBackoff))
if err != nil {
log.Printf("[ERROR] Failed to retry report: %v", err)
// Re-queue if there's space, otherwise drop
select {
case a.failedReports <- report:
default:
log.Print("[WARN] Dropping failed report - queue full")
}
} else {
log.Print("[INFO] Successfully sent queued report")
}
}
func (a *Agent) runAllChecks(ctx context.Context) map[string]gitmdm.Check {
start := time.Now()
checks := make(map[string]gitmdm.Check)
osName := runtime.GOOS
successCount := 0
failureCount := 0
if *debugMode {
log.Printf("[DEBUG] Running %d checks for OS: %s", len(a.config.Checks), osName)
}
// Use a mutex to protect the shared maps
var mu sync.Mutex
// Use a WaitGroup to wait for all checks to complete
var wg sync.WaitGroup
// Limit concurrency to avoid overwhelming the system
semaphore := make(chan struct{}, runtime.NumCPU())
for checkName := range a.config.Checks {
checkDef := a.config.Checks[checkName]
// Get the rules for this OS
rules := checkDef.CommandsForOS(osName)
if len(rules) == 0 {
if *debugMode {
log.Printf("[DEBUG] Check %s not available for OS %s", checkName, osName)
}
continue
}
wg.Add(1)
go func() {
defer wg.Done()
// Acquire semaphore
semaphore <- struct{}{}
defer func() { <-semaphore }()
checkStart := time.Now()
// Run all rules for this check
var outputs []gitmdm.CommandOutput
for _, rule := range rules {
output := a.executeCheck(ctx, checkName, rule)
outputs = append(outputs, output)
}
// Analyze all outputs to determine status
status, reason, remediation := analyzer.DetermineOverallStatus(outputs)
check := gitmdm.Check{
Timestamp: time.Now(), // Set the timestamp when the check was performed
Outputs: outputs,
Status: status,
Reason: reason,
Remediation: remediation,
}
// Update shared state with mutex
mu.Lock()
checks[checkName] = check
// Update counters based on status
switch status {
case statusPass:
successCount++
if *debugMode {
log.Printf("[DEBUG] Check %s passed in %v: %s", checkName, time.Since(checkStart), reason)
}
case statusFail:
failureCount++
if *debugMode {
log.Printf("[DEBUG] Check %s failed in %v: %s", checkName, time.Since(checkStart), reason)
}
default:
// "n/a" - no counter update
}
mu.Unlock()
}()
}
// Wait for all checks to complete
wg.Wait()
log.Printf("[INFO] Completed %d checks (%d successful, %d failed) in %v",
successCount+failureCount, successCount, failureCount, time.Since(start))
return checks
}
func (a *Agent) runSingleCheck(checkName string) string {
// Use a 60-second timeout for single check execution
ctx, cancel := context.WithTimeout(context.Background(), 60*time.Second)
defer cancel()
osName := runtime.GOOS
checkDef, exists := a.config.Checks[checkName]
if !exists {
return fmt.Sprintf("Check '%s' not found", checkName)
}
// Get the rules for this OS
rules := checkDef.CommandsForOS(osName)
if len(rules) == 0 {
return fmt.Sprintf("Check '%s' not available for %s", checkName, osName)
}
var outputBuilder strings.Builder
var outputs []gitmdm.CommandOutput
for i, rule := range rules {
if i > 0 {
outputBuilder.WriteString("\n\n=== Rule " + strconv.Itoa(i+1) + " ===\n")
}
// Display what we're checking
if rule.File != "" {
outputBuilder.WriteString("File: " + rule.File + "\n")
} else if rule.Output != "" {
outputBuilder.WriteString("Command: " + rule.Output + "\n")
}
output := a.executeCheck(ctx, checkName, rule)
outputs = append(outputs, output)
switch {
case output.FileMissing:
outputBuilder.WriteString("File not found\n")
case output.Skipped:
outputBuilder.WriteString("Command not available\n")
default:
if output.Stdout != "" {
outputBuilder.WriteString(output.Stdout)
}
if output.Stderr != "" {
outputBuilder.WriteString("\n--- STDERR ---\n" + output.Stderr)
}
if output.ExitCode != 0 {
outputBuilder.WriteString(fmt.Sprintf("\n--- EXIT CODE: %d ---", output.ExitCode))
}
}
// Show analysis for this specific rule
if output.Failed {
outputBuilder.WriteString(fmt.Sprintf("\n--- FAILED: %s ---", output.FailReason))
} else if !output.Skipped && !output.FileMissing {
outputBuilder.WriteString("\n--- PASSED ---")
}
}
// Overall status analysis
status, reason, remediation := analyzer.DetermineOverallStatus(outputs)
outputBuilder.WriteString("\n\n=== OVERALL RESULT ===")
switch status {
case statusPass:
outputBuilder.WriteString(fmt.Sprintf("\n✅ PASS: %s", reason))
case statusFail:
outputBuilder.WriteString(fmt.Sprintf("\n❌ FAIL: %s", reason))
// Show command-specific remediation steps for failed checks
if len(remediation) > 0 {
outputBuilder.WriteString("\n\n=== HOW TO FIX ===")
for i, step := range remediation {
outputBuilder.WriteString(fmt.Sprintf("\n%d. %s", i+1, step))
}
}
default:
outputBuilder.WriteString(fmt.Sprintf("\n➖ NOT APPLICABLE: %s", reason))
}
return outputBuilder.String()
}
func (*Agent) systemUptime(ctx context.Context) string {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
var cmd *exec.Cmd
switch runtime.GOOS {
case "linux", "darwin", "freebsd", "openbsd", "netbsd", "dragonfly":
cmd = exec.CommandContext(ctx, "uptime")
case "solaris", "illumos":
cmd = exec.CommandContext(ctx, "uptime")
case osWindows:
cmd = exec.CommandContext(ctx, wmicCmd, "os", wmicGetArg, "lastbootuptime")
default:
return "unsupported"
}
if output, err := cmd.Output(); err == nil {
return strings.TrimSpace(string(output))
}
return "unavailable"
}
func (*Agent) cpuLoad(ctx context.Context) string {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
var cmd *exec.Cmd
switch runtime.GOOS {
case osLinux:
cmd = exec.CommandContext(ctx, "cat", "/proc/loadavg")
case "darwin", "freebsd", "openbsd", "netbsd", "dragonfly":
cmd = exec.CommandContext(ctx, "sysctl", "-n", "vm.loadavg")
case "solaris", "illumos":
cmd = exec.CommandContext(ctx, "uptime")
case osWindows:
cmd = exec.CommandContext(ctx, wmicCmd, "cpu", wmicGetArg, "loadpercentage")
default:
return "unsupported"
}
if output, err := cmd.Output(); err == nil {
result := strings.TrimSpace(string(output))
// For Linux /proc/loadavg, extract just the three load averages
if runtime.GOOS == osLinux {
fields := strings.Fields(result)
if len(fields) >= 3 {
result = strings.Join(fields[:3], " ")
}
}
// For uptime output on Solaris, extract just the load average part
if (runtime.GOOS == "solaris" || runtime.GOOS == "illumos") && strings.Contains(result, "load average:") {
parts := strings.Split(result, "load average:")
if len(parts) > 1 {
result = strings.TrimSpace(parts[1])
}
}
return result
}
return "unavailable"
}
func (*Agent) loggedInUsers(ctx context.Context) string {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
var cmd *exec.Cmd
switch runtime.GOOS {
case "linux", "darwin", "freebsd", "openbsd", "netbsd", "dragonfly", "solaris", "illumos":
cmd = exec.CommandContext(ctx, "who")
case osWindows:
cmd = exec.CommandContext(ctx, wmicCmd, "computersystem", wmicGetArg, "username")
default:
return "unsupported"
}
if output, err := cmd.Output(); err == nil {
result := strings.TrimSpace(string(output))
// Count unique users for Unix-like systems
if runtime.GOOS != osWindows {
lines := strings.Split(result, "\n")
userMap := make(map[string]bool)
for _, line := range lines {
fields := strings.Fields(line)
if len(fields) > 0 {
userMap[fields[0]] = true
}
}
users := make([]string, 0, len(userMap))
for user := range userMap {
users = append(users, user)
}
if len(users) > 0 {
return fmt.Sprintf("%d users: %s", len(users), strings.Join(users, ", "))
}
return "no users logged in"
}
return result
}
return "unavailable"
}
func (*Agent) osInfo(ctx context.Context) string {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
var cmd *exec.Cmd
switch runtime.GOOS {
case osLinux:
// Try to get pretty name from os-release
if data, err := os.ReadFile("/etc/os-release"); err == nil {
lines := strings.Split(string(data), "\n")
for _, line := range lines {
if strings.HasPrefix(line, "PRETTY_NAME=") {
name := strings.TrimPrefix(line, "PRETTY_NAME=")
return strings.Trim(name, `"`)
}
}
}
// Fallback to uname
cmd = exec.CommandContext(ctx, "uname", "-s")
case osDarwin:
cmd = exec.CommandContext(ctx, "sw_vers", "-productName")
case osWindows:
cmd = exec.CommandContext(ctx, wmicCmd, "os", wmicGetArg, "Caption", "/value")
default:
cmd = exec.CommandContext(ctx, "uname", "-s")
}
if cmd != nil {
if output, err := cmd.Output(); err == nil {
result := strings.TrimSpace(string(output))
if runtime.GOOS == osWindows && strings.Contains(result, "Caption=") {
result = strings.TrimPrefix(result, "Caption=")
}
if result != "" {
return result
}
}
}
// Fallback to Go's runtime info
return runtime.GOOS
}
func (*Agent) osVersion(ctx context.Context) string {
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
var cmd *exec.Cmd
switch runtime.GOOS {
case osLinux:
cmd = exec.CommandContext(ctx, "uname", "-r")
case osDarwin:
cmd = exec.CommandContext(ctx, "sw_vers", "-productVersion")
case osWindows:
cmd = exec.CommandContext(ctx, wmicCmd, "os", wmicGetArg, "Version", "/value")
default:
cmd = exec.CommandContext(ctx, "uname", "-r")
}
if output, err := cmd.Output(); err == nil {
result := strings.TrimSpace(string(output))
if runtime.GOOS == osWindows && strings.Contains(result, "Version=") {
result = strings.TrimPrefix(result, "Version=")