-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
453 lines (402 loc) · 17.2 KB
/
Program.cs
File metadata and controls
453 lines (402 loc) · 17.2 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.IO.Compression;
using System.Net;
using System.Reflection;
namespace ElevationExample
{
class Program
{
// Indique si on écrit dans un fichier .log
private static bool _logToFile = false;
// Chemin du fichier de logs
private static string _logFilePath = "";
// URL par défaut d’AdvancedRun
private static string _advancedRunUrl = "https://github.com/danbenba/ElevationExploit/raw/refs/heads/project/AdvancedRun.zip";
// Par défaut, on prend le mode 8 (TrustedInstaller)
private static int _runAsMode = 8;
// Arguments supplémentaires passés à la commande (remplace qrg par arg)
private static string _additionalArguments = "";
// Indique si on veut utiliser AdvancedRun (télécharger, etc.)
private static bool _downloadAdvancedRun = false;
// Dictionnaire des modes (pour logs)
private static readonly Dictionary<int, string> _runAsDescriptions = new Dictionary<int, string>
{
{1, "Utilisateur actuel - Autoriser élévation (LIAC)"},
{2, "Utilisateur actuel - Sans élévation (IJAC)"},
{3, "Administrateur (Forcer élévation)"},
{4, "Utilisateur SYSTEM"},
{5, "Utilisateur du processus sélectionné"},
{6, "Descendant du processus sélectionné (Injection code)"},
{7, "Nom d’utilisateur + mot de passe (spécifiés)"},
{8, "TrustedInstaller"},
{9, "Autre utilisateur connecté"},
{10, "Service réseau"},
{11, "Service local"}
};
static void Main(string[] args)
{
// Affiche un petit "banner"
PrintBanner();
// Si aucun argument ou si on demande l'aide
if (args.Length == 0 || args[0].Equals("-h", StringComparison.OrdinalIgnoreCase)
|| args[0].Equals("--help", StringComparison.OrdinalIgnoreCase))
{
PrintHelp();
return;
}
// Premièrement, la commande à exécuter (ex: cmd.exe)
string command = args[0];
// Analyse des options
for (int i = 1; i < args.Length; i++)
{
string arg = args[i];
if (arg.Equals("-t", StringComparison.OrdinalIgnoreCase))
{
_downloadAdvancedRun = true;
}
else if (arg.Equals("-s", StringComparison.OrdinalIgnoreCase))
{
_logToFile = true;
}
else if (arg.Equals("-e", StringComparison.OrdinalIgnoreCase))
{
if (i + 1 < args.Length)
{
_logFilePath = args[++i];
_logToFile = true;
}
}
else if (arg.Equals("-u", StringComparison.OrdinalIgnoreCase))
{
if (i + 1 < args.Length)
{
_advancedRunUrl = args[++i];
}
}
else if (arg.Equals("-m", StringComparison.OrdinalIgnoreCase))
{
if (i + 1 < args.Length && int.TryParse(args[i + 1], out int mode))
{
if (mode >= 1 && mode <= 11)
{
_runAsMode = mode;
_downloadAdvancedRun = true;
}
i++;
}
}
// Remplacement : au lieu de -qrg => -arg
else if (arg.Equals("-arg", StringComparison.OrdinalIgnoreCase))
{
// Arguments supplémentaires
if (i + 1 < args.Length)
{
_additionalArguments = args[++i];
}
}
}
// Si on doit logger dans un fichier sans -e, on utilise Elevation.log
if (_logToFile && string.IsNullOrWhiteSpace(_logFilePath))
{
_logFilePath = Path.Combine(Environment.CurrentDirectory, "Elevation.log");
}
// Vérifie si on est admin
if (!IsRunningAsAdmin())
{
RelaunchAsAdmin(args);
return;
}
WriteLog("[OK] Exécuté avec droits administrateur.", LogLevel.Success);
if (_downloadAdvancedRun)
{
DownloadAndRunAdvancedRun(command, _additionalArguments);
}
else
{
ExecuteCommand(command, _additionalArguments);
}
}
/// <summary>
/// Affiche un banner en console.
/// </summary>
private static void PrintBanner()
{
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
Console.WriteLine(" _____ _ _ _ _____ _ _ _ ");
Console.WriteLine(" | ___| | | | (_) | ___| | | (_) | ");
Console.WriteLine(" | |__ | | _____ ____ _| |_ _ ___ _ __ | |____ ___ __ | | ___ _| |_ ");
Console.WriteLine(" | __|| |/ _ \\ \\ / / _` | __| |/ _ \\| '_ \\ | __\\ \\/ / '_ \\| |/ _ \\| | __|");
Console.WriteLine(" | |___| | __/\\ V / (_| | |_| | (_) | | | | | |___> <| |_) | | (_) | | |_ ");
Console.WriteLine(" \\____/|_|\\___| \\_/ \\__,_|\\__|_|\\___/|_| |_| \\____/_/\\_\\ .__/|_|\\___/|_|\\__|");
Console.WriteLine(" | | ");
Console.WriteLine(" |_| ");
Console.WriteLine("");
Console.WriteLine(" Version 0.4 - https://github.com/danbenba/ElevationExploit - Created by danbenba");
Console.WriteLine("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=");
Console.ResetColor();
}
/// <summary>
/// Affiche le menu d'aide.
/// </summary>
private static void PrintHelp()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("Usage : elevation.exe <commande> [options]");
Console.WriteLine("Exemple : elevation.exe cmd.exe -m 3 -arg \"/c dir\"");
Console.WriteLine();
Console.WriteLine("Options :");
Console.WriteLine(" -t : Mode TrustedInstaller");
Console.WriteLine(" -m <1..11> : Mode /RunAs (ex: 3=Admin forcé, 8=TrustedInstaller, etc.)");
Console.WriteLine(" -arg \"args...\" : Arguments supplémentaires passés à la commande (ex: /c dir)");
Console.WriteLine(" -s : Sauvegarder les logs dans un fichier .log (par défaut Elevation.log)");
Console.WriteLine(" -e \"cheminLog\" : Chemin personnalisé pour le fichier de log");
Console.WriteLine(" -u \"urlZip\" : URL personnalisée pour télécharger AdvancedRun.zip");
Console.WriteLine();
Console.WriteLine(" -h / --help : Afficher cette aide");
Console.ResetColor();
}
/// <summary>
/// Vérifie si l’application est exécutée en tant qu’administrateur.
/// </summary>
private static bool IsRunningAsAdmin()
{
var wi = System.Security.Principal.WindowsIdentity.GetCurrent();
var wp = new System.Security.Principal.WindowsPrincipal(wi);
return wp.IsInRole(System.Security.Principal.WindowsBuiltInRole.Administrator);
}
/// <summary>
/// Relance l’appli en mode admin (affiche prompt UAC).
/// </summary>
private static void RelaunchAsAdmin(string[] args)
{
string exeName = Process.GetCurrentProcess().MainModule.FileName;
string arguments = string.Join(" ", args);
var startInfo = new ProcessStartInfo
{
FileName = exeName,
Verb = "runas",
Arguments = arguments,
UseShellExecute = true
};
try
{
Process.Start(startInfo);
}
catch (Exception ex)
{
WriteLog("Échec lors de la relance avec privilèges élevés : " + ex.Message, LogLevel.Error);
}
}
/// <summary>
/// Exécute directement la commande (ex : cmd.exe) avec éventuellement des arguments supplémentaires.
/// </summary>
private static void ExecuteCommand(string command, string extraArgs)
{
try
{
string fullCommand = command;
if (!string.IsNullOrEmpty(extraArgs))
{
fullCommand += " " + extraArgs;
}
WriteLog($"[INFO] Exécution directe : {fullCommand}", LogLevel.Info);
Process.Start(fullCommand);
}
catch (Exception ex)
{
WriteLog($"[ERREUR] {ex.Message}", LogLevel.Error);
}
}
/// <summary>
/// Télécharge AdvancedRun, l’extrait, et l’exécute avec /RunAs _runAsMode.
/// </summary>
private static void DownloadAndRunAdvancedRun(string command, string extraArgs)
{
string appDataTemp = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"Temp"
);
Directory.CreateDirectory(appDataTemp);
string zipFilePath = Path.Combine(appDataTemp, "AdvancedRun.zip");
WriteLog($"[INFO] Téléchargement d'AdvancedRun.", LogLevel.Info);
if (!DownloadFileWithProgress(_advancedRunUrl, zipFilePath))
{
WriteLog("[ERREUR] Échec du téléchargement.", LogLevel.Error);
return;
}
WriteLog("[INFO] Téléchargement terminé.", LogLevel.Info);
// Extraction
try
{
ZipFile.ExtractToDirectory(zipFilePath, appDataTemp, true);
WriteLog("[INFO] Décompression réussie.", LogLevel.Success);
}
catch (Exception ex)
{
WriteLog($"[ERREUR] Impossible de décompresser : {ex.Message}", LogLevel.Error);
return;
}
// On affiche dans les logs le mode choisi
if (_runAsDescriptions.TryGetValue(_runAsMode, out string desc))
{
WriteLog($"[+] Mode choisi : {_runAsMode} ({desc})", LogLevel.Info);
}
else
{
WriteLog($"[+] Mode choisi : {_runAsMode}", LogLevel.Info);
}
// On injecte éventuellement les extraArgs à la commande
string runCommand = command;
if (!string.IsNullOrEmpty(extraArgs))
{
runCommand += " " + extraArgs;
}
// Exécution d'AdvancedRun
string advancedRunExe = Path.Combine(appDataTemp, "AdvancedRun.exe");
var psi = new ProcessStartInfo
{
FileName = advancedRunExe,
Arguments = $"/EXEFilename \"{runCommand}\" /RunAs {_runAsMode} /Run",
UseShellExecute = false
};
try
{
WriteLog($"[INFO] Lancement d'AdvancedRun.exe avec : {runCommand}", LogLevel.Info);
Process.Start(psi);
}
catch (Exception ex)
{
WriteLog("[ERREUR] Impossible de lancer AdvancedRun : " + ex.Message, LogLevel.Error);
}
}
/// <summary>
/// Télécharge un fichier, affiche une barre de progression ASCII et log chaque pourcentage.
/// </summary>
private static bool DownloadFileWithProgress(string url, string destinationPath)
{
try
{
using (WebClient client = new WebClient())
{
// On va mémoriser le dernier pourcentage pour éviter d'écrire 100 fois le même.
int lastProgress = -1;
client.DownloadProgressChanged += (sender, e) =>
{
int progressValue = e.ProgressPercentage;
if (progressValue != lastProgress)
{
lastProgress = progressValue;
// Affichage console : barre de progression
DrawProgressBar(progressValue, 100);
// On log aussi
WriteLog($"[DOWNLOAD] {progressValue}%", LogLevel.Info, false);
}
};
client.DownloadFileCompleted += (sender, e) =>
{
Console.WriteLine(); // pour aller à la ligne après la barre
if (e.Cancelled)
{
WriteLog("[ANNULÉ] Téléchargement annulé.", LogLevel.Warning);
}
else if (e.Error != null)
{
WriteLog($"[ERREUR] {e.Error.Message}", LogLevel.Error);
}
else
{
WriteLog("[OK] Téléchargement réussi.", LogLevel.Success);
}
};
// Téléchargement bloquant (synchrone)
client.DownloadFile(url, destinationPath);
}
return true;
}
catch (Exception ex)
{
WriteLog("[ERREUR] " + ex.Message, LogLevel.Error);
return false;
}
}
/// <summary>
/// Dessine une barre de progression (ASCII) en console.
/// ex: [##########----] 60%
/// </summary>
private static void DrawProgressBar(int current, int max)
{
const int barLength = 30; // longueur en caractères
double ratio = (double)current / max;
int nbChars = (int)(ratio * barLength);
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.Write("\r["); // retour en début de ligne
Console.Write(new string('#', nbChars));
Console.Write(new string('-', barLength - nbChars));
Console.Write($"] {current}%");
Console.ResetColor();
}
// --- SYSTÈME DE LOGS ---
/// <summary>
/// Niveaux de log : Info, Succès, Erreur, Avertissement.
/// </summary>
enum LogLevel
{
Info,
Success,
Error,
Warning
}
/// <summary>
/// Écrit un message dans la console (avec couleur) + fichier log si demandé.
/// Le paramètre "logToConsoleOverride" permet de forcer ou non l'affichage console.
/// </summary>
static void WriteLog(string message, LogLevel level, bool logToConsoleOverride = true)
{
// Si on veut afficher en console
if (logToConsoleOverride)
{
ConsoleColor oldColor = Console.ForegroundColor;
switch (level)
{
case LogLevel.Info:
Console.ForegroundColor = ConsoleColor.White;
break;
case LogLevel.Success:
Console.ForegroundColor = ConsoleColor.Green;
break;
case LogLevel.Error:
Console.ForegroundColor = ConsoleColor.Red;
break;
case LogLevel.Warning:
Console.ForegroundColor = ConsoleColor.Yellow;
break;
}
// Écrit en console
Console.WriteLine(message);
Console.ForegroundColor = oldColor;
}
// Écrit dans un fichier .log si activé
if (_logToFile && !string.IsNullOrWhiteSpace(_logFilePath))
{
try
{
using (var sw = new StreamWriter(_logFilePath, true))
{
sw.WriteLine($"[{DateTime.Now:yyyy-MM-dd HH:mm:ss}] {message}");
}
}
catch (Exception ex)
{
// Si on échoue à écrire, on l’affiche en console
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("[ERREUR-LOG] " + ex.Message);
Console.ResetColor();
}
}
}
}
}