using System.Globalization; using System.Net; using System.Security.Claims; using System.Text.Encodings.Web; using Anubis.Access; using Microsoft.AspNetCore.Authentication; using Microsoft.Extensions.Options; namespace Anubis.Server; /// /// Sign-in by session cookie (SPEC 15.4): the cookie holds a random token, the database only its hash. HttpOnly, /// SameSite=Strict, Secure when the request is HTTPS. In demo mode everyone on the computer itself is signed in. /// internal sealed class SessionAuthentication( IOptionsMonitor options, ILoggerFactory logger, UrlEncoder encoder, AnubisHost host) : AuthenticationHandler(options, logger, encoder) { public const string SchemeName = "anubis"; public const string Cookie = "anubis_session"; public const string SessionClaim = "anubis:session"; public const string MustChangeClaim = "anubis:must_change"; public const string SecondFactorClaim = "anubis:second_factor"; protected override async Task HandleAuthenticateAsync() { var services = host.Services; if (services is null) { return AuthenticateResult.NoResult(); } if (host.IsDemo) { var user = await services.Access.GetUserAsync(Context.RequestAborted).ConfigureAwait(false); return user is null ? AuthenticateResult.NoResult() : Success(user, Guid.Empty); } if (!Request.Cookies.TryGetValue(Cookie, out var token) || string.IsNullOrEmpty(token)) { return AuthenticateResult.NoResult(); } var session = await services.Access.ValidateAsync(token, Context.RequestAborted).ConfigureAwait(false); return session is null ? AuthenticateResult.Fail("Sessione scaduta") : Success(session.User, session.Id); } private static AuthenticateResult Success(User user, Guid session) { Claim[] claims = [ new(ClaimTypes.NameIdentifier, user.Id.ToString("D")), new(ClaimTypes.Name, user.Username), new(SessionClaim, session.ToString("D")), new(MustChangeClaim, user.MustChangePassword ? "1" : "0"), new(SecondFactorClaim, user.HasSecondFactor ? "1" : "0"), ]; var principal = new ClaimsPrincipal(new ClaimsIdentity(claims, SchemeName)); return AuthenticateResult.Success(new AuthenticationTicket(principal, SchemeName)); } protected override Task HandleChallengeAsync(AuthenticationProperties properties) { if (IsApi(Request)) { Response.StatusCode = StatusCodes.Status401Unauthorized; return Response.WriteAsJsonAsync(new ApiError("non_autenticato", "Accedi di nuovo.")); } var back = Request.Path + Request.QueryString; Response.Redirect("/accesso" + (back == "/" ? "" : "?ritorno=" + Uri.EscapeDataString(back))); return Task.CompletedTask; } protected override Task HandleForbiddenAsync(AuthenticationProperties properties) { Response.StatusCode = StatusCodes.Status403Forbidden; return Task.CompletedTask; } internal static bool IsApi(HttpRequest request) => request.Path.StartsWithSegments("/api", StringComparison.Ordinal) || request.Path.StartsWithSegments("/ws", StringComparison.Ordinal); public static void WriteCookie(HttpContext context, string token) => context.Response.Cookies.Append(Cookie, token, new CookieOptions { HttpOnly = true, SameSite = SameSiteMode.Strict, Secure = context.Request.IsHttps, Path = "/", MaxAge = AccessStore.MaxLifetime, IsEssential = true, }); public static void ClearCookie(HttpContext context) => context.Response.Cookies.Delete(Cookie, new CookieOptions { Path = "/", HttpOnly = true, SameSite = SameSiteMode.Strict, Secure = context.Request.IsHttps }); } /// Who is signed in, read from the claims. internal static class CurrentUser { public static Guid Id(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(ClaimTypes.NameIdentifier)!, CultureInfo.InvariantCulture); public static Guid Session(ClaimsPrincipal user) => Guid.Parse(user.FindFirstValue(SessionAuthentication.SessionClaim) ?? Guid.Empty.ToString(), CultureInfo.InvariantCulture); public static bool MustChangePassword(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.MustChangeClaim) == "1"; public static bool HasSecondFactor(ClaimsPrincipal user) => user.FindFirstValue(SessionAuthentication.SecondFactorClaim) == "1"; /// /// The request comes from the computer the server runs on, addressed to it by a local name. The name matters too: /// a web page that points its own name at 127.0.0.1 (DNS rebinding) arrives from the loopback with a foreign Host. /// public static bool IsLocal(HttpContext context) => context.Connection.RemoteIpAddress is { } address && IPAddress.IsLoopback(address) && IsLocalName(context.Request.Host.Host); internal static bool IsLocalName(string host) => host.Equals("localhost", StringComparison.OrdinalIgnoreCase) || host is "127.0.0.1" or "[::1]" or "::1"; } /// Error body of the API: a code for programs and a sentence for people. internal sealed record ApiError(string Code, string Message);