2

I am trying to create a Regular Expression for validation to stop directory traversal attacks. I want the user to be able to specify anything within the C:\temp directory. So the below is fine

c:\temp\hello\world.txt

but obviously, the directory below would be unacceptable.

c:\temp\..\Windows\world.txt

My issue is that I am unsure how I can allow one period (.) but not two in a row. I need one obviously for extensions i.e. (world.txt) but can not have two. This is what I have so far:

^([c]:\\)\\?(temp)([^(\.\.)]){0,200}$

So I am trying to say not two periods [^\.\.] and the \\? part is because it accepts escaped directories as well. Thanks in advance.

melpomene
  • 84,125
  • 8
  • 85
  • 148
meowcat
  • 171
  • 1
  • 12

1 Answers1

4

You may try with this:

^(c:\\)\\?(temp)(?!.*\.\.).{0,200}$

Here I have modified your regex a bit to ensure that there is no consecutive dots.

  1. (?!.*\.\.) This negative look ahead starts scanning right after c:\temp part is found. Itd will scan till the end of string and if it returns true (which means no consecutive dots) then the following part takes action.
  2. .{0,200} the dot here matches any character from 0 to 200 times

Regex Demo

Mustofa Rizwan
  • 10,215
  • 2
  • 28
  • 43
  • 1
    Thanks, to all who replied, I am looking at alternative methods, but have marked Rizwan's answer as correct... as it was the only actual answer and the regular expression works :). – meowcat Nov 09 '17 at 02:23