HIGH session fixationchibasic auth

Session Fixation in Chi with Basic Auth

Session Fixation in Chi with Basic Auth — how this specific combination creates or exposes the vulnerability

Session fixation occurs when an application forces or accepts a session identifier that an attacker knows or chooses. In Chi, this typically arises when session state is managed via cookies and the server does not issue a new session identifier after a successful authentication event. When Basic Auth is used, the credentials are transmitted on each request via the Authorization header, but if the application also relies on session cookies for authorization or tracking, an attacker can craft a URL with a known session value or coerce a victim into using a session they control.

Chi routes are often built as a series of middleware and handlers. If a route uses session middleware but does not rotate the session ID after login, the session cookie established before authentication remains valid after authentication. An attacker who can predict or set a session identifier (for example, by sending a victim a link like https://example.com/login?session_id=attacker123) can later reuse that identifier to impersonate the victim once the victim authenticates with Basic Auth. Even though Basic Auth transmits credentials with each request, the server-side session tied to the cookie may not be invalidated or reassigned, leaving a window where the session is linked to the authenticated identity but the identifier was chosen by an attacker.

Chi does not inherently enforce session regeneration on authentication; this must be implemented explicitly. If the application authenticates via Basic Auth and then relies on a session cookie for subsequent authorization checks without regenerating the session, an attacker who knows the session ID can exploit this mismatch. The risk is higher in scenarios where session cookies are used to store authorization state (e.g., user role or ID) and where the session store does not validate the authenticated identity on each request. Because the scan types included in middleBrick test Authentication and BOLA/IDOR checks in parallel, findings may surface when session handling does not properly align with Basic Auth flows, highlighting that unauthenticated session identifiers can become linked to authenticated contexts.

Basic Auth-Specific Remediation in Chi — concrete code fixes

Remediation focuses on ensuring that session identifiers are not predictable or controllable by the client and are rotated after successful authentication. Even when using Basic Auth, you should treat the session cookie as an independent token that must be issued server-side and never derived from user input or attacker-supplied values.

Below are concrete Chi examples in F# that demonstrate secure session handling alongside Basic Auth. The first example shows a login handler that validates Basic Auth credentials and then explicitly sets a new session identifier, removing any prior session linkage.

open System
open System.Security.Cryptography
open Microsoft.AspNetCore.Http
open Microsoft.AspNetCore.Builder
open Microsoft.AspNetCore.Hosting
open Microsoft.Extensions.DependencyInjection

let createSessionId () =
    let bytes = Array.zeroCreate 32
    use rng = RandomNumberGenerator.Create()
    rng.GetBytes(bytes)
    Convert.ToBase64String(bytes)

let validateBasicAuth (header: string) = 
    // Simplified validation; in production use proper credential checks
    header.StartsWith("Basic ") 
    && Convert.FromBase64String(header.Substring(6)) 
    |> fun data -> Encoding.UTF8.GetString(data).Split(":")
    |> fun parts -> parts.Length = 2 && parts[0] = "alice" && parts[1] = "secret"

let app = 
    WebApplication.CreateBuilder()
        .Services
        .AddSession(fun opts ->
            opts.IdleTimeout <- TimeSpan.FromMinutes(30.0)
            opts.Cookie.Name <- "secure_session"
            opts.Cookie.HttpOnly <- true
            opts.Cookie.SecurePolicy <- CookieSecurePolicy.Always)
        .AddAuthentication()
        .Services
        .AddAuthorization()
        .Build()

app.UseSession()

app.MapPost("/login", fun (ctx: HttpContext) =
    let authHeader = ctx.Request.Headers["Authorization"]
    if validateBasicAuth authHeader then
        // Invalidate any existing session and issue a new identifier
        ctx.Session.Clear()
        let newId = createSessionId()
        ctx.Session.SetString("SessionId", newId)
        ctx.Session.SetString("Authenticated", "true")
        ctx.Response.StatusCode <- 200
        "Logged in, session rotated"
    else
        ctx.Response.StatusCode <- 401
        "Unauthorized")

app.MapGet("/profile", fun (ctx: HttpContext) ->
    if ctx.Session.GetString("Authenticated") = "true" then
        // Use server-side session data, never trust client-supplied identifiers
        Results.Ok($"Profile for session {ctx.Session.GetString("SessionId")}")
    else
        Results.Unauthorized())

app.Run()

The second example demonstrates middleware that rejects requests where the session identifier appears tampered with or predictable, reinforcing defense-in-depth. This pattern helps ensure that even if a victim’s browser sends a known or attacker-set cookie, the server does not treat it as valid after authentication.

app.Use(async (ctx, next) ->
    let currentSession = ctx.Session.GetString("SessionId")
    // Reject obviously weak or predictable session identifiers
    if String.IsNullOrEmpty(currentSession) || currentSession.Length < 24 then
        ctx.Response.StatusCode <- 400
        "Invalid session"
    else
        do! next()
)

Additionally, ensure that any session-related data used for authorization is re-validated on each request and that the session store does not implicitly trust the authenticated identity derived from Basic Auth without confirming the session binding. middleBrick scans can surface misconfigurations where session handling does not align with authentication flows, supporting compliance checks against frameworks such as OWASP API Top 10 and SOC2.

Frequently Asked Questions

Does Basic Auth alone prevent session fixation?
No. Basic Auth transmits credentials per request but does not inherently protect session identifiers. If the application does not rotate session IDs after login, an attacker can fixate a session and reuse it after the victim authenticates.
Should I stop using session cookies if I use Basic Auth?
Not necessarily. You can continue to use session cookies if you ensure session IDs are generated server-side, are cryptographically random, are rotated after authentication, and are validated on each request alongside proper authorization checks.