-
Notifications
You must be signed in to change notification settings - Fork 308
/
analyzer.go
772 lines (708 loc) · 23.5 KB
/
analyzer.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
package analyzer
import (
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"sync"
"github.com/Checkmarx/kics/v2/internal/metrics"
"github.com/Checkmarx/kics/v2/pkg/engine/provider"
"github.com/Checkmarx/kics/v2/pkg/model"
"github.com/Checkmarx/kics/v2/pkg/utils"
"github.com/pkg/errors"
"github.com/rs/zerolog/log"
ignore "github.com/sabhiram/go-gitignore"
yamlParser "gopkg.in/yaml.v3"
)
// move the openApi regex to public to be used on file.go
// openAPIRegex - Regex that finds OpenAPI defining property "openapi" or "swagger"
// openAPIRegexInfo - Regex that finds OpenAPI defining property "info"
// openAPIRegexPath - Regex that finds OpenAPI defining property "paths", "components", or "webhooks" (from 3.1.0)
// cloudRegex - Regex that finds CloudFormation defining property "Resources"
// k8sRegex - Regex that finds Kubernetes defining property "apiVersion"
// k8sRegexKind - Regex that finds Kubernetes defining property "kind"
// k8sRegexMetadata - Regex that finds Kubernetes defining property "metadata"
// k8sRegexSpec - Regex that finds Kubernetes defining property "spec"
var (
OpenAPIRegex = regexp.MustCompile(`("(openapi|swagger)"|(openapi|swagger))\s*:`)
OpenAPIRegexInfo = regexp.MustCompile(`("info"|info)\s*:`)
OpenAPIRegexPath = regexp.MustCompile(`("(paths|components|webhooks)"|(paths|components|webhooks))\s*:`)
armRegexContentVersion = regexp.MustCompile(`"contentVersion"\s*:`)
armRegexResources = regexp.MustCompile(`"resources"\s*:`)
cloudRegex = regexp.MustCompile(`("Resources"|Resources)\s*:`)
k8sRegex = regexp.MustCompile(`("apiVersion"|apiVersion)\s*:`)
k8sRegexKind = regexp.MustCompile(`("kind"|kind)\s*:`)
tfPlanRegexPV = regexp.MustCompile(`"planned_values"\s*:`)
tfPlanRegexRC = regexp.MustCompile(`"resource_changes"\s*:`)
tfPlanRegexConf = regexp.MustCompile(`"configuration"\s*:`)
tfPlanRegexTV = regexp.MustCompile(`"terraform_version"\s*:`)
cdkTfRegexMetadata = regexp.MustCompile(`"metadata"\s*:`)
cdkTfRegexStackName = regexp.MustCompile(`"stackName"\s*:`)
cdkTfRegexTerraform = regexp.MustCompile(`"terraform"\s*:`)
artifactsRegexKind = regexp.MustCompile(`("kind"|kind)\s*:`)
artifactsRegexProperties = regexp.MustCompile(`("properties"|properties)\s*:`)
artifactsRegexParametes = regexp.MustCompile(`("parameters"|parameters)\s*:`)
policyAssignmentArtifactRegexPolicyDefinitionID = regexp.MustCompile(`("policyDefinitionId"|policyDefinitionId)\s*:`)
roleAssignmentArtifactRegexPrincipalIds = regexp.MustCompile(`("principalIds"|principalIds)\s*:`)
roleAssignmentArtifactRegexRoleDefinitionID = regexp.MustCompile(`("roleDefinitionId"|roleDefinitionId)\s*:`)
templateArtifactRegexParametes = regexp.MustCompile(`("template"|template)\s*:`)
blueprintpRegexTargetScope = regexp.MustCompile(`("targetScope"|targetScope)\s*:`)
blueprintpRegexProperties = regexp.MustCompile(`("properties"|properties)\s*:`)
buildahRegex = regexp.MustCompile(`buildah\s*from\s*\w+`)
dockerComposeServicesRegex = regexp.MustCompile(`services\s*:[\w\W]+(image|build)\s*:`)
crossPlaneRegex = regexp.MustCompile(`"?apiVersion"?\s*:\s*(\w+\.)+crossplane\.io/v\w+\s*`)
knativeRegex = regexp.MustCompile(`"?apiVersion"?\s*:\s*(\w+\.)+knative\.dev/v\w+\s*`)
pulumiNameRegex = regexp.MustCompile(`name\s*:`)
pulumiRuntimeRegex = regexp.MustCompile(`runtime\s*:`)
pulumiResourcesRegex = regexp.MustCompile(`resources\s*:`)
serverlessServiceRegex = regexp.MustCompile(`service\s*:`)
serverlessProviderRegex = regexp.MustCompile(`(^|\n)provider\s*:`)
cicdOnRegex = regexp.MustCompile(`\s*on:\s*`)
cicdJobsRegex = regexp.MustCompile(`\s*jobs:\s*`)
cicdStepsRegex = regexp.MustCompile(`\s*steps:\s*`)
queryRegexPathsAnsible = regexp.MustCompile(fmt.Sprintf(`^.*?%s(?:group|host)_vars%s.*$`, regexp.QuoteMeta(string(os.PathSeparator)), regexp.QuoteMeta(string(os.PathSeparator)))) //nolint:lll
)
var (
listKeywordsGoogleDeployment = []string{"resources"}
armRegexTypes = []string{"blueprint", "templateArtifact", "roleAssignmentArtifact", "policyAssignmentArtifact"}
possibleFileTypes = map[string]bool{
".yml": true,
".yaml": true,
".json": true,
".dockerfile": true,
"Dockerfile": true,
"possibleDockerfile": true,
".debian": true,
".ubi8": true,
".tf": true,
"tfvars": true,
".proto": true,
".sh": true,
".cfg": true,
".conf": true,
".ini": true,
".bicep": true,
}
supportedRegexes = map[string][]string{
"azureresourcemanager": append(armRegexTypes, arm),
"buildah": {"buildah"},
"cicd": {"cicd"},
"cloudformation": {"cloudformation"},
"crossplane": {"crossplane"},
"dockercompose": {"dockercompose"},
"knative": {"knative"},
"kubernetes": {"kubernetes"},
"openapi": {"openapi"},
"terraform": {"terraform", "cdkTf"},
"pulumi": {"pulumi"},
"serverlessfw": {"serverlessfw"},
}
listKeywordsAnsible = []string{"name", "gather_facts",
"hosts", "tasks", "become", "with_items", "with_dict",
"when", "become_pass", "become_exe", "become_flags"}
playBooks = "playbooks"
ansibleHost = []string{"all", "ungrouped"}
listKeywordsAnsibleHots = []string{"hosts", "children"}
)
const (
yml = ".yml"
yaml = ".yaml"
json = ".json"
sh = ".sh"
arm = "azureresourcemanager"
bicep = "bicep"
kubernetes = "kubernetes"
terraform = "terraform"
gdm = "googledeploymentmanager"
ansible = "ansible"
grpc = "grpc"
dockerfile = "dockerfile"
crossplane = "crossplane"
knative = "knative"
sizeMb = 1048576
)
type Parameters struct {
Results string
Path []string
MaxFileSize int
}
// regexSlice is a struct to contain a slice of regex
type regexSlice struct {
regex []*regexp.Regexp
}
type analyzerInfo struct {
typesFlag []string
excludeTypesFlag []string
filePath string
}
// Analyzer keeps all the relevant info for the function Analyze
type Analyzer struct {
Paths []string
Types []string
ExcludeTypes []string
Exc []string
GitIgnoreFileName string
ExcludeGitIgnore bool
MaxFileSize int
}
// types is a map that contains the regex by type
var types = map[string]regexSlice{
"openapi": {
regex: []*regexp.Regexp{
OpenAPIRegex,
OpenAPIRegexInfo,
OpenAPIRegexPath,
},
},
"kubernetes": {
regex: []*regexp.Regexp{
k8sRegex,
k8sRegexKind,
},
},
"crossplane": {
regex: []*regexp.Regexp{
crossPlaneRegex,
k8sRegexKind,
},
},
"knative": {
regex: []*regexp.Regexp{
knativeRegex,
k8sRegexKind,
},
},
"cloudformation": {
regex: []*regexp.Regexp{
cloudRegex,
},
},
"azureresourcemanager": {
[]*regexp.Regexp{
armRegexContentVersion,
armRegexResources,
},
},
"terraform": {
[]*regexp.Regexp{
tfPlanRegexConf,
tfPlanRegexPV,
tfPlanRegexRC,
tfPlanRegexTV,
},
},
"cdkTf": {
[]*regexp.Regexp{
cdkTfRegexMetadata,
cdkTfRegexStackName,
cdkTfRegexTerraform,
},
},
"policyAssignmentArtifact": {
[]*regexp.Regexp{
artifactsRegexKind,
artifactsRegexProperties,
artifactsRegexParametes,
policyAssignmentArtifactRegexPolicyDefinitionID,
},
},
"roleAssignmentArtifact": {
[]*regexp.Regexp{
artifactsRegexKind,
artifactsRegexProperties,
roleAssignmentArtifactRegexPrincipalIds,
roleAssignmentArtifactRegexRoleDefinitionID,
},
},
"templateArtifact": {
[]*regexp.Regexp{
artifactsRegexKind,
artifactsRegexProperties,
artifactsRegexParametes,
templateArtifactRegexParametes,
},
},
"blueprint": {
[]*regexp.Regexp{
blueprintpRegexTargetScope,
blueprintpRegexProperties,
},
},
"buildah": {
[]*regexp.Regexp{
buildahRegex,
},
},
"dockercompose": {
[]*regexp.Regexp{
dockerComposeServicesRegex,
},
},
"pulumi": {
[]*regexp.Regexp{
pulumiNameRegex,
pulumiRuntimeRegex,
pulumiResourcesRegex,
},
},
"serverlessfw": {
[]*regexp.Regexp{
serverlessServiceRegex,
serverlessProviderRegex,
},
},
"cicd": {
[]*regexp.Regexp{
cicdOnRegex,
cicdJobsRegex,
cicdStepsRegex,
},
},
}
var defaultConfigFiles = []string{"pnpm-lock.yaml"}
// Analyze will go through the slice paths given and determine what type of queries should be loaded
// should be loaded based on the extension of the file and the content
func Analyze(a *Analyzer) (model.AnalyzedPaths, error) {
// start metrics for file analyzer
metrics.Metric.Start("file_type_analyzer")
returnAnalyzedPaths := model.AnalyzedPaths{
Types: make([]string, 0),
Exc: make([]string, 0),
ExpectedLOC: 0,
}
var files []string
var wg sync.WaitGroup
// results is the channel shared by the workers that contains the types found
results := make(chan string)
locCount := make(chan int)
ignoreFiles := make([]string, 0)
projectConfigFiles := make([]string, 0)
done := make(chan bool)
hasGitIgnoreFile, gitIgnore := shouldConsiderGitIgnoreFile(a.Paths[0], a.GitIgnoreFileName, a.ExcludeGitIgnore)
// get all the files inside the given paths
for _, path := range a.Paths {
if _, err := os.Stat(path); err != nil {
return returnAnalyzedPaths, errors.Wrap(err, "failed to analyze path")
}
if err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}
ext, errExt := utils.GetExtension(path)
if errExt == nil {
trimmedPath := strings.ReplaceAll(path, a.Paths[0], filepath.Base(a.Paths[0]))
ignoreFiles = a.checkIgnore(info.Size(), hasGitIgnoreFile, gitIgnore, path, trimmedPath, ignoreFiles)
if isConfigFile(path, defaultConfigFiles) {
projectConfigFiles = append(projectConfigFiles, path)
a.Exc = append(a.Exc, path)
}
if _, ok := possibleFileTypes[ext]; ok && !isExcludedFile(path, a.Exc) {
files = append(files, path)
}
}
return nil
}); err != nil {
log.Error().Msgf("failed to analyze path %s: %s", path, err)
}
}
// unwanted is the channel shared by the workers that contains the unwanted files that the parser will ignore
unwanted := make(chan string, len(files))
a.Types, a.ExcludeTypes = typeLower(a.Types, a.ExcludeTypes)
// Start the workers
for _, file := range files {
wg.Add(1)
// analyze the files concurrently
a := &analyzerInfo{
typesFlag: a.Types,
excludeTypesFlag: a.ExcludeTypes,
filePath: file,
}
go a.worker(results, unwanted, locCount, &wg)
}
go func() {
// close channel results when the worker has finished writing into it
defer func() {
close(unwanted)
close(results)
close(locCount)
}()
wg.Wait()
done <- true
}()
availableTypes, unwantedPaths, loc := computeValues(results, unwanted, locCount, done)
multiPlatformTypeCheck(&availableTypes)
unwantedPaths = append(unwantedPaths, ignoreFiles...)
unwantedPaths = append(unwantedPaths, projectConfigFiles...)
returnAnalyzedPaths.Types = availableTypes
returnAnalyzedPaths.Exc = unwantedPaths
returnAnalyzedPaths.ExpectedLOC = loc
// stop metrics for file analyzer
metrics.Metric.Stop()
return returnAnalyzedPaths, nil
}
// worker determines the type of the file by ext (dockerfile and terraform)/content and
// writes the answer to the results channel
// if no types were found, the worker will write the path of the file in the unwanted channel
func (a *analyzerInfo) worker(results, unwanted chan<- string, locCount chan<- int, wg *sync.WaitGroup) { //nolint: gocyclo
defer wg.Done()
ext, errExt := utils.GetExtension(a.filePath)
if errExt == nil {
linesCount, _ := utils.LineCounter(a.filePath)
switch ext {
// Dockerfile (direct identification)
case ".dockerfile", "Dockerfile":
if a.isAvailableType(dockerfile) {
results <- dockerfile
locCount <- linesCount
}
// Dockerfile (indirect identification)
case "possibleDockerfile", ".ubi8", ".debian":
if a.isAvailableType(dockerfile) && isDockerfile(a.filePath) {
results <- dockerfile
locCount <- linesCount
} else {
unwanted <- a.filePath
}
// Terraform
case ".tf", "tfvars":
if a.isAvailableType(terraform) {
results <- terraform
locCount <- linesCount
}
// Bicep
case ".bicep":
if a.isAvailableType(bicep) {
results <- bicep
locCount <- linesCount
}
// GRPC
case ".proto":
if a.isAvailableType(grpc) {
results <- grpc
locCount <- linesCount
}
// It could be Ansible Config or Ansible Inventory
case ".cfg", ".conf", ".ini":
if a.isAvailableType(ansible) {
results <- ansible
locCount <- linesCount
}
/* It could be Ansible, Buildah, CICD, CloudFormation, Crossplane, OpenAPI, Azure Resource Manager
Docker Compose, Knative, Kubernetes, Pulumi, ServerlessFW or Google Deployment Manager*/
case yaml, yml, json, sh:
a.checkContent(results, unwanted, locCount, linesCount, ext)
}
}
}
func isDockerfile(path string) bool {
content, err := os.ReadFile(filepath.Clean(path))
if err != nil {
log.Error().Msgf("failed to analyze file: %s", err)
return false
}
regexes := []*regexp.Regexp{
regexp.MustCompile(`\s*FROM\s*`),
regexp.MustCompile(`\s*RUN\s*`),
}
check := true
for _, regex := range regexes {
if !regex.Match(content) {
check = false
break
}
}
return check
}
// overrides k8s match when all regexs passes for azureresourcemanager key and extension is set to json
func needsOverride(check bool, returnType, key, ext string) bool {
if check && returnType == kubernetes && key == arm && ext == json {
return true
} else if check && returnType == kubernetes && (key == knative || key == crossplane) && (ext == yaml || ext == yml) {
return true
}
return false
}
// checkContent will determine the file type by content when worker was unable to
// determine by ext, if no type was determined checkContent adds it to unwanted channel
func (a *analyzerInfo) checkContent(results, unwanted chan<- string, locCount chan<- int, linesCount int, ext string) {
typesFlag := a.typesFlag
excludeTypesFlag := a.excludeTypesFlag
// get file content
content, err := os.ReadFile(a.filePath)
if err != nil {
log.Error().Msgf("failed to analyze file: %s", err)
return
}
returnType := ""
// Sort map so that CloudFormation (type that as less requireds) goes last
keys := make([]string, 0, len(types))
for k := range types {
keys = append(keys, k)
}
if typesFlag[0] != "" {
keys = getKeysFromTypesFlag(typesFlag)
} else if excludeTypesFlag[0] != "" {
keys = getKeysFromExcludeTypesFlag(excludeTypesFlag)
}
sort.Sort(sort.Reverse(sort.StringSlice(keys)))
for _, key := range keys {
check := true
for _, typeRegex := range types[key].regex {
if !typeRegex.Match(content) {
check = false
break
}
}
// If all regexs passed and there wasn't a type already assigned
if check && returnType == "" {
returnType = key
} else if needsOverride(check, returnType, key, ext) {
returnType = key
}
}
returnType = checkReturnType(a.filePath, returnType, ext, content)
if returnType != "" {
if a.isAvailableType(returnType) {
results <- returnType
locCount <- linesCount
return
}
}
// No type was determined (ignore on parser)
unwanted <- a.filePath
}
func checkReturnType(path, returnType, ext string, content []byte) string {
if returnType != "" {
if returnType == "cdkTf" {
return terraform
}
if utils.Contains(returnType, armRegexTypes) {
return arm
}
} else if ext == yaml || ext == yml {
if checkHelm(path) {
return kubernetes
}
platform := checkYamlPlatform(content, path)
if platform != "" {
return platform
}
}
return returnType
}
func checkHelm(path string) bool {
_, err := os.Stat(filepath.Join(filepath.Dir(path), "Chart.yaml"))
if errors.Is(err, os.ErrNotExist) {
return false
} else if err != nil {
log.Error().Msgf("failed to check helm: %s", err)
}
return true
}
func checkYamlPlatform(content []byte, path string) string {
content = utils.DecryptAnsibleVault(content, os.Getenv("ANSIBLE_VAULT_PASSWORD_FILE"))
var yamlContent model.Document
if err := yamlParser.Unmarshal(content, &yamlContent); err != nil {
log.Warn().Msgf("failed to parse yaml file (%s): %s", path, err)
}
// check if it is google deployment manager platform
for _, keyword := range listKeywordsGoogleDeployment {
if _, ok := yamlContent[keyword]; ok {
return gdm
}
}
// check if the file contains some keywords related with Ansible
if checkForAnsible(yamlContent) {
return ansible
}
// check if the file contains some keywords related with Ansible Host
if checkForAnsibleHost(yamlContent) {
return ansible
}
// add for yaml files contained at paths (group_vars, host_vars) related with ansible
if checkForAnsibleByPaths(path) {
return ansible
}
return ""
}
func checkForAnsibleByPaths(path string) bool {
return queryRegexPathsAnsible.MatchString(path)
}
func checkForAnsible(yamlContent model.Document) bool {
isAnsible := false
if play := yamlContent[playBooks]; play != nil {
if listOfPlayBooks, ok := play.([]interface{}); ok {
for _, value := range listOfPlayBooks {
castingValue, ok := value.(map[string]interface{})
if ok {
for _, keyword := range listKeywordsAnsible {
if _, ok := castingValue[keyword]; ok {
isAnsible = true
}
}
}
}
}
}
return isAnsible
}
func checkForAnsibleHost(yamlContent model.Document) bool {
isAnsible := false
for _, ansibleDefault := range ansibleHost {
if hosts := yamlContent[ansibleDefault]; hosts != nil {
if listHosts, ok := hosts.(map[string]interface{}); ok {
for _, value := range listKeywordsAnsibleHots {
if host := listHosts[value]; host != nil {
isAnsible = true
}
}
}
}
}
return isAnsible
}
// computeValues computes expected Lines of Code to be scanned from locCount channel
// and creates the types and unwanted slices from the channels removing any duplicates
func computeValues(types, unwanted chan string, locCount chan int, done chan bool) (typesS, unwantedS []string, locTotal int) {
var val int
unwantedSlice := make([]string, 0)
typeSlice := make([]string, 0)
for {
select {
case i := <-locCount:
val += i
case i := <-unwanted:
if !utils.Contains(i, unwantedSlice) {
unwantedSlice = append(unwantedSlice, i)
}
case i := <-types:
if !utils.Contains(i, typeSlice) {
typeSlice = append(typeSlice, i)
}
case <-done:
return typeSlice, unwantedSlice, val
}
}
}
// getKeysFromTypesFlag gets all the regexes keys related to the types flag
func getKeysFromTypesFlag(typesFlag []string) []string {
ks := make([]string, 0, len(types))
for i := range typesFlag {
t := typesFlag[i]
if regexes, ok := supportedRegexes[t]; ok {
ks = append(ks, regexes...)
}
}
return ks
}
// getKeysFromExcludeTypesFlag gets all the regexes keys related to the excluding unwanted types from flag
func getKeysFromExcludeTypesFlag(excludeTypesFlag []string) []string {
ks := make([]string, 0, len(types))
for k := range supportedRegexes {
if !utils.Contains(k, excludeTypesFlag) {
if regexes, ok := supportedRegexes[k]; ok {
ks = append(ks, regexes...)
}
}
}
return ks
}
// isExcludedFile verifies if the path is pointed in the --exclude-paths flag
func isExcludedFile(path string, exc []string) bool {
for i := range exc {
exclude, err := provider.GetExcludePaths(exc[i])
if err != nil {
log.Err(err).Msg("failed to get exclude paths")
}
for j := range exclude {
if exclude[j] == path {
log.Info().Msgf("Excluded file %s from analyzer", path)
return true
}
}
}
return false
}
func isDeadSymlink(path string) bool {
fileInfo, _ := os.Stat(path)
return fileInfo == nil
}
func isConfigFile(path string, exc []string) bool {
for i := range exc {
exclude, err := provider.GetExcludePaths(exc[i])
if err != nil {
log.Err(err).Msg("failed to get exclude paths")
}
for j := range exclude {
fileInfo, _ := os.Stat(path)
if fileInfo != nil && fileInfo.IsDir() {
continue
}
if len(path)-len(exclude[j]) > 0 && path[len(path)-len(exclude[j]):] == exclude[j] && exclude[j] != "" {
log.Info().Msgf("Excluded file %s from analyzer", path)
return true
}
}
}
return false
}
// shouldConsiderGitIgnoreFile verifies if the scan should exclude the files according to the .gitignore file
func shouldConsiderGitIgnoreFile(path, gitIgnore string, excludeGitIgnoreFile bool) (hasGitIgnoreFileRes bool,
gitIgnoreRes *ignore.GitIgnore) {
gitIgnorePath := filepath.ToSlash(filepath.Join(path, gitIgnore))
_, err := os.Stat(gitIgnorePath)
if !excludeGitIgnoreFile && err == nil && gitIgnore != "" {
gitIgnore, _ := ignore.CompileIgnoreFile(gitIgnorePath)
if gitIgnore != nil {
log.Info().Msgf(".gitignore file was found in '%s' and it will be used to automatically exclude paths", path)
return true, gitIgnore
}
}
return false, nil
}
func multiPlatformTypeCheck(typesSelected *[]string) {
if utils.Contains("serverlessfw", *typesSelected) && !utils.Contains("cloudformation", *typesSelected) {
*typesSelected = append(*typesSelected, "cloudformation")
}
if utils.Contains("knative", *typesSelected) && !utils.Contains("kubernetes", *typesSelected) {
*typesSelected = append(*typesSelected, "kubernetes")
}
}
func (a *analyzerInfo) isAvailableType(typeName string) bool {
// no flag is set
if len(a.typesFlag) == 1 && a.typesFlag[0] == "" && len(a.excludeTypesFlag) == 1 && a.excludeTypesFlag[0] == "" {
return true
} else if len(a.typesFlag) > 1 || a.typesFlag[0] != "" {
// type flag is set
return utils.Contains(typeName, a.typesFlag)
} else if len(a.excludeTypesFlag) > 1 || a.excludeTypesFlag[0] != "" {
// exclude type flag is set
return !utils.Contains(typeName, a.excludeTypesFlag)
}
// no valid behavior detected
return false
}
func (a *Analyzer) checkIgnore(fileSize int64, hasGitIgnoreFile bool,
gitIgnore *ignore.GitIgnore,
fullPath string, trimmedPath string, ignoreFiles []string) []string {
exceededFileSize := a.MaxFileSize >= 0 && float64(fileSize)/float64(sizeMb) > float64(a.MaxFileSize)
if (hasGitIgnoreFile && gitIgnore.MatchesPath(trimmedPath)) || isDeadSymlink(fullPath) || exceededFileSize {
ignoreFiles = append(ignoreFiles, fullPath)
a.Exc = append(a.Exc, fullPath)
if exceededFileSize {
log.Error().Msgf("file %s exceeds maximum file size of %d Mb", fullPath, a.MaxFileSize)
}
}
return ignoreFiles
}
func typeLower(types, exclTypes []string) (typesRes, exclTypesRes []string) {
for i := range types {
types[i] = strings.ToLower(types[i])
}
for i := range exclTypes {
exclTypes[i] = strings.ToLower(exclTypes[i])
}
return types, exclTypes
}