2

問題:

私はこの人工的なサンプル関数を持っています:

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壊滅的なバックトラッキングをシミュレートし、関数をorのように強制的にハングさせるために、いくつかの「邪悪な」正規表現を試しましたが、関数はすぐ(a+)+に戻り、問題の兆候はありません。False

4

1 に答える 1

2

これを行う方法はたくさんあります。たとえば、有効な正規表現ではない単語:

>>> 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.
于 2016-07-01T23:08:22.193 に答える