-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathInvoke-Obliteration.ps1
1522 lines (1254 loc) · 65.6 KB
/
Invoke-Obliteration.ps1
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
<#PSScriptInfo
.VERSION 1.0.2
.GUID dcb430bf-7683-41f0-a17d-d64fabd18e6e
.AUTHOR francisconabas@outlook.com
.COMPANYNAME Frank Nabas Labs
.TAGS Remove Remove Delete Files Folders PowerShell Microsoft Windows Explorer
.LICENSEURI /~https://github.com/FranciscoNabas/PowerShellPublic/blob/main/LICENSE
.PROJECTURI /~https://github.com/FranciscoNabas/PowerShellPublic
.RELEASENOTES
Version 1.0.2:
- Added remaining file count to the progress bar.
- Added average speed in files/s on the progress bar.
- Added the cancellation token to the progress object.
- Added check for cancellation on the PowerShell monitoring loop.
- Added parameter 'MaxConcurrentTask'.
- Various performance enhancements.
- Replaced the delete functionality with NT functions.
- Removed the threshold for parallel delete.
- Added parallel delete for remaining folders.
- Removed 'RaiseObjectHandleClosed' unnecessary multiple allocations.
- Cancellation handler not working for big number of files. Converted to native and created a scoped handler.
- Added task state check while waiting for the API to fill the total count, in case it fails so we don't keep stuck in the loop.
- Removed alias.
Version 1.0.1:
- Native array enumeration optimization.
- Consolidated folder and file delete in single method.
- Fixed bug on progress data.
- Fixed bug on closed handle warning.
- New monitoring mechanism.
- Changes on the C# code to conform to C# 5, because Windows PowerShell thinks it's 2012.
Version 1.0.0:
- Initial version published.
#>
<#
.SYNOPSIS
Obliterates one or more files or folders recursively and in parallel.
.DESCRIPTION
This function deletes one or more files or folders recursively, including its files and sub-directories.
It was also designed to accept input from the pipeline, from Cmdlets like 'Get-ChildItem'.
If one of the file system objects are open in another process it attempts to close the handles.
The closing handle mechanism was ported from the 'WindowsUtils' module.
ATTENTION!!!
This function deletes files and potentially closes open handles without prompting for confirmation!
It was designed to be like that.
Closing other processe's handles to a file system object may cause system malfunction. Use it with care!
About privileges:
The main API tries to enable the 'SeBackupPrivilege' and 'SeRestorePrivilege' for the executing process token during execution to make sure we have the right permissions.
These privileges are disabled once the method ends.
About concurrent tasks:
This script deletes files and folders in parallel. You can set the maximum number of concurrent tasks by using the 'MaxConcurrentTask' parameter.
It's worth noting that there's a point where the bottleneck is on how fast the Operating System can open and close file handles, and not the capacity of the computer
of running the tasks, and this number is not big. 1000 concurrent tasks is plenty enough to saturate I/O without frying the CPU. You can play with this parameter to test
the limits of your system. MaxConcurrentTask = 0 means no limit.
About cancellation:
The main API implements a cancellation handler to capture 'Ctrl-C' and 'Ctrl-Break' commands.
All the internal APIs were designed with cooperative multitasking in mind, so if you press a cancellation combination the operation stops.
Due some bugs I found with Windows PowerShell I couldn't remove the handler at the end of execution because it breaks the console.
Although the handle continues registered it does nothing if it's not in the method execution 'context'.
.PARAMETER Path
One or more file system object paths.
.PARAMETER LiteralPath
One or more file system object literal paths (PSPath).
.PARAMETER MaxConcurrentTask
The maximum number of concurrent delete tasks. Zero means no limit. (see description for more info).
.EXAMPLE
Invoke-Obliteration -Path 'C:\SomeFolderIReallyHate'
.EXAMPLE
.\Invoke-Obliteration.ps1 'C:\SomeFolderIReallyHate', 'C:\IHateThisOtherOneToo'
.EXAMPLE
Invoke-Obliteration 'C:\SomeFolder*'
.EXAMPLE
Get-ChildItem -Path 'C:\SomeFolder' | .\Invoke-Obliteration.ps1 -MaxConcurrentTask 0
.INPUTS
A string array of file system object paths.
.OUTPUTS
A 'Obliteration.DeleteFileErrorInfo' is return for every object we fail to delete.
If no object fails to delete this function returns nothing.
.NOTES
Scripted by: Francisco Nabas
Scripted on: 2024-10-09
Version: 1.0.2
Version date: 2024-10-27
.LINK
/~https://github.com/FranciscoNabas
/~https://github.com/FranciscoNabas/WindowsUtils
#>
[CmdletBinding(DefaultParameterSetName = 'byPath')]
[OutputType('Obliteration.DeleteFileErrorInfo')]
param (
[Parameter(
Mandatory,
Position = 0,
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true,
ParameterSetName = 'byPath'
)]
[ValidateNotNullOrEmpty()]
[string[]]$Path,
[Parameter(
Mandatory,
ValueFromPipeline = $false,
ValueFromPipelineByPropertyName = $true,
ParameterSetName = 'byLiteralPath'
)]
[Alias('PSPath')]
[ValidateNotNullOrEmpty()]
[string[]]$LiteralPath,
[Parameter()]
[ValidateRange(0, [int]::MaxValue)]
[int]$MaxConcurrentTask = 1000
)
Begin {
$theThing = @'
namespace Obliteration
{
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
[StructLayout(LayoutKind.Sequential)]
internal struct UNICODE_STRING : IDisposable
{
internal ushort Length;
internal ushort MaximumLength;
private readonly IntPtr _buffer;
internal UNICODE_STRING(string str)
{
Length = (ushort)(str.Length * UnicodeEncoding.CharSize);
MaximumLength = (ushort)(Length + (UnicodeEncoding.CharSize * 2));
_buffer = Marshal.StringToHGlobalUni(str);
}
public override string ToString()
{
if (_buffer != IntPtr.Zero)
return Marshal.PtrToStringUni(_buffer);
return string.Empty;
}
public void Dispose()
{
if ( _buffer != IntPtr.Zero )
Marshal.FreeHGlobal(_buffer);
}
}
// This is not the correct layout. This struct actually have an union, but
// since we're not reading this anywhere I don't care.
[StructLayout(LayoutKind.Sequential)]
internal struct IO_STATUS_BLOCK
{
internal IntPtr StatusAndPointer;
internal IntPtr Information;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct OBJECT_ATTRIBUTES
{
internal int Length;
internal IntPtr RootDirectory;
internal IntPtr ObjectName;
internal int Attributes;
internal IntPtr SecurityDescriptor;
internal IntPtr SecurityQualityOfService;
}
[StructLayout(LayoutKind.Sequential)]
internal struct FILE_DISPOSITION_INFORMATION_EX
{
internal int Flags;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
internal struct FILE_FULL_DIR_INFORMATION
{
internal int NextEntryOffset;
internal uint FileIndex;
internal long CreationTime;
internal long LastAccessTime;
internal long LastWriteTime;
internal long ChangeTime;
internal long EndOfFile;
internal long AllocationSize;
internal uint FileAttributes;
internal int FileNameLength;
internal int EaSize;
private char _fileName;
internal string FileName { get { return GetName(); } }
private unsafe string GetName()
{
fixed (char* namePtr = &_fileName) {
return new string(namePtr, 0, FileNameLength / 2);
}
}
}
[StructLayout(LayoutKind.Sequential)]
internal struct FILE_PROCESS_IDS_USING_FILE_INFORMATION
{
internal uint NumberOfProcessIdsInList;
internal UIntPtr ProcessIdList;
}
// This structure has more members, but we only care about the handle value.
[StructLayout(LayoutKind.Sequential, Size = 40, Pack = 8)]
internal struct PROCESS_HANDLE_TABLE_ENTRY_INFO
{
internal IntPtr HandleValue;
}
[StructLayout(LayoutKind.Sequential)]
internal unsafe struct PROCESS_HANDLE_SNAPSHOT_INFORMATION
{
internal UIntPtr NumberOfHandles;
internal UIntPtr Reserved;
internal PROCESS_HANDLE_TABLE_ENTRY_INFO Handles;
}
// This structure has more members, but we only care about the type name.
[StructLayout(LayoutKind.Sequential, Size = 100, Pack = 4)]
internal struct OBJECT_TYPE_INFORMATION
{
internal UNICODE_STRING TypeName;
}
[StructLayout(LayoutKind.Sequential)]
internal struct OBJECT_NAME_INFORMATION
{
internal UNICODE_STRING Name;
}
[StructLayout(LayoutKind.Sequential)]
internal struct LUID
{
internal uint LowPart;
internal int HighPart;
}
[StructLayout(LayoutKind.Sequential, Pack = 4)]
internal struct LUID_AND_ATTRIBUTES
{
internal LUID Luid;
internal uint Attributes;
}
[StructLayout(LayoutKind.Sequential)]
internal struct TOKEN_PRIVILEGES
{
internal uint PrivilegeCount;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 1)]
internal LUID_AND_ATTRIBUTES[] Privileges;
}
// A wrapper for 'OBJECT_ATTRIBUTES'.
internal class ManagedObjectAttributes : IDisposable
{
private bool _isDisposed;
private readonly IntPtr _objectName;
internal OBJECT_ATTRIBUTES ObjectAttributes;
internal ManagedObjectAttributes(string objectName, int attributes)
{
int nameSize = objectName.Length * UnicodeEncoding.CharSize;
UNICODE_STRING nativeObjName = new UNICODE_STRING(objectName);
_objectName = Common.HeapAlloc(Marshal.SizeOf(typeof(UNICODE_STRING)));
Marshal.StructureToPtr(nativeObjName, _objectName, true);
ObjectAttributes = new OBJECT_ATTRIBUTES() {
Length = Marshal.SizeOf(typeof(OBJECT_ATTRIBUTES)),
RootDirectory = IntPtr.Zero,
ObjectName = _objectName,
Attributes = attributes,
SecurityDescriptor = IntPtr.Zero,
SecurityQualityOfService = IntPtr.Zero,
};
_isDisposed = false;
}
public void Dispose()
{
if (!_isDisposed) {
Marshal.FreeHGlobal(_objectName);
_isDisposed = true;
}
}
}
// This object is returned by the main API for files we fail to delete.
public sealed class DeleteFileErrorInfo
{
public string FilePath { get; private set; }
public Exception Exception { get; internal set; }
internal DeleteFileErrorInfo(string path, Exception exception)
{
this.FilePath = path;
this.Exception = exception;
}
}
public sealed class ObliteratorProgressData
{
private readonly object _syncObject = new object();
private readonly List<Tuple<string, int>> _closedHandleList = new List<Tuple<string, int>>();
private int _totalCount = 0;
private int _progress = 0;
private CancellationToken _token;
public bool IsCancellationRequested {
get {
lock (_syncObject) {
if (null != _token) {
return _token.IsCancellationRequested;
}
return false;
}
}
private set { }
}
public int TotalCount {
get { lock (_syncObject) { return _totalCount; } }
internal set { lock (_syncObject) { _totalCount = value; } }
}
public int Progress {
get { lock (_syncObject) { return _progress; } }
internal set { lock (_syncObject) { _progress = value; } }
}
public Tuple<string, int>[] ClosedHandleInfo {
get {
lock (_syncObject) {
return _closedHandleList.ToArray();
}
}
private set { }
}
internal CancellationToken Token {
get { lock (_syncObject) { return _token; } }
set { lock (_syncObject) { _token = value; } }
}
public Tuple<int, int, Tuple<string, int>[], bool> RequestData()
{
lock (_syncObject) {
return new Tuple<int, int, Tuple<string, int>[], bool>(_totalCount, _progress, _closedHandleList.ToArray(), _token.IsCancellationRequested);
}
}
internal void Clear()
{
lock (_syncObject) {
_totalCount = 0;
_progress = 0;
_closedHandleList.Clear();
}
}
internal void IncrementProgress()
{
lock (_syncObject) {
_progress++;
}
}
internal void AddClosedHandle(string path, int processId)
{
lock (_syncObject) {
_closedHandleList.Add(new Tuple<string, int>(path, processId));
}
}
}
// Main class.
public sealed class Obliterator
{
private readonly RaiseObjectHandleClosed _closeHandleHandler;
public ObliteratorProgressData ProgressData { get; private set; }
public Obliterator()
{
this.ProgressData = new ObliteratorProgressData();
_closeHandleHandler = new RaiseObjectHandleClosed(InformObjectHandleClosed);
}
// Main API. Deletes files and directories recursively, closing open handles and storing progress.
public DeleteFileErrorInfo[] Obliterate(string[] pathList, int maxConcurrentTask)
{
if (maxConcurrentTask == 0 || maxConcurrentTask < -1)
maxConcurrentTask = -1;
this.ProgressData.Clear();
ConcurrentBag<DeleteFileErrorInfo> errorList = new ConcurrentBag<DeleteFileErrorInfo>();
// Creating the cancellation token source.
using (CancellationHandler cancellationHandler = new CancellationHandler()) {
ProgressData.Token = cancellationHandler.Token;
// Enabling privileges to the current token. This will fail if the current token doesn't have these privileges.
using (PrivilegeCookie privilegeCookie = AccessControl.Request(new string[] { "SeBackupPrivilege", "SeRestorePrivilege" })) {
// Listing directories and files recursively.
// We do this separately so we can have the total count to add to our progress monitor.
ConcurrentQueue<Exception> exceptions = new ConcurrentQueue<Exception>();
ConcurrentBag<IO.DirectoryFileInformation> fsInfoBag = new ConcurrentBag<IO.DirectoryFileInformation>();
Parallel.ForEach(pathList, new ParallelOptions { CancellationToken = cancellationHandler.Token }, path => {
try {
IO.GetDirectoryFileInfoRecurse(path, ref fsInfoBag, cancellationHandler.Token);
}
catch (Exception ex) {
exceptions.Enqueue(ex);
}
});
// If something failed we ball.
if (!exceptions.IsEmpty)
throw new AggregateException(exceptions);
// Getting the count of items to delete.
this.ProgressData.TotalCount = fsInfoBag.Select(info => info.Files.Count).Sum() + fsInfoBag.Count;
// Creating the tasks to delete the files.
List<Task> taskList = new List<Task>(fsInfoBag.Count);
ConcurrentBag<string> remainingDirectoryBag = new ConcurrentBag<string>();
foreach (IO.DirectoryFileInformation fsInfo in fsInfoBag) {
cancellationHandler.Token.ThrowIfCancellationRequested();
taskList.Add(Task.Run(() => {
switch (fsInfo.Type) {
case IO.FsObjectType.Directory:
bool hadErrors = false;
Parallel.ForEach(fsInfo.Files, new ParallelOptions() {
CancellationToken = cancellationHandler.Token,
MaxDegreeOfParallelism = maxConcurrentTask,
}, filePath => {
cancellationHandler.Token.ThrowIfCancellationRequested();
try {
NtUtilities.DeleteObjectClosingOpenHandles(filePath, IO.FsObjectType.File, _closeHandleHandler, cancellationHandler.Token);
}
catch (Exception ex) {
hadErrors = true;
errorList.Add(new DeleteFileErrorInfo(filePath, ex));
}
this.ProgressData.IncrementProgress();
});
// At this point there are no more files in the folder (if nothing failed).
// So if the folder doesn't have sub-directories we delete it.
if (!hadErrors) {
if (!fsInfo.HasSubDirectory) {
try {
NtUtilities.DeleteObjectClosingOpenHandles(fsInfo.FullName, IO.FsObjectType.Directory, _closeHandleHandler, cancellationHandler.Token);
}
catch (Exception ex) {
errorList.Add(new DeleteFileErrorInfo(fsInfo.FullName, ex));
}
this.ProgressData.IncrementProgress();
}
else
remainingDirectoryBag.Add(fsInfo.FullName);
}
break;
case IO.FsObjectType.File:
try {
// If it's a file we just delete it.
NtUtilities.DeleteObjectClosingOpenHandles(fsInfo.FullName, IO.FsObjectType.File, _closeHandleHandler, cancellationHandler.Token);
}
catch (Exception ex) {
errorList.Add(new DeleteFileErrorInfo(fsInfo.FullName, ex));
}
this.ProgressData.IncrementProgress();
break;
}
}, cancellationHandler.Token));
}
// Waiting the tasks to complete.
Task.WaitAll(taskList.ToArray(), cancellationHandler.Token);
// Deleting remaining directories.
// We order by name descending so we delete sub-directories first.
Parallel.ForEach(remainingDirectoryBag.OrderByDescending(path => path.Length), new ParallelOptions() {
CancellationToken = cancellationHandler.Token,
MaxDegreeOfParallelism = maxConcurrentTask,
}, directory => {
cancellationHandler.Token.ThrowIfCancellationRequested();
try {
NtUtilities.DeleteObjectClosingOpenHandles(directory, IO.FsObjectType.Directory, _closeHandleHandler, cancellationHandler.Token);
}
catch (Exception ex) {
errorList.Add(new DeleteFileErrorInfo(directory, ex));
}
this.ProgressData.IncrementProgress();
});
}
}
return errorList.ToArray();
}
private void InformObjectHandleClosed(string path, int processId)
{
this.ProgressData.AddClosedHandle(path, processId);
}
}
// Delegate used to raise the 'ObjectHandleClosed' event from the NT API.
internal delegate void RaiseObjectHandleClosed(string path, int processId);
// File utilities.
internal static class IO
{
internal enum FsObjectType
{
Directory = 0x204001,
File = 0x204048,
}
internal sealed class DirectoryFileInformation
{
internal FsObjectType Type { get; set; }
internal string FullName { get; set; }
internal bool HasSubDirectory { get; set; }
internal List<string> Files { get; set; }
internal DirectoryFileInformation(FsObjectType type, string path)
{
this.Type = type;
this.FullName = path;
this.HasSubDirectory = false;
this.Files = new List<string>();
}
}
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "CreateFileW")]
private static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr lpSecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtQueryDirectoryFile(SafeFileHandle FileHandle, IntPtr Event, IntPtr ApcRoutine, IntPtr ApcContext, ref IO_STATUS_BLOCK IoStatusBlock, IntPtr FileInformation,
int Length, int FileInformationClass, bool ReturnSingleEntry, IntPtr FileName, bool RestartScan);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "QueryDosDeviceW")]
private static extern int QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, int ucchMax);
// Lists files and folders recursively for a directory.
internal static unsafe void GetDirectoryFileInfoRecurse(string rootPath, ref ConcurrentBag<DirectoryFileInformation> infoList, CancellationToken token)
{
token.ThrowIfCancellationRequested();
// Checking if it's a big path.
// Check parameter 'lpFileName' from 'CreateFileW''.
string openHandlePath;
if (rootPath.Length > 260)
openHandlePath = @"\\?\" + rootPath;
else
openHandlePath = rootPath;
// When adding support to provider-aware parameters we need to consider files.
// If it's a file we just add an entry to be consumed by the caller.
if (File.Exists(openHandlePath)) {
infoList.Add(new DirectoryFileInformation(FsObjectType.File, rootPath));
return;
}
else {
if (!Directory.Exists(openHandlePath))
throw new FileNotFoundException("Could not find '" + rootPath + "' because it doesn't exist.");
}
// Getting a handle to the file (opening it).
// 1 = FILE_LIST_DIRECTORY
// 7 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
// 3 = OPEN_EXISTING
// 33554432 = FILE_FLAG_BACKUP_SEMANTICS
using (SafeFileHandle hFile = CreateFile(openHandlePath, 1, 7, IntPtr.Zero, 3, 33554432, IntPtr.Zero)) {
if (hFile.IsInvalid)
throw new NativeException(Marshal.GetLastWin32Error(), false);
int bufferSize = 8192;
using (ScopedBuffer buffer = new ScopedBuffer(bufferSize)) {
// Getting the initial buffer;
// 2 = FILE_INFORMATION_CLASS.FileFullDirectoryInformation
IO_STATUS_BLOCK statusBlock = new IO_STATUS_BLOCK();
int status = NtQueryDirectoryFile(hFile, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref statusBlock, buffer, bufferSize, 2, false, IntPtr.Zero, false);
if (status != 0)
throw new NativeException(status, true);
// Ending with a terminator char.
string rootNormalizedName;
if (rootPath.EndsWith("\\"))
rootNormalizedName = rootPath;
else
rootNormalizedName = rootPath + "\\";
IntPtr offset = buffer;
FILE_FULL_DIR_INFORMATION* currentInfo;
DirectoryFileInformation entry = new DirectoryFileInformation(FsObjectType.Directory, rootNormalizedName);
do {
token.ThrowIfCancellationRequested();
do {
// Going through each entry in our buffer.
token.ThrowIfCancellationRequested();
currentInfo = (FILE_FULL_DIR_INFORMATION*)offset;
string name = currentInfo->FileName;
// Skipping system paths.
if (name.Equals(".", StringComparison.Ordinal) || name.Equals("..", StringComparison.Ordinal)) {
offset = IntPtr.Add(offset, currentInfo->NextEntryOffset);
continue;
}
// Checking if it's a directory.
// 16 = FILE_ATTRIBUTE_DIRECTORY
if ((currentInfo->FileAttributes & 16) == 16) {
// Calling recursively.
GetDirectoryFileInfoRecurse(rootNormalizedName + name, ref infoList, token);
entry.HasSubDirectory = true;
}
else
entry.Files.Add(rootNormalizedName + name);
offset = IntPtr.Add(offset, currentInfo->NextEntryOffset);
} while (currentInfo->NextEntryOffset != 0);
// Refreshing the buffer until there's no more items.
// 2 = FILE_INFORMATION_CLASS.FileFullDirectoryInformation
status = NtQueryDirectoryFile(hFile, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, ref statusBlock, buffer, bufferSize, 2, false, IntPtr.Zero, false);
if (status != 0 && status != -2147483642)
throw new NativeException(status, true);
offset = buffer;
} while (status == 0 && buffer != IntPtr.Zero);
infoList.Add(entry);
}
}
}
// Converts a 'DOS' path to a device path.
// E.g., C:\SomeFolder ~> \Device\HardDrive3\SomeFolder
internal static string GetFileDevicePathFromDosPath(string path)
{
string drive = string.Format("{0}:", path[0]);
StringBuilder buffer = new StringBuilder(260);
if (QueryDosDevice(drive, buffer, 260) == 0)
throw new NativeException(Marshal.GetLastWin32Error(), false);
return string.Format("{0}\\{1}", buffer.ToString(), path.Remove(0, 3));
}
}
// Process utilities.
internal static class ProcessAndThread
{
[DllImport("kernel32.dll", SetLastError = true)]
private static extern SafeNativeHandle OpenProcess(int dwDesiredAccess, bool bInheritHandle, int dwProcessId);
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern IntPtr GetCurrentProcess();
// Opens a handle to a process.
internal static SafeNativeHandle SafeOpenProcess(int desiredAccess, bool inheritHandle, int processId)
{
SafeNativeHandle hProcess = OpenProcess(desiredAccess, inheritHandle, processId);
if (hProcess.IsInvalid)
throw new NativeException(Marshal.GetLastWin32Error(), false);
return hProcess;
}
}
// NT APIs.
internal static class NtUtilities
{
[DllImport("ntdll.dll", SetLastError = true)]
private static unsafe extern int NtOpenFile(out IntPtr FileHandle, int DesiredAccess, OBJECT_ATTRIBUTES ObjectAttributes, ref IO_STATUS_BLOCK IoStatusBlock, int ShareAccess, int OpenOptions);
// 'FileInformation' here is a PVOID, but since we only use with this structure we take advantage of that.
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtSetInformationFile(IntPtr FileHandle, ref IO_STATUS_BLOCK IoStatusBlock, ref FILE_DISPOSITION_INFORMATION_EX FileInformation, int Length, int FileInformationClass);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtQueryObject(IntPtr Handle, int ObjectInformationClass, IntPtr ObjectInformation, int ObjectInformationLength, out int ReturnLength);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtDuplicateObject(IntPtr SourceProcessHandle, IntPtr SourceHandle, IntPtr TargetProcessHandle, out IntPtr TargetHandle, int DesiredAccess, int HandleAttributes, int Options);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtQueryInformationProcess(IntPtr ProcessHandle, int SystemInformationClass, IntPtr SystemInformation, int SystemInformationLength, out int ReturnLength);
[DllImport("ntdll.dll", SetLastError = true)]
private static extern int NtQueryInformationFile(IntPtr FileHandle, ref IO_STATUS_BLOCK IoStatusBlock, IntPtr FileInformation, int Length, int FileInformationClass);
[DllImport("ntdll.dll", SetLastError = true)]
internal static extern int NtClose(IntPtr Handle);
// Attempts to delete a file or folder closing open handles to it.
internal static unsafe void DeleteObjectClosingOpenHandles(string path, IO.FsObjectType type, RaiseObjectHandleClosed closedHandleDelegate, CancellationToken token)
{
token.ThrowIfCancellationRequested();
// Since the path is the result of a directory enumeration we know two things, this object exists (unless
// it was deleted/moved in between), and it's either a file or a folder. So we can get away with just prepending
// '\??\' to the path instead of calling 'RtlDosPathNameToRelativeNtPathName_U_WithStatus' (I think lol).
string ntFileName = @"\??\" + path;
// 65536 = DELETE
int desiredAccess = 65536;
// Directory: 0x204001 = FILE_OPEN_REPARSE_POINT | FILE_OPEN_FOR_BACKUP_INTENT | FILE_DIRECTORY_FILE
// File: 0x200048 = FILE_OPEN_REPARSE_POINT | FILE_NO_INTERMEDIATE_BUFFERING | FILE_OPEN_FOR_BACKUP_INTENT | FILE_NON_DIRECTORY_FILE
int openOptions = (int)type;
int status;
IntPtr hFile;
IO_STATUS_BLOCK statusBlock = new IO_STATUS_BLOCK();
// 64 = OBJ_CASE_INSENSITIVE.
using (ManagedObjectAttributes objAttributes = new ManagedObjectAttributes(ntFileName, 64)) {
// FILE_DELETE_ON_CLOSE is twice as slow.
// 7 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
status = NtOpenFile(out hFile, desiredAccess, objAttributes.ObjectAttributes, ref statusBlock, 7, openOptions);
if (status != 0) {
// 0xC0000043 = STATUS_SHARE_VIOLATION. File is open in another process.
if (status == -1073741757) {
// 128 = FILE_READ_ATTRIBUTES
// 7 = FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
status = NtOpenFile(out hFile, 128, objAttributes.ObjectAttributes, ref statusBlock, 7, openOptions);
if (status != 0)
throw new NativeException(status, true);
// Attempting to close open handles.
try { CloseExternalHandlesToFile(hFile, path, closedHandleDelegate, token); }
catch { }
NtClose(hFile);
// At this point if it fails ain't nothing we can do.
status = NtOpenFile(out hFile, desiredAccess, objAttributes.ObjectAttributes, ref statusBlock, 7, openOptions);
if (status != 0)
throw new NativeException(status, true);
}
else
throw new NativeException(status, true);
}
}
// 19 = FILE_DISPOSITION_DELETE | FILE_DISPOSITION_POSIX_SEMANTICS | FILE_DISPOSITION_IGNORE_READONLY_ATTRIBUTE
FILE_DISPOSITION_INFORMATION_EX dispositionInfo = new FILE_DISPOSITION_INFORMATION_EX() { Flags = 19 };
// 64 = FileDispositionInformationEx
status = NtSetInformationFile(hFile, ref statusBlock, ref dispositionInfo, 4, 64);
if (status != 0)
throw new NativeException(status, true);
NtClose(hFile);
}
// Attempts to close external handles to a file, searching for the owning processes first.
internal static unsafe void CloseExternalHandlesToFile(IntPtr hFile, string path, RaiseObjectHandleClosed closedHandleDelegate, CancellationToken token)
{
token.ThrowIfCancellationRequested();
// Getting the processes that have open handles to this file.
int bufferSize = 1 << 10;
IO_STATUS_BLOCK statusBlock = new IO_STATUS_BLOCK();
using (ScopedBuffer buffer = new ScopedBuffer(bufferSize)) {
int status = 0;
// Since the handle list might change we call this in a loop until we have the right size buffer.
// This is somewhat common on NT APIs.
do {
token.ThrowIfCancellationRequested();
// 47 = FILE_INFORMATION_CLASS.FileProcessIdsUsingFileInformation
status = NtQueryInformationFile(hFile, ref statusBlock, buffer, bufferSize, 47);
if (status == 0)
break;
// -1073741820 = buffer too small
if (status != -1073741820)
throw new NativeException(status, true);
bufferSize = (int)statusBlock.Information;
buffer.Resize(bufferSize);
} while (status == -1073741820);
// Calling the method to actually close the handles.
// For you C# types out there it's valid to remember we need to call this while 'buffer' is valid.
CloseExternalHandlesToFile((FILE_PROCESS_IDS_USING_FILE_INFORMATION*)(IntPtr)buffer, path, closedHandleDelegate, token);
}
}
// Attempts to close external handles to a file from a process ID list.
// It does that by opening a handle to a process, enumerating its handles, duplicating them, querying information to see
// if it's a handle to our file, if it is we duplicate again with 'DUPLICATE_CLOSE_SOURCE' to close the original handle
private static unsafe void CloseExternalHandlesToFile(FILE_PROCESS_IDS_USING_FILE_INFORMATION* pidUsingFileInfo, string path, RaiseObjectHandleClosed closedHandleDelegate, CancellationToken token)
{
string devicePath = IO.GetFileDevicePathFromDosPath(path);
for (uint i = 0; i < pidUsingFileInfo->NumberOfProcessIdsInList; i++) {
token.ThrowIfCancellationRequested();
// Opening a handle to the process;
// 1104 = PROCESS_QUERY_INFORMATION | PROCESS_VM_READ | PROCESS_DUP_HANDLE
SafeNativeHandle hProcess;
int currentProcessId = (int)(&pidUsingFileInfo->ProcessIdList)[i];
try { hProcess = ProcessAndThread.SafeOpenProcess(1104, false, currentProcessId); }
catch { continue; }
using (hProcess) {
int status = 0;
int bufferSize = 9216;
using (ScopedBuffer buffer = new ScopedBuffer(bufferSize)) {
do {
// Getting a list of all the processes handles.
token.ThrowIfCancellationRequested();
// 51 = PROCESSINFOCLASS.ProcessHandleInformation
status = NtQueryInformationProcess(hProcess.DangerousGetHandle(), 51, buffer, bufferSize, out bufferSize);
if (status == 0)
break;
// -1073741820 = buffer too small
if (status != -1073741820)
throw new NativeException(status, true);
bufferSize += 1024;
buffer.Resize(bufferSize);
} while (status == -1073741820);
// Going through each process handle.
IntPtr hCurrentProcess = ProcessAndThread.GetCurrentProcess();
PROCESS_HANDLE_SNAPSHOT_INFORMATION* processHandleInfo = (PROCESS_HANDLE_SNAPSHOT_INFORMATION*)(IntPtr)buffer;
for (int j = 0; j < (int)processHandleInfo->NumberOfHandles; j++) {
token.ThrowIfCancellationRequested();
// Duplicating the handle.
// 2 = DUPLICATE_SAME_ACCESS
IntPtr hDup;
status = NtDuplicateObject(hProcess.DangerousGetHandle(), (&processHandleInfo->Handles)[j].HandleValue, hCurrentProcess, out hDup, 0, 0, 2);
if (status != 0)
continue;
// Querying the object type.
// 2 = OBJECT_INFORMATION_CLASS.ObjectTypeInformation
int typeBufferSize = 1024;
using (ScopedBuffer typeBuffer = new ScopedBuffer(typeBufferSize)) {
status = NtQueryObject(hDup, 2, typeBuffer, typeBufferSize, out typeBufferSize);
if (status != 0) {
Common.CloseHandle(hDup);
throw new NativeException(status, true);
}
// If it's a file we go further.
var typeName = ((OBJECT_TYPE_INFORMATION*)(IntPtr)typeBuffer)->TypeName.ToString().Trim('\0');
if (typeName.Equals("File", StringComparison.OrdinalIgnoreCase)) {
// Querying the object name. We do this in a task because some asynchronous objects, like pipes
// block the call to 'NtQueryObject' forever.
Task<string> getNameTask = Task.Run(() => {
int nameBufferSize = 1024;
string output = string.Empty;
using (ScopedBuffer nameBuffer = new ScopedBuffer(nameBufferSize)) {
// 1 = OBJECT_INFORMATION_CLASS.ObjectNameInformation
int getNameStatus = NtQueryObject(hDup, 1, nameBuffer, nameBufferSize, out nameBufferSize);
if (status != 0)
throw new NativeException(status, true);
output = ((OBJECT_NAME_INFORMATION*)(IntPtr)nameBuffer)->Name.ToString();
}
return output;
}, token);
try {
// Checking if it's our file.
if (getNameTask.Wait(100, token)) {
if (!string.IsNullOrEmpty(getNameTask.Result) && getNameTask.Result.Equals(devicePath, StringComparison.OrdinalIgnoreCase)) {
Common.CloseHandle(hDup);
// Duplicating the handle again to close the source.
// 1 = DUPLICATE_CLOSE_SOURCE
status = NtDuplicateObject(hProcess.DangerousGetHandle(), (&processHandleInfo->Handles)[j].HandleValue, hCurrentProcess, out hDup, 0, 0, 1);
if (status != 0)
throw new NativeException(status, true);
closedHandleDelegate(path, currentProcessId);
}
}
// Closing our handle.
Common.CloseHandle(hDup);
}
catch {
Common.CloseHandle(hDup);
}
}
}
}
}
}
}
}
}
// Security utilities.
internal static class AccessControl
{
[DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, int DesiredAccess, out SafeAccessTokenHandle pHandle);
[DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode, EntryPoint = "LookupPrivilegeNameW")]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool LookupPrivilegeName(IntPtr lpSystemName, ref LUID lpLuid, StringBuilder lpName, ref uint cchName);
[DllImport("Advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool AdjustTokenPrivileges(SafeAccessTokenHandle TokenHandle, bool DisableAllPrivileges, ref TOKEN_PRIVILEGES NewState, uint BufferLength, IntPtr PreviousState, IntPtr ReturnLength);
[DllImport("Advapi32.dll", SetLastError = true, EntryPoint = "GetTokenInformation", ExactSpelling = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetTokenInformation(SafeAccessTokenHandle TokenHandle, int TokenInformationClass, IntPtr TokenInformation, int TokenInformationLength, out int ReturnLength);