-
Notifications
You must be signed in to change notification settings - Fork 129
Expand file tree
/
Copy pathLinuxScanner.cs
More file actions
419 lines (377 loc) · 15.3 KB
/
Copy pathLinuxScanner.cs
File metadata and controls
419 lines (377 loc) · 15.3 KB
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
namespace Microsoft.ComponentDetection.Detectors.Linux;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ComponentDetection.Common.Telemetry.Records;
using Microsoft.ComponentDetection.Contracts;
using Microsoft.ComponentDetection.Contracts.BcdeModels;
using Microsoft.ComponentDetection.Contracts.TypedComponent;
using Microsoft.ComponentDetection.Detectors.Linux.Contracts;
using Microsoft.ComponentDetection.Detectors.Linux.Factories;
using Microsoft.ComponentDetection.Detectors.Linux.Filters;
using Microsoft.Extensions.Logging;
/// <summary>
/// Scanner for Linux container layers using Syft.
/// </summary>
internal class LinuxScanner : ILinuxScanner
{
private const string ScannerImage =
"governancecontainerregistry.azurecr.io/syft:v1.37.0@sha256:48d679480c6d272c1801cf30460556959c01d4826795be31d4fd8b53750b7d91";
private static readonly IList<string> CmdParameters = ["--quiet", "--output", "json"];
private static readonly IList<string> ScopeAllLayersParameter = ["--scope", "all-layers"];
private static readonly IList<string> ScopeSquashedParameter = ["--scope", "squashed"];
private static readonly SemaphoreSlim ContainerSemaphore = new SemaphoreSlim(2);
/// <summary>
/// Caches in-flight syft runs.
/// When multiple detectors scan the same image concurrently, the second
/// caller awaits the already-running task instead of launching a new container.
/// </summary>
private static readonly ConcurrentDictionary<(string Source, LinuxScannerScope Scope, string Binds), Task<string>> SyftRunCache = new();
private static readonly int SemaphoreTimeout = Convert.ToInt32(
TimeSpan.FromHours(1).TotalMilliseconds
);
private readonly IDockerService dockerService;
private readonly ILogger<LinuxScanner> logger;
private readonly IEnumerable<IArtifactComponentFactory> componentFactories;
private readonly IEnumerable<IArtifactFilter> artifactFilters;
private readonly Dictionary<string, IArtifactComponentFactory> artifactTypeToFactoryLookup;
private readonly Dictionary<
ComponentType,
IArtifactComponentFactory
> componentTypeToFactoryLookup;
/// <summary>
/// Initializes a new instance of the <see cref="LinuxScanner"/> class.
/// </summary>
/// <param name="dockerService">The docker service.</param>
/// <param name="logger">The logger.</param>
/// <param name="componentFactories">The component factories.</param>
/// <param name="artifactFilters">The artifact filters.</param>
public LinuxScanner(
IDockerService dockerService,
ILogger<LinuxScanner> logger,
IEnumerable<IArtifactComponentFactory> componentFactories,
IEnumerable<IArtifactFilter> artifactFilters
)
{
this.dockerService = dockerService;
this.logger = logger;
this.componentFactories = componentFactories;
this.artifactFilters = artifactFilters;
this.artifactTypeToFactoryLookup = componentFactories
.SelectMany(
f => f.SupportedArtifactTypes,
(factory, artifactType) => (artifactType, factory)
)
.ToDictionary(x => x.artifactType, x => x.factory);
this.componentTypeToFactoryLookup = componentFactories.ToDictionary(
f => f.SupportedComponentType,
f => f
);
}
/// <inheritdoc/>
public async Task<IEnumerable<LayerMappedLinuxComponents>> ScanLinuxAsync(
string imageHash,
IEnumerable<DockerLayer> containerLayers,
int baseImageLayerCount,
ISet<ComponentType> enabledComponentTypes,
LinuxScannerScope scope,
CancellationToken cancellationToken = default
)
{
using var record = new LinuxScannerTelemetryRecord
{
ImageToScan = imageHash,
ScannerVersion = ScannerImage,
};
using var syftTelemetryRecord = new LinuxScannerSyftTelemetryRecord();
var stdout = await this.RunSyftAsync(imageHash, scope, additionalBinds: [], record, syftTelemetryRecord, cancellationToken);
try
{
var syftOutput = SyftOutput.FromJson(stdout);
return this.ProcessSyftOutputWithTelemetry(syftOutput, containerLayers, enabledComponentTypes, syftTelemetryRecord);
}
catch (Exception e)
{
record.FailedDeserializingScannerOutput = e.ToString();
this.logger.LogError(e, "Failed to deserialize Syft output for image {ImageHash}", imageHash);
return [];
}
}
/// <inheritdoc/>
public async Task<SyftOutput> GetSyftOutputAsync(
string syftSource,
IList<string> additionalBinds,
LinuxScannerScope scope,
CancellationToken cancellationToken = default
)
{
using var record = new LinuxScannerTelemetryRecord
{
ImageToScan = syftSource,
ScannerVersion = ScannerImage,
};
using var syftTelemetryRecord = new LinuxScannerSyftTelemetryRecord();
var stdout = await this.RunSyftAsync(syftSource, scope, additionalBinds, record, syftTelemetryRecord, cancellationToken);
try
{
return SyftOutput.FromJson(stdout);
}
catch (Exception e)
{
record.FailedDeserializingScannerOutput = e.ToString();
this.logger.LogError(e, "Failed to deserialize Syft output for source {SyftSource}", syftSource);
throw;
}
}
/// <inheritdoc/>
public IEnumerable<LayerMappedLinuxComponents> ProcessSyftOutput(
SyftOutput syftOutput,
IEnumerable<DockerLayer> containerLayers,
ISet<ComponentType> enabledComponentTypes)
{
using var syftTelemetryRecord = new LinuxScannerSyftTelemetryRecord();
return this.ProcessSyftOutputWithTelemetry(syftOutput, containerLayers, enabledComponentTypes, syftTelemetryRecord);
}
private IEnumerable<LayerMappedLinuxComponents> ProcessSyftOutputWithTelemetry(
SyftOutput syftOutput,
IEnumerable<DockerLayer> containerLayers,
ISet<ComponentType> enabledComponentTypes,
LinuxScannerSyftTelemetryRecord syftTelemetryRecord)
{
// Apply artifact filters (e.g., Mariner 2.0 workaround)
var validArtifacts = syftOutput.Artifacts.AsEnumerable();
foreach (var filter in this.artifactFilters)
{
validArtifacts = filter.Filter(validArtifacts, syftOutput.Distro);
}
// Build a set of enabled factories based on requested component types
var enabledFactories = new HashSet<IArtifactComponentFactory>();
foreach (var componentType in enabledComponentTypes)
{
if (
this.componentTypeToFactoryLookup.TryGetValue(componentType, out var factory)
&& factory != null
)
{
enabledFactories.Add(factory);
}
}
// Create components using only enabled factories
var componentsWithLayers = validArtifacts
.DistinctBy(artifact => (artifact.Name, artifact.Version, artifact.Type))
.Select(artifact =>
this.CreateComponentWithLayers(artifact, syftOutput.Distro, enabledFactories)
)
.Where(result => result.Component != null)
.Select(result => (Component: result.Component!, result.LayerIds))
.ToList();
// Track unsupported artifact types for telemetry
var unsupportedTypes = validArtifacts
.Where(a => !this.artifactTypeToFactoryLookup.ContainsKey(a.Type))
.Select(a => a.Type)
.Distinct()
.ToList();
if (unsupportedTypes.Count > 0)
{
this.logger.LogDebug(
"Encountered unsupported artifact types: {UnsupportedTypes}",
string.Join(", ", unsupportedTypes)
);
}
// Track detected components in telemetry
syftTelemetryRecord.Components = JsonSerializer.Serialize(
componentsWithLayers.Select(c => c.Component.Id)
);
// Build a layer dictionary from the provided container layers and map components.
var knownLayers = containerLayers.ToList();
if (knownLayers.Count > 0)
{
var layerDictionary = knownLayers
.DistinctBy(layer => layer.DiffId)
.ToDictionary(layer => layer.DiffId, _ => new List<TypedComponent>());
foreach (var (component, layers) in componentsWithLayers)
{
foreach (var layer in layers)
{
if (layerDictionary.TryGetValue(layer, out var componentList))
{
componentList.Add(component);
}
}
}
return layerDictionary.Select(kvp => new LayerMappedLinuxComponents
{
Components = kvp.Value,
DockerLayer = knownLayers.First(layer => layer.DiffId == kvp.Key),
});
}
// No container layers provided — return all components under a single
// entry with no layer information rather than silently dropping them.
var allComponents = componentsWithLayers.Select(c => c.Component).ToList();
if (allComponents.Count == 0)
{
return [];
}
return
[
new LayerMappedLinuxComponents
{
Components = allComponents,
DockerLayer = new DockerLayer()
{
DiffId = string.Empty,
LayerIndex = 0,
IsBaseImage = false,
},
},
];
}
/// <summary>
/// Runs the Syft scanner container and returns the stdout output.
/// Results are cached so that callers with identical parameters share a single container run.
/// </summary>
private async Task<string> RunSyftAsync(
string syftSource,
LinuxScannerScope scope,
IList<string> additionalBinds,
LinuxScannerTelemetryRecord record,
LinuxScannerSyftTelemetryRecord syftTelemetryRecord,
CancellationToken cancellationToken)
{
var bindsKey = string.Join(";", (additionalBinds ?? []).OrderBy(b => b, StringComparer.Ordinal));
var cacheKey = (syftSource, scope, bindsKey);
var tcs = new TaskCompletionSource<string>(TaskCreationOptions.RunContinuationsAsynchronously);
var existingTask = SyftRunCache.GetOrAdd(cacheKey, tcs.Task);
if (existingTask != tcs.Task)
{
// Another caller is already running syft for this image+scope — await their result,
// but allow this caller's cancellation token to abort the wait.
this.logger.LogDebug("Syft run for {SyftSource} (scope={Scope}) is already in-flight, reusing existing result", syftSource, scope);
return await existingTask.WaitAsync(cancellationToken);
}
// We own this cache entry — run syft and propagate the result.
try
{
var result = await this.RunSyftCoreAsync(syftSource, scope, additionalBinds ?? [], record, syftTelemetryRecord, cancellationToken);
tcs.SetResult(result);
return result;
}
catch (Exception ex)
{
tcs.SetException(ex);
throw;
}
finally
{
// Remove the entry once complete. The cache only deduplicates concurrent
// in-flight calls — keeping completed entries would leak memory for the
// lifetime of the process.
SyftRunCache.TryRemove(cacheKey, out _);
}
}
/// <summary>
/// Executes the Syft scanner container and returns the stdout output.
/// </summary>
private async Task<string> RunSyftCoreAsync(
string syftSource,
LinuxScannerScope scope,
IList<string> additionalBinds,
LinuxScannerTelemetryRecord record,
LinuxScannerSyftTelemetryRecord syftTelemetryRecord,
CancellationToken cancellationToken)
{
var acquired = false;
var stdout = string.Empty;
var stderr = string.Empty;
var scopeParameters = scope switch
{
LinuxScannerScope.AllLayers => ScopeAllLayersParameter,
LinuxScannerScope.Squashed => ScopeSquashedParameter,
_ => throw new ArgumentOutOfRangeException(
nameof(scope),
$"Unsupported scope value: {scope}"
),
};
try
{
acquired = await ContainerSemaphore.WaitAsync(SemaphoreTimeout, cancellationToken);
if (acquired)
{
try
{
var command = new List<string> { syftSource }
.Concat(CmdParameters)
.Concat(scopeParameters)
.ToList();
(stdout, stderr) = await this.dockerService.CreateAndRunContainerAsync(
ScannerImage,
command,
additionalBinds,
cancellationToken
);
}
catch (Exception e)
{
syftTelemetryRecord.Exception = e.ToString();
this.logger.LogError(e, "Failed to run syft");
throw;
}
}
else
{
record.SemaphoreFailure = true;
this.logger.LogWarning(
"Failed to enter the container semaphore for image {SyftSource}",
syftSource
);
}
}
finally
{
if (acquired)
{
ContainerSemaphore.Release();
}
}
record.ScanStdErr = stderr;
record.ScanStdOut = stdout;
if (string.IsNullOrWhiteSpace(stdout) || !string.IsNullOrWhiteSpace(stderr))
{
throw new InvalidOperationException(
$"Scan failed with exit info: {stdout}{System.Environment.NewLine}{stderr}"
);
}
return stdout;
}
private (TypedComponent? Component, IEnumerable<string> LayerIds) CreateComponentWithLayers(
ArtifactElement artifact,
Distro distro,
HashSet<IArtifactComponentFactory> enabledFactories
)
{
if (!this.artifactTypeToFactoryLookup.TryGetValue(artifact.Type, out var factory))
{
return (null, []);
}
// Skip this artifact if its factory is not in the enabled set
if (!enabledFactories.Contains(factory))
{
return (null, []);
}
var component = factory.CreateComponent(artifact, distro);
if (component == null)
{
return (null, []);
}
var layerIds = artifact.Locations?.Select(location => location.LayerId).Distinct() ?? [];
return (component, layerIds);
}
/// <summary>
/// Clears the syft run cache. Intended for test isolation only.
/// </summary>
internal static void ResetCache() => SyftRunCache.Clear();
}