-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
404 lines (369 loc) · 12.3 KB
/
main.go
File metadata and controls
404 lines (369 loc) · 12.3 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
// Copyright (c) 2025–2026 André Gustavo Leão de Melo Ataíde (had-nu). All rights reserved.
// SPDX-License-Identifier: AGPL-3.0-or-later OR LicenseRef-Wardex-Commercial
package main
import (
"fmt"
"os"
"time"
"github.com/had-nu/wardex/cmd/aggregate"
"github.com/had-nu/wardex/cmd/assess"
"github.com/had-nu/wardex/cmd/convert"
"github.com/had-nu/wardex/cmd/evaluate"
"github.com/had-nu/wardex/cmd/policy"
"github.com/had-nu/wardex/cmd/simulate"
"github.com/had-nu/wardex/config"
"github.com/had-nu/wardex/pkg/accept/cli"
"github.com/had-nu/wardex/pkg/accept"
"github.com/had-nu/wardex/pkg/analyzer"
"github.com/had-nu/wardex/pkg/catalog"
"github.com/had-nu/wardex/pkg/correlator"
enrichCli "github.com/had-nu/wardex/pkg/enrich/cli"
"github.com/had-nu/wardex/pkg/epss"
"github.com/had-nu/wardex/pkg/exitcodes"
"github.com/had-nu/wardex/pkg/ingestion"
"github.com/had-nu/wardex/pkg/model"
"github.com/had-nu/wardex/pkg/releasegate"
"github.com/had-nu/wardex/pkg/report"
"github.com/had-nu/wardex/pkg/snapshot"
"github.com/had-nu/wardex/pkg/ui"
"github.com/had-nu/wardex/pkg/utils"
"github.com/spf13/cobra"
"gopkg.in/yaml.v3"
)
var (
Version = "1.8.0"
configPath string
outputFormat string
outFile string
gateFile string
gateMode string
failAbove float64
noSnapshot bool
minConfidence string
verbose bool
roadmapLimit int
profileName string
snapshotFile string
frameworkName string
epssEnrich string
)
var convertCmd = &cobra.Command{
Use: "convert",
Short: "Convert third-party vulnerability outputs into Wardex format",
}
var rootCmd = &cobra.Command{
Use: "wardex [flags] <input-file(s)>",
Short: "Wardex generates compliance gap analysis from implemented controls.",
Version: Version,
Args: func(cmd *cobra.Command, args []string) error {
if v, _ := cmd.Flags().GetBool("version"); v {
return nil
}
if len(args) < 1 {
return fmt.Errorf("requires at least 1 arg(s), only received %d", len(args))
}
return nil
},
Run: runWardex,
}
func init() {
rootCmd.PersistentFlags().StringVar(&configPath, "config", "./wardex-config.yaml", "Path to wardex-config.yaml")
rootCmd.Flags().StringVarP(&outputFormat, "output", "o", "markdown", "Output format: markdown|json|csv")
rootCmd.Flags().StringVar(&outFile, "out-file", "stdout", "Output file destination")
rootCmd.Flags().StringVar(&gateFile, "gate", "", "Vulnerabilities file for release gate")
rootCmd.Flags().StringVar(&gateMode, "gate-mode", "any", "Gate mode: any|aggregate")
rootCmd.Flags().Float64Var(&failAbove, "fail-above", 0.0, "Exit code 1 if gap with final_score above this value")
rootCmd.Flags().BoolVar(&noSnapshot, "no-snapshot", false, "Do not read or write snapshot")
rootCmd.Flags().StringVar(&snapshotFile, "snapshot-file", ".wardex_snapshot.json", "Path to snapshot file")
rootCmd.Flags().StringVar(&minConfidence, "min-confidence", "low", "Minimum matching confidence: high|low")
rootCmd.Flags().BoolVar(&verbose, "verbose", false, "Verbose output")
rootCmd.Flags().IntVar(&roadmapLimit, "roadmap-limit", 10, "Max roadmap items in report (0 for unlimited)")
rootCmd.Flags().StringVar(&profileName, "profile", "", "RBAC threshold override (Warning: Identity is cryptographically trusted only in CI environments via WARDEX_ACTOR)")
rootCmd.Flags().StringVar(&frameworkName, "framework", "iso27001", "Compliance framework: iso27001|soc2|nis2|dora")
rootCmd.Flags().StringVar(&epssEnrich, "epss-enrichment", "", "Path to a cryptographically signed EPSS enrichment file")
convertCmd.AddCommand(convert.GrypeCmd, convert.SbomCmd)
rootCmd.AddCommand(convertCmd)
rootCmd.AddCommand(simulate.SimulateCmd)
rootCmd.AddCommand(policy.PolicyCmd)
rootCmd.AddCommand(evaluate.EvaluateCmd)
rootCmd.AddCommand(aggregate.AggregateCmd)
rootCmd.AddCommand(assess.AssessCmd)
cli.AddCommands(rootCmd, &configPath)
enrichCli.AddCommands(rootCmd, &configPath)
}
func main() {
ui.PrintBanner(Version)
if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
func runWardex(cmd *cobra.Command, args []string) {
cfg, err := config.Load(configPath)
if err != nil {
fmt.Fprintf(os.Stderr, "Warning: failed to load config from %s: %v\n", configPath, err)
cfg = &config.Config{}
}
if profileName != "" {
if p, ok := cfg.Profiles[profileName]; ok {
actor := os.Getenv("WARDEX_ACTOR")
if actor == "" {
actor = os.Getenv("GITHUB_ACTOR")
}
if actor == "" {
actor = os.Getenv("USER")
}
allowed := false
if len(p.AllowedActors) == 0 {
allowed = true // Fallback to open access for legacy configs
} else {
for _, a := range p.AllowedActors {
if a == "*" || a == actor {
allowed = true
break
}
}
}
if !allowed {
fmt.Fprintf(os.Stderr, "[RBAC VIOLATION] Actor '%s' is not authorized for profile '%s'!\n[RBAC ENFORCEMENT] Override rejected. Falling back to stict baseline configuration.\n", actor, profileName)
} else {
cfg.ReleaseGate.RiskAppetite = p.RiskAppetite
cfg.ReleaseGate.WarnAbove = p.WarnAbove
fmt.Fprintf(os.Stderr, "[INFO] RBAC Verified. Loaded profile '%s' for actor '%s' (RiskAppetite: %.2f, WarnAbove: %.2f)\n", profileName, actor, p.RiskAppetite, p.WarnAbove)
}
} else {
fmt.Fprintf(os.Stderr, "Warning: Profile '%s' not found in config. Using defaults.\n", profileName)
}
}
extControls, err := ingestion.LoadMany(args)
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to load controls: %v\n", err)
os.Exit(1)
}
cat := catalog.Load(frameworkName)
corr := correlator.New(cat)
mappings, err := corr.Correlate(extControls)
if err != nil {
fmt.Fprintf(os.Stderr, "Correlation failed: %v\n", err)
os.Exit(1)
}
// Filter confidence if necessary (not fully required by spec, but added for robust coverage)
var filtered []model.Mapping
for _, m := range mappings {
if minConfidence == "high" && m.Confidence == "low" {
continue
}
filtered = append(filtered, m)
}
an := analyzer.New(cat, filtered, extControls)
findings, err := an.Analyze()
if err != nil {
fmt.Fprintf(os.Stderr, "Analysis failed: %v\n", err)
os.Exit(1)
}
var sortedRoadmap []model.Finding
for _, f := range findings {
if f.Status != model.StatusCovered {
sortedRoadmap = append(sortedRoadmap, f)
}
}
// Sort highest risk first (simple bubble for ease since size is < 93)
for i := 0; i < len(sortedRoadmap); i++ {
for j := i + 1; j < len(sortedRoadmap); j++ {
if sortedRoadmap[i].FinalScore < sortedRoadmap[j].FinalScore {
sortedRoadmap[i], sortedRoadmap[j] = sortedRoadmap[j], sortedRoadmap[i]
}
}
}
rep := model.GapReport{
Summary: model.ExecutiveSummary{
GeneratedAt: time.Now(),
},
Findings: findings,
Roadmap: sortedRoadmap,
}
domainMap := make(map[string]*model.DomainSummary)
for _, f := range findings {
dom := f.Control.Domain
if dom == "" {
dom = "general"
}
ds, ok := domainMap[dom]
if !ok {
ds = &model.DomainSummary{Domain: dom}
domainMap[dom] = ds
}
ds.TotalControls++
switch f.Status {
case model.StatusCovered:
ds.CoveredCount++
case model.StatusPartial:
ds.PartialCount++
default:
ds.GapCount++
}
ds.MaturityScore += f.FinalScore
}
for _, ds := range domainMap {
if ds.TotalControls > 0 {
ds.MaturityScore = ds.MaturityScore / float64(ds.TotalControls)
}
rep.Summary.DomainSummaries = append(rep.Summary.DomainSummaries, *ds)
}
rep.Summary.TotalControls = len(cat)
for _, f := range findings {
switch f.Status {
case model.StatusCovered:
rep.Summary.CoveredCount++
case model.StatusPartial:
rep.Summary.PartialCount++
default:
rep.Summary.GapCount++
}
}
rep.Summary.GlobalCoverage = float64(rep.Summary.CoveredCount) / float64(rep.Summary.TotalControls) * 100.0
gateFailed := false
if cfg.ReleaseGate.Enabled && gateFile != "" {
gateModeVal := "any"
if cfg.ReleaseGate.Mode != "" {
gateModeVal = cfg.ReleaseGate.Mode
}
if gateMode != "any" {
gateModeVal = gateMode
}
gate := releasegate.Gate{
AssetContext: cfg.ReleaseGate.AssetContext,
CompensatingControls: cfg.ReleaseGate.CompensatingControls,
RiskAppetite: cfg.ReleaseGate.RiskAppetite,
WarnAbove: cfg.ReleaseGate.WarnAbove,
AggregateLimit: cfg.ReleaseGate.AggregateLimit,
Mode: gateModeVal,
}
cwd, _ := os.Getwd()
safePathStr, err := utils.SafePath(cwd, gateFile)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
vdata, err := os.ReadFile(safePathStr) // #nosec G304
if err != nil {
fmt.Fprintf(os.Stderr, "Failed to read gate file: %v\n", err)
os.Exit(1)
}
var vulnsFormat struct {
Vulnerabilities []model.Vulnerability `yaml:"vulnerabilities"`
}
if err := yaml.Unmarshal(vdata, &vulnsFormat); err != nil {
fmt.Fprintf(os.Stderr, "Failed to parse gate vulnerabilities: %v\n", err)
os.Exit(1)
}
if key, err := accept.ResolveSecret(*cfg); err == nil {
configHash, _ := accept.ConfigHash(configPath)
if accs, err := accept.Load("wardex-acceptances.yaml", key, "wardex-accept-audit.log", "", configHash); err == nil {
acceptedMap := make(map[string]bool)
for _, a := range accs {
if !a.Revoked {
acceptedMap[a.CVE] = true
}
}
var filtered []model.Vulnerability
for _, v := range vulnsFormat.Vulnerabilities {
if !acceptedMap[v.CVEID] {
filtered = append(filtered, v)
} else {
fmt.Fprintf(os.Stderr, "[INFO] CVE %s is covered by an active risk acceptance and will be ignored.\n", v.CVEID)
}
}
vulnsFormat.Vulnerabilities = filtered
}
}
if epssEnrich != "" {
if key, err := accept.ResolveSecret(*cfg); err == nil {
cwd, _ := os.Getwd()
safePathStr, err := utils.SafePath(cwd, epssEnrich)
if err != nil {
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
os.Exit(1)
}
edata, err := os.ReadFile(safePathStr) // #nosec G304
if err == nil {
var enrichFormat model.EPSSEnrichmentFile
if err := yaml.Unmarshal(edata, &enrichFormat); err == nil {
if err := epss.Verify(enrichFormat, key); err == nil {
scoreMap := make(map[string]float64)
for _, e := range enrichFormat.Enrichments {
scoreMap[e.CVE] = e.Score
}
for i, v := range vulnsFormat.Vulnerabilities {
if s, ok := scoreMap[v.CVEID]; ok {
vulnsFormat.Vulnerabilities[i].EPSSScore = s
fmt.Fprintf(os.Stderr, "[INFO] Applied signed EPSS Enrichment for %s: %.6f\n", v.CVEID, s)
}
}
} else {
fmt.Fprintf(os.Stderr, "WARNING: EPSS Enrichment signature invalid: %v\n", err)
}
}
}
} else {
fmt.Fprintf(os.Stderr, "WARNING: Cannot verify EPSS Enrichment without WARDEX_ACCEPT_SECRET configured.\n")
}
}
gateReport := gate.Evaluate(vulnsFormat.Vulnerabilities)
rep.Gate = &gateReport
switch gateReport.OverallDecision {
case "block":
gateFailed = true
missingEpss := 0
for _, v := range vulnsFormat.Vulnerabilities {
if v.EPSSScore == 0.0 {
missingEpss++
}
}
if missingEpss > 0 {
fmt.Fprintf(os.Stderr, "\n[HINT] %d vulnerabilities lacked EPSS scores and defaulted to worst-case (1.0).\n", missingEpss)
fmt.Fprintf(os.Stderr, " Run 'wardex enrich epss %s' to fetch real probabilities from FIRST.org and sign the enrichment.\n", gateFile)
}
case "warn":
fmt.Fprintf(os.Stderr, "WARNING: Risk threshold exceeded WarnAbove for %d vulnerability(ies).\n", gateReport.WarnCount)
}
}
if !noSnapshot {
prev, _ := snapshot.Load(snapshotFile)
if prev != nil {
delta := snapshot.Diff(rep, *prev)
rep.Delta = &delta
}
if err := snapshot.Save(snapshotFile, &rep); err != nil {
fmt.Fprintf(os.Stderr, "Failed to save snapshot: %v\n", err)
}
}
finalFormat := outputFormat
if outputFormat == "markdown" && cfg.Reporting.Format != "" {
finalFormat = cfg.Reporting.Format
}
finalOutFile := outFile
if outFile == "stdout" && cfg.Reporting.Output != "" {
finalOutFile = cfg.Reporting.Output
}
if err := report.Generate(rep, finalFormat, finalOutFile, roadmapLimit); err != nil {
fmt.Fprintf(os.Stderr, "Failed to generate report: %v\n", err)
os.Exit(1)
}
if gateFailed {
os.Exit(exitcodes.GateBlocked)
}
compFail := false
if failAbove > 0 {
for _, gap := range sortedRoadmap {
if gap.FinalScore > failAbove {
compFail = true
break
}
}
}
if compFail {
os.Exit(exitcodes.ComplianceFail)
}
os.Exit(exitcodes.OK)
}