Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions changes-entries/70376.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
*) mod_session_cookie: Fix mod_auth_form login not setting the session
cookie with SessionCookieRemove On. PR 70376 [Arturo Bernal]
12 changes: 6 additions & 6 deletions modules/session/mod_session_cookie.c
Original file line number Diff line number Diff line change
Expand Up @@ -142,13 +142,13 @@ static apr_status_t session_cookie_load(request_rec * r, session_rec ** z)
note = apr_pstrcat(m->pool, MOD_SESSION_COOKIE, name, NULL);
zz = (session_rec *)apr_table_get(m->notes, note);
if (zz) {
if (!conf->remove) {
*z = zz;
return OK;
} else {
/* remove the note */
apr_table_unset(m->notes, note);
/* keep the session already loaded, it may have been changed,
* but still remove the cookie from this request's headers */
if (conf->remove) {
ap_cookie_read(r, name, &val, 1);
}
*z = zz;
return OK;
}

/* otherwise, try parse the cookie */
Expand Down
Empty file.
36 changes: 36 additions & 0 deletions test/modules/session/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
import logging
import os

import pytest
import sys

from .env import SessionTestEnv
from pyhttpd.env import HttpdTestEnv

sys.path.append(os.path.join(os.path.dirname(__file__), '../..'))


def pytest_report_header(config, start_path):
env = SessionTestEnv()
return f"mod_session [apache: {env.get_httpd_version()}, mpm: {env.mpm_module}, {env.prefix}]"


@pytest.fixture(scope="package")
def env(pytestconfig) -> SessionTestEnv:
level = logging.INFO
console = logging.StreamHandler()
console.setLevel(level)
console.setFormatter(logging.Formatter('%(levelname)s: %(message)s'))
logging.getLogger('').addHandler(console)
logging.getLogger('').setLevel(level=level)
env = SessionTestEnv(pytestconfig=pytestconfig)
env.setup_httpd()
env.apache_access_log_clear()
env.httpd_error_log.clear_log()
return env


@pytest.fixture(autouse=True, scope="package")
def _stop_package_scope(env):
yield
assert env.apache_stop() == 0
26 changes: 26 additions & 0 deletions test/modules/session/env.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
import inspect
import logging
import os

from pyhttpd.env import HttpdTestEnv, HttpdTestSetup

log = logging.getLogger(__name__)


class SessionTestSetup(HttpdTestSetup):

def __init__(self, env: 'HttpdTestEnv'):
super().__init__(env=env)
self.add_source_dir(os.path.dirname(inspect.getfile(SessionTestSetup)))
self.add_modules(["cgid", "session", "session_cookie"])
self.add_optional_modules(["auth_form", "authn_file", "authn_core",
"authz_user", "request"])


class SessionTestEnv(HttpdTestEnv):

def __init__(self, pytestconfig=None):
super().__init__(pytestconfig=pytestconfig)

def setup_httpd(self, setup: HttpdTestSetup = None):
super().setup_httpd(setup=SessionTestSetup(env=self))
10 changes: 10 additions & 0 deletions test/modules/session/htdocs/test1/cgi/session.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
#!/usr/bin/env python3

import os

print("Content-Type: text/plain")
print("X-Replace-Session: key1=foo&key2=&key3=bar")
print()

for key, value in sorted(os.environ.items()):
print(f"{key}={value}")
94 changes: 94 additions & 0 deletions test/modules/session/test_002_auth_form_cookie_remove.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import base64
import hashlib
import os
import re

import pytest

from pyhttpd.conf import HttpdConf


class TestAuthFormCookieRemove:
"""A login through mod_auth_form sets the session cookie even when
SessionCookieRemove hides that cookie from the request."""

@pytest.fixture(autouse=True, scope='class')
@classmethod
def _class_scope(cls, env):
for mod in ("auth_form", "request"):
env.require(env.has_shared_module(mod), f"mod_{mod} is not built",
dep=f"mod_{mod}")
docs = os.path.join(env.server_dir, "htdocs", "test1")
for d in ("form-remove", "form-keep", "redir"):
os.makedirs(os.path.join(docs, d), exist_ok=True)
with open(os.path.join(docs, d, "index.html"), "w") as fd:
fd.write("ok\n")
passwd = os.path.join(env.server_dir, "form.passwd")
sha = base64.b64encode(hashlib.sha1(b"secret").digest()).decode()
with open(passwd, "w") as fd:
fd.write(f"user:{{SHA}}{sha}\n")
cgi_dir = os.path.join(docs, "cgi")
form = f"""
AuthType form
AuthName form
AuthFormProvider file
AuthUserFile {passwd}
AuthFormLoginSuccessLocation /index.html
Require valid-user
Session On
SessionCookieName session path=/
"""
conf = HttpdConf(env, extras={
f"test1.{env.http_tld}": f"""
<Directory "{cgi_dir}">
Options +ExecCGI
AddHandler cgi-script .py
Session On
SessionCookieName session path=/
SessionCookieRemove On
</Directory>
<Location /form-remove>{form}
SessionCookieRemove On
</Location>
<Location /form-keep>{form}
</Location>
<Location /redir>
Session On
SessionCookieName session path=/
ErrorDocument 404 /cgi/session.py
</Location>
""",
})
conf.add_vhost_test1()
conf.install()
assert env.apache_restart() == 0

def _login(self, env, path):
url = env.mkurl("http", "test1", path)
return env.curl_raw(url, options=[
"--data", "httpd_username=user&httpd_password=secret",
])

@pytest.mark.parametrize("path", ["/form-keep/", "/form-remove/"])
def test_session_002_01_login_sets_cookie(self, env, path):
r = self._login(env, path)
assert r.exit_code == 0
assert r.response["status"] == 302, f"{r.stdout}"
cookies = [v for k, v in r.response["header"].items()
if k.lower() == "set-cookie"]
assert any(re.match(r"session=.*form-user=user", c)
for c in cookies), f"no session cookie: {r.response['header']}"

def test_session_002_02_removed_after_internal_redirect(self, env):
# the session is loaded where it is kept, then the internal
# redirect lands where it must be removed (CVE-2026-47360)
url = env.mkurl("http", "test1", "/redir/missing")
r = env.curl_raw(url, options=[
"--cookie", "session=key1=foo; other=bar",
])
assert r.exit_code == 0
assert r.response["status"] == 404
cookie = [line for line in r.stdout.splitlines()
if line.startswith("HTTP_COOKIE=")]
assert cookie, r.stdout
assert cookie[0].split("=", 1)[1].strip() == "other=bar", cookie[0]
Loading