-
Notifications
You must be signed in to change notification settings - Fork 1
/
apk.go
242 lines (211 loc) · 6.1 KB
/
apk.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
package apk
import (
"bufio"
"context"
"encoding/base64"
"encoding/hex"
"fmt"
"os"
"path"
"sort"
"strings"
apkVersion "github.com/knqyf263/go-apk-version"
"github.com/samber/lo"
"golang.org/x/exp/slices"
"github.com/zhanglimao/trivy/pkg/digest"
"github.com/zhanglimao/trivy/pkg/fanal/analyzer"
"github.com/zhanglimao/trivy/pkg/fanal/types"
"github.com/zhanglimao/trivy/pkg/licensing"
"github.com/zhanglimao/trivy/pkg/log"
)
func init() {
analyzer.RegisterAnalyzer(&alpinePkgAnalyzer{})
}
const analyzerVersion = 2
var requiredFiles = []string{"lib/apk/db/installed"}
type alpinePkgAnalyzer struct{}
func (a alpinePkgAnalyzer) Analyze(_ context.Context, input analyzer.AnalysisInput) (*analyzer.AnalysisResult, error) {
scanner := bufio.NewScanner(input.Content)
parsedPkgs, installedFiles := a.parseApkInfo(scanner)
return &analyzer.AnalysisResult{
PackageInfos: []types.PackageInfo{
{
FilePath: input.FilePath,
Packages: parsedPkgs,
},
},
SystemInstalledFiles: installedFiles,
}, nil
}
func (a alpinePkgAnalyzer) parseApkInfo(scanner *bufio.Scanner) ([]types.Package, []string) {
var (
pkgs []types.Package
pkg types.Package
version string
dir string
installedFiles []string
provides = map[string]string{} // for dependency graph
)
for scanner.Scan() {
line := scanner.Text()
// check package if paragraph end
if len(line) < 2 {
if !pkg.Empty() {
pkgs = append(pkgs, pkg)
}
pkg = types.Package{}
continue
}
// ref. https://wiki.alpinelinux.org/wiki/Apk_spec
switch line[:2] {
case "P:":
pkg.Name = line[2:]
case "V:":
version = line[2:]
if !apkVersion.Valid(version) {
log.Logger.Warnf("Invalid Version Found : OS %s, Package %s, Version %s", "alpine", pkg.Name, version)
continue
}
pkg.Version = version
case "o:":
origin := line[2:]
pkg.SrcName = origin
pkg.SrcVersion = version
case "L:":
pkg.Licenses = a.parseLicense(line)
case "F:":
dir = line[2:]
case "R:":
installedFiles = append(installedFiles, path.Join(dir, line[2:]))
case "p:": // provides (corresponds to provides in PKGINFO, concatenated by spaces into a single line)
a.parseProvides(line, pkg.ID, provides)
case "D:": // dependencies (corresponds to depend in PKGINFO, concatenated by spaces into a single line)
pkg.DependsOn = a.parseDependencies(line)
case "A:":
pkg.Arch = line[2:]
case "C:":
d := decodeChecksumLine(line)
if d != "" {
pkg.Digest = d
}
}
if pkg.Name != "" && pkg.Version != "" {
pkg.ID = fmt.Sprintf("%s@%s", pkg.Name, pkg.Version)
// Dependencies could be package names or provides, so package names are stored as provides here.
// e.g. D:scanelf so:libc.musl-x86_64.so.1
provides[pkg.Name] = pkg.ID
}
}
// in case of last paragraph
if !pkg.Empty() {
pkgs = append(pkgs, pkg)
}
pkgs = a.uniquePkgs(pkgs)
// Replace dependencies with package IDs
a.consolidateDependencies(pkgs, provides)
return pkgs, installedFiles
}
func (a alpinePkgAnalyzer) trimRequirement(s string) string {
// Trim version requirements
// e.g.
// so:libssl.so.1.1=1.1 => so:libssl.so.1.1
// musl>=1.2 => musl
if strings.ContainsAny(s, "<>=") {
s = s[:strings.IndexAny(s, "><=")]
}
return s
}
func (a alpinePkgAnalyzer) parseLicense(line string) []string {
line = line[2:] // Remove "L:"
if line == "" {
return nil
}
var licenses []string
// e.g. MPL 2.0 GPL2+ => {"MPL2.0", "GPL2+"}
for i, s := range strings.Fields(line) {
s = strings.Trim(s, "()")
if s == "AND" || s == "OR" {
continue
} else if i > 0 && (s == "1.0" || s == "2.0" || s == "3.0") {
licenses[i-1] = licensing.Normalize(licenses[i-1] + s)
} else {
licenses = append(licenses, licensing.Normalize(s))
}
}
return licenses
}
func (a alpinePkgAnalyzer) parseProvides(line, pkgID string, provides map[string]string) {
for _, p := range strings.Fields(line[2:]) {
p = a.trimRequirement(p)
// Assume name ("P:") and version ("V:") are defined before provides ("p:")
provides[p] = pkgID
}
}
func (a alpinePkgAnalyzer) parseDependencies(line string) []string {
line = line[2:] // Remove "D:"
return lo.FilterMap(strings.Fields(line), func(d string, _ int) (string, bool) {
// e.g. D:!uclibc-utils scanelf musl=1.1.14-r10 so:libc.musl-x86_64.so.1
if strings.HasPrefix(d, "!") {
return "", false
}
return a.trimRequirement(d), true
})
}
func (a alpinePkgAnalyzer) consolidateDependencies(pkgs []types.Package, provides map[string]string) {
for i := range pkgs {
// e.g. libc6 => libc6@2.31-13+deb11u4
pkgs[i].DependsOn = lo.FilterMap(pkgs[i].DependsOn, func(d string, _ int) (string, bool) {
if pkgID, ok := provides[d]; ok {
return pkgID, true
}
return "", false
})
sort.Strings(pkgs[i].DependsOn)
pkgs[i].DependsOn = slices.Compact(pkgs[i].DependsOn)
if len(pkgs[i].DependsOn) == 0 {
pkgs[i].DependsOn = nil
}
}
}
func (a alpinePkgAnalyzer) uniquePkgs(pkgs []types.Package) (uniqPkgs []types.Package) {
uniq := map[string]struct{}{}
for _, pkg := range pkgs {
if _, ok := uniq[pkg.Name]; ok {
continue
}
uniqPkgs = append(uniqPkgs, pkg)
uniq[pkg.Name] = struct{}{}
}
return uniqPkgs
}
func (a alpinePkgAnalyzer) Required(filePath string, _ os.FileInfo) bool {
return slices.Contains(requiredFiles, filePath)
}
func (a alpinePkgAnalyzer) Type() analyzer.Type {
return analyzer.TypeApk
}
func (a alpinePkgAnalyzer) Version() int {
return analyzerVersion
}
// decodeChecksumLine decodes checksum line
func decodeChecksumLine(line string) digest.Digest {
if len(line) < 2 {
log.Logger.Debugf("Unable to decode checksum line of apk package: %s", line)
return ""
}
// https://wiki.alpinelinux.org/wiki/Apk_spec#Package_Checksum_Field
// https://stackoverflow.com/a/71712569
alg := digest.MD5
d := line[2:]
if strings.HasPrefix(d, "Q1") {
alg = digest.SHA1
d = d[2:] // remove `Q1` prefix
}
decodedDigestString, err := base64.StdEncoding.DecodeString(d)
if err != nil {
log.Logger.Debugf("unable to decode digest: %s", err)
return ""
}
h := hex.EncodeToString(decodedDigestString)
return digest.NewDigestFromString(alg, h)
}