search
HomeBackend DevelopmentPHP Tutorial用户上传a.jpg文件,文件内容实际为php代码,会不会有安全问题?如果有,如何防止?

用户上传a.jpg文件,文件内容实际为php代码,会不会有安全问题?如果有,如何防止?

回复内容:

用户上传a.jpg文件,文件内容实际为php代码,会不会有安全问题?如果有,如何防止?

设置 mimetype

有风险,判断文件头是不完全的。你可以参看

http://zone.wooyun.org/content/5429

你需要在服务端禁止执行这些代码。简单的说,就是不管他的扩展名是什么,反正这个目录是静态的,不要丢改cgi之类的东西。

如果你是虚拟主机环境,你可能面临对主机环境无法深度配置的问题。
如果你想求个放心,我建议把这些用户上传的静态文件,托管到又拍云、七牛云等外部的CDN服务器上去。
放到外边去就不可能(也不用关心)有php会被意外执行的安全问题了。对于虚拟主机跑得起来的小站,花费也不多甚至几近免费。


10-23补充:想到一个正面突破的好办法。

用户上传之后,存储成任意安全的扩展名(例:raw、bin等)。在需要调用的时候,通过一个php脚本作为中间层传递文件内容(读取请求的文件名,找到文件,把图片文件类型对应的MIME写入HTTP头,图片文件实际的内容写入HTTP正文)。

例如:http://example.com/attach.php?id=13776
也可以用一种更加优雅的语法:http://example.com/attach.php/13776.jpg
http://example.com/attach.php/13776
甚至动用rewrite实现类似http://example.com/attach/13776的URL。

这样会收到若干好处:

  1. 绝对安全。所有的恶意代码都绝对不经执行,通过HTTP原样返回浏览器,给攻击者个自讨没趣。
  2. URL显而易见,符合REST原则,外人无法从URL猜测程序的目录结构。
  3. 经过PHP,就方便实现鉴权、防盗链等若干实用功能。
  4. 保持网址恒定性,无论是程序目录结构修改,还是静态文件将来托管到CDN上,网址都保持不变。

据我所知 原来有个漏洞,如果目录名是 a.php 然后目录里的 a.jpg 会被当作 PHP 执行。

直接上图片处理,gd或者imagick等,重新存一下

用图形库验证一下。不是图片不让上传。

当 nginx 搭配 php-cgi 时候,在路径解析问题上可能要防下。当年争议比较大的就是 cgi.fix_pathinfo 的问题。另外当nginx 处于反代模式时。mimetype 设置的对,应该没什么问题。

如果是Nginx的话可以考虑区分jpg和php的文件夹,即使上传了jpg但是路径不对也不会被执行0.0

<code>chmod 0444 a.jpg
</code>

禁止文件执行

gd库获取一下图片的长宽大小,为0阻止。

很简单,检测文件头,如果不是规定的类型就删除。

以下为摘抄自网络的代码示例。

<?php   

function file_type($filename)
{
    $file = fopen($filename, "rb");
    $bin = fread($file, 2); //只读2字节
    fclose($file);
    $strInfo = @unpack("C2chars", $bin);
    $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
    $fileType = '';
    switch ($typeCode)
    {
        case 7790:
            $fileType = 'exe';
            break;
        case 7784:
            $fileType = 'midi';
            break;
        case 8297:
            $fileType = 'rar';
            break;        
        case 8075:
            $fileType = 'zip';
            break;
        case 255216:
            $fileType = 'jpg';
            break;
        case 7173:
            $fileType = 'gif';
            break;
        case 6677:
            $fileType = 'bmp';
            break;
        case 13780:
            $fileType = 'png';
            break;
        default:
            $fileType = 'unknown: '.$typeCode;
    }

    //Fix
    if ($strInfo['chars1']=='-1' AND $strInfo['chars2']=='-40' ) return 'jpg';
    if ($strInfo['chars1']=='-119' AND $strInfo['chars2']=='80' ) return 'png';

    return $fileType;
}

echo file_type('start.php');   // 6063 or 6033

摘自:http://justcoding.iteye.com/blog/891241

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools