2

I am writing a server application on node js. Operating system is Linux.

I receive filename as a plain string, so it can be hacked. Then I concatenate the filename string and path string like this:

filepath = '/home/www/upload/' + filename;

I want to protect an upload script from writing to anywhere except upload folder [or it's subfolders : optional], using my application logic, not Linux.

My current naive solution is blocking filenames which have .. substring. I don't care if someone has filename with two dots.

Sure, when it comes to security, I have to ask the audience for advice: can anything go wrong?

TheHippo
  • 61,720
  • 15
  • 75
  • 100
Dan
  • 55,715
  • 40
  • 116
  • 154
  • 1
    I would follow some of the guidances from http://stackoverflow.com/questions/11100821/javascript-regex-for-validating-filenames Basically, avoid anything not being `[a-zA-Z0-9]` and just a few more characters. – fedorqui Oct 25 '13 at 12:28
  • @fedorqui I think if would be better to use node's filesystem or path API. – TheHippo Oct 25 '13 at 13:30

2 Answers2

2

I'd use path.resolve for this: http://nodejs.org/api/path.html

Try filepath = path.resolve(filepath)

and then

goodPath = filepath.startsWith('/your/allowed/upload/dir');

ikari
  • 331
  • 2
  • 8
0
if (path.basename(filepath) != filename) {
  // reject that sukka
}
SilverlightFox
  • 32,436
  • 11
  • 76
  • 145