【问题标题】:Proving a function has no proper input validation证明一个函数没有正确的输入验证
【发布时间】:2016-07-01 23:01:17
【问题描述】:

问题:

我有这个人工示例函数:

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

问题:

我如何测试这个函数以证明没有正确的正则表达式转义或输入清理

换句话说,我应该提供words 列表中的哪些项目来“破坏”此功能?


我尝试了几个“邪恶”的正则表达式来模拟灾难性的回溯并强制函数像 (x+x+)+y(a+)+ 一样挂起,但函数只返回 False 立即没有任何问题的迹象。

【问题讨论】:

  • 一个总是返回“true”的空字符串(不管其他词).

标签: python regex input-sanitization


【解决方案1】:

有很多方法可以做到这一点。例如,一个不是有效正则表达式的词:

>>> 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.

【讨论】:

  • 哦,是的,“没什么可重复的”很好。谢谢!我们能否模拟灾难性的回溯并查看函数的行为非常缓慢?
  • @alecxe:是的,那也行。我添加了一个灾难性回溯的示例。
猜你喜欢
  • 1970-01-01
  • 2023-02-04
  • 2013-12-18
  • 2016-01-29
  • 1970-01-01
  • 1970-01-01
  • 2016-01-24
  • 2012-10-28
  • 2013-01-28
相关资源
最近更新 更多