我正在编写一个需要将用户提供的输入转换为文件名的IRC和XMPP机器人。我已经编写了一个函数来执行此操作。它足够健全吗?
以下是代码:
allowednamechars = string.ascii_letters + string.digits + '_+/$.-'
def stripname(name, allowed=""):
""" strip all not allowed chars from name. """
n = name.replace(os.sep, '+')
n = n.replace("@", '+')
n = n.replace("#", '-')
n = n.replace("!", '.')
res = u""
for c in n:
if ord(c) < 31: continue
elif c in allowednamechars + allowed: res += c
else: res += "-" + str(ord(c))
return res
这是一个白名单,带有额外的代码来删除控制字符并替换os.sep,以及一些repaces以使文件名Google App Engine兼容。
有问题的机器人位于http://jsonbot.googlecode.com。
那你觉得怎么样?
答案 0 :(得分:0)
您可能会考虑只执行base64.urlsafe_b64encode(name)
,它将始终生成一个安全的名称,除非您真的需要一个人类可读的文件名。否则,边缘情况的数量很长,如果你忘记其中一个,你就会遇到安全问题。
答案 1 :(得分:0)
urllib.quote(name.encode("utf8"))
会产生人类可读的东西,这也应该是安全的。例如:
In [1]: urllib.quote(u"foo bar$=+:;../..(boo)\u00c5".encode('utf8'))
Out[1]: 'foo%20bar%24%3D%2B%3A%3B../..%28boo%29%C3%85'