-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathScanner.cs
More file actions
522 lines (447 loc) · 21.1 KB
/
Copy pathScanner.cs
File metadata and controls
522 lines (447 loc) · 21.1 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
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
using System;
using System.Collections.Generic;
using System.IO;
using BinaryObjectScanner.Data;
using BinaryObjectScanner.Interfaces;
using SabreTools.Collections.Extensions;
using SabreTools.IO.Extensions;
using SabreTools.Numerics.Extensions;
using SabreTools.Wrappers;
namespace BinaryObjectScanner
{
public class Scanner
{
#region Instance Variables
/// <summary>
/// Determines whether archives are decompressed and scanned
/// </summary>
private readonly bool _scanArchives;
/// <summary>
/// Determines if content matches are used
/// </summary>
private readonly bool _scanContents;
/// <summary>
/// Determines if path matches are used
/// </summary>
private readonly bool _scanPaths;
/// <summary>
/// Determines if subdirectories are scanned
/// </summary>
private readonly bool _scanSubdirectories;
/// <summary>
/// Determines if debug information is output
/// </summary>
private readonly bool _includeDebug;
/// <summary>
/// Optional progress callback during scanning
/// </summary>
private readonly IProgress<ProtectionProgress>? _fileProgress;
#endregion
/// <summary>
/// Constructor
/// </summary>
/// <param name="scanArchives">Enable scanning archive contents</param>
/// <param name="scanContents">Enable including content detections in output</param>
/// <param name="scanPaths">Enable including path detections in output</param>
/// <param name="scanSubdirectories">Enable scanning subdirectories</param>
/// <param name="includeDebug">Enable including debug information</param>
/// <param name="fileProgress">Optional progress callback</param>
public Scanner(bool scanArchives,
bool scanContents,
bool scanPaths,
bool scanSubdirectories,
bool includeDebug,
IProgress<ProtectionProgress>? fileProgress = null)
{
_scanArchives = scanArchives;
_scanContents = scanContents;
_scanPaths = scanPaths;
_scanSubdirectories = scanSubdirectories;
_includeDebug = includeDebug;
_fileProgress = fileProgress;
#if NET462_OR_GREATER || NETCOREAPP || NETSTANDARD2_0_OR_GREATER
// Register the codepages
System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance);
#endif
}
#region Scanning
/// <summary>
/// Scan a single path and get all found protections
/// </summary>
/// <param name="path">Path to scan</param>
/// <returns>Dictionary of list of strings representing the found protections</returns>
public Dictionary<string, List<string>> GetProtections(string path)
=> GetProtectionsImpl(path, depth: 0).ToDictionary();
/// <summary>
/// Scan the list of paths and get all found protections
/// </summary>
/// <param name="paths">Paths to scan</param>
/// <returns>Dictionary of list of strings representing the found protections</returns>
public Dictionary<string, List<string>> GetProtections(List<string>? paths)
=> GetProtectionsImpl(paths, depth: 0).ToDictionary();
/// <summary>
/// Scan a single path and get all found protections
/// </summary>
/// <param name="path">Path to scan</param>
/// <param name="depth">Depth of the current scanner pertaining to extracted data</param>
/// <returns>Dictionary of list of strings representing the found protections</returns>
private ProtectionDictionary GetProtectionsImpl(string path, int depth)
=> GetProtectionsImpl([path], depth);
/// <summary>
/// Scan a single path and get all found protections
/// </summary>
/// <param name="paths">Paths to scan</param>
/// <param name="depth">Depth of the current scanner pertaining to extracted data</param>
/// <returns>Dictionary of list of strings representing the found protections</returns>
private ProtectionDictionary GetProtectionsImpl(List<string>? paths, int depth)
{
// If we have no paths, we can't scan
if (paths is null || paths.Count == 0)
{
if (_includeDebug) Console.WriteLine("No paths found to scan, skipping...");
return [];
}
// Set a starting starting time for debug output
DateTime startTime = DateTime.UtcNow;
// Checkpoint
_fileProgress?.Report(new ProtectionProgress(null, depth, 0, null));
// Temp variables for reporting
string tempFilePath = Path.GetTempPath();
string tempFilePathWithGuid = Path.Combine(tempFilePath, Guid.NewGuid().ToString());
// Loop through each path and get the returned values
var protections = new ProtectionDictionary();
foreach (string path in paths)
{
// Directories scan each internal file individually
if (Directory.Exists(path))
{
// Enumerate all files at first for easier access
SearchOption searchOption = _scanSubdirectories ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
List<string> files = [.. IOExtensions.SafeGetFiles(path, "*", searchOption)];
// Scan for path-detectable protections
if (_scanPaths)
{
var directoryPathProtections = HandlePathChecks(path, files);
protections.Append(directoryPathProtections);
}
// Scan each file in directory separately
for (int i = 0; i < files.Count; i++)
{
// Get the current file
string file = files[i];
// Get the reportable file name
string reportableFileName = file;
if (reportableFileName.StartsWith(tempFilePath))
#if NETCOREAPP || NETSTANDARD2_1_OR_GREATER
reportableFileName = reportableFileName[tempFilePathWithGuid.Length..];
#else
reportableFileName = reportableFileName.Substring(tempFilePathWithGuid.Length);
#endif
// Checkpoint
_fileProgress?.Report(new ProtectionProgress(reportableFileName, depth, i / (float)files.Count, "Checking file" + (file != reportableFileName ? " from archive" : string.Empty)));
// Scan for path-detectable protections
if (_scanPaths)
{
var filePathProtections = HandlePathChecks(file, files: null);
if (filePathProtections is not null && filePathProtections.Count > 0)
protections.Append(filePathProtections);
}
// Scan for content-detectable protections
var fileProtections = GetInternalProtections(file, depth);
if (fileProtections is not null && fileProtections.Count > 0)
protections.Append(fileProtections);
// Checkpoint
protections.TryGetValue(file, out var fullProtectionList);
#if NET20 || NET35
var fullProtection = fullProtectionList is not null && fullProtectionList.Count > 0
#else
var fullProtection = fullProtectionList is not null && !fullProtectionList.IsEmpty
#endif
? string.Join(", ", [.. fullProtectionList])
: null;
_fileProgress?.Report(new ProtectionProgress(reportableFileName, depth, (i + 1) / (float)files.Count, fullProtection ?? string.Empty));
}
}
// Scan a single file by itself
else if (File.Exists(path))
{
// Get the reportable file name
string reportableFileName = path;
if (reportableFileName.StartsWith(tempFilePath))
#if NETCOREAPP || NETSTANDARD2_1_OR_GREATER
reportableFileName = reportableFileName[tempFilePathWithGuid.Length..];
#else
reportableFileName = reportableFileName.Substring(tempFilePathWithGuid.Length);
#endif
// Checkpoint
_fileProgress?.Report(new ProtectionProgress(reportableFileName, depth, 0, "Checking file" + (path != reportableFileName ? " from archive" : string.Empty)));
// Scan for path-detectable protections
if (_scanPaths)
{
var filePathProtections = HandlePathChecks(path, files: null);
if (filePathProtections is not null && filePathProtections.Count > 0)
protections.Append(filePathProtections);
}
// Scan for content-detectable protections
var fileProtections = GetInternalProtections(path, depth);
if (fileProtections is not null && fileProtections.Count > 0)
protections.Append(fileProtections);
// Checkpoint
protections.TryGetValue(path, out var fullProtectionList);
#if NET20 || NET35
var fullProtection = fullProtectionList is not null && fullProtectionList.Count > 0
#else
var fullProtection = fullProtectionList is not null && !fullProtectionList.IsEmpty
#endif
? string.Join(", ", [.. fullProtectionList])
: null;
_fileProgress?.Report(new ProtectionProgress(reportableFileName, depth, 1, fullProtection ?? string.Empty));
}
// Invalid path
else
{
if (_includeDebug) Console.Error.WriteLine($"{path} is not a directory or file, skipping...");
//throw new FileNotFoundException($"{path} is not a directory or file, skipping...");
}
}
// Clear out any empty keys
protections.ClearEmptyKeys();
// If we're in debug, output the elasped time to console
if (_includeDebug)
Console.WriteLine($"Time elapsed: {DateTime.UtcNow.Subtract(startTime)}");
return protections;
}
/// <summary>
/// Get the content-detectable protections associated with a single path
/// </summary>
/// <param name="file">Path to the file to scan</param>
/// <param name="depth">Depth of the current scanner pertaining to extracted data</param>
/// <returns>Dictionary of list of strings representing the found protections</returns>
private ProtectionDictionary GetInternalProtections(string file, int depth)
{
// Quick sanity check before continuing
if (!File.Exists(file))
{
if (_includeDebug) Console.WriteLine($"{file} does not exist, skipping...");
return [];
}
// Open the file and begin scanning
try
{
using FileStream fs = File.Open(file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
return GetInternalProtections(fs.Name, fs, depth);
}
catch (DirectoryNotFoundException ex)
{
if (_includeDebug) Console.WriteLine(ex);
return [];
}
catch (FileNotFoundException ex)
{
if (_includeDebug) Console.WriteLine(ex);
return [];
}
catch (UnauthorizedAccessException ex)
{
if (_includeDebug) Console.WriteLine(ex);
var protections = new ProtectionDictionary();
protections.Append(file, _includeDebug ? ex.ToString() : "[Access issue when opening file, please check permissions and try again]");
return protections;
}
catch (Exception ex)
{
if (_includeDebug) Console.WriteLine(ex);
var protections = new ProtectionDictionary();
protections.Append(file, _includeDebug ? ex.ToString() : "[Exception opening file, please try again]");
return protections;
}
}
/// <summary>
/// Get the content-detectable protections associated with a single path
/// </summary>
/// <param name="fileName">Name of the source file of the stream, for tracking</param>
/// <param name="stream">Stream to scan the contents of</param>
/// <param name="depth">Depth of the current scanner pertaining to extracted data</param>
/// <returns>Dictionary of list of strings representing the found protections</returns>
private ProtectionDictionary GetInternalProtections(string fileName, Stream stream, int depth)
{
// Quick sanity check before continuing
if (!stream.CanRead)
{
if (_includeDebug) Console.WriteLine($"{fileName} does not have a readable stream, skipping...");
return [];
}
// Get the extension for certain checks
string extension = Path.GetExtension(fileName).ToLower().TrimStart('.');
// Get the first 16 bytes for matching
byte[] magic;
try
{
int bytesToRead = (int)Math.Min(16, stream.Length);
magic = stream.ReadBytes(bytesToRead);
stream.Seek(0, SeekOrigin.Begin);
}
catch (Exception ex)
{
if (_includeDebug) Console.Error.WriteLine(ex);
return [];
}
// Get the file type either from magic number or extension
WrapperType fileType = WrapperFactory.GetFileType(magic, extension);
if (fileType == WrapperType.UNKNOWN)
{
if (_includeDebug) Console.WriteLine($"{fileName} not a scannable file type, skipping...");
return [];
}
// Get the wrapper, if possible
var wrapper = WrapperFactory.CreateWrapper(fileType, stream);
// Initialize the protections found
var protections = new ProtectionDictionary();
#region Non-Archive File Types
// Try to scan file contents
var detectable = CreateDetectable(fileType, wrapper);
if (_scanContents && detectable is not null)
{
try
{
var subProtection = detectable.Detect(stream, fileName, _includeDebug);
protections.Append(fileName, subProtection);
}
catch (Exception ex)
{
if (_includeDebug) Console.WriteLine(ex);
protections.Append(fileName, _includeDebug ? ex.ToString() : "[Exception opening file, please try again]");
}
}
#endregion
#region Archive File Types
// If we're scanning archives
if (_scanArchives && wrapper is IExtractable extractable)
{
// If the extractable file itself fails
try
{
// Extract and get the output path
string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
Directory.CreateDirectory(tempPath);
_ = extractable.Extract(tempPath, _includeDebug);
// Check if any files extracted
if (IOExtensions.SafeGetFileSystemEntries(tempPath).Length > 0)
{
// Scan the output path
var subProtections = GetProtectionsImpl(tempPath, depth + 1);
// Prepare the returned values
subProtections.StripFromKeys(tempPath);
subProtections.PrependToKeys(fileName);
// Append the values
protections.Append(subProtections);
}
// If temp directory cleanup fails
try
{
if (Directory.Exists(tempPath))
Directory.Delete(tempPath, true);
}
catch (Exception ex)
{
if (_includeDebug) Console.Error.WriteLine(ex);
}
}
catch (Exception ex)
{
if (_includeDebug) Console.Error.WriteLine(ex);
}
}
#endregion
// Clear out any empty keys
protections.ClearEmptyKeys();
return protections;
}
#endregion
#region Path Handling
/// <summary>
/// Handle a single path based on all path check implementations
/// </summary>
/// <param name="path">Path of the file or directory to check</param>
/// <param name="scanner">Scanner object to use for options and scanning</param>
/// <returns>Set of protections in file, null on error</returns>
private static ProtectionDictionary HandlePathChecks(string path, List<string>? files)
{
// Create the output dictionary
var protections = new ProtectionDictionary();
// Preprocess the list of files
files = files?
.ConvertAll(f => f.Replace(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar));
// Iterate through all checks
StaticChecks.PathCheckClasses.IterateWithAction(checkClass =>
{
var subProtections = PerformPathCheck(checkClass, path, files);
protections.Append(path, subProtections);
});
return protections;
}
/// <summary>
/// Handle files based on an IPathCheck implementation
/// </summary>
/// <param name="impl">IPathCheck class representing the file type</param>
/// <param name="path">Path of the file or directory to check</param>
/// <returns>Set of protections in path, empty on error</returns>
private static List<string> PerformPathCheck(IPathCheck impl, string? path, List<string>? files)
{
// If we have an invalid path
if (string.IsNullOrEmpty(path))
return [];
// Setup the list
var protections = new List<string>();
// If we have a file path
if (File.Exists(path))
{
var protection = impl.CheckFilePath(path!);
if (protection is not null)
protections.Add(protection);
}
// If we have a directory path
if (Directory.Exists(path) && files is not null && files.Count > 0)
{
var subProtections = impl.CheckDirectoryPath(path!, files);
if (subProtections is not null)
protections.AddRange(subProtections);
}
return protections;
}
#endregion
#region Helpers
/// <summary>
/// Create an instance of a detectable based on file type
/// </summary>
private static IDetectable? CreateDetectable(WrapperType fileType, IWrapper? wrapper)
{
// Use the wrapper before the type
return wrapper switch
{
AACSMediaKeyBlock obj => new FileType.AACSMediaKeyBlock(obj),
BDPlusSVM obj => new FileType.BDPlusSVM(obj),
GCF obj => new FileType.GCF(obj),
ISO9660 obj => new FileType.ISO9660(obj),
LDSCRYPT obj => new FileType.LDSCRYPT(obj),
LinearExecutable obj => new FileType.LinearExecutable(obj),
MSDOS obj => new FileType.MSDOS(obj),
NewExecutable obj => new FileType.NewExecutable(obj),
PlayJAudioFile obj => new FileType.PLJ(obj),
PortableExecutable obj => new FileType.PortableExecutable(obj),
RealArcadeInstaller obj => new FileType.RealArcadeInstaller(obj),
RealArcadeMezzanine obj => new FileType.RealArcadeMezzanine(obj),
SFFS obj => new FileType.SFFS(obj),
// Fall back on the file type for types not implemented in Serialization
#pragma warning disable IDE0072
_ => fileType switch
{
WrapperType.Textfile => new FileType.Textfile(),
_ => null,
},
#pragma warning restore IDE0072
};
}
#endregion
}
}