Skip to content

IIS: propagate Location header on redirect interventions - #3689

Open
A13501350 wants to merge 1 commit into
owasp-modsecurity:v2/masterfrom
A13501350:fix-729-iis-redirect-request-phase
Open

A13501350 wants to merge 1 commit into
owasp-modsecurity:v2/masterfrom
A13501350:fix-729-iis-redirect-request-phase

Conversation

@A13501350

@A13501350 A13501350 commented Oct 14, 2026 •

Copy link
Copy Markdown

Summary

When a rule with a redirect action matches, the core engine stores the target URI in the Location header of the request_rec's headers_out table and perform_interception() returns the redirect status. Both the request (OnBeginRequest) and response (OnSendResponse) intervention paths on IIS only forwarded the status code, so clients received a 301/302 without a Location header.

This fix introduces a shared ApplyInterventionResponse() helper for both OnBeginRequest and OnSendResponse (after Clear()), forwarding Location and falling back to HTTP 500 if the target is empty, exceeds USHRT_MAX, contains control characters (< 0x20 except HTAB, or 0x7f), or if SetStatus()/SetHeader() fails. Errors are recorded in the transaction debug/audit logs with rule metadata and UNIQUE_ID rather than Windows Event Viewer.

Fixes #729

Tests

Verified phases 1–4 redirects and invalid/oversized Location 500 fallbacks in CI on Windows IIS; permanent FTW regression tests will be added once #3613's iis/tests harness lands.

@coderabbitai

coderabbitai Bot commented Oct 14, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Auto reviews are disabled on base/target branches other than the default branch.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

Run configuration

  • Source mode: Auto
  • Repository: Unavailable
  • Branch: Unavailable
  • File: No configuration file from this repository applied
  • Commit: Unavailable
  • Layers: defaults
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: 2e618bdb-2d3f-4a40-b8d0-ce9995dc2361

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • Trigger review
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

Share

Comment thread iis/mymodule.cpp Fixed
@A13501350
A13501350 force-pushed the fix-729-iis-redirect-request-phase branch from b413e8b to b9a1758 Compare October 14, 2026 15:35
@airween airween added the 2.x Related to ModSecurity version 2.x label Oct 15, 2026
@airween

airween commented Oct 15, 2026

Copy link
Copy Markdown
Member

Hi @A13501350,

thanks for this patch - could you add a new test case to the existing regression tests collection? Thanks!

