This is a bad regex.
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF)$
Let's do it part by part.
([a-zA-Z]:)
This requires the file path starts with a driveletter like C:
, d:
, etc.
(\\{2}\w+)\$?)
\\{2}
means the backslash repeated twice (note the \
needs to be escaped), followed by some alphanumerics (\w+
), and then maybe a dollar sign (\$?
). This is the host part of UNC path.
([a-zA-Z]:)|(\\{2}\w+)\$?)
The |
means "or". So either starts with a drive letter or an UNC path. Congratulations for kicking out non-Windows users.
(\\(\w[\w].*))
This should the directory part of the path, but actually is 2 alphanumerics followed by anything except new lines (.*
), like \ab!@#*(#$*)
.
The proper regex for this part should be (?:\\\w+)+
(.jpg|.JPG|.gif|.GIF)$
This means the last 3 characters of the path must be jpg
, JPG
, gif
or GIF
. Note that .
is not a dot, but matches anything except \n
, so a filename like haha.abcgif
or malicious.exe\0gif
will pass.
The proper regex for this part should be \.(?:jpg|JPG|gif|GIF)$
Together,
^(([a-zA-Z]:)|(\\{2}\w+)\$?)(\\(\w[\w].*))(.jpg|.JPG|.gif|.GIF)$
will match
D:\foo.jpg
\\remote$\dummy\..\C:\Windows\System32\Logo.gif
C:\Windows\System32\cmd.exe;--gif
and will fail
/home/user/pictures/myself.jpg
C:\a.jpg
C:\d\e.jpg
The proper regex is /\.(?:jpg|gif)$/i
, and check whether the uploaded file is really an image on the server side.