This commit is contained in:
Elijah R
2024-04-04 00:57:59 -04:00
commit b626220fd3
17 changed files with 35217 additions and 0 deletions

View File

@@ -0,0 +1,13 @@
namespace Computernewb.CollabVMAuthServer;
public class AuthServerInformation
{
public bool registrationOpen { get; set; }
public AuthServerInformationCaptcha hcaptcha { get; set; }
}
public class AuthServerInformationCaptcha
{
public bool required { get; set; }
public string? siteKey { get; set; }
}

View File

@@ -0,0 +1,20 @@
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
<Nullable>enable</Nullable>
<ImplicitUsings>enable</ImplicitUsings>
<InvariantGlobalization>true</InvariantGlobalization>
<PublishAot>false</PublishAot>
<RootNamespace>Computernewb.CollabVMAuthServer</RootNamespace>
<Company>Computernewb Development Team</Company>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Isopoh.Cryptography.Argon2" Version="2.0.0" />
<PackageReference Include="MailKit" Version="4.4.0" />
<PackageReference Include="MySqlConnector" Version="2.3.6" />
<PackageReference Include="Samboy063.Tomlet" Version="5.3.1" />
</ItemGroup>
</Project>

View File

@@ -0,0 +1,103 @@
using Isopoh.Cryptography.Argon2;
using MySqlConnector;
namespace Computernewb.CollabVMAuthServer;
public class Database
{
private readonly string connectionString;
public Database(MySQLConfig config)
{
connectionString = new MySqlConnectionStringBuilder
{
Server = config.Host,
UserID = config.Username,
Password = config.Password,
Database = config.Database
}.ToString();
}
public async Task Init()
{
await using var conn = new MySqlConnection(connectionString);
await conn.OpenAsync();
await using var cmd = conn.CreateCommand();
cmd.CommandText = """
CREATE TABLE IF NOT EXISTS users (
id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(20) NOT NULL UNIQUE KEY,
password TEXT NOT NULL,
email TEXT NOT NULL UNIQUE KEY,
email_verified BOOLEAN NOT NULL DEFAULT 0,
email_verification_code CHAR(8) DEFAULT NULL,
cvm_rank INT UNSIGNED NOT NULL DEFAULT 0,
banned BOOLEAN NOT NULL DEFAULT 0
);
""";
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = """
CREATE TABLE IF NOT EXISTS sessions (
token CHAR(32) NOT NULL PRIMARY KEY,
username VARCHAR(20) NOT NULL,
created TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
last_used TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (username) REFERENCES users(username) ON UPDATE CASCADE ON DELETE CASCADE
)
""";
await cmd.ExecuteNonQueryAsync();
}
public async Task<User?> GetUser(string? username = null, string? email = null)
{
if (username == null && email == null)
throw new ArgumentException("username or email must be provided");
await using var conn = new MySqlConnection(connectionString);
await conn.OpenAsync();
await using var cmd = conn.CreateCommand();
if (username != null)
{
cmd.CommandText = "SELECT * FROM users WHERE username = @username";
cmd.Parameters.AddWithValue("@username", username);
}
else if (email != null)
{
cmd.CommandText = "SELECT * FROM users WHERE email = @email";
cmd.Parameters.AddWithValue("@email", email);
}
await using var reader = await cmd.ExecuteReaderAsync();
if (!await reader.ReadAsync())
return null;
return new User
{
Id = reader.GetUInt32("id"),
Username = reader.GetString("username"),
Password = reader.GetString("password"),
Email = reader.GetString("email"),
EmailVerified = reader.GetBoolean("email_verified"),
EmailVerificationCode = reader.GetString("email_verification_code"),
Rank = (Rank)reader.GetUInt32("cvm_rank"),
Banned = reader.GetBoolean("banned")
};
}
public async Task RegisterAccount(string username, string email, string password, bool verified,
string? verificationcode = null)
{
await using var db = new MySqlConnection(connectionString);
await db.OpenAsync();
await using var cmd = db.CreateCommand();
cmd.CommandText = """
INSERT INTO users
(username, password, email, email_verified, email_verification_code)
VALUES
(@username, @password, @email, @email_verified, @email_verification_code)
""";
cmd.Parameters.AddWithValue("@username", username);
cmd.Parameters.AddWithValue("@password", Argon2.Hash(password));
cmd.Parameters.AddWithValue("@email", email);
cmd.Parameters.AddWithValue("@email_verified", verified);
cmd.Parameters.AddWithValue("@email_verification_code", verificationcode);
await cmd.ExecuteNonQueryAsync();
}
}

