generated from falcosecurity/template-repository
-
Notifications
You must be signed in to change notification settings - Fork 52
/
Copy pathbuilders.go
433 lines (383 loc) · 11.3 KB
/
builders.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
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
// SPDX-License-Identifier: Apache-2.0
/*
Copyright (C) 2023 The Falco Authors.
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.
*/
package builder
import (
"bytes"
_ "embed"
"errors"
"fmt"
"github.com/falcosecurity/falcoctl/pkg/output"
"net/http"
"net/url"
"path"
"strings"
"text/template"
"github.com/blang/semver"
"github.com/falcosecurity/driverkit/pkg/kernelrelease"
)
// DriverDirectory is the directory the processor uses to store the driver.
const (
DriverDirectory = "/tmp/driver"
cmakeCmdFmt = `cmake -Wno-dev \
-DUSE_BUNDLED_DEPS=On \
-DCREATE_TEST_TARGETS=Off \
-DBUILD_LIBSCAP_GVISOR=Off \
-DBUILD_LIBSCAP_MODERN_BPF=Off \
-DENABLE_DRIVERS_TESTS=Off \
-DDRIVER_NAME=%s \
-DPROBE_NAME=%s \
-DBUILD_BPF=On \
-DDRIVER_VERSION=%s \
-DPROBE_VERSION=%s \
-DGIT_COMMIT=%s \
-DDRIVER_DEVICE_NAME=%s \
-DPROBE_DEVICE_NAME=%s \
.. && \
sed -i s/'DRIVER_COMMIT ""'/'DRIVER_COMMIT "%s"'/g driver/src/driver_config.h`
)
//go:embed templates/libs_download.sh
var libsDownloadTemplate string
var HeadersNotFoundErr = errors.New("kernel headers not found")
// Config contains all the configurations needed to build the kernel module or the eBPF probe.
type Config struct {
DriverName string
DeviceName string
DownloadBaseURL string
*Build
}
func (c Config) ToDriverFullPath() string {
return path.Join(DriverDirectory, "build", "driver", fmt.Sprintf("%s.ko", c.DriverName))
}
func (c Config) ToProbeFullPath() string {
return path.Join(DriverDirectory, "build", "driver", "bpf", "probe.o")
}
type commonTemplateData struct {
DriverBuildDir string
ModuleDriverName string
ModuleFullPath string
BuildModule bool
BuildProbe bool
GCCVersion string
CmakeCmd string
}
// Builder represents a builder capable of generating a script for a driverkit target.
type Builder interface {
Name() string
TemplateKernelUrlsScript() string
TemplateScript() string
URLs(kr kernelrelease.KernelRelease) ([]string, error)
KernelTemplateData(kr kernelrelease.KernelRelease, urls []string) interface{} // error return type is managed
}
// MinimumURLsBuilder is an optional interface implemented by builders
// to specify minimum number of requested headers urls
type MinimumURLsBuilder interface {
MinimumURLs() int
}
// TemplateDataSpecifier is an optional interface implemented by builders
// to specify a custom template data instead of the default one.
type TemplateDataSpecifier interface {
TemplateData(c Config, kr kernelrelease.KernelRelease) interface{}
}
type libsDownloadTemplateData struct {
DriverBuildDir string
ModuleDownloadURL string
}
// LibsDownloadScript returns the script that downloads and configures libs repo at requested commit/tag
func LibsDownloadScript(c Config) (string, error) {
t := template.New("download-libs")
parsed, err := t.Parse(libsDownloadTemplate)
if err != nil {
return "", err
}
td := libsDownloadTemplateData{
DriverBuildDir: DriverDirectory,
ModuleDownloadURL: fmt.Sprintf("%s/%s.tar.gz", c.DownloadBaseURL, c.DriverVersion),
}
buf := bytes.NewBuffer(nil)
err = parsed.Execute(buf, td)
if err != nil {
return "", err
}
return buf.String(), nil
}
// KernelDownloadScript returns the script that will download and extract kernel headers
func KernelDownloadScript(b Builder,
kernelurls []string,
kr kernelrelease.KernelRelease,
printer *output.Printer,
) (string, error) {
t := template.New("download-kernel")
parsed, err := t.Parse(b.TemplateKernelUrlsScript())
if err != nil {
return "", err
}
var urls []string
minimumURLs := 1
if bb, ok := b.(MinimumURLsBuilder); ok {
minimumURLs = bb.MinimumURLs()
}
if kernelurls == nil {
urls, err = b.URLs(kr)
if err != nil {
return "", err
}
// Only if returned urls array is not empty
// Otherwise, it is up to the builder to return an error
if len(urls) > 0 {
// Check (and filter) existing kernels before continuing
urls, err = GetResolvingURLs(urls)
}
} else {
urls, err = GetResolvingURLs(kernelurls)
}
if err != nil {
return "", err
}
if len(urls) < minimumURLs {
return "", fmt.Errorf("not enough headers packages found; expected %d, found %d", minimumURLs, len(urls))
}
printer.Logger.Debug("kernel headers found",
printer.Logger.Args("urls", urls))
td := b.KernelTemplateData(kr, urls)
if tdErr, ok := td.(error); ok {
return "", tdErr
}
buf := bytes.NewBuffer(nil)
err = parsed.Execute(buf, td)
if err != nil {
return "", err
}
return buf.String(), nil
}
// Script retrieves the actually drivers building script
func Script(b Builder, c Config, kr kernelrelease.KernelRelease) (string, error) {
t := template.New(b.Name())
parsed, err := t.Parse(b.TemplateScript())
if err != nil {
return "", err
}
var td interface{}
if bb, ok := b.(TemplateDataSpecifier); ok {
td = bb.TemplateData(c, kr)
} else {
td = c.toTemplateData(b, kr)
}
buf := bytes.NewBuffer(nil)
err = parsed.Execute(buf, td)
if err != nil {
return "", err
}
return buf.String(), nil
}
type GCCVersionRequestor interface {
// GCCVersion returns the GCC version to be used.
// If the returned value is empty, the default algorithm will be enforced.
GCCVersion(kr kernelrelease.KernelRelease) semver.Version
}
func defaultGCC(kr kernelrelease.KernelRelease) semver.Version {
switch kr.Major {
case 6:
if kr.Minor >= 10 {
return semver.Version{Major: 14, Minor: 2, Patch: 1}
}
if kr.Minor >= 5 {
return semver.Version{Major: 13}
}
return semver.Version{Major: 12}
case 5:
if kr.Minor >= 15 {
return semver.Version{Major: 12}
}
return semver.Version{Major: 11}
case 4:
return semver.Version{Major: 8}
case 3:
if kr.Minor >= 18 {
return semver.Version{Major: 5}
}
return semver.Version{Major: 4, Minor: 9}
case 2:
return semver.Version{Major: 4, Minor: 8}
default:
return semver.Version{Major: 14, Minor: 2, Patch: 1}
}
}
func mustParseTolerant(gccStr string) semver.Version {
g, err := semver.ParseTolerant(gccStr)
if err != nil {
panic(err)
}
return g
}
// Algorithm.
// * always load images (note that it loads only images that provide gccversion, if set by user)
// * if user set a fixed gccversion, we are good to go
// * otherwise, try to fix the best-match gcc version provided by any of the loaded images;
// see below for algorithm explanation
func (b *Build) setGCCVersion(builder Builder, kr kernelrelease.KernelRelease) {
if !b.hasCustomBuilderImage() {
b.LoadImages()
}
if len(b.GCCVersion) > 0 {
// If set from user, go on
return
}
b.GCCVersion = "8" // default value
// if builder implements "GCCVersionRequestor" interface -> use it
// Else, fetch the best builder available from the kernelrelease version
// using the deadly simple defaultGCC() algorithm
// Always returns the nearest one
var targetGCC semver.Version
if bb, ok := builder.(GCCVersionRequestor); ok {
targetGCC = bb.GCCVersion(kr)
}
// If builder implements GCCVersionRequestor but returns an empty semver.Version
// it means that it does not want to manage this kernelrelease,
// and instead wants to fallback to default algorithm
if targetGCC.EQ(semver.Version{}) {
targetGCC = defaultGCC(kr)
}
if b.hasCustomBuilderImage() {
b.GCCVersion = targetGCC.String()
return
}
// Step 1:
// If we are able to either find a specific-target image,
// or "any" target image that provide desired gcc,
// we are over.
image, ok := b.Images.findImage(b.TargetType, targetGCC)
if ok {
b.GCCVersion = image.GCCVersion.String()
} else {
// Step 2:
// Build the list of "proposed" GCC versions,
// that is, the list of available gccs from images
// for each builder image
proposedGCCs := make([]semver.Version, 0)
for _, img := range b.Images {
proposedGCCs = append(proposedGCCs, img.GCCVersion)
b.Logger.Debug("proposed GCC",
b.Logger.Args("image", img.Name,
"targetGCC", targetGCC.String(),
"proposedGCC", img.GCCVersion.String()))
}
// Now, sort versions and fetch
// the nearest gcc, that is also < targetGCC
semver.Sort(proposedGCCs)
lastGCC := proposedGCCs[0]
for _, gcc := range proposedGCCs {
if gcc.GT(targetGCC) {
break
}
lastGCC = gcc
}
b.GCCVersion = lastGCC.String()
}
b.Logger.Debug("found GCC",
b.Logger.Args("targetGCC", targetGCC.String(), "version", b.GCCVersion))
}
type BuilderImageNetworkMode interface {
// sets the network mode of the builder image, allows individual builders to override
BuilderImageNetMode() string
}
func (b *Build) GetBuilderImage() string {
if b.hasCustomBuilderImage() {
// BuilderImage MUST have requested GCC installed inside
return b.BuilderImage
}
// NOTE: here below we are already sure that we are going
// to find an image, because setGCCVersion()
// has already set an existent gcc version
// (ie: one provided by an image) for us
image, _ := b.Images.findImage(b.TargetType, mustParseTolerant(b.GCCVersion))
return image.Name
}
// Factory returns a builder for the given target.
func Factory(target Type) (Builder, error) {
// Workaround for "local" target (that is not exposed to users,
// nor registered in byTarget map)".
if target.String() == "local" {
return &LocalBuilder{}, nil
}
// Driverkit builder is named "ubuntu"; there is no ubuntu-foo
if strings.HasPrefix(target.String(), "ubuntu") {
target = Type("ubuntu")
}
b, ok := byTarget[target]
if !ok {
return nil, fmt.Errorf("no builder found for target: %s", target)
}
return b, nil
}
// Targets returns the list of all the supported targets.
func Targets() []string {
res := []string{}
for k := range byTarget {
res = append(res, k.String())
}
return res
}
func (c Config) toTemplateData(b Builder, kr kernelrelease.KernelRelease) commonTemplateData {
c.setGCCVersion(b, kr)
return commonTemplateData{
DriverBuildDir: DriverDirectory,
ModuleDriverName: c.DriverName,
ModuleFullPath: c.ToDriverFullPath(),
BuildModule: len(c.ModuleFilePath) > 0,
BuildProbe: len(c.ProbeFilePath) > 0,
GCCVersion: c.GCCVersion,
CmakeCmd: fmt.Sprintf(cmakeCmdFmt,
c.DriverName,
c.DriverName,
c.DriverVersion,
c.DriverVersion,
c.DriverVersion,
c.DeviceName,
c.DeviceName,
c.DriverVersion),
}
}
func resolveURLReference(u string) string {
uu, err := url.Parse(u)
if err != nil {
panic(err)
}
base, err := url.Parse(uu.Host)
if err != nil {
panic(err)
}
return base.ResolveReference(uu).String()
}
func GetResolvingURLs(urls []string) ([]string, error) {
var results []string
for _, u := range urls {
// in case url has some relative paths
// (kernel-crawler does not resolve them for us,
// neither it is expected, because they are effectively valid urls),
// resolve the absolute one.
// HEAD would fail otherwise.
u = resolveURLReference(u)
res, err := http.Head(u)
if err != nil {
continue
}
if res.StatusCode == http.StatusOK {
results = append(results, u)
}
}
if len(results) == 0 {
return nil, HeadersNotFoundErr
}
return results, nil
}