diff --git a/Controller/Controller.cs b/Controller/Controller.cs index 2c10c64..9487d08 100644 --- a/Controller/Controller.cs +++ b/Controller/Controller.cs @@ -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") { /* @@ -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"; @@ -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 { 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); @@ -134,24 +139,23 @@ static async Task 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"; @@ -196,18 +200,17 @@ Retourne un nouvel Id return Result; } - public static async Task VulnerableHandleFileUpload(IFormFile UserFile, string Header, string Token, string Secret, string LogFile) + public static async Task 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); } diff --git a/Identity/VLAIdentity.cs b/Identity/VLAIdentity.cs index e50b0ab..f067255 100644 --- a/Identity/VLAIdentity.cs +++ b/Identity/VLAIdentity.cs @@ -10,11 +10,27 @@ namespace VulnerableWebApplication.VLAIdentity { public class VLAIdentity { - public static async Task 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 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(); @@ -25,10 +41,10 @@ public static async Task 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 diff --git a/MidlWare/MidlWare.cs b/MidlWare/MidlWare.cs index cdb81ac..001ae79 100644 --- a/MidlWare/MidlWare.cs +++ b/MidlWare/MidlWare.cs @@ -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 { @@ -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); + } + } + } diff --git a/Program.cs b/Program.cs index 3ecc820..b76d283 100644 --- a/Program.cs +++ b/Program.cs @@ -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(); @@ -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(); +app.UseMiddleware(); app.UseHttpLogging(); app.UseSwagger(); app.UseSwaggerUI(); // Variables : - -var Secret = configuration["Secret"]; -var LogFile = configuration["LogFile"]; +VLAIdentity.SetSecret(app.Configuration["Secret"]); +VLAIdentity.SetLogFile(app.Configuration["LogFile"]); +VLAController.SetLogFile(app.Configuration["LogFile"]); // Endpoints : app.MapGet("/", async (string? lang) => await Task.FromResult(VLAController.VulnerableHelloWorld(HttpUtility.UrlDecode(lang)))); -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(); -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("/Client"); diff --git a/TestCpu/TestCpu.cs b/TestCpu/TestCpu.cs index 1f7b07d..bb45959 100644 --- a/TestCpu/TestCpu.cs +++ b/TestCpu/TestCpu.cs @@ -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);