-
Notifications
You must be signed in to change notification settings - Fork 0
/
dpkg.go
313 lines (268 loc) · 7.67 KB
/
dpkg.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
package dpkg
import (
"bufio"
"context"
"fmt"
"os"
"path/filepath"
"regexp"
"sort"
"strings"
"github.com/aquasecurity/trivy/pkg/fanal/analyzer"
"github.com/aquasecurity/trivy/pkg/fanal/types"
"github.com/aquasecurity/trivy/pkg/log"
"github.com/castai/image-analyzer/pathutil"
debVersion "github.com/knqyf263/go-deb-version"
"github.com/samber/lo"
"golang.org/x/xerrors"
)
func init() {
analyzer.RegisterAnalyzer(&dpkgAnalyzer{})
}
const (
analyzerVersion = 3
statusFile = "var/lib/dpkg/status"
statusDir = "var/lib/dpkg/status.d/"
infoDir = "var/lib/dpkg/info/"
)
var (
dpkgSrcCaptureRegexp = regexp.MustCompile(`Source: (?P<name>[^\s]*)( \((?P<version>.*)\))?`)
dpkgSrcCaptureRegexpNames = dpkgSrcCaptureRegexp.SubexpNames()
)
type dpkgAnalyzer struct{}
func (a dpkgAnalyzer) Analyze(ctx context.Context, input analyzer.AnalysisInput) (*analyzer.AnalysisResult, error) {
scanner := bufio.NewScanner(input.Content)
path, filename := filepath.Split(input.FilePath)
if a.isListFile(path, filename) {
installedFiles, err := a.parseDpkgInfoList(scanner)
if err != nil {
return nil, err
}
result := &analyzer.AnalysisResult{
SystemInstalledFiles: installedFiles,
}
binaries := lo.Filter(lo.Map(installedFiles, func(item string, index int) string {
return pathutil.CleanPath(item)
}), pathutil.BinariesPathFilter)
if len(binaries) > 0 {
name, _ := pathutil.Split(filename, '.')
pkgName, _ := pathutil.Split(name, ':')
result.CustomResources = []types.CustomResource{
{
Type: pathutil.TypeInstalledBinaries,
FilePath: input.FilePath,
Data: map[string][]string{pkgName: binaries},
},
}
}
return result, nil
}
return a.parseDpkgStatus(ctx, input.FilePath, scanner)
}
func (a dpkgAnalyzer) parseDpkgInfoList(scanner *bufio.Scanner) ([]string, error) {
var installedFiles []string
var previous string
for scanner.Scan() {
current := scanner.Text()
if current == "/." {
continue
}
// 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
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)
}
return installedFiles, nil
}
// parseDpkgStatus parses /var/lib/dpkg/status or /var/lib/dpkg/status/*
func (a dpkgAnalyzer) parseDpkgStatus(ctx context.Context, filePath string, scanner *bufio.Scanner) (*analyzer.AnalysisResult, error) {
var pkg *types.Package
pkgs := map[string]*types.Package{}
pkgIDs := map[string]string{}
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if line == "" {
continue
}
pkg = a.parseDpkgPkg(ctx, scanner)
if pkg != nil {
pkgs[pkg.ID] = pkg
pkgIDs[pkg.Name] = pkg.ID
}
}
if err := scanner.Err(); err != nil {
return nil, xerrors.Errorf("scan error: %w", err)
}
a.consolidateDependencies(pkgs, pkgIDs)
return &analyzer.AnalysisResult{
PackageInfos: []types.PackageInfo{
{
FilePath: filePath,
Packages: lo.MapToSlice(pkgs, func(_ string, p *types.Package) types.Package {
return *p
}),
},
},
}, nil
}
func (a dpkgAnalyzer) parseDpkgPkg(ctx context.Context, scanner *bufio.Scanner) (pkg *types.Package) {
var (
name string
version string
sourceName string
dependencies []string
isInstalled bool
sourceVersion string
maintainer string
)
isInstalled = true
for {
line := strings.TrimSpace(scanner.Text())
if line == "" {
break
}
switch {
case strings.HasPrefix(line, "Package: "):
name = strings.TrimSpace(strings.TrimPrefix(line, "Package: "))
case strings.HasPrefix(line, "Source: "):
// Source line (Optional)
// Gives the name of the source package
// May also specifies a version
srcCapture := dpkgSrcCaptureRegexp.FindAllStringSubmatch(line, -1)[0]
md := map[string]string{}
for i, n := range srcCapture {
md[dpkgSrcCaptureRegexpNames[i]] = strings.TrimSpace(n)
}
sourceName = md["name"]
if md["version"] != "" {
sourceVersion = md["version"]
}
case strings.HasPrefix(line, "Version: "):
version = strings.TrimPrefix(line, "Version: ")
case strings.HasPrefix(line, "Status: "):
isInstalled = a.parseStatus(line)
case strings.HasPrefix(line, "Depends: "):
dependencies = a.parseDepends(line)
case strings.HasPrefix(line, "Maintainer: "):
maintainer = strings.TrimSpace(strings.TrimPrefix(line, "Maintainer: "))
}
if !scanner.Scan() {
break
}
}
if name == "" || version == "" || !isInstalled {
return nil
} else if !debVersion.Valid(version) {
log.WarnContext(ctx, "Invalid Version Found : OS %s, Package %s, Version %s", "debian", name, version)
return nil
}
pkg = &types.Package{
ID: a.pkgID(name, version),
Name: name,
Version: version,
DependsOn: dependencies, // Will be consolidated later
Maintainer: maintainer,
}
// Source version and names are computed from binary package names and versions
// in dpkg.
// Source package name:
// https://git.dpkg.org/cgit/dpkg/dpkg.git/tree/lib/dpkg/pkg-format.c#n338
// Source package version:
// https://git.dpkg.org/cgit/dpkg/dpkg.git/tree/lib/dpkg/pkg-format.c#n355
if sourceName == "" {
sourceName = name
}
if sourceVersion == "" {
sourceVersion = version
}
if !debVersion.Valid(sourceVersion) {
log.WarnContext(ctx, "Invalid Version Found : OS %s, Package %s, Version %s", "debian", sourceName, sourceVersion)
return pkg
}
pkg.SrcName = sourceName
pkg.SrcVersion = sourceVersion
return pkg
}
func (a dpkgAnalyzer) Required(filePath string, _ os.FileInfo) bool {
dir, fileName := filepath.Split(filePath)
if a.isListFile(dir, fileName) || filePath == statusFile {
return true
}
if dir == statusDir {
return true
}
return false
}
func (a dpkgAnalyzer) pkgID(name, version string) string {
return fmt.Sprintf("%s@%s", name, version)
}
func (a dpkgAnalyzer) parseStatus(line string) bool {
for _, ss := range strings.Fields(strings.TrimPrefix(line, "Status: ")) {
if ss == "deinstall" || ss == "purge" {
return false
}
}
return true
}
func (a dpkgAnalyzer) parseDepends(line string) []string {
line = strings.TrimPrefix(line, "Depends: ")
// e.g. Depends: passwd, debconf (>= 0.5) | debconf-2.0
var dependencies []string
depends := strings.Split(line, ",")
for _, dep := range depends {
// e.g. gpgv | gpgv2 | gpgv1
for _, d := range strings.Split(dep, "|") {
d = a.trimVersionRequirement(d)
// Store only package names here
dependencies = append(dependencies, strings.TrimSpace(d))
}
}
return dependencies
}
func (a dpkgAnalyzer) trimVersionRequirement(s string) string {
// e.g.
// libapt-pkg6.0 (>= 2.2.4) => libapt-pkg6.0
// adduser => adduser
if strings.Contains(s, "(") {
s = s[:strings.Index(s, "(")]
}
return s
}
func (a dpkgAnalyzer) consolidateDependencies(pkgs map[string]*types.Package, pkgIDs map[string]string) {
for _, pkg := range pkgs {
// e.g. libc6 => libc6@2.31-13+deb11u4
pkg.DependsOn = lo.FilterMap(pkg.DependsOn, func(d string, _ int) (string, bool) {
if pkgID, ok := pkgIDs[d]; ok {
return pkgID, true
}
return "", false
})
sort.Strings(pkg.DependsOn)
if len(pkg.DependsOn) == 0 {
pkg.DependsOn = nil
}
}
}
func (a dpkgAnalyzer) isListFile(dir, fileName string) bool {
if dir != infoDir {
return false
}
return strings.HasSuffix(fileName, ".list")
}
func (a dpkgAnalyzer) Type() analyzer.Type {
return analyzer.TypeDpkg
}
func (a dpkgAnalyzer) Version() int {
return analyzerVersion
}