0

Currently my web site will try to find directory by going backwards through folders using URI constructed this way:

http://dummy.domain.com/home/../../section/

I would like to prevent this using mod_rewrite, but I wasn't able to write a regular expression which will be able to remove all ../ from URI. The best try was:

RewriteRule ^(.*)([\.]{2}[\/]{1})(.*)$ $1$3 [L]

but rule above will only remove one occurrence of ../

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
draskomikic
  • 167
  • 2
  • 9
  • 1
    Possible duplicate of [this](http://stackoverflow.com/questions/1279681/mod-rewrite-replace-underscores-with-dashes). – tenub Aug 21 '14 at 16:22
  • So you want `http://dummy.domain.com/home/../../section/` => `http://dummy.domain.com/home/section/` or something else? – anubhava Aug 21 '14 at 16:53
  • Yes, and looks like it is only doable using Apache mod security to prevent directory traversal. – draskomikic Aug 22 '14 at 15:51

2 Answers2

1

Your regex to match URL pattern seems to be wrong.

Try this rule in your root .htaccess:

RewriteRule ^(.*?)(?:\.{2}/)+(.*)$ $1$2 [L,R,NE]

RewriteRule ^((?!home)[^/]+)/?$ /home/area/$1 [L,NC]

Here \.{2}/ pattern will match ../ and R flag will make sure URL is redirected.

anubhava
  • 761,203
  • 64
  • 569
  • 643
  • It is missing + after second group, but you helped me a lot to figure out that: ^(.*?)(\.{2}\/)+(.*?)$. Now it is matching the URI above but don't solves the problem because Apache REQUEST_URI will then be something like http://dummy.domain.com/section instead http://dummy.domain.com/home/area/section – draskomikic Aug 22 '14 at 15:54
0

I finally success to prevent directory traversal using Apache mod_security and this rule in mod_security.conf

SecRule REQUEST_URI_RAW "\.{1,2}\/?" "log,deny,msg:'Directory Traversal Attack Detected - %{MATCHED_VAR_NAME}:%{MATCHED_VAR}',id:123"

draskomikic
  • 167
  • 2
  • 9
  • Also managed to achieve same thing using mod_rewrite and rules: RewriteEngine On RewriteCond %{THE_REQUEST} (\.{1,}\/)|(\/{2,}) [NC] RewriteRule ^(.*)$ /$1 [R=400,L,NE] – draskomikic Aug 25 '14 at 15:14