-
Notifications
You must be signed in to change notification settings - Fork 22
/
scanner.go
433 lines (382 loc) · 12.9 KB
/
scanner.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
// Copyright © 2023 Cisco Systems, Inc. and its affiliates.
// All rights reserved.
//
// 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 scanner
import (
"context"
"errors"
"fmt"
"io"
"os"
"path/filepath"
"github.com/docker/docker/api/types"
containertypes "github.com/docker/docker/api/types/container"
"github.com/docker/docker/api/types/filters"
imagetypes "github.com/docker/docker/api/types/image"
"github.com/docker/docker/api/types/mount"
"github.com/docker/docker/api/types/network"
"github.com/docker/docker/api/types/volume"
"github.com/docker/docker/client"
"github.com/docker/docker/pkg/archive"
"gopkg.in/yaml.v3"
apitypes "github.com/openclarity/vmclarity/api/types"
"github.com/openclarity/vmclarity/core/log"
"github.com/openclarity/vmclarity/provider"
"github.com/openclarity/vmclarity/scanner/families"
)
// mountPointPath defines the location in the container where assets will be mounted.
var mountPointPath = "/mnt/snapshot"
var _ provider.Scanner = &Scanner{}
type Scanner struct {
DockerClient *client.Client
HelperImage string
NetworkName string
}
func (s *Scanner) RunAssetScan(ctx context.Context, t *provider.ScanJobConfig) error {
assetVolume, err := s.prepareScanAssetVolume(ctx, t)
if err != nil {
return provider.FatalErrorf("failed to prepare scan volume. Provider=%s: %w", apitypes.Docker, err)
}
networkID, err := s.createScanNetwork(ctx)
if err != nil {
return provider.FatalErrorf("failed to prepare scan network. Provider=%s: %w", apitypes.Docker, err)
}
containerID, err := s.createScanContainer(ctx, assetVolume, networkID, t)
if err != nil {
return provider.FatalErrorf("failed to create scan container. Provider=%s: %w", apitypes.Docker, err)
}
err = s.DockerClient.ContainerStart(ctx, containerID, containertypes.StartOptions{})
if err != nil {
return provider.FatalErrorf("failed to start scan container. Provider=%s: %w", apitypes.Docker, err)
}
return nil
}
func (s *Scanner) RemoveAssetScan(ctx context.Context, t *provider.ScanJobConfig) error {
containerID, err := s.getContainerIDFromName(ctx, t.AssetScanID)
if err != nil {
return provider.FatalErrorf("failed to get scan container id. Provider=%s: %w", apitypes.Docker, err)
}
err = s.DockerClient.ContainerRemove(ctx, containerID, containertypes.RemoveOptions{Force: true})
if err != nil {
return provider.FatalErrorf("failed to remove scan container. Provider=%s: %w", apitypes.Docker, err)
}
err = s.DockerClient.VolumeRemove(ctx, t.AssetScanID, true)
if err != nil {
return provider.FatalErrorf("failed to remove volume. Provider=%s: %w", apitypes.Docker, err)
}
return nil
}
// prepareScanAssetVolume returns volume name or error.
func (s *Scanner) prepareScanAssetVolume(ctx context.Context, t *provider.ScanJobConfig) (string, error) {
logger := log.GetLoggerFromContextOrDiscard(ctx)
volumeName := t.AssetScanID
// Create volume if not found
err := s.createScanAssetVolume(ctx, volumeName)
if err != nil {
return "", fmt.Errorf("failed to create scan volume : %w", err)
}
// Pull image for ephemeral container
imagePullResp, err := s.DockerClient.ImagePull(ctx, s.HelperImage, imagetypes.PullOptions{})
if err != nil {
return "", fmt.Errorf("failed to pull helper image: %w", err)
}
// Drain response to avoid blocking
_, _ = io.Copy(io.Discard, imagePullResp)
_ = imagePullResp.Close()
// Create an ephemeral container to populate volume with asset contents
containerResp, err := s.DockerClient.ContainerCreate(
ctx,
&containertypes.Config{
Image: s.HelperImage,
},
&containertypes.HostConfig{
Mounts: []mount.Mount{
{
Type: mount.TypeVolume,
Source: volumeName,
Target: "/data",
},
},
},
nil,
nil,
"",
)
if err != nil {
return "", fmt.Errorf("failed to create helper container: %w", err)
}
defer func() {
err := s.DockerClient.ContainerRemove(ctx, containerResp.ID, containertypes.RemoveOptions{Force: true})
if err != nil {
logger.Errorf("Failed to remove helper container=%s: %v", containerResp.ID, err)
}
}()
// Export asset data to tar reader
assetContents, exportCleanup, err := s.exportAsset(ctx, t)
if err != nil {
return "", fmt.Errorf("failed to export asset: %w", err)
}
defer func() {
err := assetContents.Close()
if err != nil {
logger.Errorf("failed to close asset contents stream: %s", err.Error())
}
if exportCleanup != nil {
exportCleanup()
}
}()
// Copy asset data to ephemeral container
err = s.DockerClient.CopyToContainer(ctx, containerResp.ID, "/data", assetContents, types.CopyToContainerOptions{})
if err != nil {
return "", fmt.Errorf("failed to copy asset to container: %w", err)
}
return volumeName, nil
}
func (s *Scanner) createScanAssetVolume(ctx context.Context, volumeName string) error {
logger := log.GetLoggerFromContextOrDiscard(ctx)
// Create volume if not found
volumesResp, err := s.DockerClient.VolumeList(ctx, volume.ListOptions{
Filters: filters.NewArgs(filters.Arg("name", volumeName)),
})
if err != nil {
return fmt.Errorf("failed to get volumes: %w", err)
}
if len(volumesResp.Volumes) == 1 {
logger.Infof("Scan volume=%s already exists", volumeName)
return nil
}
if len(volumesResp.Volumes) == 0 {
_, err = s.DockerClient.VolumeCreate(ctx, volume.CreateOptions{
Name: volumeName,
})
if err != nil {
return fmt.Errorf("failed to create scan volume: %w", err)
}
return nil
}
return errors.New("invalid number of volumes found")
}
// createScanNetwork returns network id or error.
func (s *Scanner) createScanNetwork(ctx context.Context) (string, error) {
// Do nothing if network already exists
networkID, _ := s.getNetworkIDFromName(ctx, s.NetworkName)
if networkID != "" {
return networkID, nil
}
// Create network
networkResp, err := s.DockerClient.NetworkCreate(
ctx,
s.NetworkName,
types.NetworkCreate{
CheckDuplicate: true,
Driver: "bridge",
},
)
if err != nil {
return "", fmt.Errorf("failed to create scan network: %w", err)
}
return networkResp.ID, nil
}
// copyScanConfigToContainer copies scan configuration as a file to the scan container.
func (s *Scanner) copyScanConfigToContainer(ctx context.Context, containerID string, t *provider.ScanJobConfig) error {
// Add volume mount point to family configuration
familiesConfig := families.Config{}
err := yaml.Unmarshal([]byte(t.ScannerCLIConfig), &familiesConfig)
if err != nil {
return fmt.Errorf("failed to unmarshal family scan configuration: %w", err)
}
families.SetMountPointsForFamiliesInput([]string{mountPointPath}, &familiesConfig)
familiesConfigByte, err := yaml.Marshal(familiesConfig)
if err != nil {
return fmt.Errorf("failed to marshal family scan configuration: %w", err)
}
// Write scan config file to temp dir
src := filepath.Join(os.TempDir(), getScanConfigFileName(t))
err = os.WriteFile(src, familiesConfigByte, 0o400) // nolint:gomnd,mnd
if err != nil {
return fmt.Errorf("failed write scan config file: %w", err)
}
// Create tar archive from scan config file
srcInfo, err := archive.CopyInfoSourcePath(src, false)
if err != nil {
return fmt.Errorf("failed to get copy info: %w", err)
}
srcArchive, err := archive.TarResource(srcInfo)
if err != nil {
return fmt.Errorf("failed to create tar archive: %w", err)
}
defer srcArchive.Close()
// Prepare archive for copy
dstInfo := archive.CopyInfo{Path: filepath.Join("/", getScanConfigFileName(t))}
dst, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, dstInfo)
if err != nil {
return fmt.Errorf("failed to prepare archive: %w", err)
}
defer preparedArchive.Close()
// Copy scan config file to container
err = s.DockerClient.CopyToContainer(ctx, containerID, dst, preparedArchive, types.CopyToContainerOptions{})
if err != nil {
return fmt.Errorf("failed to copy config file to container: %w", err)
}
return nil
}
// createScanContainer returns container id or error.
func (s *Scanner) createScanContainer(ctx context.Context, assetVolume, networkID string, t *provider.ScanJobConfig) (string, error) {
containerName := t.AssetScanID
// Do nothing if scan container already exists
containerID, _ := s.getContainerIDFromName(ctx, containerName)
if containerID != "" {
return containerID, nil
}
// Pull scanner image if required
images, err := s.DockerClient.ImageList(ctx, imagetypes.ListOptions{
Filters: filters.NewArgs(filters.Arg("reference", t.ScannerImage)),
})
if err != nil {
return "", fmt.Errorf("failed to get images: %w", err)
}
if len(images) == 0 {
imagePullResp, err := s.DockerClient.ImagePull(ctx, t.ScannerImage, imagetypes.PullOptions{})
if err != nil {
return "", fmt.Errorf("failed to pull scanner image: %w", err)
}
// Drain response to avoid blocking
_, _ = io.Copy(io.Discard, imagePullResp)
_ = imagePullResp.Close()
}
// Create scan container
containerResp, err := s.DockerClient.ContainerCreate(
ctx,
&containertypes.Config{
Image: t.ScannerImage,
Cmd: []string{
"scan",
"--config",
filepath.Join("/", getScanConfigFileName(t)),
"--server",
t.VMClarityAddress,
"--asset-scan-id",
t.AssetScanID,
},
},
&containertypes.HostConfig{
Mounts: []mount.Mount{
{
Type: mount.TypeVolume,
Source: assetVolume,
Target: mountPointPath,
},
},
},
&network.NetworkingConfig{
EndpointsConfig: map[string]*network.EndpointSettings{
t.AssetScanID: {
NetworkID: networkID,
},
},
},
nil,
containerName,
)
if err != nil {
return "", fmt.Errorf("failed to create scan container: %w", err)
}
err = s.copyScanConfigToContainer(ctx, containerResp.ID, t)
if err != nil {
return "", fmt.Errorf("failed to copy scan config to container: %w", err)
}
return containerResp.ID, nil
}
func (s *Scanner) getContainerIDFromName(ctx context.Context, containerName string) (string, error) {
containers, err := s.DockerClient.ContainerList(ctx, containertypes.ListOptions{
All: true,
Filters: filters.NewArgs(filters.Arg("name", containerName)),
})
if err != nil {
return "", fmt.Errorf("failed to list containers: %w", err)
}
if len(containers) == 0 {
return "", fmt.Errorf("scan container not found: %w", err)
}
if len(containers) > 1 {
return "", fmt.Errorf("found more than one scan container: %w", err)
}
return containers[0].ID, nil
}
func (s *Scanner) getNetworkIDFromName(ctx context.Context, networkName string) (string, error) {
networks, err := s.DockerClient.NetworkList(ctx, types.NetworkListOptions{
Filters: filters.NewArgs(filters.Arg("name", networkName)),
})
if err != nil {
return "", fmt.Errorf("failed to list networks: %w", err)
}
if len(networks) == 0 {
return "", fmt.Errorf("scan network not found: %w", err)
}
if len(networks) > 1 {
for _, n := range networks {
if n.Name == networkName {
return n.ID, nil
}
}
return "", fmt.Errorf("found more than one scan network: %w", err)
}
return networks[0].ID, nil
}
// nolint:cyclop
func (s *Scanner) exportAsset(ctx context.Context, t *provider.ScanJobConfig) (io.ReadCloser, func(), error) {
logger := log.GetLoggerFromContextOrDiscard(ctx)
objectType, err := t.AssetInfo.ValueByDiscriminator()
if err != nil {
return nil, nil, fmt.Errorf("failed to get asset object type: %w", err)
}
switch value := objectType.(type) {
case apitypes.ContainerInfo:
contents, err := s.DockerClient.ContainerExport(ctx, value.ContainerID)
if err != nil {
return nil, nil, fmt.Errorf("failed to export container: %w", err)
}
return contents, nil, nil
case apitypes.ContainerImageInfo:
// Create an ephemeral container to export asset
containerResp, err := s.DockerClient.ContainerCreate(
ctx,
&containertypes.Config{Image: value.ImageID},
nil,
nil,
nil,
"",
)
if err != nil {
return nil, nil, fmt.Errorf("failed to create helper container: %w", err)
}
cleanup := func() {
err := s.DockerClient.ContainerRemove(ctx, containerResp.ID, containertypes.RemoveOptions{Force: true})
if err != nil {
logger.Errorf("failed to remove helper container=%s: %v", containerResp.ID, err)
}
}
contents, err := s.DockerClient.ContainerExport(ctx, containerResp.ID)
if err != nil {
cleanup()
return nil, nil, fmt.Errorf("failed to export container: %w", err)
}
return contents, cleanup, nil
default:
return nil, nil, fmt.Errorf("failed to export asset object type %T: Not implemented", value)
}
}
func getScanConfigFileName(t *provider.ScanJobConfig) string {
return fmt.Sprintf("scanconfig_%s.yaml", t.AssetScanID)
}