[BUG] Anonymous Authelia redirects can overwrite a newer login session

Aperta
#634 1 commento 0 reazioni 0 assegnatari Vedi su GitHub

@MeiXu6693 ci sta già lavorando.

Dal 29/10/2026.

  • #635 di @MeiXu6693 — aperta

Valutazione

Difficoltà
3/5
Tempo stimato
1-2 giorni
Idoneità per principianti
48/100
Tipo di issue
Bug
Chiarezza
Specificata chiaramente
Stato di attività
Attiva
Stack tecnologico
docker, nginx

Direzione di ricerca

Start with root/defaults/nginx/authelia-server.conf.sample, which the issue identifies as forwarding the subrequest cookie on the 401 redirect; compare it with the Authelia Nginx example linked in the report. The issue describes a candidate that removes cookie forwarding only from that redirect location. Check the sample configuration and its behavior against the described anonymous redirect and portal login flow; done means a delayed anonymous redirect cannot replace the authenticated session while portal cookies still work.

Scritto dal modello di indicizzazione a partire dal testo della issue.

Descrizione

Is there an existing issue for this?
  • I searched the existing issues and did not find this race. I also reviewed #366, which addressed add_header inheritance and subfolder compatibility.
Current Behavior

When SWAG forwards an anonymous Authelia auth-request response, @authelia_proxy_signin adds the subrequest's Set-Cookie to its 302 response. Several outstanding anonymous requests can each receive a different session cookie. A 302 response that reaches the browser after a successful portal login can therefore replace the authenticated cookie with an older anonymous one and make the next request redirect to the login page again.

This is a potential session-stability bug, not a claim of an authentication bypass. The original user incident has not been confirmed with browser cookie timing. I reproduced the underlying cookie overwrite with an isolated test account and controlled response ordering, first using HTTP requests and then in headless Chromium. This does not establish what happened in the original user's browser.

Expected Behavior

A delayed anonymous auth-request redirect should not replace the session established by the portal. Unauthenticated requests should still be denied and the portal should still be able to set login, MFA and logout cookies.

Steps To Reproduce
  1. Run the current SWAG image, Authelia 4.39.28 and an Authelia-protected test site on a private Docker network. Use the stock authelia-server.conf and authelia-location.conf; use an isolated test user and a temporary test certificate.
  2. Request the protected site without cookies and retain the authelia_session value from its 302 response. This represents an earlier anonymous response that is delayed in transit.
  3. Independently authenticate the test user through the Authelia portal and retain the resulting authenticated cookie. A request using that cookie returns 200.
  4. Simulate delivery of the delayed response by using the anonymous cookie as the browser's current cookie. The protected request now returns 302; restoring the authenticated cookie returns 200.

Observed without publishing any cookie values:

stock:  anonymous=302, anonymous cookie present=yes, login=200,
        authenticated=200, after applying old anonymous cookie=302
patched: anonymous=302, anonymous cookie present=no,
         first factor=200, second factor=200, protected page=200,
         logout=200, request using old authenticated session=302

The candidate removes cookie forwarding only from the named 401 redirect location. It does not change access policy or the portal's own responses. The Authelia Nginx example does not forward this subrequest cookie on the redirect. The current SWAG sample does. An isolated Chromium test, OIDC authorization-code + PKCE exchange, and a portal hosted under a subpath have also passed with the candidate; see below. Testing with other versions and client configurations remains valuable.

Additional compatibility checks

With isolated SWAG and Authelia 4.39.28 containers using the candidate configuration:

  • A two-factor protected site redirected after first factor, accepted a TOTP, and returned 200 only after the second factor. After logout, the old authenticated session was rejected.
  • An OIDC public client with S256 PKCE completed discovery, first-factor login, authorization (303), and a token exchange (200) with an ID token; state matched. Token and cookie values were not recorded.
  • With Authelia configured on /authelia and an unprotected portal location on the same application host, an anonymous request redirected to the subpath without a session cookie; the portal loaded, first factor succeeded, and the protected page returned 200.
  • The stock 302 test returned no inherited Strict-Transport-Security header; the candidate 302 did include it in this fixture. Both configurations passed nginx -t.

