Question

I have a predefined path which is concatenated with a userinput to delete a specific directory. The current code looks like this, and given such a userinput will harm very badly:

import os
import shutil
userinput = '../../'
path = os.path.join('/my/self/defined/path', userinput)
shutil.rmtree(path)

This will obviously allow the user to delete any files or directories. What is a good way to “jail” the user, so it will only be possible to enter any path below /my/self/defined/path, taking care of ../ or starting the string with / and all other malicious input I might not think of?

Was it helpful?

Solution

How about

my = os.path.abspath('/my/self/defined/path')
new = os.path.abspath(path)
if len(new) < len(my) or not new.startswith(my):
   print 'bzzzt'

http://docs.python.org/2/library/os.path.html

OTHER TIPS

import os
import shutil
import sys
userinput = '../../'
selfdefinedpath = '/my/self/defined/path'
path = os.path.join(selfdefinedpath, userinput)
if not selfdefinedpath in os.path.realpath(path):
  print 'not proper path %s' % path
  sys.exit()
shutil.rmtree(path)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top