forked from J0113/SCA_Scanner
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathTrivySbomGenerator.cs
More file actions
314 lines (261 loc) · 10.7 KB
/
Copy pathTrivySbomGenerator.cs
File metadata and controls
314 lines (261 loc) · 10.7 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
namespace SCAScanner;
using System.Diagnostics;
using System.Text;
using System.Threading;
public sealed class TrivySbomGenerator
{
public sealed record Result(
string OutputPath,
string TargetPath,
string? DiagnosticLogPath,
bool HasDiagnostics);
public string ResolveDefaultOutputPath()
{
string hostName = GetSafeHostName();
string? reportsDir = Environment.GetEnvironmentVariable("REPORTS_DIR");
string outputRoot;
if (!string.IsNullOrWhiteSpace(reportsDir))
{
outputRoot = reportsDir;
}
else if (OperatingSystem.IsWindows())
{
string programData = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
if (string.IsNullOrWhiteSpace(programData))
programData = @"C:\ProgramData";
outputRoot = Path.Combine(programData, "platform-scanning");
}
else if (OperatingSystem.IsMacOS())
{
outputRoot = "/Library/Application Support/platform-scanning";
}
else
{
outputRoot = "/var/lib/platform-scanning";
}
return Path.Combine(outputRoot, $"sbom-{hostName}.cdx.json");
}
public sealed class Options
{
public string? TargetPath { get; init; }
public TimeSpan Timeout { get; init; } = TimeSpan.FromMinutes(5);
public string? TrivyTimeoutArgument { get; init; }
public IReadOnlyList<string> SkipDirs { get; init; } = Array.Empty<string>();
public IReadOnlyList<string> SkipFiles { get; init; } = Array.Empty<string>();
}
public Result GenerateSbom(string? outputPath, Options options)
{
string trivyPath = ResolveTrivyPath();
string finalOutput = string.IsNullOrWhiteSpace(outputPath) ? ResolveDefaultOutputPath() : outputPath;
string fullOutput = Path.GetFullPath(finalOutput);
string? outputDir = Path.GetDirectoryName(fullOutput);
if (!string.IsNullOrWhiteSpace(outputDir))
Directory.CreateDirectory(outputDir);
string targetPath = ResolveTargetPath(options.TargetPath);
var stdOut = new StringBuilder();
var stdErr = new StringBuilder();
var startInfo = new ProcessStartInfo
{
FileName = trivyPath,
WorkingDirectory = Directory.Exists(targetPath) ? targetPath : Path.GetDirectoryName(targetPath) ?? targetPath,
RedirectStandardError = true,
RedirectStandardOutput = true,
UseShellExecute = false,
CreateNoWindow = true,
ArgumentList =
{
"fs",
"--format", "cyclonedx",
"--output", fullOutput
}
};
if (!string.IsNullOrWhiteSpace(options.TrivyTimeoutArgument))
{
startInfo.ArgumentList.Add("--timeout");
startInfo.ArgumentList.Add(options.TrivyTimeoutArgument);
}
if (options.SkipDirs.Count > 0)
{
startInfo.ArgumentList.Add("--skip-dirs");
startInfo.ArgumentList.Add(string.Join(",", options.SkipDirs));
}
if (options.SkipFiles.Count > 0)
{
startInfo.ArgumentList.Add("--skip-files");
startInfo.ArgumentList.Add(string.Join(",", options.SkipFiles));
}
startInfo.ArgumentList.Add(targetPath);
using var process = new Process { StartInfo = startInfo };
process.OutputDataReceived += (_, args) =>
{
if (args.Data is not null)
stdOut.AppendLine(args.Data);
};
process.ErrorDataReceived += (_, args) =>
{
if (args.Data is not null)
stdErr.AppendLine(args.Data);
};
if (!process.Start())
throw new InvalidOperationException("Failed to start Trivy process.");
process.BeginOutputReadLine();
process.BeginErrorReadLine();
bool exited;
if (options.Timeout == Timeout.InfiniteTimeSpan)
{
process.WaitForExit();
exited = true;
}
else
{
int timeoutMs = options.Timeout.TotalMilliseconds > int.MaxValue
? int.MaxValue
: (int)options.Timeout.TotalMilliseconds;
exited = process.WaitForExit(timeoutMs);
}
if (!exited)
{
try
{
process.Kill(entireProcessTree: true);
}
catch
{
// Best-effort kill; if it fails, still treat as timeout.
}
throw new TimeoutException($"Trivy SBOM generation exceeded timeout of {options.Timeout}.");
}
process.WaitForExit();
// Written before either failure check below so a diagnostics record survives
// even when Trivy fails outright, instead of only ever being written on success.
string? diagnosticLogPath = WriteDiagnosticsLog(fullOutput, targetPath, stdOut.ToString(), stdErr.ToString());
if (process.ExitCode != 0)
{
string detail = stdErr.Length == 0 ? stdOut.ToString() : stdErr.ToString();
string diagnosticsNote = diagnosticLogPath is not null ? $" Diagnostics: {diagnosticLogPath}" : string.Empty;
throw new InvalidOperationException($"Trivy exited with code {process.ExitCode}: {detail.Trim()}.{diagnosticsNote}");
}
if (!File.Exists(fullOutput))
throw new InvalidOperationException($"Trivy completed but SBOM file was not created: {fullOutput}");
return new Result(
fullOutput,
targetPath,
diagnosticLogPath,
diagnosticLogPath is not null);
}
public static IReadOnlyList<string> ResolveTargetPaths(string? targetPath, bool allLocalDrives)
{
if (!string.IsNullOrWhiteSpace(targetPath))
return new[] { ResolveTargetPath(targetPath) };
if (allLocalDrives && OperatingSystem.IsWindows())
{
string[] drives = DriveInfo.GetDrives()
.Where(drive => drive.IsReady && drive.DriveType == DriveType.Fixed)
.Select(drive => drive.RootDirectory.FullName)
.OrderBy(path => path, StringComparer.OrdinalIgnoreCase)
.ToArray();
if (drives.Length > 0)
return drives;
}
return new[] { ResolveDefaultTargetPath() };
}
public static string ResolveOutputPathForTarget(string outputPath, string targetPath, int targetCount)
{
string fullOutput = Path.GetFullPath(outputPath);
if (targetCount <= 1)
return fullOutput;
string directory = Path.GetDirectoryName(fullOutput) ?? Directory.GetCurrentDirectory();
string fileName = Path.GetFileName(fullOutput);
string suffix = GetTargetSuffix(targetPath);
const string cycloneDxJsonSuffix = ".cdx.json";
string outputFileName = fileName.EndsWith(cycloneDxJsonSuffix, StringComparison.OrdinalIgnoreCase)
? fileName[..^cycloneDxJsonSuffix.Length] + $".{suffix}" + cycloneDxJsonSuffix
: Path.GetFileNameWithoutExtension(fileName) + $".{suffix}" + Path.GetExtension(fileName);
return Path.Combine(directory, outputFileName);
}
public static string ResolveDefaultTargetPath()
{
if (OperatingSystem.IsWindows())
{
string? drive = Environment.GetEnvironmentVariable("SystemDrive");
if (string.IsNullOrWhiteSpace(drive))
drive = "C:";
return $"{drive}\\";
}
return "/";
}
private static string ResolveTargetPath(string? targetPath)
{
if (!string.IsNullOrWhiteSpace(targetPath))
{
string fullPath = Path.GetFullPath(targetPath);
if (!File.Exists(fullPath) && !Directory.Exists(fullPath))
throw new InvalidOperationException($"SBOM target does not exist: {fullPath}");
return fullPath;
}
return ResolveDefaultTargetPath();
}
private static string GetTargetSuffix(string targetPath)
{
string? root = Path.GetPathRoot(targetPath);
string raw = string.IsNullOrWhiteSpace(root) ? targetPath : root;
string suffix = new string(raw
.Where(c => char.IsLetterOrDigit(c))
.ToArray());
return string.IsNullOrWhiteSpace(suffix) ? "root" : suffix;
}
private static string GetSafeHostName()
{
string hostName = Environment.MachineName;
char[] invalidChars = Path.GetInvalidFileNameChars();
string safe = new(hostName
.Select(c => invalidChars.Contains(c) ? '_' : c)
.ToArray());
return string.IsNullOrWhiteSpace(safe) ? "unknown-host" : safe;
}
private static string? WriteDiagnosticsLog(string outputPath, string targetPath, string stdOut, string stdErr)
{
if (string.IsNullOrWhiteSpace(stdOut) && string.IsNullOrWhiteSpace(stdErr))
return null;
const string cycloneDxJsonSuffix = ".cdx.json";
string outputBase = outputPath.EndsWith(cycloneDxJsonSuffix, StringComparison.OrdinalIgnoreCase)
? outputPath[..^cycloneDxJsonSuffix.Length]
: Path.Combine(Path.GetDirectoryName(outputPath) ?? string.Empty, Path.GetFileNameWithoutExtension(outputPath));
string logPath = outputBase + ".trivy.log";
var log = new StringBuilder();
log.AppendLine($"Target: {targetPath}");
log.AppendLine($"SBOM: {outputPath}");
log.AppendLine();
if (!string.IsNullOrWhiteSpace(stdOut))
{
log.AppendLine("STDOUT:");
log.AppendLine(stdOut.TrimEnd());
log.AppendLine();
}
if (!string.IsNullOrWhiteSpace(stdErr))
{
log.AppendLine("STDERR:");
log.AppendLine(stdErr.TrimEnd());
log.AppendLine();
}
File.WriteAllText(logPath, log.ToString());
return logPath;
}
private static string ResolveTrivyPath()
{
string executableName = OperatingSystem.IsWindows() ? "trivy.exe" : "trivy";
var candidates = new[]
{
Path.Combine(AppContext.BaseDirectory, "bin", executableName),
Path.Combine(Directory.GetCurrentDirectory(), "bin", executableName),
Path.Combine(AppContext.BaseDirectory, executableName)
};
foreach (string candidate in candidates)
{
if (File.Exists(candidate))
return candidate;
}
throw new FileNotFoundException(
$"Trivy executable not found. Expected at SCA_SCANNER/bin/{executableName}. Checked: {string.Join(", ", candidates.Select(Path.GetFullPath))}");
}
}