-
Notifications
You must be signed in to change notification settings - Fork 10
/
extractor_linux.go
249 lines (214 loc) · 6.02 KB
/
extractor_linux.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
// Copyright 2024 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//go:build linux
// Package rpm extracts packages from rpm database.
package rpm
import (
"context"
"fmt"
"io/fs"
"path/filepath"
"slices"
"strconv"
"time"
rpmdb "github.com/erikvarga/go-rpmdb/pkg"
"github.com/google/osv-scalibr/extractor"
"github.com/google/osv-scalibr/extractor/os/osrelease"
"github.com/google/osv-scalibr/log"
"github.com/google/osv-scalibr/purl"
// SQLite driver needed for parsing rpmdb.sqlite files.
_ "github.com/mattn/go-sqlite3"
)
// Name is the name for the RPM extractor
const Name = "os/rpm"
const defaultTimeout = 5 * time.Minute
// Config contains RPM specific configuration values
type Config struct {
Timeout time.Duration
}
// DefaultConfig returns the default configuration values for the RPM extractor.
func DefaultConfig() Config { return Config{Timeout: defaultTimeout} }
// Extractor extracts rpm packages from rpm database.
type Extractor struct {
Timeout time.Duration
}
// New returns an RPM extractor.
//
// For most use cases, initialize with:
// ```
// e := New(DefaultConfig())
// ```
func New(cfg Config) *Extractor {
return &Extractor{Timeout: cfg.Timeout}
}
// Name of the extractor.
func (e Extractor) Name() string { return Name }
// Version of the extractor.
func (e Extractor) Version() int { return 0 }
// FileRequired returns true if the specified file matches rpm status file pattern.
func (e Extractor) FileRequired(path string, _ fs.FileMode) bool {
// For Windows
path = filepath.ToSlash(path)
requiredDirectory := []string{
"usr/lib/sysimage/rpm",
"var/lib/rpm",
"usr/share/rpm",
}
requiredFilename := []string{
// Berkley DB (old format)
"Packages",
// NDB (very rare alternative to sqlite)
"Packages.db",
// SQLite3 (new format)
"rpmdb.sqlite",
}
return slices.Contains(requiredDirectory, filepath.Dir(path)) &&
slices.Contains(requiredFilename, filepath.Base(path))
}
// Extract extracts packages from rpm status files passed through the scan input.
func (e Extractor) Extract(ctx context.Context, input *extractor.ScanInput) ([]*extractor.Inventory, error) {
absPath := filepath.Join(input.ScanRoot, input.Path)
rpmPkgs, err := e.parseRPMDB(absPath)
if err != nil {
return nil, fmt.Errorf("ParseRPMDB(%s): %w", absPath, err)
}
m, err := osrelease.GetOSRelease(input.ScanRoot)
if err != nil {
log.Errorf("osrelease.ParseOsRelease(): %v", err)
}
pkgs := []*extractor.Inventory{}
for _, p := range rpmPkgs {
metadata := &Metadata{
PackageName: p.Name,
SourceRPM: p.SourceRPM,
Epoch: p.Epoch,
OSName: m["NAME"],
OSID: m["ID"],
OSVersionID: m["VERSION_ID"],
OSBuildID: m["BUILD_ID"],
Vendor: p.Vendor,
Architecture: p.Architecture,
License: p.License,
}
i := &extractor.Inventory{
Name: p.Name,
Version: fmt.Sprintf("%s-%s", p.Version, p.Release),
Locations: []string{input.Path},
Extractor: e.Name(),
Metadata: metadata,
}
pkgs = append(pkgs, i)
}
return pkgs, nil
}
// parseRPMDB returns a slice of OS packages parsed from a RPM DB.
func (e Extractor) parseRPMDB(path string) ([]rpmPackageInfo, error) {
db, err := rpmdb.Open(path)
if err != nil {
return nil, err
}
defer db.Close()
var pkgs []*rpmdb.PackageInfo
if e.Timeout == 0 {
pkgs, err = db.ListPackages()
if err != nil {
return nil, err
}
} else {
ctx, cancelFunc := context.WithTimeout(context.Background(), e.Timeout)
defer cancelFunc()
// The timeout is only for corrupt bdb databases
pkgs, err = db.ListPackagesWithContext(ctx)
if err != nil {
return nil, err
}
}
var result []rpmPackageInfo
for _, pkg := range pkgs {
newPkg := rpmPackageInfo{
Name: pkg.Name,
Version: pkg.Version,
Release: pkg.Release,
Epoch: pkg.EpochNum(),
SourceRPM: pkg.SourceRpm,
Vendor: pkg.Vendor,
Architecture: pkg.Arch,
License: pkg.License,
}
result = append(result, newPkg)
}
return result, nil
}
type rpmPackageInfo struct {
Name string
Version string
Release string
Epoch int
SourceRPM string
Maintainer string
Vendor string
Architecture string
License string
}
func toNamespace(m *Metadata) string {
if m.OSID != "" {
return m.OSID
}
log.Errorf("os-release[ID] not set, fallback to ''")
return ""
}
func toDistro(m *Metadata) string {
v := m.OSVersionID
if v == "" {
v = m.OSBuildID
if v == "" {
log.Errorf("VERSION_ID and BUILD_ID not set in os-release")
return ""
}
log.Errorf("os-release[VERSION_ID] not set, fallback to BUILD_ID")
}
id := m.OSID
if id == "" {
log.Errorf("os-release[ID] not set, fallback to ''")
return v
}
return fmt.Sprintf("%s-%s", id, v)
}
// ToPURL converts an inventory created by this extractor into a PURL.
func (e Extractor) ToPURL(i *extractor.Inventory) (*purl.PackageURL, error) {
m := i.Metadata.(*Metadata)
q := map[string]string{}
if m.Epoch > 0 {
q[purl.Epoch] = strconv.Itoa(m.Epoch)
}
distro := toDistro(m)
if distro != "" {
q[purl.Distro] = distro
}
if m.SourceRPM != "" {
q[purl.SourceRPM] = m.SourceRPM
}
if m.Architecture != "" {
q[purl.Arch] = m.Architecture
}
return &purl.PackageURL{
Type: purl.TypeRPM,
Namespace: toNamespace(m),
Name: i.Name,
Version: i.Version,
Qualifiers: purl.QualifiersFromMap(q),
}, nil
}
// ToCPEs is not applicable as this extractor does not infer CPEs from the Inventory.
func (e Extractor) ToCPEs(i *extractor.Inventory) ([]string, error) { return []string{}, nil }