HTML のエスケープ

flask-app プロジェクトで pages/a7.py を開くと、render_template_string がここでも使われていることが分かります。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from flask import (
    Blueprint,
    request,
    render_template_string
)

bp = Blueprint(
    "a7", __name__,
    template_folder='templates',
    static_folder='static'
)

@bp.route("/A7")
def a7():
    name = request.args.get("name", "")
    with open("templates/a7.html") as f:
        template = f.read()
    content = template.replace("{{ name }}", name)
    
    return render_template_string(content)

SSTI の脆弱性を修正した方法と同様に、HTML を厳密かつ迅速に自動エスケープする render_template を使用できます。

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
from flask import (
    Blueprint,
    request,
    render_template
)

bp = Blueprint(
    "a7", __name__,
    template_folder='templates',
    static_folder='static'
)

@bp.route("/A7")
def a7():
    name = request.args.get("name", "")
    return render_template("a7.html", name=name)

これを防ぐさらに良い方法は、入力をサニタイズすることです。Pythonには、Bleach のようなこれに特化したライブラリがあります。