View File

@@ -0,0 +1,48 @@
namespace Computernewb.CollabVMAuthServer;
public class IConfig
{
public RegistrationConfig Registration { get; set; }
public HTTPConfig HTTP { get; set; }
public MySQLConfig MySQL { get; set; }
public SMTPConfig SMTP { get; set; }
public hCaptchaConfig hCaptcha { get; set; }
}
public class RegistrationConfig
{
public bool EmailVerificationRequired { get; set; }
public bool EmailDomainWhitelist { get; set; }
public string[] AllowedEmailDomains { get; set; }
}
public class HTTPConfig
{
public string Host { get; set; }
public int Port { get; set; }
}
public class MySQLConfig
{
public string Host { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Database { get; set; }
}
public class SMTPConfig
{
public string Host { get; set; }
public int Port { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string FromName { get; set; }
public string FromEmail { get; set; }
public string VerificationCodeSubject { get; set; }
public string VerificationCodeBody { get; set; }
}
public class hCaptchaConfig
{
public bool Enabled { get; set; }
public string? Secret { get; set; }
public string? SiteKey { get; set; }
}

View File

@@ -0,0 +1,38 @@
using MailKit.Net.Smtp;
using MailKit.Security;
using MimeKit;
namespace Computernewb.CollabVMAuthServer;
public class Mailer
{
private SMTPConfig Config;
public Mailer(SMTPConfig config)
{
Config = config;
}
public async Task SendVerificationCode(string username, string email, string code)
{
var message = new MimeMessage();
message.From.Add(new MailboxAddress(Config.FromName, Config.FromEmail));
message.To.Add(new MailboxAddress(username, email));
message.Subject = Config.VerificationCodeSubject
.Replace("$USERNAME", username)
.Replace("$EMAIL", email)
.Replace("$CODE", code);
message.Body = new TextPart("plain")
{
Text = Config.VerificationCodeBody
.Replace("$USERNAME", username)
.Replace("$EMAIL", email)
.Replace("$CODE", code)
};
using var client = new SmtpClient();
await client.ConnectAsync(Config.Host, Config.Port, SecureSocketOptions.StartTlsWhenAvailable);
await client.AuthenticateAsync(Config.Username, Config.Password);
await client.SendAsync(message);
await client.DisconnectAsync(true);
Utilities.Log(LogLevel.INFO, $"Sent verification code to {username} <{email}>");
}
}

View File

@@ -0,0 +1,72 @@
using System.Net;
using Tomlet;
namespace Computernewb.CollabVMAuthServer;
public class Program
{
public static IConfig Config { get; private set; }
public static Database Database { get; private set; }
public static hCaptchaClient? hCaptcha { get; private set; }
public static Mailer Mailer { get; private set; }
public static string[] BannedPasswords { get; set; }
public static readonly Random Random = new Random();
public static async Task Main(string[] args)
{
Utilities.Log(LogLevel.INFO, "CollabVM Authentication Server starting up");
// Read config.toml
string configraw;
try
{
configraw = File.ReadAllText("config.toml");
}
catch (Exception ex)
{
Utilities.Log(LogLevel.FATAL, "Failed to read config.toml: " + ex.Message);
Environment.Exit(1);
return;
}
// Parse config.toml to IConfig
try
{
Config = TomletMain.To<IConfig>(configraw);
} catch (Exception ex)
{
Utilities.Log(LogLevel.FATAL, "Failed to parse config.toml: " + ex.Message);
Environment.Exit(1);
return;
}
// Initialize database
Database = new Database(Config.MySQL);
await Database.Init();
Utilities.Log(LogLevel.INFO, "Connected to database");
// Create mailer
Mailer = new Mailer(Config.SMTP);
// Create hCaptcha client
if (Config.hCaptcha.Enabled)
{
hCaptcha = new hCaptchaClient(Config.hCaptcha.Secret!, Config.hCaptcha.SiteKey!);
Utilities.Log(LogLevel.INFO, "hCaptcha enabled");
}
else
{
Utilities.Log(LogLevel.INFO, "hCaptcha disabled");
}
// load password list
BannedPasswords = await File.ReadAllLinesAsync("rockyou.txt");
// Configure web server
var builder = WebApplication.CreateBuilder(args);
#if !DEBUG
builder.Logging.SetMinimumLevel(Microsoft.Extensions.Logging.LogLevel.Warning);
#endif
builder.WebHost.UseKestrel(k =>
{
k.Listen(IPAddress.Parse(Config.HTTP.Host), Config.HTTP.Port);
});
var app = builder.Build();
app.Lifetime.ApplicationStarted.Register(() => Utilities.Log(LogLevel.INFO, $"Webserver listening on {Config.HTTP.Host}:{Config.HTTP.Port}"));
// Register routes
Routes.RegisterRoutes(app);
app.Run();
}
}

View File

@@ -0,0 +1,9 @@
namespace Computernewb.CollabVMAuthServer;
public class RegisterPayload
{
public string username { get; set; }
public string password { get; set; }
public string email { get; set; }
public string? captchaToken { get; set; }
}

View File

@@ -0,0 +1,10 @@
namespace Computernewb.CollabVMAuthServer;
public class RegisterResponse
{
public bool success { get; set; }
public string? error { get; set; }
public bool? verificationRequired { get; set; } = null;
public string? username { get; set; }
public string? email { get; set; }
}

View File

@@ -0,0 +1,232 @@
using System.ComponentModel.DataAnnotations;
using System.Text.Json;
using System.Text.Json.Serialization;
using Isopoh.Cryptography.Argon2;
namespace Computernewb.CollabVMAuthServer;
public static class Routes
{
public static void RegisterRoutes(WebApplication app)
{
app.MapGet("/api/v1/info", HandleInfo);
app.MapPost("/api/v1/register", (Delegate) HandleRegister);
app.MapPost("/api/v1/verify", (Delegate) HandleVerify);
}
private static async Task<IResult> HandleVerify(HttpContext context)
{
// Check payload
if (context.Request.ContentType != "application/json")
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid request body"
}, Utilities.JsonSerializerOptions);
}
var payload = await context.Request.ReadFromJsonAsync<VerifyPayload>();
if (payload == null || string.IsNullOrWhiteSpace(payload.username) ||
string.IsNullOrWhiteSpace(payload.password) || string.IsNullOrWhiteSpace(payload.password))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid request body"
}, Utilities.JsonSerializerOptions);
}
// Validate username and password
var user = await Program.Database.GetUser(payload.username);
if (user == null || !Argon2.Verify(user.Password, payload.password))
{
context.Response.StatusCode = 403;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid username or password"
}, Utilities.JsonSerializerOptions);
}
// Check if account is verified
if (user.EmailVerified)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Account is already verified"
}, Utilities.JsonSerializerOptions);
}
// Check if code is correct
if (user.EmailVerificationCode != payload.code)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid verification code"
}, Utilities.JsonSerializerOptions);
}
// Verify the account
}
private static async Task<IResult> HandleRegister(HttpContext context)
{
// Check payload
if (context.Request.ContentType != "application/json")
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid request body"
}, Utilities.JsonSerializerOptions);
}
var payload = await context.Request.ReadFromJsonAsync<RegisterPayload>();
if (payload == null || string.IsNullOrWhiteSpace(payload.username) || string.IsNullOrWhiteSpace(payload.password) || string.IsNullOrWhiteSpace(payload.email))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid request body"
}, Utilities.JsonSerializerOptions);
}
// Check captcha response
if (Program.Config.hCaptcha.Enabled)
{
if (string.IsNullOrWhiteSpace(payload.captchaToken))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Missing hCaptcha token"
}, Utilities.JsonSerializerOptions);
}
var result =
await Program.hCaptcha!.Verify(payload.captchaToken, context.Connection.RemoteIpAddress!.ToString());
if (!result.success)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Invalid captcha response"
}, Utilities.JsonSerializerOptions);
}
}
// Make sure username isn't taken
var user = await Program.Database.GetUser(payload.username);
if (user != null)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "That username is taken."
}, Utilities.JsonSerializerOptions);
}
// Check if E-Mail is in use
user = await Program.Database.GetUser(email: payload.email);
if (user != null)
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "That E-Mail is already in use."
}, Utilities.JsonSerializerOptions);
}
// Validate username
if (!Utilities.ValidateUsername(payload.username))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Usernames can contain only numbers, letters, spaces, dashes, underscores, and dots, and must be between 3 and 20 characters."
}, Utilities.JsonSerializerOptions);
}
// Validate E-Mail
if (!new EmailAddressAttribute().IsValid(payload.email))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Malformed E-Mail address."
}, Utilities.JsonSerializerOptions);
}
if (Program.Config.Registration.EmailDomainWhitelist &&
!Program.Config.Registration.AllowedEmailDomains.Contains(payload.email.Split("@")[1]))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "That E-Mail domain is not allowed."
}, Utilities.JsonSerializerOptions);
}
// Validate password
if (!Utilities.ValidatePassword(payload.password))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "Passwords must be at least 8 characters and must contain an uppercase and lowercase letter, a number, and a symbol."
}, Utilities.JsonSerializerOptions);
}
if (Program.BannedPasswords.Contains(payload.password))
{
context.Response.StatusCode = 400;
return Results.Json(new RegisterResponse
{
success = false,
error = "That password is commonly used and is not allowed."
}, Utilities.JsonSerializerOptions);
}
// Create the account
if (Program.Config.Registration.EmailVerificationRequired)
{
var code = Program.Random.Next(10000000, 99999999).ToString();
await Program.Database.RegisterAccount(payload.username, payload.email, payload.password, false, code);
await Program.Mailer.SendVerificationCode(payload.username, payload.email, code);
return Results.Json(new RegisterResponse
{
success = true,
verificationRequired = true,
email = payload.email,
username = payload.username
}, Utilities.JsonSerializerOptions);
}
else
{
await Program.Database.RegisterAccount(payload.username, payload.email, payload.password, true, null);
return Results.Json(new RegisterResponse
{
success = true,
verificationRequired = false,
email = payload.email,
username = payload.username
}, Utilities.JsonSerializerOptions);
}
}
private static IResult HandleInfo(HttpContext context)
{
return Results.Json(new AuthServerInformation
{
// TODO: Implement registration closure
registrationOpen = true,
hcaptcha =
new() {
required = Program.Config.hCaptcha.Enabled,
siteKey = Program.Config.hCaptcha.Enabled ? Program.Config.hCaptcha.SiteKey : null
}
});
}
}

