github.com/devseccon/trivy@v0.47.1-0.20231123133102-bd902a0bd996/pkg/fanal/external/config_scan.go (about) 1 package external 2 3 import ( 4 "context" 5 "errors" 6 7 "github.com/devseccon/trivy/pkg/fanal/analyzer" 8 "github.com/devseccon/trivy/pkg/fanal/applier" 9 "github.com/devseccon/trivy/pkg/fanal/artifact" 10 "github.com/devseccon/trivy/pkg/fanal/artifact/local" 11 "github.com/devseccon/trivy/pkg/fanal/cache" 12 "github.com/devseccon/trivy/pkg/fanal/types" 13 "github.com/devseccon/trivy/pkg/misconf" 14 15 _ "github.com/devseccon/trivy/pkg/fanal/analyzer/config/all" 16 ) 17 18 type ConfigScanner struct { 19 cache cache.FSCache 20 policyPaths []string 21 dataPaths []string 22 namespaces []string 23 allowEmbedded bool 24 } 25 26 func NewConfigScanner(cacheDir string, policyPaths, dataPaths, namespaces []string, allowEmbedded bool) (*ConfigScanner, error) { 27 // Initialize local cache 28 cacheClient, err := cache.NewFSCache(cacheDir) 29 if err != nil { 30 return nil, err 31 } 32 33 return &ConfigScanner{ 34 cache: cacheClient, 35 policyPaths: policyPaths, 36 dataPaths: dataPaths, 37 namespaces: namespaces, 38 allowEmbedded: allowEmbedded, 39 }, nil 40 } 41 42 func (s ConfigScanner) Scan(dir string) ([]types.Misconfiguration, error) { 43 art, err := local.NewArtifact(dir, s.cache, artifact.Option{ 44 MisconfScannerOption: misconf.ScannerOption{ 45 PolicyPaths: s.policyPaths, 46 DataPaths: s.dataPaths, 47 Namespaces: s.namespaces, 48 DisableEmbeddedPolicies: !s.allowEmbedded, 49 DisableEmbeddedLibraries: !s.allowEmbedded, 50 }, 51 }) 52 if err != nil { 53 return nil, err 54 } 55 56 // Scan config files 57 result, err := art.Inspect(context.Background()) 58 if err != nil { 59 return nil, err 60 } 61 62 // Merge layers 63 a := applier.NewApplier(s.cache) 64 mergedLayer, err := a.ApplyLayers(result.ID, result.BlobIDs) 65 if !errors.Is(err, analyzer.ErrUnknownOS) && !errors.Is(err, analyzer.ErrNoPkgsDetected) { 66 return nil, err 67 } 68 69 // Do not assert successes and layer 70 for i := range mergedLayer.Misconfigurations { 71 mergedLayer.Misconfigurations[i].Layer = types.Layer{} 72 } 73 74 return mergedLayer.Misconfigurations, nil 75 } 76 77 func (s ConfigScanner) Close() error { 78 return s.cache.Close() 79 }