These are controlled test configurations, not an exhaustive compatibility guarantee.

Controlled browser verification

Using Playwright and headless Chromium with an isolated SWAG/Authelia fixture, I intercepted a real protected background response and held its 302 until after a separate portal login. A minimal mocked app page provided a same-origin context; authentication and the delayed 302 were real requests to the test containers. The browser used a disposable profile.

stock:   login=200, protected-before=200, protected-after=302, cookie-changed=yes
patched: login=200, protected-before=200, protected-after=200, cookie-changed=no
Browser test (the target IP is an isolated SWAG container)

Set TARGET_IP and EXPECT=baseline or EXPECT=patched; replace the test password placeholder with the isolated fixture user's password. No real credentials or cookie values are needed in the report.

import asyncio,json,os
from playwright.async_api import async_playwright
async def main():
 async with async_playwright() as p:
  browser=await p.chromium.launch(executable_path='/root/.cloakbrowser/chromium-146.0.7680.177.5/chrome',headless=True,args=['--no-sandbox','--disable-dev-shm-usage','--no-proxy-server','--host-resolver-rules=MAP *.example.test '+os.environ['TARGET_IP']])
  context=await browser.new_context(ignore_https_errors=True);app=await context.new_page();pending=asyncio.Event();release=asyncio.Event()
  async def fake_page(route): await route.fulfill(status=200,content_type='text/html',body='<html><body>isolated test</body></html>')
  async def delay(route):
   response=await route.fetch(url='https://'+os.environ['TARGET_IP']+'/background-test',headers={**route.request.headers,'host':'app.example.test'},max_redirects=0);pending.set();await release.wait();await route.fulfill(response=response)
  await app.route('https://app.example.test/test-app',fake_page)
  await app.route('https://app.example.test/background-test',delay)
  await app.goto('https://app.example.test/test-app',wait_until='domcontentloaded',timeout=20000)
  auth=await context.new_page();await auth.goto('https://auth.example.test/',wait_until='domcontentloaded',timeout=20000)
  task=asyncio.create_task(app.evaluate("fetch('/background-test',{credentials:'include'}).catch(()=>null)"))
  await asyncio.wait_for(pending.wait(),10)
  result=await auth.evaluate("""async () => {const r=await fetch('/api/firstfactor',{method:'POST',headers:{'Content-Type':'application/json'},body:JSON.stringify({username:'verification',password:'<test-user-password>',targetURL:'https://app.example.test/',keepMeLoggedIn:false})});return r.status;}""")
  before=next((c['value'] for c in await context.cookies() if c['name']=='authelia_session'),None)
  fresh=await context.request.get('https://'+os.environ['TARGET_IP']+'/',headers={'Host':'app.example.test','Cookie':'authelia_session='+str(before)},max_redirects=0)
  release.set();await asyncio.wait_for(task,10);await app.wait_for_timeout(200)
  after=next((c['value'] for c in await context.cookies() if c['name']=='authelia_session'),None)
  stale=await context.request.get('https://'+os.environ['TARGET_IP']+'/',headers={'Host':'app.example.test','Cookie':'authelia_session='+str(after)},max_redirects=0)
  output={'first_factor':result,'before_late_response':fresh.status,'after_late_response':stale.status,'cookie_changed':before!=after}
  print(json.dumps(output),flush=True)
  expected=(200,200,302,True) if os.environ['EXPECT']=='baseline' else (200,200,200,False)
  if (result,fresh.status,stale.status,before!=after)!=expected:raise SystemExit('unexpected browser race result')
  await browser.close()
