1

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?

2 Answers 2

0

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

Sign up to request clarification or add additional context in comments.

7 Comments

That would prevent deleting for example /my/self/, but if the user enters ../../some/where/else, he might get to a directory outside of the defined path which could be also longer than the original one. Better than no filtering of course, but still too dangerous.
In that case, it would trip the new.startswith(my) test.
Oh, I wonder how I could miss reading the second condition, sorry. But the check for the length can be left out completely, couldn’t it? Also, I wonder if realpath or abspath should be preferred.
The length check could be eliminated.
wrap abspath in os.path.normpath() to remove things like ../. realpath is good, but you'll also want to call it on '/my/self/defined/path' in case its symlinked.
|
0
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)

2 Comments

I would replace selfdefinedpath in os.path.realpath(path) with os.path.realpath(path).startswith(selfdefinedpath), otherwise /some/where/my/self/defined/path/foo/bar could be deleted (although it is pretty unlikely). Otherwise the solution seems pretty solid to me, but I will wait a bit before setting it to accepted, maybe someone else finds another issue.
Yes you are wright it is highly unlikely some one will provide such input, but never take chances specially if security is the main concern.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.