@fzipi fzipi left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @A13501350, this fixes a long-standing one (#729) and looks good to me.

I reviewed it by reading the code; I haven't built or run it. Windows CI is green.

  • modsecProcessRequest runs both phase 1 and phase 2, so this covers the default-phase-2 case from #729 (SecRule ARGS ... redirect:/).
  • At that point the only thing that puts Location into r->headers_out is the redirect branch of perform_interception, so there's no risk of forwarding a stale value.

Two questions:

  1. The commit message says response phases never run on this connector. From what I can see, OnSendResponse does call modsecProcessResponse when SecResponseBodyAccess is On and there's a body. Its intercept path does Clear() + SetStatus() without a Location, the same symptom as #729. Would you mind either applying the same lookup there, or opening a follow-up issue and rewording that line? I'd rather not have the "never run" claim in the history if it isn't accurate.
  2. The redirect target can include macros (e.g. redirect:/login?next=%{ARGS.next}), and ARGS are decoded, so the value could in theory contain CR/LF. Apache rejects such header values on output. I'm not sure IIS/HTTP.SYS does the same for SetHeader. Do you know? If not, a small guard (skip the header, or return 500, if strpbrk(location, "\r\n") matches) would settle it.

On tests: the existing redirect regression tests run on Apache, so they wouldn't catch this. Once the iis/tests harness from #3613 is in, a small FTW case expecting a 302 with a Location header would be great. I'm fine with that as a follow-up.

@A13501350
A13501350 force-pushed the fix-729-iis-redirect-request-phase branch from b9a1758 to f83a0df Compare October 27, 2026 06:47
@sonarqubecloud

Copy link
Copy Markdown

A13501350 added a commit to A13501350/ModSecurity that referenced this pull request Oct 27, 2026
The original OnBeginRequest config-load path had two architectural
shortcomings that made fail-closed impossible to implement cleanly:
 1. No single exit — every failure path before Finished was either
    silently promoted to hr=S_OK or returned early from the function,
    so the lock was released at N different call sites and no
    centralized response construction existed.
 2. No per-context sticky state — once config loading failed there was
    nothing to stop every subsequent request on the same app pool from
    re-entering the load path and hitting the same bug until a crash.

This commit restructures the function around a single Finished label
with a new bool configError that every failure path sets before
goto Finished. The Finished block now owns:
  - LeaveCriticalSection (only one site in the function)
  - Marking the context sticky-failed (configLoadingFailed + m_Config=NULL)
    so subsequent requests also fail closed
  - Writing the 500 response (without SetRequestHandled so IIS renders
    its httpErrors page)

Bug fixes that fell out of the refactor:
  - GlobalWideCharToMultiByte returns a Win32 DWORD positive error code,
    which FAILED() sees as success. Replace two FAILED(hr) checks in this
    function with hr != 0 (safe whether the signature stays DWORD or is
    later changed to HRESULT).
  - delete → delete[] at all six sites that free memory allocated via
    new CHAR[] inside GlobalWideCharToMultiByte.
  - GetConfig failure now includes a pConfig==NULL guard and a WriteEventViewerLog
    instead of silently downgrading hr to S_OK.
  - A previously-skipped branch (path[0]==0, empty config path on an
    enabled module) now also fails closed instead of running with zero
    rules.

New sticky flag: MODSECURITY_STORED_CONTEXT::configLoadingFailed. Once
set, every subsequent request returns 500 until the application pool
is recycled (IIS does not notify native modules when modsecurity.conf
changes, so no automatic recovery is possible).

Fixes owasp-modsecurity#729 (config-load side). Redirect-on-redirect is handled separately
by PR owasp-modsecurity#3689.
A13501350 added a commit to A13501350/ModSecurity that referenced this pull request Oct 30, 2026
The original OnBeginRequest config-load path had two architectural
shortcomings that made fail-closed impossible to implement cleanly:
 1. No single exit — every failure path before Finished was either
    silently promoted to hr=S_OK or returned early from the function,
    so the lock was released at N different call sites and no
    centralized response construction existed.
 2. No per-context sticky state — once config loading failed there was
    nothing to stop every subsequent request on the same app pool from
    re-entering the load path and hitting the same bug until a crash.

This commit restructures the function around a single Finished label
with a new bool configError that every failure path sets before
goto Finished. The Finished block now owns:
  - LeaveCriticalSection (only one site in the function)
  - Marking the context sticky-failed (configLoadingFailed + m_Config=NULL)
    so subsequent requests also fail closed
  - Writing the 500 response (without SetRequestHandled so IIS renders
    its httpErrors page)

Bug fixes that fell out of the refactor:
  - GlobalWideCharToMultiByte returns a Win32 DWORD positive error code,
    which FAILED() sees as success. Replace two FAILED(hr) checks in this
    function with hr != 0 (safe whether the signature stays DWORD or is
    later changed to HRESULT).
  - delete → delete[] at all six sites that free memory allocated via
    new CHAR[] inside GlobalWideCharToMultiByte.
  - GetConfig failure now includes a pConfig==NULL guard and a WriteEventViewerLog
    instead of silently downgrading hr to S_OK.
  - A previously-skipped branch (path[0]==0, empty config path on an
    enabled module) now also fails closed instead of running with zero
    rules.

New sticky flag: MODSECURITY_STORED_CONTEXT::configLoadingFailed. Once
set, every subsequent request returns 500 until the application pool
is recycled (IIS does not notify native modules when modsecurity.conf
changes, so no automatic recovery is possible).

Fixes owasp-modsecurity#729 (config-load side). Redirect-on-redirect is handled separately
by PR owasp-modsecurity#3689.
@airween

airween commented Nov 30, 2026

Copy link
Copy Markdown
Member

Hi @A13501350,

thanks for adding the CR/LF guard, that resolves @fzipi's second point. A few more things I noticed while reading the current head (f83a0df):

  1. Fixes #729: a redirect from phase 3/4 still reaches the client as a 3xx without Location, because the OnSendResponse intercept path calls Clear() + SetStatus() and never copies r->headers_out Location. @fzipi asked for a follow-up issue for this; until that exists, please change Fixes #729 to Part of #729 in the PR description, so merging this does not close the issue. (Or, if you prefer, apply the same Location handling in OnSendResponse in this PR.)

  2. Length cast: (USHORT)strlen(location) wraps around for a target longer than 65535 bytes, and SetHeader then sends a truncated (or empty) Location. The target can grow from request data through macros (e.g. redirect:'/login?next=%{ARGS.next}' with a large POST body). Please return 500 in that case instead of casting, the same way as for CR/LF.

  3. SetHeader result: the HRESULT of SetHeader is ignored here, while OnSendResponse in the same file checks FAILED(hr). If it fails, the client gets the original Redirect action does not work properly in IIS #729 symptom again (3xx without Location) and nothing is logged. Please check it and handle it like the CR/LF branch.

  4. Other control characters: the commit message says the guard matches Apache, but Apache 2.4 (with the default strict HttpProtocolOptions) rejects every control character except HTAB in a response header value, not only CR and LF. Please either reject all bytes < 0x20 except \t, plus 0x7f, or drop the "match that behavior" part from the commit message.

  5. Event Viewer entry: the CR/LF branch writes an EVENTLOG_ERROR_TYPE entry on every such request, while holding m_csLock, and the message carries no rule id or unique id. Any client can produce one entry per request. I think this should go to ModSecurity's own error/debug log (with the rule id and UNIQUE_ID), and the Event Viewer should be kept for configuration errors.

  6. Log vs. response: the audit/debug log still says "Access denied with redirection to ... using status 302", while the client gets 500. It would help to log the reason for the 500 in the transaction as well (this is related to the audit log status work in fix: record real response status for IIS audit log F part #3613).

And a reminder about the regression test from my earlier comment: I know the IIS harness is in #3613, so it is fine to add the test there or right after it lands, but please note it in the PR description so it does not get lost.

Thanks!

When a rule with a redirect action matches, the core engine stores the
target URI in r->headers_out ("Location") and perform_interception()
returns the redirect status. Both OnBeginRequest and OnSendResponse
only forwarded the status code to IIS, leaving clients with a 301/302
without a Location header.

Add a shared ApplyInterventionResponse() helper used by both request
(OnBeginRequest) and response (OnSendResponse, after Clear()) paths to
validate and forward the Location header. Targets that are empty, exceed
USHRT_MAX, or contain control characters (< 0x20 except HTAB, or 0x7f)
are rejected with HTTP 500, and SetStatus()/SetHeader() failures also
fall back to 500.

Validation and SetHeader() failures are recorded in the transaction's
debug and audit logs (with rule metadata and UNIQUE_ID) via
modsecLogInterventionError() rather than writing per-request Event
Viewer entries.

Fixes owasp-modsecurity#729
@A13501350
A13501350 force-pushed the fix-729-iis-redirect-request-phase branch from f83a0df to ffe3530 Compare December 2, 2026 12:40
@A13501350

Copy link
Copy Markdown
Author

@airween @fzipi Rebased onto v2/master (03bbda9a) and updated the PR in ffe3530e to address all points:

  • Applied the shared ApplyInterventionResponse() handling to both OnBeginRequest and OnSendResponse (after Clear()), so Fixes #729 covers both request and response phases (when SecResponseBodyAccess is On with a non-empty body).
  • Rejected empty targets and lengths > USHRT_MAX instead of casting (USHORT)strlen(location).
  • Checked SetStatus()/SetHeader() HRESULT and cleared/fell back to 500 on failure.
  • Rejected all control characters (< 0x20 except \t, and 0x7f) matching Apache's strict header validation.
  • Replaced per-request WriteEventViewerLog calls with modsecLogInterventionError(), recording the 500 fallback reason with rule metadata and UNIQUE_ID into the debug log and audit log Part H without writing to Event Viewer.
  • Noted the follow-up FTW test pending fix: record real response status for IIS audit log F part #3613 in the PR description (all phase 1–4 and invalid/oversized Location cases passed on Windows IIS in a test-branch CI run).

@sonarqubecloud

sonarqubecloud Bot commented Dec 2, 2026

Copy link
Copy Markdown

Comment thread iis/mymodule.cpp
if(location == nullptr)
return false;

size_t len = strlen(location);

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

2.x Related to ModSecurity version 2.x

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants