python / python/cpython

Escaping the `repl` argument to `re.sub()`, `re.subn()`

未關閉
#128,138 2 則留言 0 個 reaction 已指派 0 人 在 GitHub 檢視

還沒有人認領這個 Issue。

docs topic-regex
主要語言
Python
星號
77.2k
分支
35.9k
PR 合併指標
PR 指標待擷取

描述

Documentation

It's not immediately obvious how to escape the repl (replacement for matches) argument to re.sub() and re.subn() if repl is chosen by a potentially hostile actor. Obviously, re.escape() isn't the answer, as that escapes far too much.

The right answer seems to be escaped_repl = raw_repl.replace(bslash, bslash*2) where bslash = '\\'. It might be worth adding this to the documentation.

Here's the code I used to empirically validate the "right answer" given above (checked on Python 3.8 & 3.12):

from __future__ import annotations
import re, sys

def escape_re_sub_repl(repl: str) -> str:

    return repl.replace('\\', '\\\\')

def test_escape_re_sub_repl() -> None:

    backslash = '\\'
    assert len(backslash) == 1

    base_regex = 'TARGET'
    assert base_regex == re.escape(base_regex)
    base_prefix = 'BEFORE:'
    base_suffix = ':AFTER'
    base_input = f'{base_prefix}{base_regex}{base_suffix}'

    base_chars = tuple(chr(p) for p in range(sys.maxunicode + 1))
    escaped_chars = tuple(f'{backslash}{c}' for c in base_chars)
    test_cases = base_chars + escaped_chars
    assert {len(f) for f in test_cases} == {1, 2}

    for raw in test_cases:
        repl = escape_re_sub_repl(raw)
        got, change_count = re.subn(base_regex, repl, base_input)
        assert change_count == 1
        assert got == f'{base_prefix}{raw}{base_suffix}'

貢獻指南

開啟貢獻指南

從這裡開始

  1. 先讀完整個 Issue,再讀專案的貢獻指南。
  2. 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
  3. Fork 儲存庫,在一個分支上完成修改。
  4. 送出 Pull Request,並在描述裡引用這個 Issue 編號。

研究方向

先找到 re.sub() 和 re.subn() 的文件,以及它們的替換字串規則。檢查現有的 re.escape() 相關指南,接著記錄針對惡意替換文字採用反斜線加倍的方法,並根據提供的範例進行驗證;當相關文件中的安全逸出指南清楚明確時,即表示完成。

由索引模型根據 Issue 內容生成。

評估

技術堆疊
python
領域
documentation
Issue 類型
文件
難度
2/5
預估耗時
1-3 小時
活躍度
停滯
描述清晰度
基本清楚
新手友好度
45/100

把新 issue 寄到你的電子郵件信箱

精選適合新手參與的 GitHub issue 摘要。