-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
3346 lines (3098 loc) · 106 KB
/
main.go
File metadata and controls
3346 lines (3098 loc) · 106 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
import (
"bytes"
"context"
"crypto/sha256"
"crypto/tls"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"time"
policyManager "github.com/compliance-framework/agent/policy-manager"
"github.com/compliance-framework/agent/runner"
"github.com/compliance-framework/agent/runner/proto"
"github.com/hashicorp/go-hclog"
goplugin "github.com/hashicorp/go-plugin"
"github.com/mitchellh/mapstructure"
"gopkg.in/yaml.v3"
)
const (
defaultCheckTimeoutSeconds = 300
schemaVersionV2 = "v2"
sourceCloudCustodian = "cloud-custodian"
defaultRemotePolicyTimeout = 30 * time.Second
defaultMaxRemotePolicyBytes = 1 << 20 // 1 MiB
evidenceBatchSize = 100
nonComplianceMessageField = "non_compliance_message"
custodianWatchInterval = 30 * time.Second
custodianOutputTailBytes = 4096
custodianLogTailMaxSections = 5
)
var lookPath = exec.LookPath
var lookupHost = net.DefaultResolver.LookupHost
var tlsProbeEndpoint = defaultTLSProbeEndpoint
var awsResourceServices = map[string][]string{
"app-elb": {"elasticloadbalancing"},
"backup-plan": {"backup"},
"backup-vault": {"backup"},
"cache-cluster": {"elasticache"},
"distribution": {"cloudfront"},
"dynamodb-table": {"dynamodb"},
"ebs": {"ec2"},
"ec2": {"ec2"},
"ecs-service": {"ecs"},
"efs": {"elasticfilesystem"},
"eks": {"eks"},
"firewall": {"network-firewall"},
"hostedzone": {"route53"},
"iam-group": {"iam"},
"iam-policy": {"iam"},
"iam-role": {"iam"},
"iam-user": {"iam"},
"kms-key": {"kms"},
"lambda": {"lambda"},
"log-group": {"logs"},
"rds": {"rds"},
"rds-cluster": {"rds"},
"s3": {"s3"},
"secrets-manager": {"secretsmanager"},
"sns": {"sns"},
"sqs": {"sqs"},
"transfer-server": {"transfer"},
"wafv2": {"wafv2"},
}
var awsGlobalEndpointServices = map[string]string{
"cloudfront": "cloudfront.amazonaws.com",
"iam": "iam.amazonaws.com",
"route53": "route53.amazonaws.com",
}
// PluginConfig receives string-only config from the agent gRPC interface.
type PluginConfig struct {
PoliciesYAML string `mapstructure:"policies_yaml"`
PoliciesPath string `mapstructure:"policies_path"`
CustodianBinary string `mapstructure:"custodian_binary"`
CustodianDebug string `mapstructure:"custodian_debug"`
CustodianVerbose string `mapstructure:"custodian_verbose"`
CustodianAWSAPITrace string `mapstructure:"custodian_aws_api_trace"`
CustodianNetworkDiag string `mapstructure:"custodian_network_diagnostics"`
CustodianNetworkDiagnosticEndpoints string `mapstructure:"custodian_network_diagnostic_endpoints"`
CustodianLogTail string `mapstructure:"custodian_log_tail_during_run"`
AWSRegions string `mapstructure:"aws_regions"`
PolicyLabels string `mapstructure:"policy_labels"`
ResourceIdentityFields string `mapstructure:"resource_identity_fields"`
CheckTimeoutSeconds string `mapstructure:"check_timeout_seconds"`
DebugDumpPayloads string `mapstructure:"debug_dump_payloads"`
DebugPayloadOutputDir string `mapstructure:"debug_payload_output_dir"`
PreserveArtifacts string `mapstructure:"preserve_execution_artifacts"`
}
// ParsedConfig stores normalized and validated values for runtime use.
type ParsedConfig struct {
PoliciesYAML string
PoliciesPath string
CustodianBinary string
CustodianDebug bool
CustodianVerbose bool
CustodianAWSAPITrace bool
CustodianNetworkDiag bool
CustodianNetworkDiagnosticEndpoints []string
CustodianLogTail bool
AWSRegions []string
PolicyLabels map[string]string
ResourceIdentityFields map[string][]string
CheckTimeout time.Duration
DebugDumpPayloads bool
DebugPayloadOutputDir string
PreserveArtifacts bool
}
func (c *PluginConfig) Parse() (*ParsedConfig, error) {
inlineYAML := strings.TrimSpace(c.PoliciesYAML)
policiesPath := strings.TrimSpace(c.PoliciesPath)
if inlineYAML == "" && policiesPath == "" {
return nil, errors.New("either policies_yaml or policies_path is required")
}
policyLabels := map[string]string{}
if strings.TrimSpace(c.PolicyLabels) != "" {
if err := json.Unmarshal([]byte(c.PolicyLabels), &policyLabels); err != nil {
return nil, fmt.Errorf("could not parse policy_labels: %w", err)
}
}
resourceIdentityFields := map[string][]string{}
if strings.TrimSpace(c.ResourceIdentityFields) != "" {
if err := json.Unmarshal([]byte(c.ResourceIdentityFields), &resourceIdentityFields); err != nil {
return nil, fmt.Errorf("could not parse resource_identity_fields: %w", err)
}
normalizedIdentityFields := make(map[string][]string, len(resourceIdentityFields))
for resourceType, fields := range resourceIdentityFields {
trimmedType := strings.TrimSpace(resourceType)
if trimmedType == "" {
return nil, errors.New("resource_identity_fields cannot contain an empty resource type")
}
normalizedFields := make([]string, 0, len(fields))
for _, field := range fields {
field = strings.TrimSpace(field)
if field != "" {
normalizedFields = append(normalizedFields, field)
}
}
if len(normalizedFields) == 0 {
return nil, fmt.Errorf("resource_identity_fields for %q must include at least one field", trimmedType)
}
if _, exists := normalizedIdentityFields[trimmedType]; exists {
return nil, fmt.Errorf("resource_identity_fields contains duplicate resource type %q after trimming whitespace", trimmedType)
}
normalizedIdentityFields[trimmedType] = normalizedFields
}
resourceIdentityFields = normalizedIdentityFields
}
checkTimeoutSeconds := defaultCheckTimeoutSeconds
if strings.TrimSpace(c.CheckTimeoutSeconds) != "" {
parsedTimeout, err := strconv.Atoi(c.CheckTimeoutSeconds)
if err != nil {
return nil, fmt.Errorf("check_timeout_seconds must be a positive integer: %w", err)
}
if parsedTimeout <= 0 {
return nil, errors.New("check_timeout_seconds must be greater than 0")
}
checkTimeoutSeconds = parsedTimeout
}
binary := strings.TrimSpace(c.CustodianBinary)
if binary == "" {
binary = "custodian"
}
resolvedBinary, err := lookPath(binary)
if err != nil {
return nil, fmt.Errorf("could not resolve custodian binary %q: %w", binary, err)
}
awsRegions := parseDelimitedList(c.AWSRegions)
networkDiagnosticEndpoints := parseDelimitedList(c.CustodianNetworkDiagnosticEndpoints)
custodianDebug, err := parseOptionalBool("custodian_debug", c.CustodianDebug)
if err != nil {
return nil, err
}
custodianVerbose, err := parseOptionalBool("custodian_verbose", c.CustodianVerbose)
if err != nil {
return nil, err
}
custodianAWSAPITrace, err := parseOptionalBool("custodian_aws_api_trace", c.CustodianAWSAPITrace)
if err != nil {
return nil, err
}
custodianNetworkDiag, err := parseOptionalBool("custodian_network_diagnostics", c.CustodianNetworkDiag)
if err != nil {
return nil, err
}
custodianLogTail, err := parseOptionalBool("custodian_log_tail_during_run", c.CustodianLogTail)
if err != nil {
return nil, err
}
debugDumpPayloads, err := parseOptionalBool("debug_dump_payloads", c.DebugDumpPayloads)
if err != nil {
return nil, err
}
preserveArtifacts, err := parseOptionalBool("preserve_execution_artifacts", c.PreserveArtifacts)
if err != nil {
return nil, err
}
debugPayloadOutputDir := strings.TrimSpace(c.DebugPayloadOutputDir)
if debugPayloadOutputDir != "" {
debugDumpPayloads = true
}
if debugDumpPayloads && debugPayloadOutputDir == "" {
debugPayloadOutputDir = "debug-standardized-payloads"
}
return &ParsedConfig{
PoliciesYAML: inlineYAML,
PoliciesPath: policiesPath,
CustodianBinary: resolvedBinary,
CustodianDebug: custodianDebug,
CustodianVerbose: custodianVerbose,
CustodianAWSAPITrace: custodianAWSAPITrace,
CustodianNetworkDiag: custodianNetworkDiag,
CustodianNetworkDiagnosticEndpoints: networkDiagnosticEndpoints,
CustodianLogTail: custodianLogTail,
AWSRegions: awsRegions,
PolicyLabels: policyLabels,
ResourceIdentityFields: resourceIdentityFields,
CheckTimeout: time.Duration(checkTimeoutSeconds) * time.Second,
DebugDumpPayloads: debugDumpPayloads,
DebugPayloadOutputDir: debugPayloadOutputDir,
PreserveArtifacts: preserveArtifacts,
}, nil
}
func parseOptionalBool(name, value string) (bool, error) {
value = strings.TrimSpace(value)
if value == "" {
return false, nil
}
parsed, err := strconv.ParseBool(value)
if err != nil {
return false, fmt.Errorf("%s must be a boolean value: %w", name, err)
}
return parsed, nil
}
func parseDelimitedList(value string) []string {
parts := strings.FieldsFunc(value, func(r rune) bool {
return r == ',' || r == ' ' || r == '\n' || r == '\t' || r == '\r'
})
return compactUniqueStrings(parts)
}
// CustodianCheck represents a single Cloud Custodian policy entry used as one check iteration.
type CustodianCheck struct {
Index int
Name string
Resource string
Provider string
RawPolicy map[string]interface{}
ParseErrors []string
}
// CustodianExecutionRequest contains execution-time settings for one check run.
type CustodianExecutionRequest struct {
BinaryPath string
Check CustodianCheck
Timeout time.Duration
OutputDir string
Debug bool
Verbose bool
AWSRegions []string
AWSAPITrace bool
NetworkDiagnostics bool
NetworkDiagnosticEndpoints []string
LogTailDuringRun bool
}
// CustodianExecutionResult captures runtime output and artifacts from one check run.
type CustodianExecutionResult struct {
StartedAt time.Time
EndedAt time.Time
ExitCode int
Stdout string
Stderr string
Error string
Errors []string
Err error
Resources []interface{}
ArtifactPath string
ResourcesPath string
LogPaths []string
DiagnosticWarnings []string
}
// CustodianExecutor runs one Cloud Custodian check and captures execution artifacts.
type CustodianExecutor interface {
Execute(ctx context.Context, req CustodianExecutionRequest) CustodianExecutionResult
}
// CommandCustodianExecutor executes the custodian CLI.
type CommandCustodianExecutor struct {
Logger hclog.Logger
}
type lockedBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *lockedBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *lockedBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
func (b *lockedBuffer) Len() int {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Len()
}
func (b *lockedBuffer) Tail(maxBytes int) string {
b.mu.Lock()
defer b.mu.Unlock()
content := b.buf.Bytes()
if maxBytes <= 0 || len(content) <= maxBytes {
return string(content)
}
return string(content[len(content)-maxBytes:])
}
func custodianDiagnosticInterval(timeout time.Duration) time.Duration {
if timeout <= 0 {
return custodianWatchInterval
}
interval := custodianWatchInterval
if timeout < 2*interval {
interval = timeout / 2
}
if interval < time.Second {
return time.Second
}
return interval
}
func (e *CommandCustodianExecutor) Execute(ctx context.Context, req CustodianExecutionRequest) CustodianExecutionResult {
e.Logger.Debug("Starting cloud custodian execution",
"check_name", req.Check.Name,
"check_index", req.Check.Index,
"resource", req.Check.Resource,
"provider", req.Check.Provider,
"binary", req.BinaryPath,
"timeout", req.Timeout.String(),
"output_dir", req.OutputDir,
"aws_regions", req.AWSRegions,
)
result := CustodianExecutionResult{
StartedAt: time.Now().UTC(),
ExitCode: -1,
Resources: []interface{}{},
Errors: []string{},
ArtifactPath: req.OutputDir,
}
if err := os.MkdirAll(req.OutputDir, 0o755); err != nil {
result.Err = fmt.Errorf("failed to create output directory: %w", err)
result.Error = result.Err.Error()
result.Errors = []string{result.Error}
e.Logger.Error("Failed creating output directory for check", "check_name", req.Check.Name, "error", result.Error)
result.EndedAt = time.Now().UTC()
return result
}
e.Logger.Trace("Created output directory for check", "check_name", req.Check.Name, "output_dir", req.OutputDir)
policyDocument := map[string]interface{}{
"policies": []map[string]interface{}{custodianPolicyForExecution(req.Check.RawPolicy)},
}
policyContent, err := yaml.Marshal(policyDocument)
if err != nil {
result.Err = fmt.Errorf("failed to marshal single policy document: %w", err)
result.Error = result.Err.Error()
result.Errors = []string{result.Error}
e.Logger.Error("Failed marshaling single policy yaml for check", "check_name", req.Check.Name, "error", result.Error)
result.EndedAt = time.Now().UTC()
return result
}
policyPath := filepath.Join(req.OutputDir, "policy.yaml")
if err := os.WriteFile(policyPath, policyContent, 0o600); err != nil {
result.Err = fmt.Errorf("failed to write single policy file: %w", err)
result.Error = result.Err.Error()
result.Errors = []string{result.Error}
e.Logger.Error("Failed writing single policy file for check", "check_name", req.Check.Name, "policy_path", policyPath, "error", result.Error)
result.EndedAt = time.Now().UTC()
return result
}
e.Logger.Trace("Wrote single policy file", "check_name", req.Check.Name, "policy_path", policyPath)
runCtx, cancel := context.WithTimeout(ctx, req.Timeout)
defer cancel()
regions := req.AWSRegions
if strings.EqualFold(req.Check.Provider, "aws") {
// Ensure AWS policies evaluate across all regions by default while
// allowing operators to narrow problematic service/region scans.
if len(regions) == 0 {
regions = []string{"all"}
}
}
if req.NetworkDiagnostics && strings.EqualFold(req.Check.Provider, "aws") {
diagnostics, diagErr := e.runAWSEndpointDiagnostics(runCtx, req)
result.DiagnosticWarnings = append(result.DiagnosticWarnings, diagnostics.executionWarnings(req.Check)...)
if diagErr != nil {
result.Err = fmt.Errorf("aws endpoint network diagnostics failed: %w", diagErr)
result.Errors = []string{result.Err.Error()}
result.Error = executionErrorString(result)
result.EndedAt = time.Now().UTC()
e.Logger.Error("Skipping custodian command because AWS endpoint diagnostics failed", "check_name", req.Check.Name, "error", result.Error)
return result
}
if availableRegions, ok := diagnostics.availableAWSRegions(regions); ok {
if len(availableRegions) == 0 {
result.Err = fmt.Errorf("cloud custodian policy %s could not be checked because no AWS service endpoints were reachable for resource %s in requested regions %s", req.Check.Name, req.Check.Resource, strings.Join(regions, ","))
result.Errors = append([]string{result.Err.Error()}, result.Errors...)
result.Error = executionErrorString(result)
e.Logger.Warn("Skipping custodian command because no AWS service endpoints were reachable for policy",
"check_name", req.Check.Name,
"resource", req.Check.Resource,
"aws_regions", regions,
"unavailable_endpoint_count", len(diagnostics.Failures),
)
result.EndedAt = time.Now().UTC()
return result
}
if !slices.Equal(regions, availableRegions) {
e.Logger.Warn("Running custodian command only for AWS regions with reachable service endpoints",
"check_name", req.Check.Name,
"resource", req.Check.Resource,
"requested_aws_regions", regions,
"available_aws_regions", availableRegions,
"unavailable_endpoint_count", len(diagnostics.Failures),
)
regions = availableRegions
}
}
}
args := []string{"run"}
if req.Debug {
args = append(args, "--debug")
}
if req.Verbose {
args = append(args, "-v")
}
args = append(args, "--dryrun", "-s", req.OutputDir, policyPath)
if strings.EqualFold(req.Check.Provider, "aws") {
for _, region := range regions {
args = append(args, "--region", region)
}
}
cmd := exec.CommandContext(runCtx, req.BinaryPath, args...)
cmd.Env = os.Environ()
if req.AWSAPITrace {
traceDir, traceLogPath, traceErr := setupCustodianAWSAPITrace(req.OutputDir)
if traceErr != nil {
e.Logger.Warn("Failed setting up custodian AWS API trace", "check_name", req.Check.Name, "error", traceErr)
} else {
cmd.Env = upsertEnv(cmd.Env, "PYTHONPATH", prependPathList(traceDir, os.Getenv("PYTHONPATH")))
cmd.Env = upsertEnv(cmd.Env, "CCF_CUSTODIAN_AWS_API_TRACE_LOG", traceLogPath)
cmd.Env = upsertEnv(cmd.Env, "PYTHONUNBUFFERED", "1")
e.Logger.Info("Custodian AWS API trace enabled", "check_name", req.Check.Name, "trace_log_path", traceLogPath, "pythonpath_dir", traceDir)
}
}
e.Logger.Debug("Executing custodian command",
"check_name", req.Check.Name,
"command", req.BinaryPath,
"args", args,
)
stdoutBuf := &lockedBuffer{}
stderrBuf := &lockedBuffer{}
cmd.Stdout = stdoutBuf
cmd.Stderr = stderrBuf
err = cmd.Start()
if err == nil {
pid := -1
if cmd.Process != nil {
pid = cmd.Process.Pid
}
e.Logger.Info("Custodian command process started",
"check_name", req.Check.Name,
"pid", pid,
)
waitDone := make(chan error, 1)
e.Logger.Debug("Setting up custodian command wait channel",
"check_name", req.Check.Name,
"pid", pid,
"buffered", true,
"capacity", cap(waitDone),
)
go func() {
waitDone <- cmd.Wait()
}()
diagnosticInterval := custodianDiagnosticInterval(req.Timeout)
ticker := time.NewTicker(diagnosticInterval)
defer ticker.Stop()
contextDoneLogged := false
runCtxDone := runCtx.Done()
lastCustodianLogTail := ""
logTailCache := &custodianLogTailCache{}
e.Logger.Debug("Starting custodian command monitor loop",
"check_name", req.Check.Name,
"pid", pid,
"diagnostic_interval", diagnosticInterval.String(),
"timeout", req.Timeout.String(),
)
for {
select {
case err = <-waitDone:
e.Logger.Info("Custodian command wait completed",
"check_name", req.Check.Name,
"pid", pid,
"elapsed", time.Since(result.StartedAt).Round(time.Second).String(),
"wait_error", err,
"context_error", runCtx.Err(),
"stdout_len", stdoutBuf.Len(),
"stderr_len", stderrBuf.Len(),
)
goto commandFinished
case <-ticker.C:
elapsed := time.Since(result.StartedAt).Round(time.Second).String()
remaining := ""
if deadline, ok := runCtx.Deadline(); ok {
remaining = time.Until(deadline).Round(time.Second).String()
}
e.Logger.Info("Custodian command still running",
"check_name", req.Check.Name,
"pid", pid,
"elapsed", elapsed,
"remaining", remaining,
"timeout", req.Timeout.String(),
"stdout_len", stdoutBuf.Len(),
"stderr_len", stderrBuf.Len(),
)
if req.NetworkDiagnostics {
e.logCustodianProcessSockets(pid, req.Check.Name)
}
if req.LogTailDuringRun {
lastCustodianLogTail = e.logCustodianRunLogTail(req.OutputDir, req.Check.Name, lastCustodianLogTail, logTailCache)
}
case <-runCtxDone:
if !contextDoneLogged {
e.Logger.Warn("Custodian command context done while process is still running",
"check_name", req.Check.Name,
"pid", pid,
"elapsed", time.Since(result.StartedAt).Round(time.Second).String(),
"timeout", req.Timeout.String(),
"context_error", runCtx.Err(),
"stdout_len", stdoutBuf.Len(),
"stderr_len", stderrBuf.Len(),
"stderr_tail", stderrBuf.Tail(custodianOutputTailBytes),
)
if req.NetworkDiagnostics {
e.logCustodianProcessSockets(pid, req.Check.Name)
}
if req.LogTailDuringRun {
lastCustodianLogTail = e.logCustodianRunLogTail(req.OutputDir, req.Check.Name, lastCustodianLogTail, logTailCache)
}
contextDoneLogged = true
}
runCtxDone = nil
}
}
} else {
e.Logger.Warn("Failed to start custodian command process",
"check_name", req.Check.Name,
"command", req.BinaryPath,
"args", args,
"error", err,
)
}
commandFinished:
result.Stdout = stdoutBuf.String()
result.Stderr = stderrBuf.String()
if cmd.ProcessState != nil {
result.ExitCode = cmd.ProcessState.ExitCode()
}
e.Logger.Debug("Custodian command finished",
"check_name", req.Check.Name,
"exit_code", result.ExitCode,
"stdout_len", len(result.Stdout),
"stderr_len", len(result.Stderr),
)
resourcesPath, resources, resourcesErr := readResourcesArtifact(req.OutputDir)
result.ResourcesPath = resourcesPath
if resources != nil {
result.Resources = resources
}
var logTail string
var logErr error
if req.LogTailDuringRun || err != nil || runCtx.Err() != nil || resourcesErr != nil {
logPaths, tail, readErr := readCustodianLogArtifacts(req.OutputDir, custodianOutputTailBytes)
result.LogPaths = logPaths
logTail = tail
logErr = readErr
}
if err != nil {
result.Err = fmt.Errorf("custodian execution failed: %w", err)
result.Errors = append(result.Errors, result.Err.Error())
if result.Stderr != "" {
result.Errors = append(result.Errors, result.Stderr)
}
}
if runErr := runCtx.Err(); runErr != nil {
// Avoid duplicating context timeout/cancel errors when cmd.Run already
// returned an error that wraps the same context failure.
if err == nil || !errors.Is(err, runErr) {
result.Err = errors.Join(result.Err, runErr)
result.Errors = append(result.Errors, runErr.Error())
}
}
if resourcesErr != nil {
result.Err = errors.Join(result.Err, resourcesErr)
result.Errors = append(result.Errors, resourcesErr.Error())
}
if logErr != nil {
if result.Err != nil {
result.Err = errors.Join(result.Err, logErr)
result.Errors = append(result.Errors, logErr.Error())
} else {
e.Logger.Warn("Failed collecting custodian log artifacts after successful execution",
"check_name", req.Check.Name,
"error", logErr,
)
}
}
if result.Err != nil && logTail != "" {
result.Errors = append(result.Errors, logTail)
}
if result.Err != nil {
result.Error = executionErrorString(result)
e.Logger.Warn("Custodian execution completed with errors",
"check_name", req.Check.Name,
"error_count", len(result.Errors),
"errors", result.Errors,
)
} else {
e.Logger.Debug("Custodian execution completed successfully",
"check_name", req.Check.Name,
"resource_count", len(result.Resources),
"resources_path", result.ResourcesPath,
)
}
result.EndedAt = time.Now().UTC()
return result
}
func setupCustodianAWSAPITrace(outputDir string) (string, string, error) {
traceDir := filepath.Join(outputDir, "ccf-custodian-python-trace")
if err := os.MkdirAll(traceDir, 0o700); err != nil {
return "", "", err
}
traceLogPath := filepath.Join(outputDir, "custodian-aws-api-trace.jsonl")
traceLog, err := os.OpenFile(traceLogPath, os.O_CREATE|os.O_APPEND|os.O_WRONLY, 0o600)
if err != nil {
return "", "", err
}
if err := traceLog.Close(); err != nil {
return "", "", err
}
if err := os.Chmod(traceLogPath, 0o600); err != nil {
return "", "", err
}
siteCustomizePath := filepath.Join(traceDir, "sitecustomize.py")
siteCustomize := `import json
import os
import sys
import time
def _ccf_trace_write(record):
record["timestamp"] = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
line = json.dumps(record, sort_keys=True, default=str)
path = os.environ.get("CCF_CUSTODIAN_AWS_API_TRACE_LOG")
if path:
try:
with open(path, "a", encoding="utf-8") as handle:
handle.write(line + "\n")
except Exception as exc:
sys.stderr.write("[CCF_AWS_API_TRACE] trace_write_failed " + type(exc).__name__ + ": " + str(exc) + "\n")
sys.stderr.write("[CCF_AWS_API_TRACE] " + line + "\n")
sys.stderr.flush()
try:
from botocore.client import BaseClient
_ccf_original_make_api_call = BaseClient._make_api_call
def _ccf_make_api_call(self, operation_name, api_params):
meta = getattr(self, "meta", None)
service = ""
endpoint = ""
region = ""
if meta is not None:
service_model = getattr(meta, "service_model", None)
service = getattr(service_model, "service_name", "")
endpoint = getattr(meta, "endpoint_url", "")
region = getattr(meta, "region_name", "")
start = time.time()
_ccf_trace_write({
"event": "aws_api_start",
"service": service,
"operation": operation_name,
"endpoint": endpoint,
"region": region,
})
try:
response = _ccf_original_make_api_call(self, operation_name, api_params)
except Exception as exc:
_ccf_trace_write({
"event": "aws_api_error",
"service": service,
"operation": operation_name,
"endpoint": endpoint,
"region": region,
"elapsed_ms": int((time.time() - start) * 1000),
"error_type": type(exc).__name__,
"error": str(exc),
})
raise
_ccf_trace_write({
"event": "aws_api_end",
"service": service,
"operation": operation_name,
"endpoint": endpoint,
"region": region,
"elapsed_ms": int((time.time() - start) * 1000),
})
return response
BaseClient._make_api_call = _ccf_make_api_call
_ccf_trace_write({"event": "aws_api_trace_installed"})
except Exception as exc:
sys.stderr.write("[CCF_AWS_API_TRACE] install_failed " + type(exc).__name__ + ": " + str(exc) + "\n")
sys.stderr.flush()
`
if err := os.WriteFile(siteCustomizePath, []byte(siteCustomize), 0o600); err != nil {
return "", "", err
}
return traceDir, traceLogPath, nil
}
func upsertEnv(env []string, key, value string) []string {
prefix := key + "="
for index, entry := range env {
if strings.HasPrefix(entry, prefix) {
env[index] = prefix + value
return env
}
}
return append(env, prefix+value)
}
func prependPathList(path, existing string) string {
if strings.TrimSpace(existing) == "" {
return path
}
return path + string(os.PathListSeparator) + existing
}
type networkDiagnosticEndpoint struct {
Host string
Port string
ServerName string
Source string
Service string
Region string
}
type awsEndpointDiagnosticFailure struct {
Endpoint networkDiagnosticEndpoint
Stage string
Err error
}
type awsEndpointDiagnosticResult struct {
Failures []awsEndpointDiagnosticFailure
regionProbeSucceeded map[string]bool
regionProbeFailed map[string]bool
}
func (r awsEndpointDiagnosticResult) availableAWSRegions(regions []string) ([]string, bool) {
if len(r.regionProbeSucceeded) == 0 && len(r.regionProbeFailed) == 0 {
return nil, false
}
available := make([]string, 0, len(regions))
for _, region := range regions {
region = strings.TrimSpace(region)
if region == "" || strings.EqualFold(region, "all") {
continue
}
if r.regionProbeSucceeded[region] && !r.regionProbeFailed[region] {
available = append(available, region)
}
}
return available, true
}
func (e *CommandCustodianExecutor) runAWSEndpointDiagnostics(ctx context.Context, req CustodianExecutionRequest) (awsEndpointDiagnosticResult, error) {
result := awsEndpointDiagnosticResult{
Failures: []awsEndpointDiagnosticFailure{},
regionProbeSucceeded: map[string]bool{},
regionProbeFailed: map[string]bool{},
}
endpoints, knownResource, endpointErr := awsDiagnosticEndpointsForCheck(req.Check.Resource, req.AWSRegions, req.NetworkDiagnosticEndpoints)
if endpointErr != nil {
e.Logger.Error("AWS endpoint diagnostics configuration is invalid", "check_name", req.Check.Name, "resource", req.Check.Resource, "error", endpointErr)
return result, endpointErr
}
if !knownResource && len(endpoints) == 0 {
e.Logger.Warn("Skipping AWS endpoint diagnostics because resource service is not mapped and no explicit endpoints are configured", "check_name", req.Check.Name, "resource", req.Check.Resource)
return result, nil
}
if len(endpoints) == 0 {
e.Logger.Warn("Skipping AWS endpoint diagnostics because no concrete endpoint hosts are available; configure aws_regions or custodian_network_diagnostic_endpoints for preflight probes", "check_name", req.Check.Name, "resource", req.Check.Resource, "aws_regions", req.AWSRegions)
return result, nil
}
if !knownResource {
e.Logger.Warn("AWS endpoint diagnostics will use only configured endpoints because resource service is not mapped", "check_name", req.Check.Name, "resource", req.Check.Resource)
}
for _, endpoint := range endpoints {
if err := ctx.Err(); err != nil {
return result, err
}
lookupCtx, cancel := context.WithTimeout(ctx, 5*time.Second)
lookupStarted := time.Now()
ips, err := lookupHost(lookupCtx, endpoint.Host)
cancel()
if err != nil {
result.recordFailure(endpoint, "DNS lookup", err)
e.Logger.Warn("AWS endpoint diagnostics detected an unreachable service endpoint; evaluation may be partial",
"check_name", req.Check.Name,
"resource", req.Check.Resource,
"service", endpoint.Service,
"region", endpoint.Region,
"host", endpoint.Host,
"stage", "DNS lookup",
"source", endpoint.Source,
"elapsed", time.Since(lookupStarted).Round(time.Millisecond).String(),
"error", err,
)
continue
} else {
e.Logger.Info("AWS endpoint DNS lookup succeeded", "check_name", req.Check.Name, "host", endpoint.Host, "source", endpoint.Source, "ips", ips, "elapsed", time.Since(lookupStarted).Round(time.Millisecond).String())
}
tlsStarted := time.Now()
tlsResult, err := tlsProbeEndpoint(ctx, endpoint)
if err != nil {
result.recordFailure(endpoint, "TLS handshake", err)
e.Logger.Warn("AWS endpoint diagnostics detected an unreachable service endpoint; evaluation may be partial",
"check_name", req.Check.Name,
"resource", req.Check.Resource,
"service", endpoint.Service,
"region", endpoint.Region,
"host", endpoint.Host,
"stage", "TLS handshake",
"port", endpoint.Port,
"server_name", endpoint.ServerName,
"source", endpoint.Source,
"elapsed", time.Since(tlsStarted).Round(time.Millisecond).String(),
"error", err,
)
continue
}
if endpoint.Source == "aws-service" && endpoint.Region != "" {
if result.regionProbeSucceeded == nil {
result.regionProbeSucceeded = map[string]bool{}
}
result.regionProbeSucceeded[endpoint.Region] = true
}
e.Logger.Info("AWS endpoint TLS probe succeeded", "check_name", req.Check.Name, "host", endpoint.Host, "port", endpoint.Port, "server_name", endpoint.ServerName, "source", endpoint.Source, "remote_addr", tlsResult.RemoteAddr, "tls_version", tlsResult.TLSVersion, "elapsed", time.Since(tlsStarted).Round(time.Millisecond).String())
}
return result, nil
}
func (r *awsEndpointDiagnosticResult) recordFailure(endpoint networkDiagnosticEndpoint, stage string, err error) {
if r.regionProbeFailed == nil {
r.regionProbeFailed = map[string]bool{}
}
r.Failures = append(r.Failures, awsEndpointDiagnosticFailure{
Endpoint: endpoint,
Stage: stage,
Err: err,
})
if endpoint.Source == "aws-service" && endpoint.Region != "" {
r.regionProbeFailed[endpoint.Region] = true
}
}
func (r awsEndpointDiagnosticResult) executionWarnings(check CustodianCheck) []string {
if len(r.Failures) == 0 {
return nil
}
messages := make([]string, 0, len(r.Failures))
for _, failure := range r.Failures {
endpoint := failure.Endpoint
service := endpoint.Service
if service == "" {
service = endpoint.Source
}
region := endpoint.Region
if region == "" {
region = "global"
}
messages = append(messages, fmt.Sprintf(
"unreachable AWS service endpoint %s.%s (%s:%s) detected while evaluating cloud custodian policy %s; evaluation may be partial: %s failed: %v",
service,
region,
endpoint.Host,
endpoint.Port,
check.Name,
failure.Stage,
failure.Err,
))
}
return messages
}
func executionErrorString(result CustodianExecutionResult) string {
messages := make([]string, 0, len(result.Errors)+len(result.DiagnosticWarnings))
seen := map[string]bool{}
for _, values := range [][]string{result.Errors, result.DiagnosticWarnings} {
for _, message := range values {
message = strings.TrimSpace(message)
if message == "" || seen[message] {
continue
}
messages = append(messages, message)
seen[message] = true
}
}
return strings.Join(messages, "; ")
}
func awsEndpointHostsForCheck(resource string, regions []string) ([]string, bool) {
endpoints, knownResource, err := awsDiagnosticEndpointsForCheck(resource, regions, nil)
if err != nil {
return nil, knownResource
}
hosts := make([]string, 0, len(endpoints))
for _, endpoint := range endpoints {
hosts = append(hosts, endpoint.Host)
}
return hosts, knownResource
}