Skip to content

Commit

Permalink
Identity++
Browse files Browse the repository at this point in the history
  • Loading branch information
Aif4thah committed May 28, 2024
1 parent 328e79d commit 63b3b0e
Show file tree
Hide file tree
Showing 3 changed files with 86 additions and 75 deletions.
80 changes: 6 additions & 74 deletions Controller/Controller.cs
Original file line number Diff line number Diff line change
@@ -1,20 +1,17 @@
using System.Data;
using System.Security.Claims;
using System.Text;
using System.Xml;
using Newtonsoft.Json;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Net.Http.Headers;
using System.Diagnostics;
using System.Text.RegularExpressions;
using Microsoft.CodeAnalysis.CSharp.Scripting;
using System.Security.Cryptography;
using System.Xml.Linq;
using System.Xml.Xsl;
using VulnerableWebApplication.VLAModel;
using System.Runtime.InteropServices;
using System.Web;
using VulnerableWebApplication.VLAModel;


namespace VulnerableWebApplication.VLAController
Expand All @@ -38,7 +35,7 @@ public static object VulnerableDeserialize(string Json, string Token, string Sec
Deserialise les données JSON passées en paramètre.
On enregistre les objets "employé" valides dans un fichier en lecture seule
*/
if (!VulnerableValidateToken(Token, Secret)) return Results.Unauthorized();
if (!VLAIdentity.VLAIdentity.VulnerableValidateToken(Token, Secret)) return Results.Unauthorized();
string NewId = "-1";
string HaveToBeEmpty = string.Empty;
string ROFile = "NewEmployees.txt";
Expand Down Expand Up @@ -69,7 +66,7 @@ public static string VulnerableXmlParser(string Xml, string Token, string Secret
/*
Parse les contrats au format XML passées en paramètre et retourne son contenu
*/
if (!VulnerableValidateToken(Token, Secret)) return Results.Unauthorized().ToString();
if (!VLAIdentity.VLAIdentity.VulnerableValidateToken(Token, Secret)) return Results.Unauthorized().ToString();
try
{
var Xsl = XDocument.Parse(Xml);
Expand Down Expand Up @@ -114,71 +111,6 @@ public static void VulnerableLogs(string Str, string LogFile)
File.WriteAllText(LogFile, Page);
}

public static async Task<object> VulnerableQuery(string User, string Passwd, string Secret, string LogFile)
{
/*
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();
for (int i = 0; i < Bytes.Length; i++) stringbuilder.Append(Bytes[i].ToString("x2"));
string Hash = stringbuilder.ToString();

VulnerableLogs("login attempt for:\n" + User + "\n" + Passwd + "\n", LogFile);
var DataSet = Data.GetDataSet();
var Result = DataSet.Tables[0].Select("Passwd = '" + Hash + "' and User = '" + User + "'");

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

public static string VulnerableGenerateToken(string User, string Secret)
{
/*
Retourne un token JWT signé pour l'utilisateur passé en paramètre
*/
var TokenHandler = new JwtSecurityTokenHandler();
var Key = Encoding.ASCII.GetBytes(Secret);
var TokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("Id", User) }),
Expires = DateTime.UtcNow.AddDays(365),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Key), SecurityAlgorithms.HmacSha256Signature)
};
var Token = TokenHandler.CreateToken(TokenDescriptor);

return TokenHandler.WriteToken(Token);
}

public static bool VulnerableValidateToken(string Token, string Secret)
{
/*
Vérifie la validité du token JWT passé en paramètre
*/
var TokenHandler = new JwtSecurityTokenHandler();
var Key = Encoding.ASCII.GetBytes(Secret);
bool Result = true;
try
{
var JwtSecurityToken = TokenHandler.ReadJwtToken(Token.Substring("Bearer ".Length));
if (JwtSecurityToken.Header.Alg == "HS256" && JwtSecurityToken.Header.Typ == "JWT")
{
TokenHandler.ValidateToken(Token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Key),
ValidateIssuer = false,
ValidateAudience = false,
}, out SecurityToken validatedToken);

var JwtToken = (JwtSecurityToken)validatedToken;
}
}
catch { Result = false; }

return Result;
}