View File

@@ -0,0 +1,9 @@
namespace Computernewb.CollabVMAuthServer;
public class Session
{
public string Token { get; set; }
public uint UserId { get; set; }
public DateTime Created { get; set; }
public DateTime LastUsed { get; set; }
}

View File

@@ -0,0 +1,20 @@
namespace Computernewb.CollabVMAuthServer;
public class User
{
public uint Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public string Email { get; set; }
public bool EmailVerified { get; set; }
public string EmailVerificationCode { get; set; }
public Rank Rank { get; set; }
public bool Banned { get; set; }
}
public enum Rank : uint
{
Registered = 1,
Admin = 2,
Moderator = 3,
}

View File

@@ -0,0 +1,87 @@
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.RegularExpressions;
namespace Computernewb.CollabVMAuthServer;
public enum LogLevel
{
DEBUG,
INFO,
WARN,
ERROR,
FATAL
}
public static class Utilities
{
public static JsonSerializerOptions JsonSerializerOptions => new JsonSerializerOptions
{
DefaultIgnoreCondition = JsonIgnoreCondition.WhenWritingNull
};
public static void Log(LogLevel level, string msg)
{
#if !DEBUG
if (level == LogLevel.DEBUG)
return;
#endif
StringBuilder logstr = new StringBuilder();
logstr.Append("[");
logstr.Append(DateTime.Now.ToString("G"));
logstr.Append("] [");
switch (level)
{
case LogLevel.DEBUG:
logstr.Append("DEBUG");
break;
case LogLevel.INFO:
logstr.Append("INFO");
break;
case LogLevel.WARN:
logstr.Append("WARN");
break;
case LogLevel.ERROR:
logstr.Append("ERROR");
break;
case LogLevel.FATAL:
logstr.Append("FATAL");
break;
default:
throw new ArgumentException("Invalid log level");
}
logstr.Append("] ");
logstr.Append(msg);
switch (level)
{
case LogLevel.DEBUG:
case LogLevel.INFO:
Console.WriteLine(logstr.ToString());
break;
case LogLevel.WARN:
case LogLevel.ERROR:
case LogLevel.FATAL:
Console.Error.Write(logstr.ToString());
break;
}
}
public static bool ValidateUsername(string username)
{
return username.Length >= 3 &&
username.Length <= 20 &&
username[0] != ' ' &&
username[^1] != ' ' &&
new Regex("^[a-zA-Z0-9 \\-_\\.]+$").IsMatch(username);
}
public static bool ValidatePassword(string password)
{
return password.Length > 8 &&
new Regex("[a-z]").IsMatch(password) &&
new Regex("[A-Z]").IsMatch(password) &&
new Regex("[!@#$%^&*()\\-_=+\\\\|\\[\\];:'\\\",<.>/?`~]").IsMatch(password) &&
new Regex("[0-9]").IsMatch(password);
}
}

