如何将扩展程序过滤到已上传或发布到PHP Web服务器的文件



我从c#发出了一个帖子函数,将文件发送到网络服务器(PHP),每个上传的每个文件都不会被扩展程序过滤,我担心如果有坏人将恶意文件(例如Webshells或其他恶意软件)上传到我的Web服务器中。我只想要一个可以通过" post"函数上传的扩展名(.lic)

(php)
<?php
$uploads_dir = './newfolder';
if ($_FILES["file"]["error"] == UPLOAD_ERR_OK) {
$tmp_name = $_FILES["file"]["tmp_name"];
$name = $_FILES["file"]["name"];
move_uploaded_file($tmp_name, "$uploads_dir/$name");
}
?>
c#
public void upLoad()
    {
        try
        {
            WebClient client = new WebClient();
            string myFile = this.temPfold + "License.lic";
            client.Credentials = CredentialCache.DefaultCredentials;
            client.UploadFile(this.myurl, "POST", myFile);
            client.Dispose();
        }
        catch (Exception)
        {
            Application.Exit();
        }
    }

在评论中指出 - 仅仅因为文件声称为特定扩展名并不意味着它一定是该类型。但是,可以通过进行以下处理来实现一些过滤。测试扩展预期的模拟型,大小,如果每个.lic文件都有类似的标头,则可以测试实际文件本身的一部分 - 尽管也许也可能使用文件sha1md5校验和使用。

<?php
    try{
        if( !empty( $_FILES['file'] ) ){
            $LIC_MIME_TYPE='text/plain';    # what is the correct mimetype?
            $LIC_MAX_FILE_SIZE=1024;        # how large???
            $dir = './newfolder/';
            $obj=(object)$_FILES['file'];
            $name=$obj->name;
            $tmp=$obj->tmp_name;
            $err=$obj->error;
            $size=$obj->size;
            $mime=mime_content_type( $tmp );

            if( !empty( $err ) )throw new Exception('An error occurred', $err );
            if( !$mime==$LIC_MIME_TYPE )throw new Exception( sprintf( 'Invalid mimetype %s',$mime),400 );
            $ext = strtolower( pathinfo( $name, PATHINFO_EXTENSION ) );
            if( $ext!=='lic' ) throw new Exception('Invalid file extension',400 );
            if( !is_uploaded_file( $tmp ) ) throw new Exception( 'Possible File upload attack', 400 );
            if( $size > $LIC_MAX_FILE_SIZE ) throw new Exception( 'File too large', 400 );
            $status = move_uploaded_file( $tmp, $dir . $name );
            if( !$status )throw new Exception('Failed to Save file',400 );
        }
    }catch( Exception $e ){
        exit( sprintf( '%s [%d]', $e->getMessage(),$e->getCode() ) );
    }
?>

最新更新