目录
转义
{{ title }}
hello
world
hello<br />world
{{ noescape(title) }}
exec 的安全问题
打赏支持我写出更多好文章,谢谢!
关于作者:mozillazg
首页 web前端 html教程 让我们一起来构建一个模板引擎(四)_html/css_WEB-ITnose

让我们一起来构建一个模板引擎(四)_html/css_WEB-ITnose

Jun 24, 2016 am 11:15 AM

在 上篇文章 中我们的模板引擎实现了对 include 和 extends 的支持, 到此为止我们已经实现了模板引擎所需的大部分功能。 在本文中我们将解决一些用于生成 html 的模板引擎需要面对的一些安全问题。

转义

首先要解决的就是转义问题。到目前为止我们的模板引擎并没有对变量和表达式结果进行转义处理, 如果用于生成 html 源码的话就会出现下面这样的问题 ( template3c.py ):

>>> from template3c import Template>>> t = Template('<h1 id="title">{{ title }}</h1>')>>> t.render({'title': 'hello<br />world'})'<h1 id="hello-br-world">hello<br />world</h1>'
登录后复制

很明显 title 中包含的标签需要被转义,不然就会出现非预期的结果。 这里我们只对 & " ' > < 这几个字符做转义处理,其他的字符可根据需要进行处理。

html_escape_table = {    '&': '&',    '"': '"',    '\'': '&apos;',    '>': '>',    '<': '<',}def html_escape(text):    return ''.join(html_escape_table.get(c, c) for c in text)
登录后复制

转义效果:

>>> html_escape('hello<br />world')'hello<br />world'
登录后复制

既然有转义自然也要有禁止转义的功能,毕竟不能一刀切否则就丧失灵活性了。

class NoEscape:    def __init__(self, raw_text):        self.raw_text = raw_textdef escape(text):    if isinstance(text, NoEscape):        return str(text.raw_text)    else:        text = str(text)        return html_escape(text)def noescape(text):    return NoEscape(text)
登录后复制

最终我们的模板引擎针对转义所做的修改如下(可以下载 template4a.py ):

class Template:    def __init__(self, ..., auto_escape=True):        ...        self.auto_escape = auto_escape        self.default_context.setdefault('escape', escape)        self.default_context.setdefault('noescape', noescape)        ...    def _handle_variable(self, token):        if self.auto_escape:            self.buffered.append('escape({})'.format(variable))        else:            self.buffered.append('str({})'.format(variable))    def _parse_another_template_file(self, filename):        ...        template = self.__class__(                ...,                auto_escape=self.auto_escape        )        ...class NoEscape:    def __init__(self, raw_text):        self.raw_text = raw_texthtml_escape_table = {    '&': '&',    '"': '"',    '\'': '&apos;',    '>': '>',    '<': '<',}def html_escape(text):    return ''.join(html_escape_table.get(c, c) for c in text)def escape(text):    if isinstance(text, NoEscape):        return str(text.raw_text)    else:        text = str(text)        return html_escape(text)def noescape(text):    return NoEscape(text)
登录后复制

效果:

>>> from template4a import Template>>> t = Template('<h1 id="title">{{ title }}</h1>')>>> t.render({'title': 'hello<br />world'})'<h1 id="hello-lt-br-gt-world">hello<br />world</h1>'>>> t = Template('<h1 id="noescape-title">{{ noescape(title) }}</h1>')>>> t.render({'title': 'hello<br />world'})'<h1 id="hello-br-world">hello<br />world</h1>'>>>
登录后复制

exec 的安全问题

由于我们的模板引擎是使用 exec 函数来执行生成的代码的,所以就需要注意一下 exec 函数的安全问题,预防可能的服务端模板注入攻击(详见 使用 exec 函数时需要注意的一些安全问题 )。

首先要限制的是在模板中使用内置函数和执行时上下文变量( template4b.py ):

class Template:    ...    def render(self, context=None):        """渲染模版"""        namespace = {}        namespace.update(self.default_context)        namespace.setdefault('__builtins__', {})   # <---        if context:            namespace.update(context)        exec(str(self.code_builder), namespace)        result = namespace[self.func_name]()        return result
登录后复制

效果:

>>> from template4b import Template>>> t = Template('{{ open("/etc/passwd").read() }}')>>> t.render()Traceback (most recent call last):  File "", line 1, in module>  File "/Users/mg/develop/lsbate/part4/template4b.py", line 245, in render    result = namespace[self.func_name]()  File "", line 3, in __func_nameNameError: name 'open' is not defined
登录后复制

然后就是要限制通过其他方式调用内置函数的行为:

>>> from template4b import Template>>> t = Template('{{ escape.__globals__["__builtins__"]["open"]("/etc/passwd").read()[0] }}')>>> t.render()'#'>>>>>> t = Template("{{ [x for x in [].__class__.__base__.__subclasses__() if x.__name__ == '_wrap_close'][0].__init__.__globals__['path'].os.system('date') }}")>>> t.render()Mon May 30 22:10:46 CST 2016'0'
登录后复制

一种解决办法就是不允许在模板中访问以下划线 _ 开头的属性。 为什么要包括单下划线呢,因为约定单下划线开头的属性是约定的私有属性, 不应该在外部访问这些属性。

这里我们使用 dis 模块来帮助我们解析生成的代码,然后再找出其中的特殊属性。

