安全使用shutil.rmtree / os.path.join和Directory Traversal

时间:2013-08-21 12:55:10

标签: python security path escaping shutil

我有一个预定义的路径,它与userinput连接以删除特定目录。当前代码看起来像这样,并且如果这样的用户输入将会非常严重地损坏:

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

这显然允许用户删除任何文件或目录。什么是“监禁”用户的好方法,因此只能输入/my/self/defined/path以下的任何路径,负责../或使用/和其他所有字符串开始字符串我可能没想到的恶意输入?

2 个答案:

答案 0 :(得分:0)

怎么样

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

答案 1 :(得分: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)