-
Notifications
You must be signed in to change notification settings - Fork 80
Expand file tree
/
Copy pathHomeController.cs
More file actions
444 lines (366 loc) · 11.7 KB
/
HomeController.cs
File metadata and controls
444 lines (366 loc) · 11.7 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
using System.Diagnostics;
using Microsoft.AspNetCore.Mvc;
using AspGoat.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.EntityFrameworkCore;
using AspGoat.Data;
using System.Data.SqlClient;
using Microsoft.Data.Sqlite;
using System.Xml;
using System.Runtime.InteropServices;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Formatting = Newtonsoft.Json.Formatting;
using System.Text.Json;
using System.Threading.Tasks;
using RazorLight;
namespace AspGoat.Controllers;
[Authorize]
public class HomeController : Controller
{
private readonly ApplicationDbContext _context;
private readonly IConfiguration _config;
public HomeController(ApplicationDbContext context, IConfiguration config)
{
_context = context;
_config = config;
}
public IActionResult Dashboard()
{
return View();
}
[HttpGet]
public IActionResult ReflectedXSS(string query)
{
ViewData["Query"] = query;
return View();
}
[HttpGet]
public IActionResult StoredXSS()
{
var comments = _context.Comments.Select(c => c.Content).ToList();
return View(comments);
}
[HttpPost]
public IActionResult StoredXSS(string comment)
{
var newComment = new Comment
{
Content = comment
};
_context.Comments.Add(newComment);
_context.SaveChanges();
return RedirectToAction("StoredXSS");
}
[HttpGet]
public IActionResult SqlInjection()
{
string ip = Request.Headers["X-Forwarded-For"].ToString();
if (String.IsNullOrEmpty(ip)) ip = "127.0.0.1";
var _connString = _config.GetConnectionString("DefaultConnection");
using var conn = new SqliteConnection(_connString);
conn.Open();
// Vulnerable to SQL Injection
string query = "SELECT * FROM Users " + "WHERE LastLoginIP = '" + ip + "'";
using var cmd = new SqliteCommand(query, conn);
using var reader = cmd.ExecuteReader();
if (reader.Read()) // take first row only
{
ViewData["Id"] = reader["Id"].ToString();
ViewData["UserName"] = reader["UserName"].ToString();
ViewData["PasswordHash"] = reader["PasswordHash"].ToString();
ViewData["Email"] = reader["Email"].ToString();
ViewData["LastLoginIP"] = reader["LastLoginIP"].ToString();
ViewData["Role"] = reader["Role"].ToString();
}
return View();
}
[HttpGet]
public IActionResult BrokenAuthentication()
{
return View();
}
[HttpPost]
public IActionResult BrokenAuthentication(string username, string password)
{
if (username != "admin")
{
//Username enumeration vulnerability
ViewData["Error"] = "User does not exist.";
return View();
}
if (password != "admin")
{
//Indicates username is valid
ViewData["Error"] = "Incorrect password.";
return View();
}
ViewData["LoginMessage"] = $"Welcome, {username}!";
return View();
}
[HttpGet]
public IActionResult InformationDisclosure()
{
return View();
}
[HttpGet]
public IActionResult XXE()
{
return View();
}
[HttpPost]
public IActionResult XXE(string xmlInput)
{
string result = "";
try
{
var xmlDoc = new XmlDocument
{
XmlResolver = new XmlUrlResolver() //Enables external entity fetching
};
//Vulnerable: External entity resolution enabled by default
xmlDoc.LoadXml(xmlInput);
result = xmlDoc.InnerText;
}
catch (Exception ex)
{
result = $"Error: {ex.Message}";
}
ViewData["ParsedXml"] = result;
return View();
}
[HttpGet]
public IActionResult OpenRedirect(string returnUrl)
{
if (returnUrl != null)
{
return Redirect(returnUrl);
}
return View();
}
[HttpGet]
public IActionResult InsecureDirectObjectReference()
{
return View(new Dictionary<string, object>());
}
[HttpPost]
public IActionResult InsecureDirectObjectReference(int UserId)
{
// Simulating dynamic user data with hardcoding
var userData = new Dictionary<int, Dictionary<string, object>>
{
{ 1, new Dictionary<string, object>
{
{ "user_id", 1 },
{ "username", "admin" },
{ "email", "administrator@aspgoat.net" },
{ "api_key", "a1b2c3d4e5f678g9h0i1j2k3l4m5n6o7p8q9r0s1t2u3v4w5x6y7z8" },
{ "account_status", "active" }
}
},
{ 2, new Dictionary<string, object>
{
{ "user_id", 2 },
{ "username", "john356" },
{ "email", "john.smith@user.net" },
{ "api_key", "a1b2c3d4e5f678g9h0i1j2k3l4m5n6o7p8q9r0s1t2u3v4w5x6y7z8" },
{ "account_status", "active" }
}
}
};
if (userData.ContainsKey(UserId))
{
return View(userData[UserId]);
}
return NotFound("User not found");
}
[HttpGet]
public IActionResult DomXSS()
{
return View();
}
[HttpGet]
public IActionResult PrototypePollution()
{
return View();
}
[HttpGet]
public IActionResult LFI()
{
return View();
}
[HttpGet]
public IActionResult Download(string file)
{
// Vulnerable file concatenation
var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", file);
if (!System.IO.File.Exists(path))
{
return NotFound("File not found");
}
var contentType = "application/octet-stream";
var fileBytes = System.IO.File.ReadAllBytes(path);
return File(fileBytes, contentType, file);
}
[HttpGet]
public IActionResult FileUpload()
{
return View();
}
[HttpPost]
public async Task<IActionResult> FileUpload(IFormFile file)
{
if (file == null || file.Length == 0)
return Content("No file selected.");
var uploads = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "uploads");
Directory.CreateDirectory(uploads);
// Vulnerable filename concatenation
var filePath = Path.Combine(uploads, file.FileName);
using (var stream = new FileStream(filePath, FileMode.Create))
{
await file.CopyToAsync(stream);
}
return Content($"File {file.FileName} uploaded successfully to /uploads.");
}
[HttpGet]
public IActionResult CommandInjection(string domain)
{
if (!String.IsNullOrEmpty(domain))
{
// Choose shell on the basis of OS
string shell, args;
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
shell = "cmd.exe";
// VULNERABLE: direct concatenation of user input into shell command
args = $"/c nslookup {domain}";
}
else
{
shell = "/bin/bash";
// VULNERABLE: direct concatenation of user input into shell command
args = $"-c \"nslookup {domain}\"";
}
var process = new Process();
process.StartInfo.FileName = shell;
process.StartInfo.Arguments = args;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();
process.WaitForExit();
ViewData["Output"] = output;
}
return View();
}
[HttpGet]
public IActionResult InsecureDeserialization()
{
return View();
}
[HttpPost]
public IActionResult InsecureDeserialization([FromBody] JsonElement body)
{
var json = body.GetRawText();
// Vulnerable code as TypeNameHandling.All let's attacker inject arbitrary objects of classes
var settings = new JsonSerializerSettings
{
TypeNameHandling = TypeNameHandling.All
};
var obj = JsonConvert.DeserializeObject<SafeMessage>(json, settings);
var message = obj?.Message;
return Json(new { message });
}
[HttpGet]
public async Task<IActionResult> CSRF()
{
var email = await _context.EmailIds.Select(e => e.Email).FirstOrDefaultAsync();
ViewData["Email"] = email;
return View();
}
[HttpPost]
public async Task<IActionResult> CSRF(int id, string email)
{
var emailRow = await _context.EmailIds.FindAsync(id);
if (emailRow == null)
return NotFound($"EmailId {id} not found.");
emailRow.Email = email;
await _context.SaveChangesAsync();
return RedirectToAction();
}
[HttpGet]
public IActionResult SSRF()
{
return View();
}
[HttpPost]
public async Task<IActionResult> SSRF(string targetUrl)
{
// Vulnerable as the targetUrl is not whitelisted
using var http = new HttpClient();
var response = await http.GetStringAsync(targetUrl);
ViewData["Response"] = response;
return View();
}
[HttpGet]
// Vulnerable as the X-Forwarded-Host is not taken into account for the Cache Key
[ResponseCache(Duration = 60, Location = ResponseCacheLocation.Any, VaryByHeader = "")]
public IActionResult CachePoisoning()
{
var host = Request.Headers["X-Forwarded-Host"];
ViewData["X-Forwarded-Host"] = host;
return View();
}
[HttpGet]
public async Task<IActionResult> SSTI([FromServices] IRazorLightEngine razor)
{
var userName = _context.Users.Where(u => u.Id == 2).Select(u => u.UserName).FirstOrDefault();
var key = Guid.NewGuid().ToString("N");
var html = "";
try
{
// Vulnerable as it compiles & executes user-supplied Razor (Razorlight Template Engine)
html = await razor.CompileRenderStringAsync(key, userName ?? "Null", new { });
}
catch (Exception e)
{
html = e.Message;
}
ViewData["Html"] = html;
return View();
}
[HttpPost]
public async Task<IActionResult> SSTI(int id, string userName)
{
var userRow = await _context.Users.FindAsync(id);
if (userRow == null)
return NotFound($"User {id} not found.");
userRow.UserName = userName;
await _context.SaveChangesAsync();
return RedirectToAction();
}
[AllowAnonymous]
[HttpGet("/internal/config")]
public IActionResult InternalConfig()
{
return Ok(new
{
service = "AspGoat.Internal.Config",
dbConnection = "Server=aspgoat-db;User=app;Password=SuperSecret!",
jwtSigningKey = "FAKE-KEY-123456789",
adminEmail = "admin@aspgoat.local"
});
}
public IActionResult LLM_Vulnerabilities()
{
return View("LLM_Vuln");
}
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public IActionResult Error()
{
return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
}
}