Skip to content
Open
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
4 changes: 2 additions & 2 deletions src/ngx_http_modsecurity_module.c
Original file line number Diff line number Diff line change
Expand Up @@ -334,14 +334,14 @@ ngx_http_modsecurity_get_module_ctx(ngx_http_request_t *r)
ctx = ngx_http_get_module_ctx(r, ngx_http_modsecurity_module);
if (ctx == NULL) {
/*
* refer <nginx>/src/http/modules/ngx_http_realip_module.c
* if module context was reset, the original address
* if module context was reset, the transaction
* can still be found in the cleanup handler
*/
ngx_pool_cleanup_t *cln;
for (cln = r->pool->cleanup; cln; cln = cln->next) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Efficiency follow-up: after a successful walk, the recovered pointer is not written back. Every later call for the same request walks the whole cleanup list again: the header filter, each body-filter chain (one per output buffer chain), and the log handler. try_files $uri /index.php is a very common pattern and sets r->internal on nearly every request, so those requests still take the slow path once per chain.

Calling ngx_http_set_ctx(r, ctx, ngx_http_modsecurity_module) once ctx is found would make every later lookup an O(1) array read. Most of the walks this PR is meant to avoid would then disappear, including the redirected case.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in b85a200: get_module_ctx() now calls ngx_http_set_ctx() once the walk finds the context. Later calls for the same request (the header filter, each body filter call, the log handler, the access handler of a redirect target) are then an array read until the next reset.

With the write-back in place I also dropped the r->internal || r->filter_finalize guard (see the lua thread). A request with a transaction now walks once per context reset.

One correction: requests that never had a transaction, such as locations with modsecurity off, have nothing to write back. They still walk on every filter call, as on master. Skipping that walk safely would need a negative marker in our r->ctx slot, one that any reset also clears. I left that out because the walk only covers the cleanups registered on r->pool.

if (cln->handler == ngx_http_modsecurity_cleanup) {
ctx = cln->data;
ngx_http_set_ctx(r, ctx, ngx_http_modsecurity_module);
break;
}
}
Expand Down
150 changes: 150 additions & 0 deletions tests/modsecurity-internal-redirect.t
Original file line number Diff line number Diff line change
@@ -0,0 +1,150 @@
#!/usr/bin/perl

#
# ModSecurity, http://www.modsecurity.org/
# Copyright (c) 2015 Trustwave Holdings, Inc. (http://www.trustwave.com/)
#
# You may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# If any of the files related to licensing are missing or if you have any
# other questions related to licensing please contact Trustwave Holdings, Inc.
# directly using the email address security@modsecurity.org.
#


# Tests for ModSecurity module (module context recovery after the request
# context has been discarded: internal redirects, named locations and
# filter finalization).

###############################################################################

use warnings;
use strict;

use Test::More;

BEGIN { use FindBin; chdir($FindBin::Bin); }

use lib 'lib';
use Test::Nginx;

###############################################################################

select STDERR; $| = 1;
select STDOUT; $| = 1;

my $t = Test::Nginx->new()->has(qw/http rewrite/);

$t->write_file_expand('nginx.conf', <<'EOF');

%%TEST_GLOBALS%%

daemon off;

events {
}

http {
%%TEST_GLOBALS_HTTP%%

server {
listen 127.0.0.1:8080;
server_name localhost;

modsecurity on;
modsecurity_rules '
SecRuleEngine On
SecRule ARGS:what "@streq ok" "id:90,phase:1,pass,log"
SecRule ARGS:what "@streq bad" "id:91,phase:1,deny,status:403,log,auditlog"
SecRule RESPONSE_HEADERS:X-Fallback "@streq yes" "id:92,phase:3,log,auditlog,pass"
SecRule ARGS:what "@streq precond" "id:93,phase:1,log,auditlog,pass"
SecAuditEngine RelevantOnly
SecAuditLogParts ABH
SecAuditLog %%TESTDIR%%/audit.txt
SecAuditLogType Serial
';

error_log %%TESTDIR%%/msc.log info;

error_page 403 /denied.html;

location / {
try_files $uri /fallback;
}

location = /fallback {
internal;
add_header X-Fallback yes;
}

location = /denied.html {
internal;
}

location /named {
try_files $uri @named;
}

location @named {
add_header X-Fallback yes;
return 200 "NAMED";
}

location /static {
}
}
}

EOF

$t->write_file('fallback', 'FALLBACK');
$t->write_file('denied.html', 'DENIED');
mkdir($t->testdir() . '/static');
$t->write_file('static/precond.html', 'PRECOND');
$t->run();
$t->plan(8);

###############################################################################

like(http_get('/missing?what=ok'), qr/FALLBACK/, 'try_files fallback served');
like(http_get('/named/missing?what=ok'), qr/NAMED/, 'named location served');
like(http_get('/missing?what=bad'), qr/^HTTP.*403.*DENIED/s,
'phase 1 deny, error_page served');

# a failed precondition makes the not modified filter call
# ngx_http_filter_finalize_request(), which discards the module contexts
# without setting r->internal

like(http(<<EOF), qr/^HTTP.*412/, 'precondition failed');
GET /static/precond.html?what=precond HTTP/1.0
Host: localhost
If-Match: "bogus"

EOF

my $d = $t->testdir();

my $audit = do {
local $/ = undef;
open my $fh, "<", "$d/audit.txt"
or die "could not open: $!";
<$fh>;
};

my $log = $t->read_file('msc.log');

# a request whose context is lost after the redirect gets a second
# transaction, which runs phase 1 again

my @p1 = ($log =~ /\[id "90"\]/g);
is(scalar @p1, 2, 'phase 1 ran once per redirected request (ctx recovered)');
my @p3 = ($audit =~ /\[id "92"\]/g);
is(scalar @p3, 2, 'phase 3 ran once per redirected request');
my @deny = ($audit =~ /\[id "91"\]/g);
is(scalar @deny, 1, 'deny audited once across error_page redirect');
like($audit, qr/\[id "93"\]/, 'logging phase ran after filter finalization');

###############################################################################
Loading