From 4b2ad030fa381662f4b0c2464e97b0d2c5f6a716 Mon Sep 17 00:00:00 2001 From: Tim Date: Fri, 18 Apr 2025 12:25:59 +0200 Subject: Initial commit --- .gitignore | 488 +++++++++++++++++++++ LICENSE | 21 + VPNAuth.Server/Config.cs | 49 +++ VPNAuth.Server/Database/AccessToken.cs | 10 + VPNAuth.Server/Database/AuthRequest.cs | 14 + VPNAuth.Server/Database/Database.cs | 14 + VPNAuth.Server/HttpContextUtils.cs | 15 + .../Migrations/20250418102156_DbInit.Designer.cs | 91 ++++ VPNAuth.Server/Migrations/20250418102156_DbInit.cs | 61 +++ VPNAuth.Server/Migrations/DatabaseModelSnapshot.cs | 88 ++++ VPNAuth.Server/Pages/Auth.cshtml | 31 ++ VPNAuth.Server/Pages/Auth.cshtml.cs | 52 +++ VPNAuth.Server/Pages/Dashboard.cshtml | 41 ++ VPNAuth.Server/PkceUtils.cs | 17 + VPNAuth.Server/Program.cs | 98 +++++ VPNAuth.Server/Responses/Token.cs | 11 + VPNAuth.Server/Responses/UserInfo.cs | 28 ++ VPNAuth.Server/VPNAuth.Server.csproj | 87 ++++ VPNAuth.sln | 16 + 19 files changed, 1232 insertions(+) create mode 100644 .gitignore create mode 100644 LICENSE create mode 100644 VPNAuth.Server/Config.cs create mode 100644 VPNAuth.Server/Database/AccessToken.cs create mode 100644 VPNAuth.Server/Database/AuthRequest.cs create mode 100644 VPNAuth.Server/Database/Database.cs create mode 100644 VPNAuth.Server/HttpContextUtils.cs create mode 100644 VPNAuth.Server/Migrations/20250418102156_DbInit.Designer.cs create mode 100644 VPNAuth.Server/Migrations/20250418102156_DbInit.cs create mode 100644 VPNAuth.Server/Migrations/DatabaseModelSnapshot.cs create mode 100644 VPNAuth.Server/Pages/Auth.cshtml create mode 100644 VPNAuth.Server/Pages/Auth.cshtml.cs create mode 100644 VPNAuth.Server/Pages/Dashboard.cshtml create mode 100644 VPNAuth.Server/PkceUtils.cs create mode 100644 VPNAuth.Server/Program.cs create mode 100644 VPNAuth.Server/Responses/Token.cs create mode 100644 VPNAuth.Server/Responses/UserInfo.cs create mode 100644 VPNAuth.Server/VPNAuth.Server.csproj create mode 100644 VPNAuth.sln diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7cd6c3e --- /dev/null +++ b/.gitignore @@ -0,0 +1,488 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from `dotnet new gitignore` + +# dotenv files +.env + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET +project.lock.json +project.fragment.lock.json +artifacts/ + +# Tye +.tye/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.tlog +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio 6 auto-generated project file (contains which files were open etc.) +*.vbp + +# Visual Studio 6 workspace and project file (working project files containing files to include in project) +*.dsw +*.dsp + +# Visual Studio 6 technical files +*.ncb +*.aps + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# Visual Studio History (VSHistory) files +.vshistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# VS Code files for those working on multiple tools +.vscode/* +!.vscode/settings.json +!.vscode/tasks.json +!.vscode/launch.json +!.vscode/extensions.json +*.code-workspace + +# Local History for Visual Studio Code +.history/ + +# Windows Installer files from build outputs +*.cab +*.msi +*.msix +*.msm +*.msp + +# JetBrains Rider +*.sln.iml +.idea/ + +## +## Visual studio for Mac +## + + +# globs +Makefile.in +*.userprefs +*.usertasks +config.make +config.status +aclocal.m4 +install-sh +autom4te.cache/ +*.tar.gz +tarballs/ +test-results/ + +# Mac bundle stuff +*.dmg +*.app + +# content below from: https://github.com/github/gitignore/blob/main/Global/macOS.gitignore +# General +.DS_Store +.AppleDouble +.LSOverride + +# Icon must end with two \r +Icon + + +# Thumbnails +._* + +# Files that might appear in the root of a volume +.DocumentRevisions-V100 +.fseventsd +.Spotlight-V100 +.TemporaryItems +.Trashes +.VolumeIcon.icns +.com.apple.timemachine.donotpresent + +# Directories potentially created on remote AFP share +.AppleDB +.AppleDesktop +Network Trash Folder +Temporary Items +.apdisk + +# content below from: https://github.com/github/gitignore/blob/main/Global/Windows.gitignore +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + +# Vim temporary swap files +*.swp + +# Project Specific +VPNAuth.Server/vpnauth.db +VPNAuth.Server/config.json diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..4e2870f --- /dev/null +++ b/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2025 Tim R. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/VPNAuth.Server/Config.cs b/VPNAuth.Server/Config.cs new file mode 100644 index 0000000..84b01ef --- /dev/null +++ b/VPNAuth.Server/Config.cs @@ -0,0 +1,49 @@ +using System.Text.Json; + +namespace VPNAuth.Server; + +public class ConfigUser +{ + public string? Username { get; set; } + public List? Ips { get; set; } + + public string? Sub { get; set; } + public string? Name { get; set; } + public string? GivenName { get; set; } + public string? FamilyName { get; set; } + public string? PreferredUsername { get; set; } + public string? Email { get; set; } + public string? Picture { get; set; } +} + +public class ConfigApp +{ + public string? ClientId { get; set; } + public string? RedirectUri { get; set; } + public string? Secret { get; set; } +} + +public class Config +{ + public List? Users { get; set; } + public List? Apps { get; set; } + + public ConfigApp? FindApp(string clientId) + => Apps?.Find(app => app.ClientId == clientId); + + private static string _filePath = "./config.json"; + + public static void CreateIfNotExists() + { + if (File.Exists(_filePath)) return; + + File.Create(_filePath); + File.WriteAllText(_filePath, JsonSerializer.Serialize(new Config + { + Users = [] + })); + } + + public static Config Read() + => JsonSerializer.Deserialize(File.ReadAllText(_filePath))!; +} diff --git a/VPNAuth.Server/Database/AccessToken.cs b/VPNAuth.Server/Database/AccessToken.cs new file mode 100644 index 0000000..3cdc3ba --- /dev/null +++ b/VPNAuth.Server/Database/AccessToken.cs @@ -0,0 +1,10 @@ +namespace VPNAuth.Server.Database; + +public class AccessToken +{ + public int Id { get; set; } + public string Token { get; set; } + public string ClientId { get; set; } + public DateTime CreationTime { get; set; } + public List Scopes { get; set; } +} diff --git a/VPNAuth.Server/Database/AuthRequest.cs b/VPNAuth.Server/Database/AuthRequest.cs new file mode 100644 index 0000000..98fe001 --- /dev/null +++ b/VPNAuth.Server/Database/AuthRequest.cs @@ -0,0 +1,14 @@ +namespace VPNAuth.Server.Database; + +public class AuthRequest +{ + public int Id { get; set; } + public DateTime InitTime { get; set; } + public string Code { get; set; } + public string? State { get; set; } + public string ClientId { get; set; } + public List Scopes { get; set; } + public string CodeChallenge { get; set; } + public string CodeChallengeMethod { get; set; } + public bool Accepted { get; set; } +} diff --git a/VPNAuth.Server/Database/Database.cs b/VPNAuth.Server/Database/Database.cs new file mode 100644 index 0000000..a8cf8eb --- /dev/null +++ b/VPNAuth.Server/Database/Database.cs @@ -0,0 +1,14 @@ +using Microsoft.EntityFrameworkCore; + +namespace VPNAuth.Server.Database; + +public class Database : DbContext +{ + protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) + { + optionsBuilder.UseSqlite("Data Source=vpnauth.db"); + } + + public DbSet AuthRequests { get; set; } + public DbSet AccessTokens { get; set; } +} diff --git a/VPNAuth.Server/HttpContextUtils.cs b/VPNAuth.Server/HttpContextUtils.cs new file mode 100644 index 0000000..5bba471 --- /dev/null +++ b/VPNAuth.Server/HttpContextUtils.cs @@ -0,0 +1,15 @@ +namespace VPNAuth.Server; + +public static class HttpContextUtils +{ + public static string GetRemoteIpAddress(this HttpContext context) + => context.Request.Headers["X-Forwarded-For"].DefaultIfEmpty(context.Connection.RemoteIpAddress!.ToString()) + .First()!; + + public static ConfigUser? GetUser(this HttpContext context) + { + var config = Config.Read(); + if (config.Users == null || config.Users.Count == 0) return null; + return config.Users!.Find(user => user.Ips!.Contains(context.GetRemoteIpAddress())); + } +} diff --git a/VPNAuth.Server/Migrations/20250418102156_DbInit.Designer.cs b/VPNAuth.Server/Migrations/20250418102156_DbInit.Designer.cs new file mode 100644 index 0000000..57eda44 --- /dev/null +++ b/VPNAuth.Server/Migrations/20250418102156_DbInit.Designer.cs @@ -0,0 +1,91 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using VPNAuth.Server.Database; + +#nullable disable + +namespace VPNAuth.Server.Migrations +{ + [DbContext(typeof(Database.Database))] + [Migration("20250418102156_DbInit")] + partial class DbInit + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.4"); + + modelBuilder.Entity("VPNAuth.Server.Database.AccessToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreationTime") + .HasColumnType("TEXT"); + + b.PrimitiveCollection("Scopes") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Token") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AccessTokens"); + }); + + modelBuilder.Entity("VPNAuth.Server.Database.AuthRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Accepted") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Code") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CodeChallenge") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CodeChallengeMethod") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("InitTime") + .HasColumnType("TEXT"); + + b.PrimitiveCollection("Scopes") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AuthRequests"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/VPNAuth.Server/Migrations/20250418102156_DbInit.cs b/VPNAuth.Server/Migrations/20250418102156_DbInit.cs new file mode 100644 index 0000000..70967ca --- /dev/null +++ b/VPNAuth.Server/Migrations/20250418102156_DbInit.cs @@ -0,0 +1,61 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace VPNAuth.Server.Migrations +{ + /// + public partial class DbInit : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.CreateTable( + name: "AccessTokens", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + Token = table.Column(type: "TEXT", nullable: false), + ClientId = table.Column(type: "TEXT", nullable: false), + CreationTime = table.Column(type: "TEXT", nullable: false), + Scopes = table.Column(type: "TEXT", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AccessTokens", x => x.Id); + }); + + migrationBuilder.CreateTable( + name: "AuthRequests", + columns: table => new + { + Id = table.Column(type: "INTEGER", nullable: false) + .Annotation("Sqlite:Autoincrement", true), + InitTime = table.Column(type: "TEXT", nullable: false), + Code = table.Column(type: "TEXT", nullable: false), + State = table.Column(type: "TEXT", nullable: true), + ClientId = table.Column(type: "TEXT", nullable: false), + Scopes = table.Column(type: "TEXT", nullable: false), + CodeChallenge = table.Column(type: "TEXT", nullable: false), + CodeChallengeMethod = table.Column(type: "TEXT", nullable: false), + Accepted = table.Column(type: "INTEGER", nullable: false) + }, + constraints: table => + { + table.PrimaryKey("PK_AuthRequests", x => x.Id); + }); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "AccessTokens"); + + migrationBuilder.DropTable( + name: "AuthRequests"); + } + } +} diff --git a/VPNAuth.Server/Migrations/DatabaseModelSnapshot.cs b/VPNAuth.Server/Migrations/DatabaseModelSnapshot.cs new file mode 100644 index 0000000..d735267 --- /dev/null +++ b/VPNAuth.Server/Migrations/DatabaseModelSnapshot.cs @@ -0,0 +1,88 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using VPNAuth.Server.Database; + +#nullable disable + +namespace VPNAuth.Server.Migrations +{ + [DbContext(typeof(Database.Database))] + partial class DatabaseModelSnapshot : ModelSnapshot + { + protected override void BuildModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder.HasAnnotation("ProductVersion", "9.0.4"); + + modelBuilder.Entity("VPNAuth.Server.Database.AccessToken", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CreationTime") + .HasColumnType("TEXT"); + + b.PrimitiveCollection("Scopes") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Token") + .IsRequired() + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AccessTokens"); + }); + + modelBuilder.Entity("VPNAuth.Server.Database.AuthRequest", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("INTEGER"); + + b.Property("Accepted") + .HasColumnType("INTEGER"); + + b.Property("ClientId") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("Code") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CodeChallenge") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("CodeChallengeMethod") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("InitTime") + .HasColumnType("TEXT"); + + b.PrimitiveCollection("Scopes") + .IsRequired() + .HasColumnType("TEXT"); + + b.Property("State") + .HasColumnType("TEXT"); + + b.HasKey("Id"); + + b.ToTable("AuthRequests"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/VPNAuth.Server/Pages/Auth.cshtml b/VPNAuth.Server/Pages/Auth.cshtml new file mode 100644 index 0000000..5ac8efe --- /dev/null +++ b/VPNAuth.Server/Pages/Auth.cshtml @@ -0,0 +1,31 @@ +@page "/auth" +@model VPNAuth.Server.Pages.Auth + +@{ + Layout = null; +} + + + + + + VPNAuth - Auth + + +

Authorization

+

VPNAuth

+ @if (Model.ValidRequest) + { +
+

Do you want to log into @Request.Query["client_id"]?

+ +
+

You are logged in as @Model.User?.Username.

+
+ } + else + { + Invalid request. + } + + diff --git a/VPNAuth.Server/Pages/Auth.cshtml.cs b/VPNAuth.Server/Pages/Auth.cshtml.cs new file mode 100644 index 0000000..bdcbc59 --- /dev/null +++ b/VPNAuth.Server/Pages/Auth.cshtml.cs @@ -0,0 +1,52 @@ +using Microsoft.AspNetCore.Mvc.RazorPages; +using Microsoft.EntityFrameworkCore.ChangeTracking; +using VPNAuth.Server.Database; + +namespace VPNAuth.Server.Pages; + +public class Auth : PageModel +{ + public Config Config; + public ConfigUser? User; + public bool ValidRequest; + public EntityEntry? RequestEntry; + + public readonly List RequiredQueryParams = + [ + "response_type", + "client_id", + "scope", + "code_challenge_method", + "code_challenge" + ]; + + public void OnGet() + { + Config = Config.Read(); + User = HttpContext.GetUser(); + + ValidRequest = RequiredQueryParams.All(key => Request.Query.ContainsKey(key)) + && Config.FindApp(Request.Query["client_id"]!) != null + && Request.Query["code_challenge_method"] == "S256" + && User != null; + + RequestEntry = null; + + if (ValidRequest) + { + using var db = new Database.Database(); + RequestEntry = db.Add(new AuthRequest + { + InitTime = DateTime.Now, + ClientId = Request.Query["client_id"]!, + Code = PkceUtils.GenerateCode(), + State = Request.Query["state"], + Scopes = Request.Query["scope"].ToString().Split(" ").ToList(), + CodeChallenge = Request.Query["code_challenge"]!, + CodeChallengeMethod = Request.Query["code_challenge_method"]!, + Accepted = false + }); + db.SaveChanges(); + } + } +} diff --git a/VPNAuth.Server/Pages/Dashboard.cshtml b/VPNAuth.Server/Pages/Dashboard.cshtml new file mode 100644 index 0000000..cb00d9f --- /dev/null +++ b/VPNAuth.Server/Pages/Dashboard.cshtml @@ -0,0 +1,41 @@ +@page "/" +@using Microsoft.EntityFrameworkCore.ChangeTracking +@using VPNAuth.Server +@using VPNAuth.Server.Database + +@{ + Layout = null; + + string remoteIp = Request.HttpContext.GetRemoteIpAddress(); + ConfigUser? user = Request.HttpContext.GetUser(); +} + + + + + + VPNAuth - Dashboard + + + @if (user == null) + { +

No user detected

+ } + else + { +
+

Dashboard

+

VPNAuth

+

Hey, @user.Username!

+ User settings coming soon... +

Your IPs

+
    + @foreach (var ip in user.Ips!) + { +
  • @ip
  • + } +
+
+ } + + diff --git a/VPNAuth.Server/PkceUtils.cs b/VPNAuth.Server/PkceUtils.cs new file mode 100644 index 0000000..a11926e --- /dev/null +++ b/VPNAuth.Server/PkceUtils.cs @@ -0,0 +1,17 @@ +namespace VPNAuth.Server; + +public static class PkceUtils +{ + private static string _codeChars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ123456789"; + + public static string GenerateCode(int length = 10) + { + string code = ""; + for (int i = 0; i < length; i++) + code += _codeChars[new Random().Next(_codeChars.Length)]; // TODO: Is that function random enough? + return code; + } + + public static string GenerateToken(int length = 20) + => GenerateCode(length); // TODO: maybe add more possible chars then for GenerateCode +} diff --git a/VPNAuth.Server/Program.cs b/VPNAuth.Server/Program.cs new file mode 100644 index 0000000..6ea0b40 --- /dev/null +++ b/VPNAuth.Server/Program.cs @@ -0,0 +1,98 @@ +using VPNAuth.Server; +using VPNAuth.Server.Database; +using VPNAuth.Server.Responses; + +Config.CreateIfNotExists(); + +var builder = WebApplication.CreateBuilder(args); + +// Add services to the container. +builder.Services.AddRazorPages(); + +var app = builder.Build(); + +// Configure the HTTP request pipeline. +if (!app.Environment.IsDevelopment()) +{ + app.UseExceptionHandler("/Error"); + // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. + app.UseHsts(); +} + +app.UseHttpsRedirection(); + +app.UseRouting(); + +app.UseAuthorization(); + +app.MapGet("/accept-auth/{id}", async (HttpContext context, int id) => +{ + using var db = new Database(); + var authRequest = db.AuthRequests.Find(id); + if (authRequest == null || authRequest.Accepted) + { + context.Response.StatusCode = StatusCodes.Status404NotFound; + return; + } + + authRequest.Accepted = true; + db.SaveChanges(); + + var config = Config.Read(); + context.Response.StatusCode = StatusCodes.Status302Found; + context.Response.Headers["Location"] = config.FindApp(authRequest.ClientId)!.RedirectUri! + + "?code=" + authRequest.Code + + "&state=" + authRequest.State; +}); + +app.MapPost("/access-token", async (HttpContext context) => +{ + var config = Config.Read(); + if (context.Request.Form["grant_type"] != "authorization_code") + { + context.Response.StatusCode = StatusCodes.Status400BadRequest; + return; + } + + var clientSecret = config.FindApp(context.Request.Form["client_id"]!)!.Secret; // FIXME: null pointer + if (clientSecret != null && clientSecret != context.Request.Form["client_secret"]) + { + context.Response.StatusCode = StatusCodes.Status403Forbidden; + return; + } + + using var db = new Database(); + var authRequest = db.AuthRequests + .Where(request => request.Code == context.Request.Form["code"].ToString()) + .ToList() + .FirstOrDefault(); + if (authRequest == null) + { + context.Response.StatusCode = StatusCodes.Status404NotFound; + return; + } + + // TODO: validate code verifier -> context.Request.Form["code_verifier"] + + var accessTokenEntry = db.AccessTokens.Add(new AccessToken + { + ClientId = authRequest.ClientId, + Scopes = authRequest.Scopes, + CreationTime = DateTime.Now, + Token = PkceUtils.GenerateToken() + }); + db.SaveChanges(); + + await context.Response.WriteAsJsonAsync(new Token + { + AccessToken = accessTokenEntry.Entity.Token, + TokenType = "Bearer", + Expires = 0 // TODO: change to actual value + }); +}); + +app.MapStaticAssets(); +app.MapRazorPages() + .WithStaticAssets(); + +app.Run("http://localhost:8080"); diff --git a/VPNAuth.Server/Responses/Token.cs b/VPNAuth.Server/Responses/Token.cs new file mode 100644 index 0000000..9d8a374 --- /dev/null +++ b/VPNAuth.Server/Responses/Token.cs @@ -0,0 +1,11 @@ +using System.Text.Json.Serialization; + +namespace VPNAuth.Server.Responses; + +public class Token +{ + [JsonPropertyName("access_token")] public string? AccessToken { get; set; } + [JsonPropertyName("refresh_token")] public string? RefreshToken { get; set; } + [JsonPropertyName("token_type")] public string? TokenType { get; set; } + [JsonPropertyName("expires")] public int? Expires { get; set; } +} diff --git a/VPNAuth.Server/Responses/UserInfo.cs b/VPNAuth.Server/Responses/UserInfo.cs new file mode 100644 index 0000000..bc4deee --- /dev/null +++ b/VPNAuth.Server/Responses/UserInfo.cs @@ -0,0 +1,28 @@ +using System.Text.Json.Serialization; + +namespace VPNAuth.Server.Responses; + +public class UserInfo +{ + [JsonPropertyName("sub")] public string? Sub { get; set; } + [JsonPropertyName("name")] public string? Name { get; set; } + [JsonPropertyName("given_name")] public string? GivenName { get; set; } + [JsonPropertyName("family_name")] public string? FamilyName { get; set; } + + [JsonPropertyName("preferred_username")] + public string? PreferredUsername { get; set; } + + [JsonPropertyName("email")] public string? Email { get; set; } + [JsonPropertyName("picture")] public string? Picture { get; set; } + + public UserInfo(ConfigUser configUser) + { + Sub = configUser.Sub; + Name = configUser.Name; + GivenName = configUser.GivenName; + FamilyName = configUser.FamilyName; + PreferredUsername = configUser.PreferredUsername; + Email = configUser.Email; + Picture = configUser.Picture; + } +} diff --git a/VPNAuth.Server/VPNAuth.Server.csproj b/VPNAuth.Server/VPNAuth.Server.csproj new file mode 100644 index 0000000..8bbec60 --- /dev/null +++ b/VPNAuth.Server/VPNAuth.Server.csproj @@ -0,0 +1,87 @@ + + + + net9.0 + enable + enable + True + + + + <_ContentIncludedByDefault Remove="wwwroot\css\site.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-grid.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-grid.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-grid.min.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-grid.min.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-grid.rtl.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-grid.rtl.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-grid.rtl.min.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-grid.rtl.min.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-reboot.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-reboot.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-reboot.min.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-reboot.min.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-reboot.rtl.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-reboot.rtl.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-reboot.rtl.min.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-reboot.rtl.min.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-utilities.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-utilities.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-utilities.min.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-utilities.min.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-utilities.rtl.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-utilities.rtl.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-utilities.rtl.min.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap-utilities.rtl.min.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap.min.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap.min.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap.rtl.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap.rtl.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap.rtl.min.css" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\css\bootstrap.rtl.min.css.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.bundle.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.bundle.js.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.bundle.min.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.bundle.min.js.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.esm.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.esm.js.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.esm.min.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.esm.min.js.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.js.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.min.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\dist\js\bootstrap.min.js.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\bootstrap\LICENSE" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery-validation-unobtrusive\dist\jquery.validate.unobtrusive.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery-validation-unobtrusive\dist\jquery.validate.unobtrusive.min.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery-validation-unobtrusive\LICENSE.txt" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery-validation\dist\additional-methods.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery-validation\dist\additional-methods.min.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery-validation\dist\jquery.validate.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery-validation\dist\jquery.validate.min.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery-validation\LICENSE.md" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery\dist\jquery.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery\dist\jquery.min.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery\dist\jquery.min.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery\dist\jquery.slim.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery\dist\jquery.slim.min.js" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery\dist\jquery.slim.min.map" /> + <_ContentIncludedByDefault Remove="wwwroot\lib\jquery\LICENSE.txt" /> + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + diff --git a/VPNAuth.sln b/VPNAuth.sln new file mode 100644 index 0000000..ced4d8e --- /dev/null +++ b/VPNAuth.sln @@ -0,0 +1,16 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VPNAuth.Server", "VPNAuth.Server\VPNAuth.Server.csproj", "{EB4283EF-9EC1-48DD-8044-4FC1AC8892E4}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {EB4283EF-9EC1-48DD-8044-4FC1AC8892E4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {EB4283EF-9EC1-48DD-8044-4FC1AC8892E4}.Debug|Any CPU.Build.0 = Debug|Any CPU + {EB4283EF-9EC1-48DD-8044-4FC1AC8892E4}.Release|Any CPU.ActiveCfg = Release|Any CPU + {EB4283EF-9EC1-48DD-8044-4FC1AC8892E4}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection +EndGlobal -- cgit v1.2.3