import disimport ioclass Template:    def __init__(self, ..., safe_attribute=True):        ...        self.safe_attribute = safe_attribute    def render(self, ...):        ...        func = namespace[self.func_name]        if self.safe_attribute:            check_unsafe_attributes(func)        result = func()def check_unsafe_attributes(code):    writer = io.StringIO()    dis.dis(code, file=writer)    output = writer.getvalue()    match = re.search(r'\d+\s+LOAD_ATTR\s+\d+\s+<span class='MathJax_Preview'><img src='http://python.jobbole.com/wp-content/plugins/latex/cache/tex_528889fac10d588d0c4bcca5fc09d9ee.gif'   style="max-width:90%" class='tex' alt="(?P<attr>_[^" /></span><script type='math/tex'>(?P<attr>_[^</script>]+)<span class='MathJax_Preview'><img src='http://python.jobbole.com/wp-content/plugins/latex/cache/tex_8e9262bd0cfe5666042f5b56e0808688.gif'   style="max-width:90%" class='tex' alt="',                      output)    if match is not None:        attr = match.group('attr')        msg = "access to attribute '{0}' is unsafe.".format(attr)        raise AttributeError(msg)
登录后复制

效果:

>>> from template4c import Template>>> t = Template("{{ [x for x in [].__class__.__base__.__subclasses__() if x.__name__ == '_wrap_close'][0].__init__.__globals__['path'].os.system('date') }}")>>> t.render()Traceback (most recent call last):  File "<stdin>", line 1, in <module>  File "/xxx/lsbate/part4/template4c.py", line 250, in render    check_unsafe_attributes(func)  File "/xxx/lsbate/part4/template4c.py", line 296, in check_unsafe_attributes    raise AttributeError(msg)AttributeError: access to attribute '__class__' is unsafe.>>>>>> t = Template('<h1 id="title">{{ title }}</h1>')>>> t.render({'title': 'hello<br />world'})'<h1 id="hello-lt-br-gt-world">hello<br />world</h1>'
登录后复制

这个系列的文章到目前为止就已经全部完成了。

如果大家感兴趣的话可以尝试使用另外的方式来解析模板内容, 即: 使用词法分析/语法分析的方式来解析模板内容(欢迎分享实现过程)。

P.S. 整个系列的所有文章地址:

  • 让我们一起来构建一个模板引擎(三)
  • 让我们一起来构建一个模板引擎(二)
  • 让我们一起来构建一个模板引擎(一)

P.S. 文章中涉及的代码已经放到 GitHub 上了: https://github.com/mozillazg/lsbate

打赏支持我写出更多好文章,谢谢!

打赏作者

打赏支持我写出更多好文章,谢谢!

关于作者:mozillazg

好好学习,天天向上。 个人主页 · 我的文章 · 1 ·    

本站声明
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

SublimeText3汉化版

SublimeText3汉化版

中文版,非常好用

禅工作室 13.0.1

禅工作室 13.0.1

功能强大的PHP集成开发环境

Dreamweaver CS6

Dreamweaver CS6

视觉化网页开发工具

SublimeText3 Mac版

SublimeText3 Mac版

神级代码编辑软件(SublimeText3)

HTML容易为初学者学习吗? HTML容易为初学者学习吗? Apr 07, 2025 am 12:11 AM

HTML适合初学者学习,因为它简单易学且能快速看到成果。1)HTML的学习曲线平缓,易于上手。2)只需掌握基本标签即可开始创建网页。3)灵活性高,可与CSS和JavaScript结合使用。4)丰富的学习资源和现代工具支持学习过程。

HTML,CSS和JavaScript的角色:核心职责 HTML,CSS和JavaScript的角色:核心职责 Apr 08, 2025 pm 07:05 PM

HTML定义网页结构,CSS负责样式和布局,JavaScript赋予动态交互。三者在网页开发中各司其职,共同构建丰富多彩的网站。

HTML中起始标签的示例是什么? HTML中起始标签的示例是什么? Apr 06, 2025 am 12:04 AM

AnexampleOfAstartingTaginHtmlis,beginSaparagraph.startingTagSareEssentialInhtmlastheyInitiateEllements,defiteTheeTheErtypes,andarecrucialforsstructuringwebpages wepages webpages andConstructingthedom。

了解HTML,CSS和JavaScript:初学者指南 了解HTML,CSS和JavaScript:初学者指南 Apr 12, 2025 am 12:02 AM

WebDevelovermentReliesonHtml,CSS和JavaScript:1)HTMLStructuresContent,2)CSSStyleSIT和3)JavaScriptAddSstractivity,形成thebasisofmodernWebemodernWebExexperiences。

网页批注如何实现Y轴位置的自适应布局? 网页批注如何实现Y轴位置的自适应布局? Apr 04, 2025 pm 11:30 PM

网页批注功能的Y轴位置自适应算法本文将探讨如何实现类似Word文档的批注功能,特别是如何处理批注之间的间�...

Gitee Pages静态网站部署失败:单个文件404错误如何排查和解决? Gitee Pages静态网站部署失败:单个文件404错误如何排查和解决? Apr 04, 2025 pm 11:54 PM

GiteePages静态网站部署失败:404错误排查与解决在使用Gitee...

HTML,CSS和JavaScript:Web开发人员的基本工具 HTML,CSS和JavaScript:Web开发人员的基本工具 Apr 09, 2025 am 12:12 AM

HTML、CSS和JavaScript是Web开发的三大支柱。1.HTML定义网页结构,使用标签如、等。2.CSS控制网页样式,使用选择器和属性如color、font-size等。3.JavaScript实现动态效果和交互,通过事件监听和DOM操作。

如何用CSS3和JavaScript实现图片点击后周围图片散开并放大效果? 如何用CSS3和JavaScript实现图片点击后周围图片散开并放大效果? Apr 05, 2025 am 06:15 AM

实现图片点击后周围图片散开并放大效果许多网页设计中,需要实现一种交互效果:点击某张图片,使其周围的...

See all articles