Pythonにおけるホワイトリスト形式のhtmlエスケープ 2015年3月16日
Pythonでもホワイトリスト形式のエスケープがしたい.
今回用いたのは以下のライブラリ
Python2系, 3系のどちらにも対応している.
導入
$ pip install bleach
使用方法等
テストコード
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
import bleach
TAG = ['img']
ATTR = {'img':['src']}
test1 = '<a href="http://ytn86.net">here</a>'
test2 = '<a href="javascript:alert(1)">here</a>'
test3 = '<img src="x" onerror=alert(1) >'
print('# test1')
print(bleach.clean(test1) + 'n')
print('# test2')
print(bleach.clean(test2) + 'n')
print('# test3 - not specify tag and attribute')
print(bleach.clean(test3) + 'n')
print('# text3 - specify tag and attribute')
print(bleach.clean(test3, tags=TAG, attributes=ATTR))
実行結果
# test1 <a href="http://ytn86.net">here</a> # test2 <a>here</a> # test3 - not specify tags and attributes <img src="x" onerror="alert(1)" "=""> # text3 - specify tag and attribute <img src="x">
その他
世の中からXSSはやく消えてくれたのむ
Leave a Reply