-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathresult.go
2666 lines (2399 loc) · 96.6 KB
/
result.go
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 commands
import (
"encoding/json"
"fmt"
"html"
"log"
"net/url"
"os"
"path/filepath"
"regexp"
"slices"
"strconv"
"strings"
"text/template"
"time"
"github.com/MakeNowJust/heredoc"
"github.com/checkmarx/ast-cli/internal/commands/util"
"github.com/checkmarx/ast-cli/internal/commands/util/printer"
errorConstants "github.com/checkmarx/ast-cli/internal/constants/errors"
"github.com/checkmarx/ast-cli/internal/logger"
"github.com/checkmarx/ast-cli/internal/services"
"github.com/checkmarx/ast-cli/internal/wrappers"
"golang.org/x/text/cases"
"golang.org/x/text/language"
commonParams "github.com/checkmarx/ast-cli/internal/params"
"github.com/pkg/errors"
"github.com/spf13/cobra"
)
const (
failedCreatingSummary = "Failed creating summary"
failedGettingScan = "Failed getting scan"
failedListingResults = "Failed listing results"
failedListingCodeBashing = "Failed codebashing link"
mediumLabel = "medium"
criticalLabel = "critical"
highLabel = "high"
lowLabel = "low"
infoLabel = "info"
sonarTypeLabel = "_sonar"
glSastTypeLabel = ".gl-sast-report"
glScaTypeLabel = ".gl-sca-report"
directoryPermission = 0700
infoSonar = "INFO"
lowSonar = "MINOR"
mediumSonar = "MAJOR"
highSonar = "CRITICAL"
criticalSonar = "BLOCKER"
infoLowSarif = "note"
mediumSarif = "warning"
highSarif = "error"
vulnerabilitySonar = "VULNERABILITY"
infoCx = "INFO"
lowCx = "LOW"
mediumCx = "MEDIUM"
highCx = "HIGH"
criticalCx = "CRITICAL"
tableResultsFormat = " | %-10s %6v %5d %6d %5d %4d %-9s |\n"
stringTableResultsFormat = " | %-10s %5s %6s %6s %5s %4s %5s |\n"
TableTitleFormat = " | %-11s %4s %4s %6s %4s %4s %6s |\n"
twoNewLines = "\n\n"
tableLine = " --------------------------------------------------------------------- "
codeBashingKey = "cb-url"
failedGettingBfl = "Failed getting BFL"
notAvailableString = "-"
disabledString = "N/A"
scanFailedString = "Failed "
scanCanceledString = "Canceled"
scanSuccessString = "Completed"
scanPartialString = "Partial"
scsScanUnavailableString = ""
notAvailableNumber = -1
scanFailedNumber = -2
scanCanceledNumber = -3
scanPartialNumber = -4
defaultPaddingSize = -13
scanPendingMessage = "Scan triggered in asynchronous mode or still running. Click more details to get the full status."
directDependencyType = "Direct Dependency"
indirectDependencyType = "Transitive Dependency"
startedStatus = "started"
requestedStatus = "requested"
completedStatus = "completed"
pdfToEmailFlagDescription = "Send the PDF report to the specified email address." +
" Use \",\" as the delimiter for multiple emails"
pdfOptionsFlagDescription = "Sections to generate PDF report. Available options: Iac-Security,Sast,Sca," +
defaultPdfOptionsDataSections
sbomReportFlagDescription = "Sections to generate SBOM report. Available options: CycloneDxJson,CycloneDxXml,SpdxJson"
reportNameScanReport = "scan-report"
reportNameImprovedScanReport = "improved-scan-report"
reportTypeEmail = "email"
defaultPdfOptionsDataSections = "ScanSummary,ExecutiveSummary,ScanResults"
exploitablePathFlagDescription = "Enable or disable exploitable path in scan. Available options: true,false"
scaLastScanTimeFlagDescription = "SCA last scan time. Available options: integer above 1"
projectPrivatePackageFlagDescription = "Enable or disable project private package. Available options: true,false"
scaPrivatePackageVersionFlagDescription = "SCA project private package version. Example: 0.1.1"
scaHideDevAndTestDepFlagDescription = "Filter SCA results to exclude dev and test dependencies"
policeManagementNoneStatus = "none"
apiDocumentationFlagDescription = "Swagger folder/file filter for API-Security scan. Example: ./swagger.json"
summaryCreatedAtLayout = "2006-01-02, 15:04:05"
glTimeFormat = "2006-01-02T15:04:05"
sarifNodeFileLength = 2
fixLabel = "fix"
redundantLabel = "redundant"
delayValueForReport = 10
fixLinkPrefix = "https://devhub.checkmarx.com/cve-details/"
ScaDevAndTestExclusionParam = "DEV_AND_TEST"
ScaExcludeResultTypesParam = "exclude-result-types"
noFileForScorecardResultString = "Issue Found in your GitHub repository"
)
var (
summaryFormats = []string{
printer.FormatSummaryConsole,
printer.FormatSummary,
printer.FormatSummaryJSON,
printer.FormatPDF,
printer.FormatSummaryMarkdown,
printer.FormatSbom,
printer.FormatGLSast,
printer.FormatGLSca,
}
filterResultsListFlagUsage = fmt.Sprintf(
"Filter the list of results. Use ';' as the delimiter for arrays. Available filters are: %s",
strings.Join(
[]string{
commonParams.ScanIDQueryParam,
commonParams.LimitQueryParam,
commonParams.OffsetQueryParam,
commonParams.SortQueryParam,
commonParams.IncludeNodesQueryParam,
commonParams.NodeIDsQueryParam,
commonParams.QueryQueryParam,
commonParams.GroupQueryParam,
commonParams.StatusQueryParam,
commonParams.SeverityQueryParam,
commonParams.StateQueryParam,
}, ",",
),
)
// Follows: over 9.0 is critical, 7.0 to 8.9 is high, 4.0 to 6.9 is medium and 3.9 or less is low.
securities = map[string]string{
infoCx: "1.0",
lowCx: "2.0",
mediumCx: "4.0",
highCx: "7.0",
criticalCx: "9.0",
}
// Match cx severity with sonar severity
sonarSeverities = map[string]string{
infoCx: infoSonar,
lowCx: lowSonar,
mediumCx: mediumSonar,
highCx: highSonar,
criticalCx: criticalSonar,
}
containerEngineUnsupportedAgents = []string{
commonParams.JetbrainsAgent, commonParams.VSCodeAgent, commonParams.VisualStudioAgent, commonParams.EclipseAgent,
}
sscsEngineToOverviewEngineMap = map[string]string{
commonParams.SCSScorecardType: commonParams.SCSScorecardOverviewType,
commonParams.SCSSecretDetectionType: commonParams.SCSSecretDetectionOverviewType,
}
)
func NewResultsCommand(
resultsWrapper wrappers.ResultsWrapper,
scanWrapper wrappers.ScansWrapper,
exportWrapper wrappers.ExportWrapper,
resultsPdfReportsWrapper wrappers.ResultsPdfWrapper,
codeBashingWrapper wrappers.CodeBashingWrapper,
bflWrapper wrappers.BflWrapper,
risksOverviewWrapper wrappers.RisksOverviewWrapper,
scsScanOverviewWrapper wrappers.ScanOverviewWrapper,
policyWrapper wrappers.PolicyWrapper,
featureFlagsWrapper wrappers.FeatureFlagsWrapper,
) *cobra.Command {
resultCmd := &cobra.Command{
Use: "results",
Short: "Retrieve results",
Annotations: map[string]string{
"command:doc": heredoc.Doc(
`
https://checkmarx.com/resource/documents/en/34965-68640-results.html
`,
),
},
}
showResultCmd := resultShowSubCommand(resultsWrapper, scanWrapper, exportWrapper, resultsPdfReportsWrapper,
risksOverviewWrapper, scsScanOverviewWrapper, policyWrapper, featureFlagsWrapper)
codeBashingCmd := resultCodeBashing(codeBashingWrapper)
bflResultCmd := resultBflSubCommand(bflWrapper)
exitCodeSubcommand := exitCodeSubCommand(scanWrapper)
resultCmd.AddCommand(
showResultCmd, bflResultCmd, codeBashingCmd, exitCodeSubcommand,
)
return resultCmd
}
func exitCodeSubCommand(scanWrapper wrappers.ScansWrapper) *cobra.Command {
exitCodeCmd := &cobra.Command{
Use: "exit-code",
Short: "Get exit code and details of a scan",
Long: "The exit-code command enables you to get the exit code and failure details of a requested scan in Checkmarx One.",
Example: heredoc.Doc(
`
$ cx results exit-code --scan-id <scan Id> --scan-types <sast | sca | iac-security | apisec>
`,
),
RunE: runGetExitCodeCommand(scanWrapper),
}
exitCodeCmd.PersistentFlags().String(commonParams.ScanIDFlag, "", "Scan ID")
exitCodeCmd.PersistentFlags().String(commonParams.ScanTypes, "", "Scan types")
return exitCodeCmd
}
func resultShowSubCommand(
resultsWrapper wrappers.ResultsWrapper,
scanWrapper wrappers.ScansWrapper,
exportWrapper wrappers.ExportWrapper,
resultsPdfReportsWrapper wrappers.ResultsPdfWrapper,
risksOverviewWrapper wrappers.RisksOverviewWrapper,
scsScanOverviewWrapper wrappers.ScanOverviewWrapper,
policyWrapper wrappers.PolicyWrapper,
featureFlagsWrapper wrappers.FeatureFlagsWrapper,
) *cobra.Command {
resultShowCmd := &cobra.Command{
Use: "show",
Short: "Show results of a scan",
Long: "The show command enables the ability to show results about a requested scan in Checkmarx One.",
Example: heredoc.Doc(
`
$ cx results show --scan-id <scan Id>
`,
),
RunE: runGetResultCommand(resultsWrapper, scanWrapper, exportWrapper, resultsPdfReportsWrapper, risksOverviewWrapper, scsScanOverviewWrapper, policyWrapper, featureFlagsWrapper),
}
addScanIDFlag(resultShowCmd, "ID to report on.")
addResultFormatFlag(
resultShowCmd,
printer.FormatJSON,
printer.FormatSummary,
printer.FormatSummaryConsole,
printer.FormatSarif,
printer.FormatSummaryJSON,
printer.FormatSbom,
printer.FormatPDF,
printer.FormatSummaryMarkdown,
printer.FormatGLSast,
printer.FormatGLSca,
)
resultShowCmd.PersistentFlags().String(commonParams.ReportFormatPdfToEmailFlag, "", pdfToEmailFlagDescription)
resultShowCmd.PersistentFlags().String(commonParams.ReportSbomFormatFlag, services.DefaultSbomOption, sbomReportFlagDescription)
resultShowCmd.PersistentFlags().String(commonParams.ReportFormatPdfOptionsFlag, defaultPdfOptionsDataSections, pdfOptionsFlagDescription)
resultShowCmd.PersistentFlags().String(commonParams.TargetFlag, "cx_result", "Output file")
resultShowCmd.PersistentFlags().String(commonParams.TargetPathFlag, ".", "Output Path")
resultShowCmd.PersistentFlags().StringSlice(commonParams.FilterFlag, []string{}, filterResultsListFlagUsage)
resultShowCmd.PersistentFlags().IntP(
commonParams.WaitDelayFlag,
"",
commonParams.WaitDelayDefault,
"Polling wait time in seconds",
)
resultShowCmd.PersistentFlags().Int(
commonParams.PolicyTimeoutFlag,
commonParams.ResultPolicyDefaultTimeout,
"Cancel the policy evaluation and fail after the timeout in minutes",
)
resultShowCmd.PersistentFlags().Bool(commonParams.IgnorePolicyFlag, false, "Do not evaluate policies")
resultShowCmd.PersistentFlags().Bool(commonParams.SastRedundancyFlag, false,
"Populate SAST results 'data.redundancy' with values '"+fixLabel+"' (to fix) or '"+redundantLabel+"' (no need to fix)")
resultShowCmd.PersistentFlags().Bool(commonParams.ScaHideDevAndTestDepFlag, false, scaHideDevAndTestDepFlagDescription)
return resultShowCmd
}
func resultBflSubCommand(bflWrapper wrappers.BflWrapper) *cobra.Command {
resultBflCmd := &cobra.Command{
Use: "bfl",
Short: "Show best fix location for a query id within the scan result.",
Long: "The bfl command enables the ability to show best fix location for a querid within the scan result.",
Example: heredoc.Doc(
`
$ cx results bfl --scan-id <scan Id> --query-id <query Id>
`,
),
RunE: runGetBestFixLocationCommand(bflWrapper),
}
addScanIDFlag(resultBflCmd, "ID to report on.")
addQueryIDFlag(resultBflCmd, "Query Id from the result.")
addFormatFlag(resultBflCmd, printer.FormatList, printer.FormatJSON)
markFlagAsRequired(resultBflCmd, commonParams.ScanIDFlag)
markFlagAsRequired(resultBflCmd, commonParams.QueryIDFlag)
return resultBflCmd
}
func runGetExitCodeCommand(scanWrapper wrappers.ScansWrapper) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
scanID, _ := cmd.Flags().GetString(commonParams.ScanIDFlag)
if scanID == "" {
return errors.New(errorConstants.ScanIDRequired)
}
scanTypesFlagValue, _ := cmd.Flags().GetString(commonParams.ScanTypes)
results, err := GetScannerResults(scanWrapper, scanID, scanTypesFlagValue)
if err != nil {
return err
}
if len(results) == 0 {
return nil
}
return printer.Print(cmd.OutOrStdout(), results, printer.FormatIndentedJSON)
}
}
func GetScannerResults(scanWrapper wrappers.ScansWrapper, scanID, scanTypesFlagValue string) ([]ScannerResponse, error) {
scanResponseModel, errorModel, err := scanWrapper.GetByID(scanID)
if err != nil {
return nil, errors.Wrapf(err, "%s", failedGetting)
}
if errorModel != nil {
return nil, errors.Errorf("%s: CODE: %d, %s", failedGettingScan, errorModel.Code, errorModel.Message)
}
results := getScannerResponse(scanTypesFlagValue, scanResponseModel)
return results, nil
}
func getScannerResponse(scanTypesFlagValue string, scanResponseModel *wrappers.ScanResponseModel) []ScannerResponse {
var results []ScannerResponse
if scanResponseModel.Status == wrappers.ScanCanceled ||
scanResponseModel.Status == wrappers.ScanRunning ||
scanResponseModel.Status == wrappers.ScanQueued ||
scanResponseModel.Status == wrappers.ScanPartial ||
scanResponseModel.Status == wrappers.ScanCompleted {
result := ScannerResponse{
ScanID: scanResponseModel.ID,
Status: string(scanResponseModel.Status),
}
results = append(results, result)
return results
}
if scanTypesFlagValue == "" {
results = createAllFailedScannersResponse(scanResponseModel)
} else {
scanTypes := sanitizeScannerNames(scanTypesFlagValue)
results = createRequestedScannersResponse(scanTypes, scanResponseModel)
}
return results
}
func createRequestedScannersResponse(scanTypes map[string]string, scanResponseModel *wrappers.ScanResponseModel) []ScannerResponse {
var results []ScannerResponse
for i := range scanResponseModel.StatusDetails {
if _, ok := scanTypes[scanResponseModel.StatusDetails[i].Name]; ok {
results = append(results, createScannerResponse(&scanResponseModel.StatusDetails[i]))
}
}
return results
}
func createAllFailedScannersResponse(scanResponseModel *wrappers.ScanResponseModel) []ScannerResponse {
var results []ScannerResponse
for i := range scanResponseModel.StatusDetails {
if scanResponseModel.StatusDetails[i].Status == wrappers.ScanFailed {
results = append(results, createScannerResponse(&scanResponseModel.StatusDetails[i]))
}
}
return results
}
func sanitizeScannerNames(scanTypes string) map[string]string {
scanTypeSlice := strings.Split(scanTypes, ",")
scanTypeMap := make(map[string]string)
for i := range scanTypeSlice {
lowered := strings.ToLower(scanTypeSlice[i])
scanTypeMap[lowered] = lowered
}
return scanTypeMap
}
func createScannerResponse(statusDetails *wrappers.StatusInfo) ScannerResponse {
return ScannerResponse{
Name: statusDetails.Name,
Status: statusDetails.Status,
Details: statusDetails.Details,
ErrorCode: stringifyErrorCode(statusDetails.ErrorCode),
}
}
func stringifyErrorCode(errorCode int) string {
if errorCode == 0 {
return ""
}
return strconv.Itoa(errorCode)
}
func runGetBestFixLocationCommand(bflWrapper wrappers.BflWrapper) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
var bflResponseModel *wrappers.BFLResponseModel
var errorModel *wrappers.WebError
var err error
scanID, _ := cmd.Flags().GetString(commonParams.ScanIDFlag)
queryID, _ := cmd.Flags().GetString(commonParams.QueryIDFlag)
scanIds := strings.Split(scanID, ",")
if len(scanIds) > 1 {
return errors.Errorf("%s", "Multiple scan-ids are not allowed.")
}
queryIds := strings.Split(queryID, ",")
if len(queryIds) > 1 {
return errors.Errorf("%s", "Multiple query-ids are not allowed.")
}
params := make(map[string]string)
params[commonParams.ScanIDQueryParam] = scanID
params[commonParams.QueryIDQueryParam] = queryID
bflResponseModel, errorModel, err = bflWrapper.GetBflByScanIDAndQueryID(params)
if err != nil {
return errors.Wrapf(err, "%s", failedGettingBfl)
}
// Checking the response
if errorModel != nil {
return errors.Errorf("%s: CODE: %d, %s", failedGettingBfl, errorModel.Code, errorModel.Message)
} else if bflResponseModel != nil {
err = printByFormat(cmd, toBflView(*bflResponseModel))
if err != nil {
return err
}
}
return nil
}
}
func toBflView(bflResponseModel wrappers.BFLResponseModel) []wrappers.ScanResultNode {
if (bflResponseModel.TotalCount) > 0 {
views := make([]wrappers.ScanResultNode, bflResponseModel.TotalCount)
for i := 0; i < bflResponseModel.TotalCount; i++ {
views[i] = wrappers.ScanResultNode{
Name: bflResponseModel.Trees[i].BFL.Name,
FileName: bflResponseModel.Trees[i].BFL.FileName,
FullName: bflResponseModel.Trees[i].BFL.FullName,
Column: bflResponseModel.Trees[i].BFL.Column,
Length: bflResponseModel.Trees[i].BFL.Length,
Line: bflResponseModel.Trees[i].BFL.Line,
MethodLine: bflResponseModel.Trees[i].BFL.MethodLine,
Method: bflResponseModel.Trees[i].BFL.Method,
DomType: bflResponseModel.Trees[i].BFL.DomType,
}
}
return views
}
views := make([]wrappers.ScanResultNode, 0)
return views
}
func resultCodeBashing(codeBashingWrapper wrappers.CodeBashingWrapper) *cobra.Command {
// Create a codeBashing wrapper
resultCmd := &cobra.Command{
Use: "codebashing",
Short: "Get codebashing lesson link",
Long: "The codebashing command enables the ability to retrieve the link about a specific vulnerability.",
Example: heredoc.Doc(
`
$ cx results codebashing --language <string> --vulnerability-type <string> --cwe-id <string> --format <string>
`,
),
RunE: runGetCodeBashingCommand(codeBashingWrapper),
}
resultCmd.PersistentFlags().String(commonParams.LanguageFlag, "", "Language of the vulnerability")
err := resultCmd.MarkPersistentFlagRequired(commonParams.LanguageFlag)
if err != nil {
log.Fatal(err)
}
resultCmd.PersistentFlags().String(commonParams.VulnerabilityTypeFlag, "", "Vulnerability type")
err = resultCmd.MarkPersistentFlagRequired(commonParams.VulnerabilityTypeFlag)
if err != nil {
log.Fatal(err)
}
resultCmd.PersistentFlags().String(commonParams.CweIDFlag, "", "CWE ID for the vulnerability")
err = resultCmd.MarkPersistentFlagRequired(commonParams.CweIDFlag)
if err != nil {
log.Fatal(err)
}
addFormatFlag(resultCmd, printer.FormatJSON, printer.FormatTable, printer.FormatList)
return resultCmd
}
func convertScanToResultsSummary(scanInfo *wrappers.ScanResponseModel, resultsWrapper wrappers.ResultsWrapper) (*wrappers.ResultSummary, error) {
if scanInfo == nil {
return nil, errors.New(failedCreatingSummary)
}
scanInfo.ReplaceMicroEnginesWithSCS()
sastIssues := 0
scaIssues := 0
kicsIssues := 0
var containersIssues *int
var scsIssues *int
enginesStatusCode := map[string]int{
commonParams.SastType: 0,
commonParams.ScaType: 0,
commonParams.KicsType: 0,
commonParams.APISecType: 0,
commonParams.ScsType: 0,
commonParams.ContainersType: 0,
}
if wrappers.IsContainersEnabled {
containersIssues = new(int)
*containersIssues = 0
enginesStatusCode[commonParams.ContainersType] = 0
}
if wrappers.IsSCSEnabled {
scsIssues = new(int)
*scsIssues = 0
enginesStatusCode[commonParams.ScsType] = 0
}
if len(scanInfo.StatusDetails) > 0 {
for _, statusDetailItem := range scanInfo.StatusDetails {
if statusDetailItem.Status == wrappers.ScanFailed || statusDetailItem.Status == wrappers.ScanCanceled {
if statusDetailItem.Name == commonParams.SastType {
sastIssues = notAvailableNumber
} else if statusDetailItem.Name == commonParams.ScaType {
scaIssues = notAvailableNumber
} else if statusDetailItem.Name == commonParams.KicsType {
kicsIssues = notAvailableNumber
} else if statusDetailItem.Name == commonParams.ScsType && wrappers.IsSCSEnabled {
*scsIssues = notAvailableNumber
} else if statusDetailItem.Name == commonParams.ContainersType && wrappers.IsContainersEnabled {
*containersIssues = notAvailableNumber
}
}
switch statusDetailItem.Status {
case wrappers.ScanFailed:
handleScanStatus(statusDetailItem, enginesStatusCode, scanFailedNumber)
case wrappers.ScanCanceled:
handleScanStatus(statusDetailItem, enginesStatusCode, scanCanceledNumber)
}
}
}
summary := &wrappers.ResultSummary{
ScanID: scanInfo.ID,
Status: string(scanInfo.Status),
CreatedAt: scanInfo.CreatedAt.Format("2006-01-02, 15:04:05"),
ProjectID: scanInfo.ProjectID,
RiskStyle: "",
RiskMsg: "",
CriticalIssues: 0,
HighIssues: 0,
MediumIssues: 0,
LowIssues: 0,
InfoIssues: 0,
SastIssues: sastIssues,
KicsIssues: kicsIssues,
ScaIssues: scaIssues,
ScsIssues: scsIssues,
ContainersIssues: containersIssues,
Tags: scanInfo.Tags,
ProjectName: scanInfo.ProjectName,
BranchName: scanInfo.Branch,
EnginesEnabled: scanInfo.Engines,
EnginesResult: map[string]*wrappers.EngineResultSummary{
commonParams.SastType: {StatusCode: enginesStatusCode[commonParams.SastType]},
commonParams.ScaType: {StatusCode: enginesStatusCode[commonParams.ScaType]},
commonParams.KicsType: {StatusCode: enginesStatusCode[commonParams.KicsType]},
commonParams.APISecType: {StatusCode: enginesStatusCode[commonParams.APISecType]},
commonParams.ContainersType: {StatusCode: enginesStatusCode[commonParams.ContainersType]},
},
}
if wrappers.IsContainersEnabled {
summary.EnginesResult[commonParams.ContainersType] = &wrappers.EngineResultSummary{StatusCode: enginesStatusCode[commonParams.ContainersType]}
}
if wrappers.IsSCSEnabled {
summary.EnginesResult[commonParams.ScsType] = &wrappers.EngineResultSummary{StatusCode: enginesStatusCode[commonParams.ScsType]}
}
baseURI, err := resultsWrapper.GetResultsURL(summary.ProjectID)
if err != nil {
return nil, err
}
summary.BaseURI = baseURI
summary.BaseURI = generateScanSummaryURL(summary)
if isScanPending(summary.Status) {
summary.ScanInfoMessage = scanPendingMessage
}
return summary, nil
}
func handleScanStatus(statusDetailItem wrappers.StatusInfo, targetTypes map[string]int, statusCode int) {
if _, ok := targetTypes[statusDetailItem.Name]; ok {
targetTypes[statusDetailItem.Name] = statusCode
}
}
func summaryReport(
summary *wrappers.ResultSummary,
policies *wrappers.PolicyResponseModel,
risksOverviewWrapper wrappers.RisksOverviewWrapper,
scsScanOverviewWrapper wrappers.ScanOverviewWrapper,
featureFlagsWrapper wrappers.FeatureFlagsWrapper,
results *wrappers.ScanResultsCollection,
) (*wrappers.ResultSummary, error) {
if summary.HasAPISecurity() {
apiSecRisks, err := getResultsForAPISecScanner(risksOverviewWrapper, summary.ScanID)
if err != nil {
return nil, err
}
summary.APISecurity = *apiSecRisks
}
if summary.HasSCS() && wrappers.IsSCSEnabled {
// Getting the base SCS overview. Results counts are overwritten in enhanceWithScanSummary->countResult
SCSOverview, err := getScanOverviewForSCSScanner(scsScanOverviewWrapper, summary.ScanID)
if err != nil {
return nil, err
}
summary.SCSOverview = SCSOverview
}
if policies != nil {
summary.Policies = filterViolatedRules(*policies)
}
enhanceWithScanSummary(summary, results, featureFlagsWrapper)
setNotAvailableNumberIfZero(summary, &summary.SastIssues, commonParams.SastType)
setNotAvailableNumberIfZero(summary, &summary.ScaIssues, commonParams.ScaType)
setNotAvailableNumberIfZero(summary, &summary.KicsIssues, commonParams.KicsType)
if wrappers.IsContainersEnabled {
setNotAvailableNumberIfZero(summary, summary.ContainersIssues, commonParams.ContainersType)
}
if wrappers.IsSCSEnabled {
setNotAvailableNumberIfZero(summary, summary.ScsIssues, commonParams.ScsType)
}
setRiskMsgAndStyle(summary)
setNotAvailableEnginesStatusCode(summary)
return summary, nil
}
func setNotAvailableEnginesStatusCode(summary *wrappers.ResultSummary) {
for engineName, engineResult := range summary.EnginesResult {
setNotAvailableNumberIfZero(summary, &engineResult.StatusCode, engineName)
}
}
func setRiskMsgAndStyle(summary *wrappers.ResultSummary) {
if summary.CriticalIssues > 0 {
summary.RiskStyle = criticalLabel
summary.RiskMsg = "Critical Risk"
} else if summary.HighIssues > 0 {
summary.RiskStyle = highLabel
summary.RiskMsg = "High Risk"
} else if summary.MediumIssues > 0 {
summary.RiskStyle = mediumLabel
summary.RiskMsg = "Medium Risk"
} else if summary.LowIssues > 0 {
summary.RiskStyle = lowLabel
summary.RiskMsg = "Low Risk"
} else if summary.TotalIssues == 0 {
summary.RiskMsg = "No Risk"
}
}
func setNotAvailableNumberIfZero(summary *wrappers.ResultSummary, counter *int, engineType string) {
if *counter == 0 && !contains(summary.EnginesEnabled, engineType) {
*counter = notAvailableNumber
}
}
func enhanceWithScanSummary(summary *wrappers.ResultSummary, results *wrappers.ScanResultsCollection, featureFlagsWrapper wrappers.FeatureFlagsWrapper) {
for _, result := range results.Results {
countResult(summary, result)
}
// Set critical count for a specific engine if critical is disabled
flagResponse, _ := wrappers.GetSpecificFeatureFlag(featureFlagsWrapper, wrappers.CVSSV3Enabled)
criticalEnabled := flagResponse.Status
if summary.HasAPISecurity() {
summary.EnginesResult[commonParams.APISecType].Low = summary.APISecurity.Risks[3]
summary.EnginesResult[commonParams.APISecType].Medium = summary.APISecurity.Risks[2]
summary.EnginesResult[commonParams.APISecType].High = summary.APISecurity.Risks[1]
if !criticalEnabled {
summary.EnginesResult[commonParams.APISecType].Critical = notAvailableNumber
} else {
summary.EnginesResult[commonParams.APISecType].Critical = summary.APISecurity.Risks[0]
}
}
summary.TotalIssues = summary.SastIssues + summary.ScaIssues + summary.KicsIssues + summary.GetAPISecurityDocumentationTotal()
if summary.HasSCS() && wrappers.IsSCSEnabled {
// Special case for SCS where status is partial if any microengines failed
if summary.SCSOverview.Status == scanPartialString {
summary.EnginesResult[commonParams.ScsType].StatusCode = scanPartialNumber
}
if !criticalEnabled {
summary.EnginesResult[commonParams.ScsType].Critical = notAvailableNumber
removeCriticalFromSCSOverview(summary)
}
if *summary.ScsIssues >= 0 {
summary.TotalIssues += *summary.ScsIssues
}
}
if wrappers.IsContainersEnabled {
if *summary.ContainersIssues >= 0 {
summary.TotalIssues += *summary.ContainersIssues
}
}
if !criticalEnabled {
summary.EnginesResult[commonParams.SastType].Critical = notAvailableNumber
summary.EnginesResult[commonParams.KicsType].Critical = notAvailableNumber
summary.EnginesResult[commonParams.ScaType].Critical = notAvailableNumber
summary.EnginesResult[commonParams.ContainersType].Critical = notAvailableNumber
}
}
func removeCriticalFromSCSOverview(summary *wrappers.ResultSummary) {
criticalCount := summary.SCSOverview.RiskSummary[criticalLabel]
summary.SCSOverview.TotalRisksCount -= criticalCount
summary.SCSOverview.RiskSummary[criticalLabel] = notAvailableNumber
for _, microEngineOverview := range summary.SCSOverview.MicroEngineOverviews {
if microEngineOverview.RiskSummary != nil && microEngineOverview.RiskSummary[criticalLabel] != nil {
engineCriticalCount := microEngineOverview.RiskSummary[criticalLabel]
microEngineOverview.TotalRisks -= engineCriticalCount.(int)
microEngineOverview.RiskSummary[criticalLabel] = disabledString
}
}
}
func writeHTMLSummary(targetFile string, summary *wrappers.ResultSummary) error {
log.Println("Creating Summary Report: ", targetFile)
summaryTemp, err := template.New("summaryTemplate").Parse(wrappers.SummaryTemplate(isScanPending(summary.Status)))
if err == nil {
f, err := os.Create(targetFile)
if err == nil {
_ = summaryTemp.ExecuteTemplate(f, "SummaryTemplate", summary)
_ = f.Close()
}
return err
}
return nil
}
func writeMarkdownSummary(targetFile string, data *wrappers.ResultSummary) error {
log.Println("Creating Markdown Summary Report: ", targetFile)
tmpl, err := template.New(printer.FormatSummaryMarkdown).Parse(wrappers.SummaryMarkdownTemplate(isScanPending(data.Status)))
if err != nil {
return err
}
file, err := os.Create(targetFile)
if err != nil {
return err
}
defer file.Close()
err = tmpl.Execute(file, &data)
if err != nil {
return err
}
return nil
}
// nolint: whitespace
func writeConsoleSummary(summary *wrappers.ResultSummary, featureFlagsWrapper wrappers.FeatureFlagsWrapper) error {
if !isScanPending(summary.Status) {
fmt.Printf(" Scan Summary: \n")
fmt.Printf(" Created At: %s\n", summary.CreatedAt)
fmt.Printf(" Project Name: %s \n", summary.ProjectName)
fmt.Printf(" Scan ID: %s \n\n", summary.ScanID)
fmt.Printf(" Results Summary: \n")
fmt.Printf(
" Risk Level: %s \n",
summary.RiskMsg,
)
if summary.Policies != nil && !strings.EqualFold(summary.Policies.Status, policeManagementNoneStatus) {
printPoliciesSummary(summary)
}
printResultsSummaryTable(summary)
if summary.HasAPISecurity() {
printAPIsSecuritySummary(summary)
}
if summary.HasSCS() && wrappers.IsSCSEnabled {
printSCSSummary(summary.SCSOverview.MicroEngineOverviews, featureFlagsWrapper)
}
fmt.Printf(" Checkmarx One - Scan Summary & Details: %s\n", summary.BaseURI)
} else {
fmt.Printf("Scan executed in asynchronous mode or still running. Hence, no results generated.\n")
fmt.Printf("For more information: %s\n", summary.BaseURI)
}
return nil
}
func printPoliciesSummary(summary *wrappers.ResultSummary) {
hasViolations := false
for _, policy := range summary.Policies.Policies {
if len(policy.RulesViolated) > 0 {
hasViolations = true
break
}
}
if hasViolations {
fmt.Printf(tableLine + "\n")
if summary.Policies.BreakBuild {
fmt.Printf(" Policy Management Violation - Break Build Enabled: \n")
} else {
fmt.Printf(" Policy Management Violation: \n")
}
for _, police := range summary.Policies.Policies {
if len(police.RulesViolated) > 0 {
fmt.Printf(" Policy: %s | Break Build: %t | Violated Rules: ", police.Name, police.BreakBuild)
for _, violatedRule := range police.RulesViolated {
fmt.Printf("%s;", violatedRule)
}
}
fmt.Printf("\n")
}
fmt.Printf("\n")
}
}
func printAPIsSecuritySummary(summary *wrappers.ResultSummary) {
fmt.Printf(" API Security - Total Detected APIs: %d \n", summary.APISecurity.APICount)
fmt.Printf(" APIS WITH RISK: %*d \n", defaultPaddingSize, summary.APISecurity.TotalRisksCount)
if summary.HasAPISecurityDocumentation() {
fmt.Printf(" APIS DOCUMENTATION: %*d \n", defaultPaddingSize, summary.GetAPISecurityDocumentationTotal())
}
fmt.Printf(tableLine + twoNewLines)
}
func printTableRow(title string, counts *wrappers.EngineResultSummary, statusNumber int) {
switch statusNumber {
case notAvailableNumber:
fmt.Printf(stringTableResultsFormat, title, notAvailableString, notAvailableString, notAvailableString, notAvailableString, notAvailableString, notAvailableString)
case scanFailedNumber:
fmt.Printf(tableResultsFormat, title, getCountValue(counts.Critical), counts.High, counts.Medium, counts.Low, counts.Info, scanFailedString)
case scanCanceledNumber:
fmt.Printf(tableResultsFormat, title, getCountValue(counts.Critical), counts.High, counts.Medium, counts.Low, counts.Info, scanCanceledString)
case scanPartialNumber:
fmt.Printf(tableResultsFormat, title, getCountValue(counts.Critical), counts.High, counts.Medium, counts.Low, counts.Info, scanPartialString)
default:
fmt.Printf(tableResultsFormat, title, getCountValue(counts.Critical), counts.High, counts.Medium, counts.Low, counts.Info, scanSuccessString)
}
}
func printSCSSummary(microEngineOverviews []*wrappers.MicroEngineOverview, featureFlagsWrapper wrappers.FeatureFlagsWrapper) {
fmt.Printf(" Supply Chain Security Results\n")
fmt.Printf(" -------------------------------------------------------------------------- \n")
fmt.Println(" | Critical High Medium Low Info Status |")
for _, microEngineOverview := range microEngineOverviews {
printSCSTableRow(microEngineOverview, featureFlagsWrapper)
}
fmt.Printf(" -------------------------------------------------------------------------- \n\n")
}
func printSCSTableRow(microEngineOverview *wrappers.MicroEngineOverview, featureFlagsWrapper wrappers.FeatureFlagsWrapper) {
formatString := " | %-20s %4v %4v %6v %4v %4v %-9s |\n"
notAvailableFormatString := " | %-20s %4v %4s %6s %4s %4s %5s |\n"
riskSummary := microEngineOverview.RiskSummary
microEngineName := microEngineOverview.FullName
switch microEngineOverview.Status {
case scsScanUnavailableString:
fmt.Printf(notAvailableFormatString, microEngineName, notAvailableString, notAvailableString, notAvailableString, notAvailableString, notAvailableString, notAvailableString)
default:
fmt.Printf(formatString, microEngineName, riskSummary[criticalLabel], riskSummary[highLabel], riskSummary[mediumLabel], riskSummary[lowLabel],
riskSummary[infoLabel], microEngineOverview.Status)
}
}
func getCountValue(count int) interface{} {
if count < 0 {
return disabledString
}
return count
}
func printResultsSummaryTable(summary *wrappers.ResultSummary) {
totalCriticalIssues := summary.EnginesResult.GetCriticalIssues()
totalHighIssues := summary.EnginesResult.GetHighIssues()
totalMediumIssues := summary.EnginesResult.GetMediumIssues()
totalLowIssues := summary.EnginesResult.GetLowIssues()
totalInfoIssues := summary.EnginesResult.GetInfoIssues()
fmt.Printf(tableLine + twoNewLines)
fmt.Printf(" Total Results: %d \n", summary.TotalIssues)
fmt.Println(tableLine)
fmt.Printf(TableTitleFormat, " ", "Critical", "High", "Medium", "Low", "Info", "Status")
printTableRow("APIs", summary.EnginesResult[commonParams.APISecType], summary.EnginesResult[commonParams.APISecType].StatusCode)
printTableRow("IAC", summary.EnginesResult[commonParams.KicsType], summary.EnginesResult[commonParams.KicsType].StatusCode)
printTableRow("SAST", summary.EnginesResult[commonParams.SastType], summary.EnginesResult[commonParams.SastType].StatusCode)
printTableRow("SCA", summary.EnginesResult[commonParams.ScaType], summary.EnginesResult[commonParams.ScaType].StatusCode)
if wrappers.IsSCSEnabled {
printTableRow("SCS", summary.EnginesResult[commonParams.ScsType], summary.EnginesResult[commonParams.ScsType].StatusCode)
}
if wrappers.IsContainersEnabled {
printTableRow("CONTAINERS", summary.EnginesResult[commonParams.ContainersType], summary.EnginesResult[commonParams.ContainersType].StatusCode)
}
fmt.Println(tableLine)
fmt.Printf(tableResultsFormat,
"TOTAL", getCountValue(totalCriticalIssues), totalHighIssues, totalMediumIssues, totalLowIssues, totalInfoIssues, summary.Status)
fmt.Printf(tableLine + twoNewLines)
}
func generateScanSummaryURL(summary *wrappers.ResultSummary) string {
summaryURL := fmt.Sprintf(
strings.Replace(summary.BaseURI, "overview", "scans?id=%s&branch=%s", 1),
summary.ScanID, url.QueryEscape(summary.BranchName),
)
return summaryURL
}
func runGetResultCommand(
resultsWrapper wrappers.ResultsWrapper,
scanWrapper wrappers.ScansWrapper,
exportWrapper wrappers.ExportWrapper,
resultsPdfReportsWrapper wrappers.ResultsPdfWrapper,
risksOverviewWrapper wrappers.RisksOverviewWrapper,
scsScanOverviewWrapper wrappers.ScanOverviewWrapper,
policyWrapper wrappers.PolicyWrapper,
featureFlagsWrapper wrappers.FeatureFlagsWrapper,
) func(cmd *cobra.Command, args []string) error {
return func(cmd *cobra.Command, args []string) error {
targetFile, _ := cmd.Flags().GetString(commonParams.TargetFlag)
targetPath, _ := cmd.Flags().GetString(commonParams.TargetPathFlag)
format, _ := cmd.Flags().GetString(commonParams.TargetFormatFlag)
formatPdfToEmail, _ := cmd.Flags().GetString(commonParams.ReportFormatPdfToEmailFlag)
formatPdfOptions, _ := cmd.Flags().GetString(commonParams.ReportFormatPdfOptionsFlag)
formatSbomOptions, _ := cmd.Flags().GetString(commonParams.ReportSbomFormatFlag)
sastRedundancy, _ := cmd.Flags().GetBool(commonParams.SastRedundancyFlag)
agent, _ := cmd.Flags().GetString(commonParams.AgentFlag)
scaHideDevAndTestDep, _ := cmd.Flags().GetBool(commonParams.ScaHideDevAndTestDepFlag)
ignorePolicy, _ := cmd.Flags().GetBool(commonParams.IgnorePolicyFlag)
waitDelay, _ := cmd.Flags().GetInt(commonParams.WaitDelayFlag)
policyTimeout, _ := cmd.Flags().GetInt(commonParams.PolicyTimeoutFlag)
scanID, _ := cmd.Flags().GetString(commonParams.ScanIDFlag)
if scanID == "" {
return errors.Errorf("%s: Please provide a scan ID", failedListingResults)
}
resultsParams, err := getFilters(cmd)
if err != nil {
return errors.Wrapf(err, "%s", failedListingResults)
}
if scaHideDevAndTestDep {
resultsParams[ScaExcludeResultTypesParam] = ScaDevAndTestExclusionParam
}
scan, errorModel, scanErr := scanWrapper.GetByID(scanID)
if scanErr != nil {
return errors.Wrapf(scanErr, "%s", failedGetting)
}
if errorModel != nil {
return errors.Errorf("%s: CODE: %d, %s", failedGettingScan, errorModel.Code, errorModel.Message)
}
var policyResponseModel *wrappers.PolicyResponseModel
if !isScanPending(string(scan.Status)) {
policyResponseModel, err = services.HandlePolicyEvaluation(cmd, policyWrapper, scan, ignorePolicy, agent, waitDelay, policyTimeout)
if err != nil {
return err
}
} else {
logger.PrintIfVerbose("Policy violations aren't returned in the pipeline for scans run in async mode.")
}
if sastRedundancy {
resultsParams[commonParams.SastRedundancyFlag] = ""