diff --git a/pkg/fanal/analyzer/pkg/dpkg/dpkg.go b/pkg/fanal/analyzer/pkg/dpkg/dpkg.go index d73c905fd413..a83592e82523 100644 --- a/pkg/fanal/analyzer/pkg/dpkg/dpkg.go +++ b/pkg/fanal/analyzer/pkg/dpkg/dpkg.go @@ -115,31 +115,42 @@ func (a dpkgAnalyzer) PostAnalyze(_ context.Context, input analyzer.PostAnalysis // parseDpkgInfoList parses /var/lib/dpkg/info/*.list func (a dpkgAnalyzer) parseDpkgInfoList(scanner *bufio.Scanner) ([]string, error) { - var installedFiles []string - var previous string + var ( + allLines []string + installedFiles []string + previous string + ) + for scanner.Scan() { current := scanner.Text() if current == "/." { continue } + allLines = append(allLines, current) + } + + if err := scanner.Err(); err != nil { + return nil, xerrors.Errorf("scan error: %w", err) + } - // Add the file if it is not directory. - // e.g. - // /usr/sbin - // /usr/sbin/tarcat - // - // In the above case, we should take only /usr/sbin/tarcat since /usr/sbin is a directory + // Add the file if it is not directory. + // e.g. + // /usr/sbin + // /usr/sbin/tarcat + // + // In the above case, we should take only /usr/sbin/tarcat since /usr/sbin is a directory + // sort first,see here:https://github.com/aquasecurity/trivy/discussions/6543 + sort.Strings(allLines) + for _, current := range allLines { if !strings.HasPrefix(current, previous+"/") { installedFiles = append(installedFiles, previous) } previous = current } - // Add the last file - installedFiles = append(installedFiles, previous) - - if err := scanner.Err(); err != nil { - return nil, xerrors.Errorf("scan error: %w", err) + // // Add the last file + if previous != "" && !strings.HasSuffix(previous, "/") { + installedFiles = append(installedFiles, previous) } return installedFiles, nil diff --git a/pkg/fanal/analyzer/pkg/dpkg/dpkg_test.go b/pkg/fanal/analyzer/pkg/dpkg/dpkg_test.go index 4dc627823200..c131b900d899 100644 --- a/pkg/fanal/analyzer/pkg/dpkg/dpkg_test.go +++ b/pkg/fanal/analyzer/pkg/dpkg/dpkg_test.go @@ -1423,7 +1423,7 @@ func Test_dpkgAnalyzer_Analyze(t *testing.T) { want: &analyzer.AnalysisResult{ SystemInstalledFiles: []string{ "/bin/tar", - "/etc", + "/etc/rmt", "/usr/lib/mime/packages/tar", "/usr/sbin/rmt-tar", "/usr/sbin/tarcat", @@ -1436,7 +1436,6 @@ func Test_dpkgAnalyzer_Analyze(t *testing.T) { "/usr/share/man/man1/tar.1.gz", "/usr/share/man/man1/tarcat.1.gz", "/usr/share/man/man8/rmt-tar.8.gz", - "/etc/rmt", }, }, },