asyncio.run(main())
Environment
  • OS: Unraid 7.3.4, Docker Engine 29.8.2
  • CPU architecture: x86-64
  • SWAG: lscr.io/linuxserver/swag:latest, version 5.8.0-ls495, pulled 2026-10-29, sample dated 2026/10/20
  • Authelia: authelia/authelia:4.39.28
  • No Docker Mods, no custom init scripts, no host ports published. A private test network, disposable test configuration, and self-signed test certificate were used.
Docker creation
docker network create --internal swag-cookie-upstream-test
docker run -d --name swag-cookie-authelia-test \
  --network swag-cookie-upstream-test --network-alias authelia \
  -v "$TEST_DIR/authelia:/config" authelia/authelia:4.39.28
docker run -d --name swag-cookie-issue-test \
  --network swag-cookie-upstream-test \
  -e PUID=1000 -e PGID=1000 -e TZ=Etc/UTC \
  -e URL=example.test -e SUBDOMAINS=www -e VALIDATION=http \
  -v "$TEST_DIR/swag-original:/config" lscr.io/linuxserver/swag:latest

The test configuration uses Authelia's file backend, an isolated user, example.test as the shared cookie domain and a private app.example.test site with the stock AuthRequest includes. A self-signed fixture certificate is pre-created under /config/etc/letsencrypt/live/example.test/; no real DNS, credentials or production volumes are used.

Container logs

Full startup log from the isolated stock-image container with the pre-existing test fixture:

[migrations] started
[migrations] 01-nginx-site-confs-default: skipped
[migrations] 02-swag-old-certbot-paths: skipped
[migrations] done
───────────────────────────────────────

      ██╗     ███████╗██╗ ██████╗
      ██║     ██╔════╝██║██╔═══██╗
      ██║     ███████╗██║██║   ██║
      ██║     ╚════██║██║██║   ██║
      ███████╗███████║██║╚██████╔╝
      ╚══════╝╚══════╝╚═╝ ╚═════╝

   Brought to you by linuxserver.io
───────────────────────────────────────

To support the app dev(s) visit:
Certbot: https://supporters.eff.org/donate/support-work-on-certbot

To support LSIO projects visit:
https://www.linuxserver.io/donate/

───────────────────────────────────────
GID/UID
───────────────────────────────────────

User UID:    1000
User GID:    1000
───────────────────────────────────────
Linuxserver.io version: 5.8.0-ls495
Build-date: 2026-10-24T08:02:34+00:00
───────────────────────────────────────
    
using keys found in /config/keys
Variables set:
PUID=1000
PGID=1000
TZ=Etc/UTC
URL=example.test
SUBDOMAINS=www
EXTRA_DOMAINS=
ONLY_SUBDOMAINS=false
VALIDATION=http
CERTPROVIDER=
CERT_PROFILE=
DNSPLUGIN=
EMAIL=
STAGING=

Using Let's Encrypt as the cert provider
SUBDOMAINS entered, processing
Sub-domains processed are: www.example.test
No e-mail address entered or address invalid
http validation is selected
Certificate exists; parameters unchanged; starting nginx
The cert does not expire within the next day. Letting the cron script handle the renewal attempts.
[custom-init] No custom files found, skipping...
[ls.io-init] done.
Server ready

Investigation, reproduction and report were produced with assistance from OpenAI Codex (GPT-6).

Lingua principale
Dockerfile
Stelle
3.8k
Fork
274
Merge medio
25m
PR unite (30g)
1

Preparare l'ambiente

Come iniziare

  1. Leggi tutta la issue e poi la guida ai contributi del progetto.
  2. Commenta sulla issue per dire che te ne occupi tu — evita che due persone facciano lo stesso lavoro.
  3. Fai un fork del repository e lavora su un branch.
  4. Apri una pull request che faccia riferimento al numero della issue.

Altre issue di linuxserver/docker-swag

Tutte le issue di linuxserver/docker-swag

Issue simili

Altre issue su Security

Ricevi le nuove issue nella tua casella

Un breve riepilogo di issue GitHub adatte ai principianti.