[unanchored_regex] Unanchored regular expressions
What this check looks for
A regular expression on the request URI that is not anchored with ^ or $, or on the host name that is not anchored with both. In an alternation, every branch needs its own anchors. The plugin checks:
location ~andlocation ~*patterns,iftests of$uri,$document_uri,$request_urior$host, and regex keys of amapon one of them,rewritepatterns,server_nameregular expressions.
Why this is a problem
An unanchored pattern matches anywhere in the input. location ~ \.php also hands /uploads/x.php.jpg to PHP, location ~ \.(jpg|png) also serves /x.jpg.php as a static file, and if ($request_uri !~ "/api/") { return 403; } lets /x/api/y through.
A host name needs both anchors, because the client chooses the name: server_name ~^(www\.)?example\.com also selects the server for example.com.attacker.net, and ~example\.com$ for notexample.com.
Bad configuration
location ~ \.php {
# ...
}
# Matches /bar, /x/bar, /foo/bar/baz, ...
location ~ ^/foo|/bar {
# ...
}
server {
server_name ~^(www\.)?example\.com;
location / {
if ($request_uri !~ "/api/") {
return 403;
}
}
}
Better configuration
location ~ \.php$ {
# ...
}
location ~ ^/foo$|^/bar$ {
# ...
}
server {
server_name ~^(www\.)?example\.com$;
location / {
if ($request_uri !~ "^/api/") {
return 403;
}
}
}
Additional notes
- A
locationor positiveifwhose block only rejects (deny,internalor a 4xx or 5xxreturn, with or without logging directives), such aslocation ~ /\.ht { deny all; }, is not reported: matching anywhere is the intent. A negatedifis still reported. - A positive
ifwhose block only sets variables, such as a cache-skip list, is not reported either. - A
rewritewhose leading text the enclosinglocationpath already starts with, such asrewrite /app(.*) $1 break;inlocation ^~ /app/, can only match at the start and is not reported. - A pattern of only
.wildcards, such asserver_name ~.;, matches anything and is not reported. Neither are tests of other variables, such asif ($http_user_agent ~* bot). - A pattern gixy cannot parse, such as branch reset
(?|...)or recursion(?R), is skipped and may still be unanchored.