public static async Task<object> VulnerableWebRequest(string Uri = "https://localhost:3000/")
{
/*
Expand Down Expand Up @@ -208,7 +140,7 @@ public static object VulnerableObjectReference(string Id, string Token, string S
Retourne les informations liées à l'ID de l'utilisateur
Permets aux employés de consulter leurs données personnelles
*/
if (!VulnerableValidateToken(Token, Secret)) return Results.Unauthorized();
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));
Expand All @@ -219,7 +151,7 @@ public static object VulnerableCmd(string UserStr, string Token, string Secret)
/*
Effectue une requête DNS pour le FQDN passé en paramètre
*/
if (VulnerableValidateToken(Token, Secret) && Regex.Match(UserStr, @"^(?:[a-zA-Z0-9_\-]+\.)+[a-zA-Z]{2,}(?:.{0,20})$").Success)
if (VLAIdentity.VLAIdentity.VulnerableValidateToken(Token, Secret) && Regex.Match(UserStr, @"^(?:[a-zA-Z0-9_\-]+\.)+[a-zA-Z]{2,}(?:.{0,20})$").Success)
{
Process Cmd = new Process();
Cmd.StartInfo.FileName = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd" : "/bin/sh";
Expand Down Expand Up @@ -269,7 +201,7 @@ public static async Task<IResult> VulnerableHandleFileUpload(IFormFile UserFile,
/*
Permets l'upload de fichier de type SVG
*/
if ((!VulnerableValidateToken(Token, Secret)) || (!Header.Contains("10.10.10.256"))) return Results.Unauthorized();
if ((!VLAIdentity.VLAIdentity.VulnerableValidateToken(Token, Secret)) || (!Header.Contains("10.10.10.256"))) return Results.Unauthorized();

if (UserFile.FileName.EndsWith(".svg"))
{
Expand Down
78 changes: 78 additions & 0 deletions Identity/VLAIdentity.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
using System.Data;
using System.Security.Claims;
using System.Text;
using System.IdentityModel.Tokens.Jwt;
using Microsoft.IdentityModel.Tokens;
using System.Security.Cryptography;


namespace VulnerableWebApplication.VLAIdentity
{
public class VLAIdentity
{
public static async Task<object> VulnerableQuery(string User, string Passwd, string Secret, string LogFile)
{
/*
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();
for (int i = 0; i < Bytes.Length; i++) stringbuilder.Append(Bytes[i].ToString("x2"));
string Hash = stringbuilder.ToString();

VLAController.VLAController.VulnerableLogs("login attempt for:\n" + User + "\n" + Passwd + "\n", LogFile);
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();
}

public static string VulnerableGenerateToken(string User, string Secret)
{
/*
Retourne un token JWT signé pour l'utilisateur passé en paramètre
*/
var TokenHandler = new JwtSecurityTokenHandler();
var Key = Encoding.ASCII.GetBytes(Secret);
var TokenDescriptor = new SecurityTokenDescriptor
{
Subject = new ClaimsIdentity(new[] { new Claim("Id", User) }),
Expires = DateTime.UtcNow.AddDays(365),
SigningCredentials = new SigningCredentials(new SymmetricSecurityKey(Key), SecurityAlgorithms.HmacSha256Signature)
};
var Token = TokenHandler.CreateToken(TokenDescriptor);

return TokenHandler.WriteToken(Token);
}

public static bool VulnerableValidateToken(string Token, string Secret)
{
/*
Vérifie la validité du token JWT passé en paramètre
*/
var TokenHandler = new JwtSecurityTokenHandler();
var Key = Encoding.ASCII.GetBytes(Secret);
bool Result = true;
try
{
var JwtSecurityToken = TokenHandler.ReadJwtToken(Token.Substring("Bearer ".Length));
if (JwtSecurityToken.Header.Alg == "HS256" && JwtSecurityToken.Header.Typ == "JWT")
{
TokenHandler.ValidateToken(Token, new TokenValidationParameters
{
ValidateIssuerSigningKey = true,
IssuerSigningKey = new SymmetricSecurityKey(Key),
ValidateIssuer = false,
ValidateAudience = false,
}, out SecurityToken validatedToken);

var JwtToken = (JwtSecurityToken)validatedToken;
}
}
catch { Result = false; }

return Result;
}
}
}
3 changes: 2 additions & 1 deletion Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
using Microsoft.AspNetCore.HttpLogging;
using Microsoft.AspNetCore.HttpOverrides;
using VulnerableWebApplication.VLAModel;
using VulnerableWebApplication.VLAIdentity;
using VulnerableWebApplication.MidlWare;
using Microsoft.AspNetCore.OpenApi;
using GraphQL.Types;
Expand Down Expand Up @@ -61,7 +62,7 @@

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

Check warning on line 63 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(VLAController.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, Secret, LogFile)).Result).WithOpenApi();

Check warning on line 65 in Program.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'Secret' in 'Task<object> VLAIdentity.VulnerableQuery(string User, string Passwd, string Secret, string LogFile)'.

Check warning on line 65 in Program.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'LogFile' in 'Task<object> VLAIdentity.VulnerableQuery(string User, string Passwd, string Secret, string LogFile)'.

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

Check warning on line 67 in Program.cs

View workflow job for this annotation

GitHub Actions / build

Possible null reference argument for parameter 'Secret' in 'string VLAController.VulnerableXmlParser(string Xml, string Token, string Secret)'.

Expand Down

0 comments on commit 63b3b0e

Please sign in to comment.