View File

@@ -0,0 +1,8 @@
namespace Computernewb.CollabVMAuthServer;
public class VerifyPayload
{
public string username { get; set; }
public string password { get; set; }
public string code { get; set; }
}

View File

@@ -0,0 +1,41 @@
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Text.Json.Serialization.Metadata;
namespace Computernewb.CollabVMAuthServer;
public class hCaptchaClient
{
private string secret;
private string sitekey;
private HttpClient http;
public hCaptchaClient(string secret, string sitekey)
{
this.secret = secret;
this.sitekey = sitekey;
this.http = new HttpClient();
}
public async Task<hCaptchaResponse> Verify(string token, string ip)
{
var response = await http.PostAsync("https://api.hcaptcha.com/siteverify", new FormUrlEncodedContent(new []
{
new KeyValuePair<string, string>("secret", secret),
new KeyValuePair<string, string>("response", token),
new KeyValuePair<string, string>("remoteip", ip),
new KeyValuePair<string, string>("sitekey", sitekey)
}));
response.EnsureSuccessStatusCode();
return await response.Content.ReadFromJsonAsync<hCaptchaResponse>() ?? throw new Exception("Failed to parse hCaptcha response");
}
}
public class hCaptchaResponse
{
public bool success { get; set; }
public string challenge_ts { get; set; }
public string hostname { get; set; }
public bool? credit { get; set; }
[JsonPropertyName("error-codes")]
public string[]? error_codes { get; set; }
}