Skip to content

Commit

Permalink
Auth++
Browse files Browse the repository at this point in the history
  • Loading branch information
Aif4thah committed Jun 11, 2024
1 parent 3167e7c commit f1ce808
Show file tree
Hide file tree
Showing 5 changed files with 94 additions and 29 deletions.
25 changes: 14 additions & 11 deletions Controller/Controller.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,13 @@ namespace VulnerableWebApplication.VLAController
{
public class VLAController
{
private static string LogFile;

public static void SetLogFile(string logFile)
{
LogFile = logFile;
}

public static object VulnerableHelloWorld(string FileName = "english")
{
/*
Expand All @@ -29,13 +36,12 @@ Retourne le contenu du fichier correspondant à la langue choisie par l'utilisat
return Results.Ok(File.ReadAllText(FileName));
}

public static object VulnerableDeserialize(string Json, string Token, string Secret)
public static object VulnerableDeserialize(string Json)
{
/*
Deserialise les données JSON passées en paramètre.
On enregistre les objets "employé" valides dans un fichier en lecture seule
*/
if (!VLAIdentity.VLAIdentity.VulnerableValidateToken(Token, Secret)) return Results.Unauthorized();
string NewId = "-1";
string HaveToBeEmpty = string.Empty;
string ROFile = "NewEmployees.txt";
Expand All @@ -61,12 +67,11 @@ On enregistre les objets "employé" valides dans un fichier en lecture seule
return Results.Ok(Newtonsoft.Json.JsonConvert.SerializeObject(new List<object> { File.GetAttributes(ROFile).ToString(), NewId, HaveToBeEmpty.IsNullOrEmpty() }));
}

public static string VulnerableXmlParser(string Xml, string Token, string Secret)
public static string VulnerableXmlParser(string Xml)
{
/*
Parse les contrats au format XML passées en paramètre et retourne son contenu
*/
if (!VLAIdentity.VLAIdentity.VulnerableValidateToken(Token, Secret)) return Results.Unauthorized().ToString();
try
{
var Xsl = XDocument.Parse(Xml);
Expand Down Expand Up @@ -134,24 +139,23 @@ static async Task<string> exec(HttpClient client, string uri)
else return Results.Unauthorized();
}

public static object VulnerableObjectReference(string Id, string Token, string Secret)
public static object VulnerableObjectReference(string Id)
{
/*
Retourne les informations liées à l'ID de l'utilisateur
Permets aux employés de consulter leurs données personnelles
*/
if (!VLAIdentity.VLAIdentity.VulnerableValidateToken(Token, Secret)) return Results.Unauthorized();
var Employee = Data.GetEmployees()?.Where(x => Id == x.Id)?.FirstOrDefault();

return Results.Ok(Newtonsoft.Json.JsonConvert.SerializeObject(Employee));
}

public static object VulnerableCmd(string UserStr, string Token, string Secret)
public static object VulnerableCmd(string UserStr)
{
/*
Effectue une requête DNS pour le FQDN passé en paramètre
*/
if (VLAIdentity.VLAIdentity.VulnerableValidateToken(Token, Secret) && Regex.Match(UserStr, @"^(?:[a-zA-Z0-9_\-]+\.)+[a-zA-Z]{2,}(?:.{0,100})$").Success)
if (Regex.Match(UserStr, @"^(?:[a-zA-Z0-9_\-]+\.)+[a-zA-Z]{2,}(?:.{0,100})$").Success)
{
Process Cmd = new Process();
Cmd.StartInfo.FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "powershell" : "/bin/sh";
Expand Down Expand Up @@ -196,18 +200,17 @@ Retourne un nouvel Id
return Result;
}

public static async Task<IResult> VulnerableHandleFileUpload(IFormFile UserFile, string Header, string Token, string Secret, string LogFile)
public static async Task<IResult> VulnerableHandleFileUpload(IFormFile UserFile, string Header)
{
/*
Permets l'upload de fichier de type SVG
*/
if ((!VLAIdentity.VLAIdentity.VulnerableValidateToken(Token, Secret)) || (!Header.Contains("10.10.10.256"))) return Results.Unauthorized();
if (!Header.Contains("10.10.10.256")) return Results.Unauthorized();

if (UserFile.FileName.EndsWith(".svg"))
{
using var Stream = File.OpenWrite(UserFile.FileName);
await UserFile.CopyToAsync(Stream);
VulnerableLogs($"Patch with : {Token} from {Header}", LogFile);

return Results.Ok(UserFile.FileName);
}
Expand Down
22 changes: 19 additions & 3 deletions Identity/VLAIdentity.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,27 @@ namespace VulnerableWebApplication.VLAIdentity
{
public class VLAIdentity
{
public static async Task<object> VulnerableQuery(string User, string Passwd, string Secret, string LogFile)
private static string Secret;

public static void SetSecret(string secret)
{
Secret = secret;
}

private static string LogFile;

public static void SetLogFile(string logFile)
{
LogFile = logFile;
}


public static async Task<object> VulnerableQuery(string User, string Passwd)
{
/*
Authentifie les utilisateurs par login et mot de passe, et renvoie un token JWT si l'authentification a réussi
*/

SHA256 Sha256Hash = SHA256.Create();
byte[] Bytes = Sha256Hash.ComputeHash(Encoding.UTF8.GetBytes(Passwd));
StringBuilder stringbuilder = new StringBuilder();
Expand All @@ -25,10 +41,10 @@ public static async Task<object> VulnerableQuery(string User, string Passwd, str
var DataSet = VLAModel.Data.GetDataSet();
var Result = DataSet.Tables[0].Select("Passwd = '" + Hash + "' and User = '" + User + "'");

return Result.Length > 0 ? Results.Ok(VulnerableGenerateToken(User, Secret)) : Results.Unauthorized();
return Result.Length > 0 ? Results.Ok(VulnerableGenerateToken(User)) : Results.Unauthorized();
}

public static string VulnerableGenerateToken(string User, string Secret)
public static string VulnerableGenerateToken(string User)
{
/*
Retourne un token JWT signé pour l'utilisateur passé en paramètre
Expand Down
44 changes: 43 additions & 1 deletion MidlWare/MidlWare.cs
Original file line number Diff line number Diff line change
@@ -1,4 +1,9 @@
namespace VulnerableWebApplication.MidlWare
using Microsoft.Extensions.Options;
using VulnerableWebApplication.VLAIdentity;
using VulnerableWebApplication;
using Microsoft.IdentityModel.Tokens;

namespace VulnerableWebApplication.MidlWare
{
public class XRealIPMiddleware
{
Expand All @@ -19,4 +24,41 @@ public async Task Invoke(HttpContext context)
}

}


public class ValidateJwtMiddleware
{
private readonly RequestDelegate _next;

public ValidateJwtMiddleware(RequestDelegate next)
{
_next = next;
}



public async Task InvokeAsync(HttpContext context, IConfiguration configuration)
{
/*
Authentifie les utilisateurs
*/

// Si l'URL est celle de l'endpoint de login, on passe à la suite sans valider le token
var path = context.Request.Path.Value;
if (path.Equals("/login", StringComparison.OrdinalIgnoreCase) || path.StartsWith("/swagger", StringComparison.OrdinalIgnoreCase))
{
await _next(context);
return;
}

string authHeader = context.Request.Headers["Authorization"];
if (authHeader.IsNullOrEmpty() || !VLAIdentity.VLAIdentity.VulnerableValidateToken(authHeader, configuration["Secret"]))
{
context.Response.StatusCode = StatusCodes.Status401Unauthorized;
return;
}
await _next(context);
}
}

}
30 changes: 18 additions & 12 deletions Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,18 @@
using Microsoft.AspNetCore.OpenApi;
using GraphQL.Types;
using GraphQL;
using System.Net.Sockets;


// Configuration :
// Configuration du service

var builder = WebApplication.CreateBuilder(args);

builder.Configuration
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings{builder.Environment.EnvironmentName}.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables();

// Swagger
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen();
Expand All @@ -41,39 +47,39 @@
logging.CombineLogs = true;
});

var configuration = new ConfigurationBuilder().SetBasePath(Directory.GetCurrentDirectory()).AddJsonFile("appsettings.json").Build();

// Configuration de l'application :
var app = builder.Build();
app.UseAntiforgery();
app.UseMiddleware<XRealIPMiddleware>();
app.UseMiddleware<ValidateJwtMiddleware>();
app.UseHttpLogging();
app.UseSwagger();
app.UseSwaggerUI();


// Variables :

var Secret = configuration["Secret"];
var LogFile = configuration["LogFile"];
VLAIdentity.SetSecret(app.Configuration["Secret"]);

Check warning on line 61 in Program.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'secret' in 'void VLAIdentity.SetSecret(string secret)'.
VLAIdentity.SetLogFile(app.Configuration["LogFile"]);

Check warning on line 62 in Program.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'logFile' in 'void VLAIdentity.SetLogFile(string logFile)'.
VLAController.SetLogFile(app.Configuration["LogFile"]);

Check warning on line 63 in Program.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'logFile' in 'void VLAController.SetLogFile(string logFile)'.


// Endpoints :

app.MapGet("/", async (string? lang) => await Task.FromResult(VLAController.VulnerableHelloWorld(HttpUtility.UrlDecode(lang))));

Check warning on line 68 in Program.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'FileName' in 'object VLAController.VulnerableHelloWorld(string FileName = "english")'.

app.MapPost("/Login", [ProducesResponseType(StatusCodes.Status200OK)] async (HttpRequest request, [FromBody] VulnerableWebApplication.VLAModel.Creds login) => await Task.FromResult(VLAIdentity.VulnerableQuery(login.User, login.Passwd, Secret, LogFile)).Result).WithOpenApi();
app.MapPost("/Login", [ProducesResponseType(StatusCodes.Status200OK)] async (HttpRequest request, [FromBody] VulnerableWebApplication.VLAModel.Creds login) => await Task.FromResult(VLAIdentity.VulnerableQuery(login.User, login.Passwd)).Result).WithOpenApi();

app.MapGet("/Contract", async (string i, [FromHeader(Name="Authorization")] string t) => await Task.FromResult(VLAController.VulnerableXmlParser(HttpUtility.UrlDecode(i), t, Secret))).WithOpenApi();
app.MapGet("/Contract", async (string i) => await Task.FromResult(VLAController.VulnerableXmlParser(HttpUtility.UrlDecode(i)))).WithOpenApi();

app.MapGet("/LocalWebQuery", async (string? i) => await VLAController.VulnerableWebRequest(i)).WithOpenApi();

Check warning on line 74 in Program.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'Uri' in 'Task<object> VLAController.VulnerableWebRequest(string Uri = "https://localhost:3000/")'.

app.MapGet("/Employee", async (string i, [FromHeader(Name="Authorization")] string t) => await Task.FromResult(VLAController.VulnerableObjectReference(i, t, Secret))).WithOpenApi();
app.MapGet("/Employee", async (string i) => await Task.FromResult(VLAController.VulnerableObjectReference(i))).WithOpenApi();

app.MapGet("/NewEmployee", async (string i, [FromHeader(Name = "Authorization")] string t) => await Task.FromResult(VLAController.VulnerableDeserialize(HttpUtility.UrlDecode(i), t, Secret))).WithOpenApi();
app.MapGet("/NewEmployee", async (string i) => await Task.FromResult(VLAController.VulnerableDeserialize(HttpUtility.UrlDecode(i)))).WithOpenApi();

app.MapGet("/LocalDNSResolver", async (string i, [FromHeader(Name="Authorization")] string t) => await Task.FromResult(VLAController.VulnerableCmd(HttpUtility.UrlDecode(i), t ,Secret))).WithOpenApi();
app.MapGet("/LocalDNSResolver", async (string i) => await Task.FromResult(VLAController.VulnerableCmd(HttpUtility.UrlDecode(i)))).WithOpenApi();

app.MapPatch("/Patch", async ([FromHeader(Name="X-Forwarded-For")] string h, [FromHeader(Name = "Authorization")] string t, [FromForm] IFormFile file) => await VLAController.VulnerableHandleFileUpload(file, h, t, Secret, LogFile)).DisableAntiforgery().WithOpenApi();
app.MapPatch("/Patch", async ([FromHeader(Name="X-Forwarded-For")] string h, [FromForm] IFormFile file) => await VLAController.VulnerableHandleFileUpload(file, h)).DisableAntiforgery().WithOpenApi();

app.UseGraphQL<ISchema>("/Client");

Expand Down
2 changes: 0 additions & 2 deletions TestCpu/TestCpu.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,6 @@ public static void TestAffinity()
var sha256 = SHA256.Create();
foreach (byte b in bytes) binary.Append(Convert.ToString(b, 2).PadLeft(8, '0'));
string BinStr = binary.ToString();

Console.WriteLine("Total proc: {0}", Environment.ProcessorCount);
foreach (char bit in BinStr)
{
Thread.Sleep(1000);
Expand Down

0 comments on commit f1ce808

Please sign in to comment.