-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathSharpLink.cs
1830 lines (1554 loc) · 65.4 KB
/
SharpLink.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.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Principal;
using Microsoft.Win32.SafeHandles;
namespace de.usd.SharpLink
{
/**
* SharpLink v1.0.1
*
* This namespace contains classes that allow low privileged user accounts to create
* file system and registry symbolic links.
*
* File system symbolic links created by functions from this namespace are pseudo-links
* that consist out of the combination of a Junction with an object manager symbolic link
* in the '\RPC Control' object directory. This technique was publicized by James Forshaw
* and implemented within his symboliclink-testing-tools:
*
* - https://github.com/googleprojectzero/symboliclink-testing-tools
*
* We used James's implementation as a reference for the classes implemented in this namespace.
* Moreover, the C# code for creating the junctions was mostly copied from these resources:
*
* - https://gist.github.com/LGM-AdrianHum/260bc9ab3c4cd49bc8617a2abe84ca74
* - https://coderedirect.com/questions/136750/check-if-a-file-is-real-or-a-symbolic-link
*
* Also the implementation of registry symbolic links is very close to the one within the
* symboliclink-testing-tools and credits go to James again. Furthermore, the following
* resource was used as a reference:
*
* - https://bugs.chromium.org/p/project-zero/issues/detail?id=872
*
* Author: Tobias Neitzel (@qtc_de)
*/
[StructLayout(LayoutKind.Sequential)]
struct KEY_VALUE_INFORMATION
{
public uint TitleIndex;
public uint Type;
public uint DataLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x400)]
public byte[] Data;
}
[StructLayout(LayoutKind.Sequential)]
struct MOUNT_POINT_REPARSE_BUFFER
{
public ushort SubstituteNameOffset;
public ushort SubstituteNameLength;
public ushort PrintNameOffset;
public ushort PrintNameLength;
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 0x3FF0)]
public byte[] PathBuffer;
}
[StructLayout(LayoutKind.Explicit)]
struct REPARSE_DATA_BUFFER
{
[FieldOffset(0)] public uint ReparseTag;
[FieldOffset(4)] public ushort ReparseDataLength;
[FieldOffset(6)] public ushort Reserved;
[FieldOffset(8)] public MOUNT_POINT_REPARSE_BUFFER MountPointBuffer;
}
[StructLayout(LayoutKind.Sequential)]
public struct OBJECT_ATTRIBUTES : IDisposable
{
public int Length;
public IntPtr RootDirectory;
private IntPtr objectName;
public uint Attributes;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
public OBJECT_ATTRIBUTES(string name, uint attrs)
{
Length = 0;
RootDirectory = IntPtr.Zero;
objectName = IntPtr.Zero;
Attributes = attrs;
SecurityDescriptor = IntPtr.Zero;
SecurityQualityOfService = IntPtr.Zero;
Length = Marshal.SizeOf(this);
ObjectName = new UNICODE_STRING(name);
}
public UNICODE_STRING ObjectName
{
get
{
return (UNICODE_STRING)Marshal.PtrToStructure(
objectName, typeof(UNICODE_STRING));
}
set
{
bool fDeleteOld = objectName != IntPtr.Zero;
if (!fDeleteOld)
objectName = Marshal.AllocHGlobal(Marshal.SizeOf(value));
Marshal.StructureToPtr(value, objectName, fDeleteOld);
}
}
public void Dispose()
{
if (objectName != IntPtr.Zero)
{
Marshal.DestroyStructure(objectName, typeof(UNICODE_STRING));
Marshal.FreeHGlobal(objectName);
objectName = IntPtr.Zero;
}
}
}
public struct UNICODE_STRING
{
public ushort Length;
public ushort MaximumLength;
[MarshalAs(UnmanagedType.LPWStr)]
public string Buffer;
public UNICODE_STRING(string str)
{
Length = (ushort)(str.Length * 2);
MaximumLength = (ushort)((str.Length * 2) + 1);
Buffer = str;
}
}
/**
* The ILink interface contains the required methods that classes need to implement to be assignable
* to a LinkGroup. Currently, this interface is implemented by the Symlink and RegistryLink types.
*
* Author: Tobias Neitzel (@qtc_de)
*/
public interface ILink
{
// open the underlying link
void Open();
// close the underlying link
void Close();
// print the current link status to stdout
void Status();
// enforce closing the link
void ForceClose();
// tell the link whether it should stay alive after the object is cleaned up
void KeepAlive(bool value);
}
/**
* A LinkGroup represents a collection of symbolic links and can be used to perform compound
* operations on them. This is useful when you have multiple links that you want to Open or
* Close at the same time. The group can store all kind of links that implement the ILink
* interface.
*
* Author: Tobias Neitzel (@qtc_de)
*/
public class LinkGroup
{
// Links stored within the LinkGroup
private HashSet<ILink> links;
/**
* On instantiation, a LinkGroup obtains a fresh HashSet to store it's links in.
*/
public LinkGroup()
{
links = new HashSet<ILink>();
}
/**
* Adds an already existing Link to the group.
*
* @param link already existing Link to add
*/
public void AddLink(ILink link)
{
links.Add(link);
}
/**
* Create a new Symlink from the specified path to the specified target and assign
* it to the LinkGroup.
*
* @param path path the symlink should be created from
* @param target target the symlink should be pointing to
*/
public void AddSymlink(string path, string target)
{
AddSymlink(path, target, false);
}
/**
* Create a new Symlink from the specified path to the specified target and assign
* it to the LinkGroup. This version of the function allows to set the keepAlive
* property of the link.
*
* @param path path the symlink should be created from
* @param target target the symlink should be pointing to
* @param keepAlive whether to keep the symlink alive after the object is cleaned up
*/
public void AddSymlink(string path, string target, bool keepAlive)
{
links.Add(new Symlink(path, target, keepAlive));
}
/**
* Create a new RegistryLink from the specified key to the specified target key and assign
* it to the LinkGroup.
*
* @param key key the RegistryLink should be created from
* @param target target the RegistryLink should be pointing to
*/
public void AddRegistryLink(string path, string target)
{
AddRegistryLink(path, target, false);
}
/**
* Create a new RegistryLink from the specified key to the specified target key and assign
* it to the LinkGroup. This version of the function allows to set the keepAlive
* property of the RegistryLink.
*
* @param key key the RegistryLink should be created from
* @param target target the RegistryLink should be pointing to
* @param keepAlive whether to keep the symlink alive after the object is cleaned up
*/
public void AddRegistryLink(string key, string target, bool keepAlive)
{
links.Add(new RegistryLink(key, target, keepAlive));
}
/**
* Tells all contained Links that they should stay alive, even after the object
* was cleaned up.
*/
public void KeepAlive()
{
KeepAlive(true);
}
/**
* Tells all contained Links whether they should stay alive, even after the object
* was cleaned up.
*
* @param value wether or not the Symlinks should stay alive
*/
public void KeepAlive(bool value)
{
foreach (ILink link in links)
link.KeepAlive(value);
}
/**
* Open all Links contained within this group.
*/
public void Open()
{
foreach (ILink link in links)
link.Open();
}
/**
* Close all Links contained within this group.
*/
public void Close()
{
foreach (ILink link in links)
link.Close();
}
/**
* Enforce the Close operation for all Links contained within this group.
*/
public void ForceClose()
{
foreach (ILink link in links)
link.ForceClose();
}
/**
* Remove all Links stored in this group. Depending on their keepAlive
* setting, the Links are only removed from the group, but not closed.
*/
public void Clear()
{
links.Clear();
}
/**
* Return the Links stored in this group as an array.
*
* @return ILink array of the contained Links
*/
public ILink[] GetLinks()
{
return links.ToArray<ILink>();
}
/**
* Print some status information on the current group. This includes the number of
* contained Links and the detailes of them.
*/
public void Status()
{
Console.WriteLine("[+] LinkGroup contains {0} link(s):", links.Count);
foreach (ILink link in links)
{
Console.WriteLine("[+]");
link.Status();
}
}
}
/**
* An instance of Symlink represents a single file system symbolic link. Each Symlink contains
* the path the Symlink should be cretaed in and the target it should be pointing to. Creating
* the Symlink object does not open it already on the file system. The Open function needs to
* be called to achieve this. Symlinks are removed when the corresponding Symlink object goes
* out of scope. This default behavior can be modified by using the keepAlive function.
*
* When opening a Symlink, it attempts to create one Junction and one DosDevice that are needed to
* setup the Symlink on the file system. Before doing so, it checks whether an approtiate Junction
* or DosDevice already exists. Only if not existing, the objects are created. After creation, the
* objects are associated to Symlink object. The Symlink is then the owner of these objects and
* responsible for maintaining their lifetime. If the objects already existed, the Symlink does not
* take ownership of them.
*
* Author: Tobias Neitzel (@qtc_de)
*/
public class Symlink : ILink
{
// file system path the symlink is created in
private string path;
// file system path the symlink should point to
private string target;
// associated Junction object (assigned when opening the link - may be null)
private Junction junction;
// associated DosDevice object (assigned when opening the link - may be null)
private DosDevice dosDevice;
// whether to keep the associated Junction and DosDevice alive after the object is removed
private bool keepAlive;
/**
* Symlinks are created by specifying the location they should be created in and the location
* they should point to.
*
* @param path file system path the link is created in
* @param target file system path the link is pointing to
*/
public Symlink(string path, string target) : this(path, target, false) { }
/**
* Symlinks are created by specifying the location they should be created in and the location
* they should point to. Additionally, this constructor allows specifying the keepAlive value
* of the link, which determines whether the physical link should be kept alive after the
* object is gone.
*
* @param path file system path the link is created in
* @param target file system path the link is pointing to
* @param keepAlive whether to keep the physical link alive after object cleanup
*/
public Symlink(string path, string target, bool keepAlive)
{
this.path = Path.GetFullPath(path);
this.target = Path.GetFullPath(target);
this.junction = null;
this.dosDevice = null;
this.keepAlive = keepAlive;
}
/**
* Set the keepAlive property to true and tell already existing Junction and DosDevice objects
* to stay alive after cleanup.
*/
public void KeepAlive()
{
KeepAlive(true);
}
/**
* Set the keepAlive property and tell already existing Junction and DosDevice objects whether to
* stay alive after cleanup.
*
* @param value whether to keep the physical link alive after object cleanup
*/
public void KeepAlive(bool value)
{
this.keepAlive = true;
if (junction != null)
junction.KeepAlive(value);
if (dosDevice != null)
dosDevice.KeepAlive(value);
}
/**
* Return the Junction object stored in this link. Links only have a Junction object set when they
* are open and a corresponding Junction does not already exist.
*/
public Junction GetJunction()
{
return junction;
}
/**
* Return the DosDevice object stored in this link. Links only have a DosDevice object set when they
* are open and a corresponding DosDevice does not already exist.
*/
public DosDevice GetDosDevice()
{
return dosDevice;
}
/**
* Print some status information on the link. This includes the link path and target path as well as
* the associated Junction and DosDevice.
*/
public void Status()
{
Console.WriteLine("[+] Link type: File system symbolic link");
Console.WriteLine("[+] \tLink path: {0}", path);
Console.WriteLine("[+] \tTarget path: {0}", target);
Console.WriteLine("[+] \tAssociated Junction: {0}", (junction == null) ? "none" : junction.GetBaseDir());
Console.WriteLine("[+] \tAssociated DosDevice: {0}", (dosDevice == null) ? "none" : dosDevice.GetName());
}
/**
* Checks whether a target was specified and open all Junctions and DosDevices that were
* configured for this container.
*/
public void Open()
{
if (junction != null && dosDevice != null)
{
Console.WriteLine("[-] Symlink was already opened. Call the Close function first if you want to reopen.");
return;
}
string linkFile = Path.GetFileName(path);
string linkDir = Path.GetDirectoryName(path);
if (String.IsNullOrEmpty(linkDir))
{
Console.WriteLine("[-] Symlinks require at least one upper directory (e.g. example\\link)");
return;
}
if (junction == null)
junction = Junction.Create(linkDir, @"\RPC CONTROL", keepAlive, true);
if (dosDevice == null)
dosDevice = DosDevice.Create(linkFile, target, keepAlive);
Console.WriteLine("[+] Symlink setup successfully.");
}
/**
* Closes all Junctions and DosDevices configured for this container. The corresponding object
* attributes are set to null afterwards, to distinguish the link from an open one.
*/
public void Close()
{
if (junction == null && dosDevice == null)
{
Console.WriteLine("[!] The current Symlink does not hold ownership on any Junction or DosDevice.");
Console.WriteLine("[!] Use ForceClose if you really want to close it.");
return;
}
if (junction != null)
junction.Close();
if (dosDevice != null)
dosDevice.Close();
junction = null;
dosDevice = null;
Console.WriteLine("[+] Symlink deleted.");
}
/**
* Enforces the Close operation on all Junctions and DosDevices configured for this container.
* The corresponding object attributes are set to null afterwards, to distinguish the link
* from an open one.
*/
public void ForceClose()
{
if (junction != null)
junction.ForceClose();
if (dosDevice != null)
dosDevice.ForceClose();
junction = null;
dosDevice = null;
Console.WriteLine("[+] Symlink deleted.");
}
/**
* Symlink objects may be stored in LinkGroups, which store them internally in a HashSet. This
* requires the type to be hashable. This function builds a HashCode consisting out of the link
* path and the target.
*/
public override int GetHashCode()
{
return (path + " -> " + target).GetHashCode();
}
/**
* Equals wrapper.
*
* @param obj object to compare with
*/
public override bool Equals(object obj)
{
return Equals(obj as Symlink);
}
/**
* Two Symlinks are equal if their path and target are matching.
*
* @param other Symlink to compare with
*/
public bool Equals(Symlink other)
{
return (path == other.path) && (target == other.target);
}
/**
* Create a Symlink from an existing file.
*
* @param path file system path to the existing file
* @param target symlink target
* @return Symlink with the requested properties
*/
public static Symlink FromFile(string path, string target)
{
if (!File.Exists(path))
{
Console.WriteLine("[-] Unable to find file: {0}", path);
return null;
}
Console.Write("[?] Delete existing file? (y/N) ");
ConsoleKey response = Console.ReadKey(false).Key;
Console.WriteLine();
if (response == ConsoleKey.Y)
File.Delete(path);
return new Symlink(path, target);
}
/**
* Create a Symlink for each file existing in the specified folder. All created
* Symlinks share the same target and are bundeled within a LinkGroup.
*
* @param src file system path to the folder to create symlinks from
* @param target shared target for all created symlinks
* @return LinkGroup containing the requested Symlinks
*/
public static LinkGroup FromFolder(string src, string target)
{
if (!Directory.Exists(src))
{
Console.WriteLine("[-] Unable to find directory: {0}", src);
return null;
}
Console.Write("[?] Delete files in link folder? (y/N) ");
ConsoleKey response = Console.ReadKey(false).Key;
Console.WriteLine();
LinkGroup linkGroup = new LinkGroup();
foreach (string filename in Directory.EnumerateFiles(src))
{
if (response == ConsoleKey.Y)
File.Delete(filename);
linkGroup.AddLink(new Symlink(filename, target));
}
return linkGroup;
}
/**
* Create a Symlink for each file existing in the specified folder. The target
* for each created Symlink is a file with the same name as the link file within
* the specified target directory. The created Symlinks are bundeled into a
* LinkGroup.
*
* @param src file system path to the folder to create symlinks from
* @param dst target directory where the symlinks are pointing to
* @return LinkGroup containing the requested Symlinks
*/
public static LinkGroup FromFolderToFolder(string src, string dst)
{
if (!Directory.Exists(src))
{
Console.WriteLine("[-] Unable to find directory: {0}", src);
return null;
}
if (!Directory.Exists(dst))
{
Console.WriteLine("[-] Unable to find directory: {0}", dst);
return null;
}
Console.Write("[?] Delete files in link folder? (y/N) ");
ConsoleKey response = Console.ReadKey(false).Key;
Console.WriteLine();
LinkGroup linkGroup = new LinkGroup();
foreach (string filename in Directory.EnumerateFiles(src))
{
if (response == ConsoleKey.Y)
File.Delete(filename);
linkGroup.AddLink(new Symlink(filename, Path.Combine(dst, Path.GetFileName(filename))));
}
return linkGroup;
}
}
/**
* The DosDevice class is used for creating mappings between the RPC Control object directory
* and the file system. These mappings are required for creating the pseudo file system links.
* DosDevices are treated as resource and are automatically removed after the associated object
* was cleaned up. This can be prevented by using the KeepAlive function.
*
* Author: Tobias Neitzel (@qtc_de)
*/
public class DosDevice
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern bool DefineDosDevice(uint dwFlags, string lpDeviceName, string lpTargetPath);
[DllImport("kernel32.dll", SetLastError = true)]
static extern uint QueryDosDevice(string lpDeviceName, StringBuilder lpTargetPath, uint ucchMax);
// name of the DosDevice
private string name;
// path to the target file on the file system with the \??\ prefix
private string target;
// whether the DosDevice was already manually closed
private bool closed;
// whether to keep the created DosDevice alive after the object is cleaned up
private bool keepAlive;
private const uint DDD_RAW_TARGET_PATH = 0x00000001;
private const uint DDD_REMOVE_DEFINITION = 0x00000002;
private const uint DDD_EXACT_MATCH_ON_REMOVE = 0x00000004;
private const uint DDD_NO_BROADCAST_SYSTEM = 0x00000008;
/**
* DosDevices should be created using the Create function of this class. The Create
* function verifies that the requested DosDevice does not already exist before creating
* it. If this is the case and the DosDevice does not exist, the Create function uses
* this Constructor to instantiate the DosDevice.
*
* @param name name of the DosDevice
* @param target file system path to the target of the DosDevice
* @param keepAlive whether to keep the DosDevice alive after object cleanup
*/
private DosDevice(string name, string target, bool keepAlive)
{
this.name = name;
this.target = target;
this.keepAlive = keepAlive;
this.closed = false;
}
/**
* If keepAlive was not set to true, cleanup the DosDevice when the object is removed.
*/
~DosDevice()
{
if (!keepAlive && !closed)
Close();
}
/**
* Get the target of the DosDevice.
*
* @return configured target of the DosDevice
*/
public string GetTarget()
{
return target;
}
/**
* Get the name of the DosDevice.
*
* @return configured name of the DosDevice
*/
public string GetName()
{
return name;
}
/**
* Set the keepAlive property to the specified value.
*
* @param value whether to keep the DosDevice alive after object cleanup
*/
public void KeepAlive(bool value)
{
keepAlive = value;
}
/**
* Cleanup the DosDevice. This is basically a wrapper around the static Close
* function.
*/
public void Close()
{
Close(name, target);
closed = true;
}
/**
* Enforce cleanup of the DosDevice. This is basically a wrapper around the static Close
* function.
*/
public void ForceClose()
{
Close(name);
closed = true;
}
/**
* Create a new DosDevice with the specified name, pointing to the specified location.
* This function should be used to create DosDevice objects, as it checks whether the
* requested DosDevice already exists before creating it. If non existing, the DosDevice
* is created and a corresponding object is returned by this function. If the DosDevice
* does already exist, null is returned.
*
* @param name name of the DosDevice
* @param target file system path the DosDevice is pointing to
* @param keepAlive whether to keep the DosDevice alive after object cleanup
* @return newly created DosDevice or null
*/
public static DosDevice Create(string name, string target, bool keepAlive)
{
name = PrepareDevicePath(name);
target = PrepareTargetPath(target);
string destination = GetTarget(name);
if (destination != null)
{
if (destination == target)
{
Console.WriteLine("[+] DosDevice {0} -> {1} does already exist.", name, target);
return null;
}
throw new IOException(String.Format("DosDevice {0} does already exist, but points to {0}", name, destination));
}
Console.WriteLine("[+] Creating DosDevice: {0} -> {1}", name, target);
if (DefineDosDevice(DDD_NO_BROADCAST_SYSTEM | DDD_RAW_TARGET_PATH, name, target) &&
DefineDosDevice(DDD_NO_BROADCAST_SYSTEM | DDD_RAW_TARGET_PATH, name, target))
{
return new DosDevice(name, target, keepAlive);
}
throw new IOException("Unable to create DosDevice.", Marshal.GetExceptionForHR(Marshal.GetHRForLastWin32Error()));
}
/**
* Close the specified DosDevice. A DosDevice is only closed if it's target path patches the target specified
* during the function call. Otherwise, a warning is printed and the device is treated as closed, without
* actually closing it.
*
* @param name name of the DosDevice to close
* @param target file system path the DosDevice points to
*/
public static void Close(string name, string target)
{
name = PrepareDevicePath(name);
target = PrepareTargetPath(target);
string destination = GetTarget(name);
if (destination == null)
{
Console.WriteLine("[+] DosDevice {0} -> {1} was already closed.", name, target);
return;
}
if (destination != target)
{
Console.WriteLine("[!] DosDevice {0} is pointing to {1}.", name, destination);
Console.WriteLine("[!] Treating as closed.");
return;
}
Console.WriteLine("[+] Deleting DosDevice: {0} -> {1}", name, target);
DefineDosDevice(DDD_NO_BROADCAST_SYSTEM | DDD_RAW_TARGET_PATH | DDD_REMOVE_DEFINITION |
DDD_EXACT_MATCH_ON_REMOVE, name, target);
DefineDosDevice(DDD_NO_BROADCAST_SYSTEM | DDD_RAW_TARGET_PATH | DDD_REMOVE_DEFINITION |
DDD_EXACT_MATCH_ON_REMOVE, name, target);
}
/**
* Simplified version of the Close function that does not perform a target check.
*
* @param name name of the DosDevice to close
* @param target file system path the DosDevice points to
*/
public static void Close(string name)
{
name = PrepareDevicePath(name);
Console.WriteLine("[+] Deleting DosDevice: {0}", name);
DefineDosDevice(DDD_NO_BROADCAST_SYSTEM | DDD_RAW_TARGET_PATH | DDD_REMOVE_DEFINITION |
DDD_EXACT_MATCH_ON_REMOVE, name, null);
DefineDosDevice(DDD_NO_BROADCAST_SYSTEM | DDD_RAW_TARGET_PATH | DDD_REMOVE_DEFINITION |
DDD_EXACT_MATCH_ON_REMOVE, name, null);
}
/**
* Get the target of the specified DosDevice name.
*
* @param name name of the DosDevice to obtain the target from
*/
public static string GetTarget(string name)
{
name = PrepareDevicePath(name);
StringBuilder pathInformation = new StringBuilder(250);
uint result = QueryDosDevice(name, pathInformation, 250);
if (result == 0)
return null;
return pathInformation.ToString();
}
/**
* DosDevices created by this class are expected to originate from the RPC Control object directory.
* This function applies the corresponding prefix to the specified DosDevice path, if required. If
* the prefix is already used, the path is returned without modification.
*
* @param path DosDevice path
* @return prefixed path if prefixing was necessary, the original path otherwise
*/
private static string PrepareDevicePath(string path)
{
string prefix = @"Global\GLOBALROOT\RPC CONTROL\";
if (path.StartsWith(prefix))
return path;
return prefix + path;
}
/**
* Target file system paths of DosDevices require the '\??\' prefix. This function applies the
* prefix if not already applied.
*
* @param path file system path
* @return prefixed path if prefixing was necessary, the original path otherwise
*/
private static string PrepareTargetPath(string path)
{
string prefix = @"\??\";
if (path.StartsWith(prefix))
return path;
return prefix + path;
}
}
/**
* The Junction class is used for creating file system junctions from C#. Together with
* DosDevices, Junctions are used to build pseudo symbolic links on the file system.
* Junctions are treated as resources and are automatically cleaned up after the corresponding
* object is deleted. This default bahvior can be changed by using the KeepAlive function.
*
* Author: Tobias Neitzel (@qtc_de)
*/
public class Junction
{
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CreateFile(string filename, FileAccess access, FileShare share, IntPtr securityAttributes, FileMode fileMode, uint flagsAndAttributes, IntPtr templateFile);
[DllImport("kernel32.dll", ExactSpelling = true, SetLastError = true, CharSet = CharSet.Auto)]
static extern bool DeviceIoControl(IntPtr hDevice, uint dwIoControlCode, IntPtr lpInBuffer, int nInBufferSize, IntPtr lpOutBuffer, int nOutBufferSize, out int lpBytesReturned, IntPtr lpOverlapped);
// base directory the junction starts from
private string baseDir;
// target directory the junction is pointing to
private string targetDir;
// whether to keep the associated Junction alive when the object is cleaned up
private bool keepAlive;
// whether the DosDevice was already closed manually
private bool closed;
// whether the junction directory was created by this instance
private bool dirCreated;
private const int FSCTL_SET_REPARSE_POINT = 0x000900A4;
private const int FSCTL_GET_REPARSE_POINT = 0x000900A8;
private const int FSCTL_DELETE_REPARSE_POINT = 0x000900AC;
private const uint ERROR_NOT_A_REPARSE_POINT = 0x80071126;
private const uint IO_REPARSE_TAG_MOUNT_POINT = 0xA0000003;
private const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
private const uint FILE_FLAG_OPEN_REPARSE_POINT = 0x00200000;
/**
* Junction objects should be created by the static Create function. The Create function
* first verifies whether the corresponding Junction exists on the file system. Only if
* this is not the case, the Junction object is created by using this constructor.
*
* @param baseDir base directory the Junction originates from
* @param targetDir target directory the Junction is pointing to
* @param dirCreated whether the baseDir was created during Junction creation
* @param keepAlive whether to keep the Junction alive after object cleanup
*/
private Junction(string baseDir, string targetDir, bool dirCreated, bool keepAlive)
{
this.baseDir = baseDir;
this.targetDir = targetDir;
this.dirCreated = dirCreated;
this.keepAlive = keepAlive;
this.closed = false;
}
/**
* If the keepAlive property was not set to true, remove the underlying Junction during
* object cleanup.
*/
~Junction()
{
if (!keepAlive && !closed)
Close();
}
/**
* Return the base directory of the junction.
*
* @return base directory of the junction
*/
public string GetBaseDir()
{
return baseDir;
}
/**
* Return the target directory of the junction.
*
* @return target directory of the junction
*/
public string GetTargetDir()
{
return targetDir;
}