0

I wrote a function in Python, that must return file from specific folder and all subfolders. File name taken from function parameter:

def ReturnFile(fileName)
  return open("C:\\folder\\" + fileName,"r")

But as fileName you can pass for example: "..\\Windows\\passwords.txt" or some unicode symbols for dots.

How to fix it? Some RegExp maybe?

SilentGhost
  • 307,395
  • 66
  • 306
  • 293
  • What do you want to do? Check that the string given as filename is a valid filename? – luc Jul 24 '09 at 09:40
  • I want that program can return files from only one folder(and subfolders), and be shure that nobody can give parametr with ex. ".." and read all files on server. –  Jul 24 '09 at 09:54
  • See: http://stackoverflow.com/questions/120656/directory-listing-in-python, http://stackoverflow.com/questions/973473/getting-a-list-of-all-subdirectories-in-the-current-directory – S.Lott Jul 24 '09 at 12:21

2 Answers2

4

The os.path.normpath function normalizes a given path py resolving things like "..". Then you can check if the resulting path is in the expected directory:

def ReturnFile(fileName)
  norm = os.path.abspath("C:\\folder\\" + fileName)
  if not norm.startswith("C:\\folder\\"):
    raise Exception("Invalid filename specified")
  return open(norm,"r")
sth
  • 222,467
  • 53
  • 283
  • 367
1

How about this:

import os

_BASE_PATH= "C:\\folder\\"

def return_file(file_name):
    "Return File Object from Base Path named `file_name`"
    os.path.normpath(file_name).split(os.path.sep)[-1]
    return(open(_BASE_PATH+file_name))