PHP文件上传安全
2023-09-27 14:25:41 时间
文件上传漏洞等危害
攻击者上传shell脚本,借助脚本控制服务器,随意执行命令。
漏洞举例
<?php
$dir = 'uploads/';
$file = $dir . basename($_FILES['file']['name']);
move_upload_file( $_FILE['file']['tmp_name'], $file);
?>
如果攻击者上传如脚本文件file.php
<?php
system($_GET['shell']);
?>
则可以通过http://host/uploads/file.php?shell=ls -la,查看服务器目录信息,并且可以执行任何shell命令。
过滤上传文件类型和文件扩展名
<?php
if( $_FILEs['file']['type'] != 'image/gif' ){
die('类型错误');
}
?>
但是如果攻击者通过修改POST数据包中的Content-Type:text/plain字段为Content-Type:image/git,则可跳过检验成功上传,所以还需检查文件扩展名。
<?php
$whiteList = [
'.jpg', '.gif', '.png', '.jpeg',
];
$ext = substr( $_FILES['file']['name'], -4 );
if( !in_array( $ext, $whiteList ) ){
die('类型错误');
}
?>
综合防护
- 白名单限制文件类型
- 白名单限制文件扩展名
- 随机文件名
- 上传目录放到项目可执行目录之外
- 禁止上传文件的执行权限
- 如果可以的话,通过php.ini配置禁用危险函数: disable_function = system,exec,scandir,shell_exec等
<?php
class FileSecurity
{
const DIR = '/data/uploads/';
private $whiteExt = [
'.jpg', '.gif', '.png', '.jpeg',
];
private $whiteType = [
'image/jpg', 'image/gif', 'image/png', 'image/jpeg',
];
private $nameChars = [
'a', 'b', 'c', 'd', 'e', 'f', 'g',
'h', 'i', 'j', 'k', 'l', 'm', 'n',
'o', 'p', 'q', 'r', 's', 't', 'u',
'v', 'w', 'x', 'y', 'z',
'A', 'B', 'C', 'D', 'E', 'F', 'G',
'H', 'I', 'J', 'K', 'L', 'M', 'N',
'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z',
'1', '2', '3', '4', '5', '6', '7', '8', '9', '0',
];
public function filter($file, $type)
{
if ( !in_array($type, $this->whiteType) ){
return false;
}
$ext = substr($file, -4);
if ( !in_array($ext, $this->whiteExt) ){
return false;
}
}
public function getFileName()
{
$len = count($this->nameChars) - 1;
shuffle($this->nameChars);
$name = '';
for ($i = 0; $i < $len; $i++){
$name .= $this->nameChars[ mt_rand(0, $len) ];
}
return $name;
}
public function chmod($file)
{
$file = self::DIR . $file;
@chmod($file, 0444);
}
}
?>
相关文章
- PHP删除当前目录及其目录下的所有文件
- PHP的类,abstract类,interface及关键字extends和implements
- PHP获得真实客户端的真实IP REMOTE_ADDR,HTTP_CLIENT_IP,HTTP_X_FORWARDED_FOR
- PHP读取CSV文件
- php $_FILES处理文件上传
- php 上传大文件主要涉及配置upload_max_filesize和post_max_size两个选项
- php-fpm进程管理方式(static和dynamic)
- 【转】JQuery插件ajaxFileUpload 异步上传文件(PHP版)
- Apache 2 解析html中的php
- PHP判断文件是否被引入的方法get_included_files
- php写文件操作
- 【PHP】原生验证码
- PHP上传文件到七牛(Qiniu)
- php文件上传相关知识点回顾
- php 文件加载方式
- php实现多文件上传
- php方法综述除去换行符(PHP_EOL使用变量)
- php阅读csv文件类
- php实现简单的文件上传和验证
- php 上传文件失败$_FILES tmp_name 为空
- MySQL+PHP大文件读取和写库
- 69.网络安全渗透测试—[SQL注入篇8]—[MySQL+PHP-报错注入读写文件]
- 66.网络安全渗透测试—[SQL注入篇5]—[MySQL+PHP-手工注入简单示例]
- 【PHP】PHP使用PHPExcel生成Excel表格文件(附带随机生成英文名函数)
- php编写RSS源