证明函数没有正确的输入验证
Proving a function has no proper input validation
问题:
我有这个人工示例函数:
def test_function(target, words):
pattern = re.compile(r"|".join(words))
return bool(pattern.search(target))
获取单词列表并动态构建正则表达式模式而无需适当转义列表中的单词。
使用示例:
text = "hello world!"
print(test_function(text, ["test"])) # prints False
print(test_function(text, ["hello"])) # prints True
print(test_function(text, ["test", "world"])) # prints True
问题:
我如何测试此函数以证明没有正确的正则表达式转义或输入清理?
换句话说,我应该向 "break" 这个函数提供 words
列表中的哪些项目?
我已经尝试了几个 "evil" 正则表达式来模拟灾难性回溯并强制函数像 (x+x+)+y
或 (a+)+
一样挂起,但函数只是 returns False
立即并且没有任何问题迹象。
有很多方法可以做到这一点。例如,一个不是有效正则表达式的词:
>>> test_function('a', ['*'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in test_function
File "/usr/lib64/python2.6/re.py", line 190, in compile
return _compile(pattern, flags)
File "/usr/lib64/python2.6/re.py", line 245, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat
或匹配正则表达式所有内容的单词:
>>> test_function('a', ['.*'])
True
或一个不符合正则表达式的词:
>>> test_function('$^', ['$^'])
False
或以反斜杠结尾并转义 |
:
的单词
>>> test_function('a', ['\', 'a'])
False
灾难性回溯也有效:
>>> test_function('a'*100, ['(a+)+b'])
# Hangs.
问题:
我有这个人工示例函数:
def test_function(target, words):
pattern = re.compile(r"|".join(words))
return bool(pattern.search(target))
获取单词列表并动态构建正则表达式模式而无需适当转义列表中的单词。
使用示例:
text = "hello world!"
print(test_function(text, ["test"])) # prints False
print(test_function(text, ["hello"])) # prints True
print(test_function(text, ["test", "world"])) # prints True
问题:
我如何测试此函数以证明没有正确的正则表达式转义或输入清理?
换句话说,我应该向 "break" 这个函数提供 words
列表中的哪些项目?
我已经尝试了几个 "evil" 正则表达式来模拟灾难性回溯并强制函数像 (x+x+)+y
或 (a+)+
一样挂起,但函数只是 returns False
立即并且没有任何问题迹象。
有很多方法可以做到这一点。例如,一个不是有效正则表达式的词:
>>> test_function('a', ['*'])
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 2, in test_function
File "/usr/lib64/python2.6/re.py", line 190, in compile
return _compile(pattern, flags)
File "/usr/lib64/python2.6/re.py", line 245, in _compile
raise error, v # invalid expression
sre_constants.error: nothing to repeat
或匹配正则表达式所有内容的单词:
>>> test_function('a', ['.*'])
True
或一个不符合正则表达式的词:
>>> test_function('$^', ['$^'])
False
或以反斜杠结尾并转义 |
:
>>> test_function('a', ['\', 'a'])
False
灾难性回溯也有效:
>>> test_function('a'*100, ['(a+)+b'])
# Hangs.