-
Notifications
You must be signed in to change notification settings - Fork 29
/
Program.cs
1677 lines (1373 loc) · 72.1 KB
/
Program.cs
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
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Collections.Generic;
using System.CommandLine;
using System.CommandLine.Help;
using System.CommandLine.NamingConventionBinder;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.Principal;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
#if NET462
using Alphaleonis.Win32.Filesystem;
using Directory = Alphaleonis.Win32.Filesystem.Directory;
using File = Alphaleonis.Win32.Filesystem.File;
using Path = Alphaleonis.Win32.Filesystem.Path;
#else
using Path = System.IO.Path;
using Directory = System.IO.Directory;
using File = System.IO.File;
#endif
using Exceptionless;
using ExtensionBlocks;
using Lnk;
using Lnk.ExtraData;
using Lnk.ShellItems;
using Serilog;
using Serilog.Core;
using Serilog.Events;
using ServiceStack;
using ServiceStack.Text;
using Spectre.Console;
using CsvWriter = CsvHelper.CsvWriter;
using Resources = LECmd.Properties.Resources;
using ShellBag = Lnk.ShellItems.ShellBag;
using VolumeInfo = Lnk.VolumeInfo;
namespace LECmd;
internal class Program
{
private static readonly string PreciseTimeFormat = "yyyy-MM-dd HH:mm:ss.fffffff";
private static string _activeDateTimeFormat;
private static RootCommand _rootCommand;
private static readonly string Header = $"LECmd version {Assembly.GetExecutingAssembly().GetName().Version}" +
"\r\n\r\nAuthor: Eric Zimmerman (saericzimmerman@gmail.com)" +
"\r\nhttps://github.com/EricZimmerman/LECmd";
private static readonly string Footer = @"Examples: LECmd.exe -f ""C:\Temp\foobar.lnk""" + "\r\n\t " +
@" LECmd.exe -f ""C:\Temp\somelink.lnk"" --json ""D:\jsonOutput"" --pretty" +
"\r\n\t " +
@" LECmd.exe -d ""C:\Temp"" --csv ""c:\temp"" --html c:\temp --xml c:\temp\xml -q" +
"\r\n\t " +
@" LECmd.exe -f ""C:\Temp\some other link.lnk"" --nid --neb " +
"\r\n\t " +
@" LECmd.exe -d ""C:\Temp"" --all" + "\r\n\t" +
"\r\n\t" +
" Short options (single letter) are prefixed with a single dash. Long commands are prefixed with two dashes\r\n";
private static List<string> _failedFiles;
private static readonly Dictionary<string, string> MacList = new Dictionary<string, string>();
private static List<LnkFile> _processedFiles;
private static void LoadMacs()
{
var lines = Resources.MACs.Split(new[] {Environment.NewLine}, StringSplitOptions.None);
foreach (var line in lines)
{
if (line.Trim().Length == 0)
{
continue;
}
var segs = line.ToUpperInvariant().Split('\t');
var key = segs[0].Trim();
var val = segs[1].Trim();
if (MacList.ContainsKey(key) == false)
{
MacList.Add(key, val);
}
}
}
private static bool IsAdministrator()
{
if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
return true;
}
var identity = WindowsIdentity.GetCurrent();
var principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
private static async Task Main(string[] args)
{
ExceptionlessClient.Default.Startup("FNWfyFuaUAPnVfofTZAhZOgeDG5lv7AnjYKNtsEJ");
LoadMacs();
_rootCommand = new RootCommand
{
new Option<string>(
"-f",
description: "File to process. Either this or -d is required"),
new Option<string>(
"-d",
description: "Directory to recursively process. Either this or -f is required"),
new Option<bool>(
"-r",
getDefaultValue: () => false,
"Only process lnk files pointing to removable drives"),
new Option<bool>(
"-q",
getDefaultValue: () => false,
"Only show the filename being processed vs all output. Useful to speed up exporting to json and/or csv"),
new Option<bool>(
"--all",
getDefaultValue: () => false,
"Process all files in directory vs. only files matching *.lnk"),
new Option<string>(
"--csv",
"Directory to save CSV formatted results to. Be sure to include the full path in double quotes"),
new Option<string>(
"--csvf",
"File name to save CSV formatted results to. When present, overrides default name\r\n"),
new Option<string>(
"--xml",
"Directory to save XML formatted results to. Be sure to include the full path in double quotes"),
new Option<string>(
"--html",
"Directory to save xhtml formatted results to. Be sure to include the full path in double quotes"),
new Option<string>(
"--json",
"Directory to save json representation to. Use --pretty for a more human readable layout"),
new Option<bool>(
"--pretty",
getDefaultValue: () => false,
"When exporting to json, use a more human readable layout"),
new Option<bool>(
"--nid",
getDefaultValue: () => false,
"Suppress Target ID list details from being displayed"),
new Option<bool>(
"--neb",
getDefaultValue: () => false,
"Suppress Extra blocks information from being displayed"),
new Option<string>(
"--dt",
getDefaultValue: () => "yyyy-MM-dd HH:mm:ss",
"The custom date/time format to use when displaying time stamps. See https://goo.gl/CNVq0k for options"),
new Option<bool>(
"--mp",
getDefaultValue: () => false,
"Display higher precision for time stamps"),
new Option<bool>(
"--debug",
() => false,
"Show debug information during processing"),
new Option<bool>(
"--trace",
() => false,
"Show trace information during processing")
};
_rootCommand.Description = Header + "\r\n\r\n" + Footer;
_rootCommand.Handler = CommandHandler.Create(DoWork);
await _rootCommand.InvokeAsync(args);
Log.CloseAndFlush();
}
class DateTimeOffsetFormatter : IFormatProvider, ICustomFormatter
{
private readonly IFormatProvider _innerFormatProvider;
public DateTimeOffsetFormatter(IFormatProvider innerFormatProvider)
{
_innerFormatProvider = innerFormatProvider;
}
public object GetFormat(Type formatType)
{
return formatType == typeof(ICustomFormatter) ? this : _innerFormatProvider.GetFormat(formatType);
}
public string Format(string format, object arg, IFormatProvider formatProvider)
{
if (arg is DateTimeOffset)
{
var size = (DateTimeOffset) arg;
return size.ToString(_activeDateTimeFormat);
}
var formattable = arg as IFormattable;
if (formattable != null)
{
return formattable.ToString(format, _innerFormatProvider);
}
return arg.ToString();
}
}
private static void DoWork(string f, string d, bool r, bool q, bool all, string csv, string csvf, string xml,
string html, string json, bool pretty, bool nid, bool neb, string dt, bool mp, bool debug, bool trace)
{
_activeDateTimeFormat = dt;
if (mp)
{
_activeDateTimeFormat = PreciseTimeFormat;
}
var formatter =
new DateTimeOffsetFormatter(CultureInfo.CurrentCulture);
var levelSwitch = new LoggingLevelSwitch();
var template = "{Message:lj}{NewLine}{Exception}";
if (debug)
{
levelSwitch.MinimumLevel = LogEventLevel.Debug;
template = "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}";
}
if (trace)
{
levelSwitch.MinimumLevel = LogEventLevel.Verbose;
template = "[{Timestamp:HH:mm:ss.fff} {Level:u3}] {Message:lj}{NewLine}{Exception}";
}
var conf = new LoggerConfiguration()
.WriteTo.Console(outputTemplate: template, formatProvider: formatter)
.MinimumLevel.ControlledBy(levelSwitch);
Log.Logger = conf.CreateLogger();
if (f.IsNullOrEmpty() && d.IsNullOrEmpty())
{
var helpBld = new HelpBuilder(LocalizationResources.Instance, Console.WindowWidth);
var hc = new HelpContext(helpBld, _rootCommand, Console.Out);
helpBld.Write(hc);
Log.Warning("Either -f or -d is required. Exiting");
Console.WriteLine();
return;
}
if (f.IsNullOrEmpty() == false && !File.Exists(f))
{
var helpBld = new HelpBuilder(LocalizationResources.Instance, Console.WindowWidth);
var hc = new HelpContext(helpBld, _rootCommand, Console.Out);
helpBld.Write(hc);
Log.Warning("File {F} not found. Exiting",f);
Console.WriteLine();
return;
}
if (d.IsNullOrEmpty() == false &&
!Directory.Exists(d))
{
var helpBld = new HelpBuilder(LocalizationResources.Instance, Console.WindowWidth);
var hc = new HelpContext(helpBld, _rootCommand, Console.Out);
helpBld.Write(hc);
Log.Warning("Directory {D} not found. Exiting",d);
Console.WriteLine();
return;
}
Log.Information("{Header}",Header);
Console.WriteLine();
Log.Information("Command line: {Args}",string.Join(" ", Environment.GetCommandLineArgs().Skip(1)));
Console.WriteLine();
if (IsAdministrator() == false)
{
Log.Warning($"Warning: Administrator privileges not found!");
Console.WriteLine();
Console.WriteLine();
}
_processedFiles = new List<LnkFile>();
_failedFiles = new List<string>();
var tsNow = DateTimeOffset.UtcNow;
if (f?.Length > 0)
{
LnkFile lnk;
try
{
f = Path.GetFullPath(f);
lnk = ProcessFile(f, q, r, dt, nid, neb);
if (lnk != null)
{
_processedFiles.Add(lnk);
}
}
catch (UnauthorizedAccessException ua)
{
Log.Error(ua,
"Unable to access {F}. Are you running as an administrator? Error: {Message}",f,ua.Message);
return;
}
catch (Exception ex)
{
Log.Error(ex,
"Error processing file {F} Please send it to saericzimmerman@gmail.com. Error: {Message}",f,ex.Message);
return;
}
}
else
{
Log.Information("Looking for lnk files in {D}",d);
Console.WriteLine();
d = Path.GetFullPath(d);
string[] lnkFiles;
try
{
var mask = "*.lnk";
if (all)
{
mask = "*";
}
IEnumerable<string> files2;
#if NET6_0
var enumerationOptions = new EnumerationOptions
{
IgnoreInaccessible = true,
MatchCasing = MatchCasing.CaseInsensitive,
RecurseSubdirectories = true,
AttributesToSkip = 0
};
files2 =
Directory.EnumerateFileSystemEntries(d, mask,enumerationOptions);
#elif NET462
// Legacy implementation for previous frameworks
var directoryEnumerationFilters = new DirectoryEnumerationFilters();
directoryEnumerationFilters.InclusionFilter = fsei =>
{
if (fsei.FileSize == 0)
{
return false;
}
mask = ".lnk".ToUpperInvariant();
if (all)
{
mask = "*";
}
if (mask == "*")
{
return true;
}
if (fsei.Extension.ToUpperInvariant() == mask)
{
return true;
}
return false;
};
directoryEnumerationFilters.RecursionFilter =
entryInfo => !entryInfo.IsMountPoint && !entryInfo.IsSymbolicLink;
directoryEnumerationFilters.ErrorFilter = (errorCode, errorMessage, pathProcessed) => true;
var dirEnumOptions =
DirectoryEnumerationOptions.Files | DirectoryEnumerationOptions.Recursive |
DirectoryEnumerationOptions.SkipReparsePoints | DirectoryEnumerationOptions.ContinueOnException |
DirectoryEnumerationOptions.BasicSearch ;
files2 =
Alphaleonis.Win32.Filesystem.Directory.EnumerateFileSystemEntries(d, dirEnumOptions, directoryEnumerationFilters);
// files2 =
// Directory.EnumerateFileSystemEntries(d, mask,SearchOption.AllDirectories);
#endif
lnkFiles = files2.ToArray();
// lnkFiles = Directory.GetFiles(_fluentCommandLineParser.Object.Directory, mask,
// SearchOption.AllDirectories);
}
catch (UnauthorizedAccessException ua)
{
Log.Error(ua,
"Unable to access {D}. Error message: {Message}",d,ua.Message);
return;
}
catch (Exception ex)
{
Log.Error(ex,
"Error getting lnk files in {D}. Error: {Message}",d,ex.Message);
return;
}
Log.Information("Found {Length:N0} files",lnkFiles.Length);
Console.WriteLine();
var sw = new Stopwatch();
sw.Start();
foreach (var file in lnkFiles)
{
var lnk = ProcessFile(file, q, r, dt, nid, neb);
if (lnk != null)
{
_processedFiles.Add(lnk);
}
}
sw.Stop();
if (q)
{
Console.WriteLine();
}
Log.Information(
"Processed {ProcessedCount:N0} out of {TotalFiles:N0} files in {TotalSeconds:N4} seconds",lnkFiles.Length - _failedFiles.Count,lnkFiles.Length,sw.Elapsed.TotalSeconds);
if (_failedFiles.Count > 0)
{
Console.WriteLine();
Log.Information("Failed files");
foreach (var failedFile in _failedFiles)
{
Log.Information(" {FailedFile}",failedFile);
}
}
}
if (_processedFiles.Count > 0)
{
Console.WriteLine();
try
{
CsvWriter csvWriter = null;
StreamWriter sw = null;
if (csv?.Length > 0)
{
if (Directory.Exists(csv) == false)
{
Log.Information(
"{Csv} does not exist. Creating...",csv);
Directory.CreateDirectory(csv);
}
var outName = $"{tsNow:yyyyMMddHHmmss}_LECmd_Output.csv";
if (csvf.IsNullOrEmpty() == false)
{
outName = Path.GetFileName(csvf);
}
var outFile = Path.Combine(csv, outName);
csv = Path.GetFullPath(outFile);
Log.Information(
"CSV output will be saved to {Path}",Path.GetFullPath(outFile));
try
{
sw = new StreamWriter(outFile);
csvWriter = new CsvWriter(sw, CultureInfo.InvariantCulture);
csvWriter.WriteHeader(typeof(CsvOut));
csvWriter.NextRecord();
}
catch (Exception ex)
{
Log.Error(ex,
"Unable to open {OutFile} for writing. CSV export canceled. Error: {Message}",outFile,ex.Message);
}
}
if (json?.Length > 0)
{
if (Directory.Exists(json) == false)
{
Log.Information(
"{Json} does not exist. Creating...",json);
Directory.CreateDirectory(json);
}
Log.Information("Saving json output to {Json}",json);
}
if (xml?.Length > 0)
{
{
if (Directory.Exists(xml) == false)
{
Log.Information("{Xml} does not exist. Creating...",xml);
Directory.CreateDirectory(xml);
}
}
Log.Information("Saving XML output to {Xml}",xml);
}
XmlTextWriter xmlTextWriter = null;
StreamWriter jsonOut = null;
if (json?.Length > 0)
{
JsConfig.DateHandler = DateHandler.ISO8601;
if (Directory.Exists(json) == false)
{
Directory.CreateDirectory(json);
}
var outName =
$"{tsNow:yyyyMMddHHmmss}_LECmd_Output.json";
var outFile = Path.Combine(json, outName);
jsonOut = new StreamWriter(new FileStream(outFile, FileMode.OpenOrCreate, FileAccess.Write),
new UTF8Encoding(false));
}
if (html?.Length > 0)
{
var outDir = Path.Combine(html,
$"{tsNow:yyyyMMddHHmmss}_LECmd_Output_for_{html.Replace(@":\", "_").Replace(@"\", "_")}");
if (Directory.Exists(outDir) == false)
{
Directory.CreateDirectory(outDir);
}
File.WriteAllText(Path.Combine(outDir, "normalize.css"), Resources.normalize);
File.WriteAllText(Path.Combine(outDir, "style.css"), Resources.style);
var outFile = Path.Combine(html, outDir, "index.xhtml");
Log.Information("Saving HTML output to {OutFile}",outFile);
xmlTextWriter = new XmlTextWriter(outFile, Encoding.UTF8)
{
Formatting = Formatting.Indented,
Indentation = 4
};
xmlTextWriter.WriteStartDocument();
xmlTextWriter.WriteProcessingInstruction("xml-stylesheet", "href=\"normalize.css\"");
xmlTextWriter.WriteProcessingInstruction("xml-stylesheet", "href=\"style.css\"");
xmlTextWriter.WriteStartElement("document");
}
foreach (var processedFile in _processedFiles)
{
var o = GetCsvFormat(processedFile, false, dt);
try
{
csvWriter?.WriteRecord(o);
csvWriter?.NextRecord();
}
catch (Exception ex)
{
Log.Error(ex,
"Error writing record for {SourceFile} to {Csv}. Error: {Message}",processedFile.SourceFile,csv,ex.Message);
}
if (jsonOut != null)
{
var oldDt = dt;
dt = "o";
var cs = GetCsvFormat(processedFile, true, dt);
dt = oldDt;
if (pretty)
{
jsonOut.WriteLine(cs.Dump());
}
else
{
jsonOut.WriteLine(cs.ToJson());
}
}
//XHTML
xmlTextWriter?.WriteStartElement("Container");
xmlTextWriter?.WriteElementString("SourceFile", o.SourceFile);
xmlTextWriter?.WriteElementString("SourceCreated", o.SourceCreated);
xmlTextWriter?.WriteElementString("SourceModified", o.SourceModified);
xmlTextWriter?.WriteElementString("SourceAccessed", o.SourceAccessed);
xmlTextWriter?.WriteElementString("TargetCreated", o.TargetCreated);
xmlTextWriter?.WriteElementString("TargetModified", o.TargetModified);
xmlTextWriter?.WriteElementString("TargetAccessed", o.TargetAccessed);
xmlTextWriter?.WriteElementString("FileSize", o.FileSize.ToString());
xmlTextWriter?.WriteElementString("RelativePath", o.RelativePath);
xmlTextWriter?.WriteElementString("WorkingDirectory", o.WorkingDirectory);
xmlTextWriter?.WriteElementString("FileAttributes", o.FileAttributes);
xmlTextWriter?.WriteElementString("HeaderFlags", o.HeaderFlags);
xmlTextWriter?.WriteElementString("DriveType", o.DriveType);
xmlTextWriter?.WriteElementString("VolumeSerialNumber", o.VolumeSerialNumber);
xmlTextWriter?.WriteElementString("VolumeLabel", o.VolumeLabel);
xmlTextWriter?.WriteElementString("LocalPath", o.LocalPath);
xmlTextWriter?.WriteElementString("NetworkPath", o.NetworkPath);
xmlTextWriter?.WriteElementString("CommonPath", o.CommonPath);
xmlTextWriter?.WriteElementString("Arguments", o.Arguments);
xmlTextWriter?.WriteElementString("TargetIDAbsolutePath", o.TargetIDAbsolutePath);
xmlTextWriter?.WriteElementString("TargetMFTEntryNumber", $"{o.TargetMFTEntryNumber}");
xmlTextWriter?.WriteElementString("TargetMFTSequenceNumber",
$"{o.TargetMFTSequenceNumber}");
xmlTextWriter?.WriteElementString("MachineID", o.MachineID);
xmlTextWriter?.WriteElementString("MachineMACAddress", o.MachineMACAddress);
xmlTextWriter?.WriteElementString("MACVendor", o.MACVendor);
xmlTextWriter?.WriteElementString("TrackerCreatedOn", o.TrackerCreatedOn);
xmlTextWriter?.WriteElementString("ExtraBlocksPresent", o.ExtraBlocksPresent);
xmlTextWriter?.WriteEndElement();
if (xml?.Length > 0)
{
SaveXml(o, xml);
}
}
//Close CSV stuff
sw?.Flush();
sw?.Close();
//close json
jsonOut?.Flush();
jsonOut?.Close();
//Close XML
xmlTextWriter?.WriteEndElement();
xmlTextWriter?.WriteEndDocument();
xmlTextWriter?.Flush();
}
catch (Exception ex)
{
Log.Error(ex,"Error exporting data! Error: {Message}",ex.Message);
}
}
}
private static CsvOut GetCsvFormat(LnkFile lnk, bool nukeNulls, string datetimeFormat)
{
string netPath = String.Empty;
if (lnk.NetworkShareInfo != null)
{
netPath = lnk.NetworkShareInfo.NetworkShareName;
}
var csOut = new CsvOut
{
SourceFile = lnk.SourceFile.Replace("\\\\?\\", ""),
SourceCreated = lnk.SourceCreated?.ToString(datetimeFormat) ?? string.Empty,
SourceModified = lnk.SourceModified?.ToString(datetimeFormat) ?? string.Empty,
SourceAccessed = lnk.SourceAccessed?.ToString(datetimeFormat) ?? string.Empty,
TargetCreated = lnk.Header.TargetCreationDate.Year == 1601
? string.Empty
: lnk.Header.TargetCreationDate.ToString(datetimeFormat),
TargetModified = lnk.Header.TargetModificationDate.Year == 1601
? string.Empty
: lnk.Header.TargetModificationDate.ToString(datetimeFormat),
TargetAccessed = lnk.Header.TargetLastAccessedDate.Year == 1601
? String.Empty
: lnk.Header.TargetLastAccessedDate.ToString(datetimeFormat),
CommonPath = lnk.CommonPath,
VolumeLabel = lnk.VolumeInfo?.VolumeLabel,
VolumeSerialNumber = lnk.VolumeInfo?.VolumeSerialNumber,
DriveType = lnk.VolumeInfo == null ? "(None)" : GetDescriptionFromEnumValue(lnk.VolumeInfo.DriveType),
FileAttributes = lnk.Header.FileAttributes.ToString(),
FileSize = lnk.Header.FileSize,
HeaderFlags = lnk.Header.DataFlags.ToString(),
LocalPath = lnk.LocalPath,
NetworkPath = netPath,
RelativePath = lnk.RelativePath,
Arguments = lnk.Arguments
};
if (lnk.TargetIDs?.Count > 0)
{
csOut.TargetIDAbsolutePath = GetAbsolutePathFromTargetIDs(lnk.TargetIDs);
}
csOut.WorkingDirectory = lnk.WorkingDirectory;
var ebPresent = string.Empty;
if (lnk.ExtraBlocks.Count > 0)
{
var names = new List<string>();
foreach (var extraDataBase in lnk.ExtraBlocks)
{
names.Add(extraDataBase.GetType().Name);
}
ebPresent = string.Join(", ", names);
}
csOut.ExtraBlocksPresent = ebPresent;
var tnb = lnk.ExtraBlocks.SingleOrDefault(t => t.GetType().Name.ToUpper() == "TRACKERDATABASEBLOCK");
if (tnb != null)
{
var tnbBlock = tnb as TrackerDataBaseBlock;
csOut.TrackerCreatedOn = tnbBlock?.CreationTime.ToString(datetimeFormat);
csOut.MachineID = tnbBlock?.MachineId;
csOut.MachineMACAddress = tnbBlock?.MacAddress;
csOut.MACVendor = GetVendorFromMac(tnbBlock?.MacAddress);
}
if (lnk.TargetIDs?.Count > 0)
{
var si = lnk.TargetIDs.Last();
if (si.ExtensionBlocks?.Count > 0)
{
var eb = si.ExtensionBlocks.LastOrDefault(t => t is Beef0004);
if (eb is Beef0004)
{
var eb4 = eb as Beef0004;
if (eb4.MFTInformation.MFTEntryNumber != null)
{
csOut.TargetMFTEntryNumber = $"0x{eb4.MFTInformation.MFTEntryNumber.Value:X}";
}
if (eb4.MFTInformation.MFTSequenceNumber != null)
{
csOut.TargetMFTSequenceNumber =
$"0x{eb4.MFTInformation.MFTSequenceNumber.Value:X}";
}
}
}
}
if (nukeNulls)
{
foreach (var prop in csOut.GetType().GetProperties())
{
if (prop.GetValue(csOut) as string == string.Empty)
{
prop.SetValue(csOut, null);
}
}
}
return csOut;
}
private static void SaveXml(CsvOut csout, string outDir)
{
try
{
if (Directory.Exists(outDir) == false)
{
Directory.CreateDirectory(outDir);
}
var outName =
$"{DateTimeOffset.UtcNow:yyyyMMddHHmmss}_{Path.GetFileName(csout.SourceFile)}.xml";
var outFile = Path.Combine(outDir, outName);
File.WriteAllText(outFile, csout.ToXml());
}
catch (Exception ex)
{
Log.Error(ex,"Error exporting XML for {SourceFile}. Error: {Message}",csout.SourceFile,ex.Message);
}
}
private static string GetDescriptionFromEnumValue(Enum value)
{
var attribute = value.GetType()
.GetField(value.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.SingleOrDefault() as DescriptionAttribute;
return attribute?.Description;
}
private static string GetAbsolutePathFromTargetIDs(List<ShellBag> ids)
{
var absPath = string.Empty;
foreach (var shellBag in ids)
{
absPath += shellBag.Value + @"\";
}
absPath = absPath.Substring(0, absPath.Length - 1);
return absPath;
}
private static LnkFile ProcessFile(string lnkFile, bool quiet, bool removableOnly, string datetimeFormat, bool nid,
bool neb)
{
if (quiet == false)
{
Log.Information("Processing {Name}",lnkFile.Replace("\\\\?\\", ""));
Console.WriteLine();
}
var sw = new Stopwatch();
sw.Start();
try
{
var lnk = Lnk.Lnk.LoadFile(lnkFile);
if (removableOnly && lnk.VolumeInfo?.DriveType != VolumeInfo.DriveTypes.DriveRemovable)
{
return null;
}
if (quiet == false)
{
Log.Information("Source file: {Name}",lnk.SourceFile.Replace("\\\\?\\", ""));
Log.Information(" Source created: {Date}",lnk.SourceCreated);
Log.Information(" Source modified: {Date}",lnk.SourceModified);
Log.Information(" Source accessed: {Date}",lnk.SourceAccessed);
Console.WriteLine();
Log.Information("--- Header ---");
DateTimeOffset? tc = lnk.Header.TargetCreationDate.Year == 1601
? null
: lnk.Header.TargetCreationDate;
DateTimeOffset? tm = lnk.Header.TargetModificationDate.Year == 1601
? null
: lnk.Header.TargetModificationDate;
DateTimeOffset? ta = lnk.Header.TargetLastAccessedDate.Year == 1601
? null
: lnk.Header.TargetLastAccessedDate;
Log.Information(" Target created: {Tc}",tc);
Log.Information(" Target modified: {Tm}",tm);
Log.Information(" Target accessed: {Ta}",ta);
Console.WriteLine();
Log.Information(" File size: {FileSize:N0}",lnk.Header.FileSize);
Log.Information(" Flags: {DataFlags}",lnk.Header.DataFlags);
Log.Information(" File attributes: {FileAttributes}",lnk.Header.FileAttributes);
if (lnk.Header.HotKey.Length > 0)
{
Log.Information(" Hot key: {HotKey}",lnk.Header.HotKey);
}
Log.Information(" Icon index: {IconIndex}",lnk.Header.IconIndex);
Log.Information(
" Show window: {ShowWindow} ({Desc})",lnk.Header.ShowWindow,GetDescriptionFromEnumValue(lnk.Header.ShowWindow));
Console.WriteLine();
if ((lnk.Header.DataFlags & Lnk.Header.DataFlag.HasName) == Lnk.Header.DataFlag.HasName)
{
Log.Information("Name: {Name}",lnk.Name);
}
if ((lnk.Header.DataFlags & Lnk.Header.DataFlag.HasRelativePath) == Lnk.Header.DataFlag.HasRelativePath)
{
Log.Information("Relative Path: {RelativePath}",lnk.RelativePath);
}
if ((lnk.Header.DataFlags & Lnk.Header.DataFlag.HasWorkingDir) == Lnk.Header.DataFlag.HasWorkingDir)
{
Log.Information("Working Directory: {WorkingDirectory}",lnk.WorkingDirectory);
}
if ((lnk.Header.DataFlags & Lnk.Header.DataFlag.HasArguments) == Lnk.Header.DataFlag.HasArguments)
{
Log.Information("Arguments: {Arguments}",lnk.Arguments);
}
if ((lnk.Header.DataFlags & Lnk.Header.DataFlag.HasIconLocation) == Lnk.Header.DataFlag.HasIconLocation)
{
Log.Information("Icon Location: {IconLocation}",lnk.IconLocation);
}
if ((lnk.Header.DataFlags & Lnk.Header.DataFlag.HasLinkInfo) == Lnk.Header.DataFlag.HasLinkInfo)
{
Console.WriteLine();
Log.Information("--- Link information ---");
Log.Information("Flags: {Flags}",lnk.LocationFlags);
if (lnk.VolumeInfo != null)
{
Console.WriteLine();
Log.Information(">> Volume information");
Log.Information(" Drive type: {Drive}",GetDescriptionFromEnumValue(lnk.VolumeInfo.DriveType));
Log.Information(" Serial number: {VolumeSerialNumber}",lnk.VolumeInfo.VolumeSerialNumber);
var label = lnk.VolumeInfo.VolumeLabel.Length > 0
? lnk.VolumeInfo.VolumeLabel
: "(No label)";
Log.Information(" Label: {Label}",label);
}
if (lnk.NetworkShareInfo != null)
{
Console.WriteLine();
Log.Information(" Network share information");
if (lnk.NetworkShareInfo.DeviceName.Length > 0)
{
Log.Information(" Device name: {DeviceName}",lnk.NetworkShareInfo.DeviceName);
}
Log.Information(" Share name: {NetworkShareName}",lnk.NetworkShareInfo.NetworkShareName);
Log.Information(" Provider type: {NetworkProviderType}",lnk.NetworkShareInfo.NetworkProviderType);
Log.Information(" Share flags: {ShareFlags}",lnk.NetworkShareInfo.ShareFlags);
Console.WriteLine();
}
if (lnk.LocalPath?.Length > 0)
{
Log.Information(" Local path: {LocalPath}",lnk.LocalPath);
}
if (lnk.CommonPath.Length > 0)
{