Score:1

Nginx match any word in if statement except one

cn flag

I'm using the following if statement regex in nginx config to match and block some bad requests inside request uri. These bad queries request always only one argument but every time with random name (and alphanum count). They also always hit the homepage.

Example of bad query: /?some1bad0query2=nminkvywbjfdysnvhp

if ($request_uri ~ "[\w]{5,25}\=[\w]{5,25}$") {
  return 403;
}

How can I modify this regex to exclude matching some argument names like key or query (ie. /?query=somestring) ?

I tried to use round brackets and ?(!query) but no luck.

Please help me correct this regex statement. Thanks in advance.

Richard Smith avatar
jp flag
Is that just a poor example, because `query=somestring` doesn't match your regular expression anyway, as `query` is less than 6 characters long?
cn flag
yes definitely it was wrong. corrected regex to start with 5 length arg name (query). but I still need an example of how I can mitigate this attack and bypass such good arguments whitelist (like query, search etc)
Score:0
jp flag

There are two ways to do this. Use a negative lookahead assertion or use a map.

For example:

if ($request_uri ~ "(?!query)\w{5,25}=\w{5,25}$") { return 403; }

The advantage of the map is that regular expressions are evaluated in order until a match is found, so complex lookahead expressions can be avoided.

For example:

map $request_uri $reject {
    ~*^/\?query=                0;
    "~*^/\?\w{5,25}=\w{5,25}$"  1;
}
server {
    ...
    if ($reject) { return 403; }
    ...
}

The map block lives outside of the server block. If the rule only applies to URIs which begin with /?, you should add that to the regular expression (as shown in my second example).

cn flag
Thanks, Richard! The map seems to be more elegant solution for me. Tested and it works flawlesly. Btw. my mistake in the if statement was that I put the ?! block after argument
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.