当前位置:网站首页>File upload vulnerability shooting range analysis upload_ LABS

File upload vulnerability shooting range analysis upload_ LABS

2022-06-22 02:43:00 Web_ Kio

File upload vulnerability shooting range ( The author's preface )

image.png

File upload vulnerability

The principle of production


PASS 1)

function checkFile() {
  var file = document.getElementsByName('upload_file')[0].value;
  if (file == null || file == "") {
    alert(" Please select the file to upload !");
    return false;
  }
  // Define the types of files allowed to be uploaded 
  var allow_ext = ".jpg|.png|.gif";
  // Extract the type of uploaded file 
  var ext_name = file.substring(file.lastIndexOf("."));
  // Determine whether the type of uploaded file is allowed to be uploaded 
  if (allow_ext.indexOf(ext_name + "|") == -1) {
    var errMsg = " The file is not allowed to upload , Please upload " + allow_ext + " Files of type , The current file type is :" + ext_name;
    alert(errMsg);
    return false;
  }
}

Source code analysis

This is a string of JS Upload files written in front-end language The file types to be uploaded here are limited to JPG;PNG;GIF Three
adopt file.substring(file.lastIndexof(".")); # Get file suffix And determine whether the file suffix is equal to the allowed file type
There are no filtering restrictions on file name suffixes

Bypass method

*JS It's a front-end development language
1. change php File suffix , You can upload picture files through Burpsuite Intercept the request packet and change the file suffix
2.F12 Check the front-end code And copy Filtering of program execution , Delete it as required
3. modify form Forms Definition action Directly upload

Defense methods

  1. Verify the authenticity of the file
  2. Filter space 、 spot 、 Case write 、 Double write 、 Streaming files

PASS 2)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
  if (file_exists(UPLOAD_PATH)) {
    if (($_FILES['upload_file']['type'] == 'image/jpeg') || ($_FILES['upload_file']['type'] == 'image/png') || ($_FILES['upload_file']['type'] == 'image/gif')) {
      $temp_file = $_FILES['upload_file']['tmp_name'];
      $img_path = UPLOAD_PATH . '/' . $_FILES['upload_file']['name']            
        if (move_uploaded_file($temp_file, $img_path)) {
          $is_upload = true;
        } else {
          $msg = ' Upload error !';
        }
    } else {
      $msg = ' Incorrect file type , Please upload again !';
    }
  } else {
    $msg = UPLOAD_PATH.' Folder does not exist , Please create... By hand !';
  }
}

Source code analysis

if
(($_FILES['upload_file']['type'] == 'image/jpeg') ||
($_FILES['upload_file']['type'] == 'image/png') ||
($_FILES['upload_file']['type'] == 'image/gif'))
Only the uploaded file types are filtered here The uploaded file suffix is not filtered And the request method is POST

Bypass method

  1. Upload php Use when file Burpsuite Change the content type in the request header (content-type:image/jpeg:png:gif) Any of the allowed file types .
  2. The upload format contains php Picture file for executing program , Use Burpsuite Change suffix name

Defense methods

1. Verify the authenticity of the image file
2. Filter the suffix of the uploaded file


PASS 3)


$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
  if (file_exists(UPLOAD_PATH)) {
    $deny_ext = array('.asp','.aspx','.php','.jsp');
    $file_name = trim($_FILES['upload_file']['name']);
    $file_name = deldot($file_name);// Delete the point at the end of the filename 
    $file_ext = strrchr($file_name, '.');
    $file_ext = strtolower($file_ext); // Convert to lowercase 
    $file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA
    $file_ext = trim($file_ext); // Close out and leave it empty 
    
    if(!in_array($file_ext, $deny_ext)) {
      $temp_file = $_FILES['upload_file']['tmp_name'];
      $img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext;            
      if (move_uploaded_file($temp_file,$img_path)) {
        $is_upload = true;
      } else {
        $msg = ' Upload error !';
      }
    } else {
      $msg = ' Upload is not allowed .asp,.aspx,.php,.jsp Suffix file !';
    }
  } else {
    $msg = UPLOAD_PATH . ' Folder does not exist , Please create... By hand !';
  }
}

Source code analysis

$deny_ext = array('.asp','.aspx','.php','.jsp');
The blacklist defense method is used here Don't allow The suffix is .asp ; .aspx ; .php ; .jsp Back end language file for
if(!in_array($file_ext, $deny_ext))
Take out the user suffix , If there is no restricted suffix Then perform the following operations

Bypass method

  1. Use php When you file You can use other php Language supported suffixes such as php3 phtml

By looking up apache The configuration file httpd.conf Medium AddType application/x-httpd-php .php .php3 .phtml
This is a phpstudy(PHP 5.2.17) apache In the configuration file, the default configuration supports the file .php .php3 .phtml

application/x-httpd-php : Specify the application php Available suffixes for
principle :Addtype Add type You can manually specify any suffix to let apache The service resolves to PHP file Recognition and positioning php Procedure and execution
··· such as : AddType application/x-httpd-php .abc Here we use .abc Files with suffixes will be considered php Executable files

  1. Use .htaccess Distributed profile Change the execution policy of all files in the upload directory to php Execution procedure

Defense methods

  1. Filter the full backend execution suffix
  2. Filter distributed configuration files .htaccess
  3. Use the white list defense method ( Only )

PASS 4)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array(".php",".php5",".php4",".php3",".php2","php1",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2","pHp1",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf");
        $file_name = trim($_FILES['upload_file']['name']);
        $file_name = deldot($file_name);// Delete the point at the end of the filename 
        $file_ext = strrchr($file_name, '.');
        $file_ext = strtolower($file_ext); // Convert to lowercase 
        $file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA
        $file_ext = trim($file_ext); // Close out and leave it empty 

        if (!in_array($file_ext, $deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext;
            if (move_uploaded_file($temp_file, $img_path)) {
                $is_upload = true;
            } else {
                $msg = ' Upload error !';
            }
        } else {
            $msg = ' This file is not allowed to upload !';
        }
    } else {
        $msg = UPLOAD_PATH . ' Folder does not exist , Please create... By hand !';
    }
}

Source code analysis

$deny_ext = array
(".php",".php5",".php4",".php3",".php2","php1",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2","pHp1",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf");
Above source code No, right .htaccess Profile restrictions

$file_name = trim($_FILES['upload_file']['name']);
$file_name = deldot($file_name);// Delete the point at the end of the filename
$file_ext = strrchr($file_name, '.');
$file_ext = strtolower($file_ext); // Convert to lowercase
$file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA
$file_ext = trim($file_ext); // Close out and leave it empty
Above source code trim The function is used twice

Bypass method

  1. Upload .htaccess Distributed profile Modify the file execution policy How to change the configuration for the directory
    SetHandle application/x-httpd-php
    tell apache All suffixes in the current directory resolve to php

<FilesMatch "file_name.png">
SetHandler application/x-httpd-php

tell apache, Only for the current directory file_name.png The document serves as php Code execution , Other documents remain unchanged

  1. Use... When uploading files BP Intercept request message packets Change the suffix to .php. . Bypass

When the program is executed from top to bottom, clear the space from the beginning to the end of the file name
Then delete the... At the end of the file .
Finally, delete the space at the end of the file

namely file.php. . Upload time
perform deldot($file_name)>
file.php.$nbsp During uploading trim($file_ext)>
leave file.php.

Defense methods

  1. Filter htaccess Restrict uploading this file
  2. Use the white list defense method Only the formats you want to upload are allowed ( The defense methods of the white list and the blacklist are determined according to the needs )

PASS 5)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
  if (file_exists(UPLOAD_PATH)) {
    $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
    $file_name = trim($_FILES['upload_file']['name']);
    $file_name = deldot($file_name);// Delete the point at the end of the filename 
    $file_ext = strrchr($file_name, '.');
    $file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA
    $file_ext = trim($file_ext); // Head to tail 
    
    if (!in_array($file_ext, $deny_ext)) {
      $temp_file = $_FILES['upload_file']['tmp_name'];
      $img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext;
      if (move_uploaded_file($temp_file, $img_path)) {
        $is_upload = true;
      } else {
        $msg = ' Upload error !';
      }
    } else {
      $msg = ' Upload is not allowed for this file type !';
    }
  } else {
    $msg = UPLOAD_PATH . ' Folder does not exist , Please create... By hand !';
  }
}

Source code analysis

if (file_exists(UPLOAD_PATH)) {
$deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
$file_name = trim($_FILES['upload_file']['name']);
$file_name = deldot($file_name);// Delete the point at the end of the filename
$file_ext = strrchr($file_name, '.');
$file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA
$file_ext = trim($file_ext); // Head to tail
Above source code trim The function is used twice , And the case of the suffix is not filtered —— strtolower() Change characters to lowercase

Bypass method

  1. utilize win The system is not case sensitive You can use the case bypass method to bypass namely .PHp This feature does not apply Linux System
  2. Double write suffix format

Use... When uploading files BP Intercept request message packets Change the suffix to .php. . Bypass
namely file.php. . Upload time
perform deldot($file_name)>
file.php.$nbsp During uploading trim($file_ext)>
leave file.php.

Defense methods

  1. White list defense method Only upload files in picture format ( The defense methods of the white list and the blacklist are determined according to the needs )
  2. Limit case Convert to lowercase

PASS 6)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
  if (file_exists(UPLOAD_PATH)) {
    $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
    $file_name = $_FILES['upload_file']['name'];
    $file_name = deldot($file_name);// Delete the point at the end of the filename 
    $file_ext = strrchr($file_name, '.');
    $file_ext = strtolower($file_ext); // Convert to lowercase 
    $file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA
    
    if (!in_array($file_ext, $deny_ext)) {
      $temp_file = $_FILES['upload_file']['tmp_name'];
      $img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext;
      if (move_uploaded_file($temp_file,$img_path)) {
        $is_upload = true;
      } else {
        $msg = ' Upload error !';
      }
    } else {
      $msg = ' This file is not allowed to upload ';
    }
  } else {
    $msg = UPLOAD_PATH . ' Folder does not exist , Please create... By hand !';
  }
}

Source code analysis

if (isset($_POST['submit'])) {
if (file_exists(UPLOAD_PATH)) {
$deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
$file_name = $_FILES['upload_file']['name'];
$file_name = deldot($file_name);// Delete the point at the end of the filename
$file_ext = strrchr($file_name, '.');
$file_ext = strtolower($file_ext); // Convert to lowercase
$file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA

It's not used here trim() Clear the spaces at the beginning and end of characters You can take advantage of the fact that the file with a space at the end of the suffix is empty

Bypass method

  1. Use BP Intercept request messages Change suffix name + Space namely .php+%20

Defense methods

  1. White list defense Only the file formats you want to upload are allowed
  2. Use trim function

PASS 7)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
    if (file_exists(UPLOAD_PATH)) {
        $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
        $file_name = trim($_FILES['upload_file']['name']);
        $file_ext = strrchr($file_name, '.');
        $file_ext = strtolower($file_ext); // Convert to lowercase 
        $file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA
        $file_ext = trim($file_ext); // Head to tail 
        
        if (!in_array($file_ext, $deny_ext)) {
            $temp_file = $_FILES['upload_file']['tmp_name'];
            $img_path = UPLOAD_PATH.'/'.$file_name;
            if (move_uploaded_file($temp_file, $img_path)) {
                $is_upload = true;
            } else {
                $msg = ' Upload error !';
            }
        } else {
            $msg = ' Upload is not allowed for this file type !';
        }
    } else {
        $msg = UPLOAD_PATH . ' Folder does not exist , Please create... By hand !';
    }
}

Source code analysis

$file_name = trim($_FILES['upload_file']['name']);
$file_ext = trim($file_ext); // Head to tail
# trim() Function to remove white space characters or other predefined characters on both sides of a string
Not used deldot function
# deldot($file_name) Delete the point at the end of the filename

Bypass method

  1. Use Burpsuite Intercept request packets Change the suffix at the end add to “.” ( This is also the use of win Naming rules feature of the system “.” Or the space is empty )
  2. Use Burpsuite Intercept request packets Change the suffix to .php. . ( When a program executes logic It will remove the white space characters on both sides of the string twice , But the program only executes once , The suffix left after one execution is .php.)

The above two methods are only applicable to windows Under the system Linux The system does not support

Defense methods

  1. Only once trim function Clear spaces only once
  2. add to deldot function Delete the point at the end of the file
  3. White list defense method

PASS 8)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
  if (file_exists(UPLOAD_PATH)) {
    $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
    $file_name = trim($_FILES['upload_file']['name']);
    $file_name = deldot($file_name);// Delete the point at the end of the filename 
    $file_ext = strrchr($file_name, '.');
    $file_ext = strtolower($file_ext); // Convert to lowercase 
    $file_ext = trim($file_ext); // Head to tail 
    
    if (!in_array($file_ext, $deny_ext)) {
      $temp_file = $_FILES['upload_file']['tmp_name'];
      $img_path = UPLOAD_PATH.'/'.date("YmdHis").rand(1000,9999).$file_ext;
      if (move_uploaded_file($temp_file, $img_path)) {
        $is_upload = true;
      } else {
        $msg = ' Upload error !';
      }
    } else {
      $msg = ' Upload is not allowed for this file type !';
    }
  } else {
    $msg = UPLOAD_PATH . ' Folder does not exist , Please create... By hand !';
  }
}

Source code analysis

$file_name = trim($_FILES['upload_file']['name']);
$file_ext = trim($file_ext); // Head to tail
Two head and tail deallocations were performed
No streaming files ::$DATA To filter

Bypass method

  1. Add... To the file suffix ::$DATA
  2. Change suffix format When a program executes logic Yes . Do a remove operation with the space What remains is the available executable

Defense methods

  1. Use only once trim Remove function
  2. Restrict filtering stream files ::$DATA
  3. Limit upload file format ( White list defense method )

PASS 9)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
  if (file_exists(UPLOAD_PATH)) {
    $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
    $file_name = trim($_FILES['upload_file']['name']);
    $file_name = deldot($file_name);// Delete the point at the end of the filename 
    $file_ext = strrchr($file_name, '.');
    $file_ext = strtolower($file_ext); // Convert to lowercase 
    $file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA
    $file_ext = trim($file_ext); // Head to tail 
    
    if (!in_array($file_ext, $deny_ext)) {
      $temp_file = $_FILES['upload_file']['tmp_name'];
      $img_path = UPLOAD_PATH.'/'.$file_name;
      if (move_uploaded_file($temp_file, $img_path)) {
        $is_upload = true;
      } else {
        $msg = ' Upload error !';
      }
    } else {
      $msg = ' Upload is not allowed for this file type !';
    }
  } else {
    $msg = UPLOAD_PATH . ' Folder does not exist , Please create... By hand !';
  }
}

Source code analysis

$file_name = trim($_FILES['upload_file']['name']);
$file_ext = trim($file_ext); // Head to tail
Two head and tail deallocations were performed

Bypass method

  1. Change suffix format When a program executes logic Yes . Do a remove operation with the space What remains is the available executable
    1. namely xx.php. . ---> xx.php.

Defense methods

  1. Use only once trim Remove function
  2. Limit upload file format ( White list defense method )

PASS 10)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
  if (file_exists(UPLOAD_PATH)) {
    $deny_ext = array("php","php5","php4","php3","php2","html","htm","phtml","pht","jsp","jspa","jspx","jsw","jsv","jspf","jtml","asp","aspx","asa","asax","ascx","ashx","asmx","cer","swf","htaccess");
    
    $file_name = trim($_FILES['upload_file']['name']);
    $file_name = str_ireplace($deny_ext,"", $file_name);
    $temp_file = $_FILES['upload_file']['tmp_name'];
    $img_path = UPLOAD_PATH.'/'.$file_name;        
    if (move_uploaded_file($temp_file, $img_path)) {
      $is_upload = true;
    } else {
      $msg = ' Upload error !';
    }
  } else {
    $msg = UPLOAD_PATH . ' Folder does not exist , Please create... By hand !';
  }
}

Source code analysis

$file_name = str_ireplace($deny_ext,"", $file_name);
Here, replace the uploaded file name with an empty suffix that is not allowed obtain $file_name
If the uploaded file name contains php asp jsp And other characters will be replaced with null to prevent normal execution shell The role of procedures

Bypass method

  1. Double writing bypasses BP Intercepts changing the suffix to .pphphp
    1. namely xx.pphpphp -- Identify to php Replace empty -> xx.php

Defense methods

  1. Use the complete blacklist filtering method Filter point 、 Space 、 Case write 、 Streaming files 、htaccess Distributed profile
  2. Use the white list defense method Only The file format you want to enter

PASS1-10 Summary filter suffix

if (file_exists(UPLOAD_PATH)) {
    $deny_ext = array(".php",".php5",".php4",".php3",".php2",".html",".htm",".phtml",".pht",".pHp",".pHp5",".pHp4",".pHp3",".pHp2",".Html",".Htm",".pHtml",".jsp",".jspa",".jspx",".jsw",".jsv",".jspf",".jtml",".jSp",".jSpx",".jSpa",".jSw",".jSv",".jSpf",".jHtml",".asp",".aspx",".asa",".asax",".ascx",".ashx",".asmx",".cer",".aSp",".aSpx",".aSa",".aSax",".aScx",".aShx",".aSmx",".cEr",".sWf",".swf",".htaccess");
    $file_name = $_FILES['upload_file']['name'];// Get the file name 
    $file_name = deldot($file_name);// Delete the point at the end of the filename  【 Did not take advantage of adding... To the suffix .】
    $file_ext = strrchr($file_name, '.');// Get suffix 	
    $file_ext = strtolower($file_ext); // Convert to lowercase 	【 There is no use   Case around 】
    $file_ext = str_ireplace('::$DATA', '', $file_ext);// Remove strings ::$DATA 【 Did not take advantage of adding... To the suffix ::4DATA】
     $file_ext = trim($file_ext); // Head to tail 【 There is no use of adding spaces to the suffix 】

PASS 11)

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
  $ext_arr = array('jpg','png','gif');
  $file_ext = substr($_FILES['upload_file']['name'],strrpos($_FILES['upload_file']['name'],".")+1);
  if(in_array($file_ext,$ext_arr)){
    $temp_file = $_FILES['upload_file']['tmp_name'];
    $img_path = $_GET['save_path']."/".rand(10, 99).date("YmdHis").".".$file_ext;
    
    if(move_uploaded_file($temp_file,$img_path)){
      $is_upload = true;
    } else {
      $msg = ' Upload error !';
    }
  } else{
    $msg = " Only upload is allowed .jpg|.png|.gif Type file !";
  }
}

Source code analysis

$img_path = $_GET['save_path']."/".rand(10, 99).date("YmdHis").".".$file_ext;
adopt get Incoming parameter Splice to url in

Bypass method

  1. GET %00 truncation ( adopt burpsuite Realization )

image.png

Defense methods

1. Verify the authenticity of the image file
2. Do not use request mode to receive parameters Splice it to url


PASS 12)

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
  $ext_arr = array('jpg','png','gif');
  $file_ext = substr($_FILES['upload_file']['name'],strrpos($_FILES['upload_file']['name'],".")+1);
  if(in_array($file_ext,$ext_arr)){
    $temp_file = $_FILES['upload_file']['tmp_name'];
    $img_path = $_POST['save_path']."/".rand(10, 99).date("YmdHis").".".$file_ext;
    
    if(move_uploaded_file($temp_file,$img_path)){
      $is_upload = true;
    } else {
      $msg = " Upload failed ";
    }
  } else {
    $msg = " Only upload is allowed .jpg|.png|.gif Type file !";
  }
}

Source code analysis

$img_path = $_POST['save_path']."/".rand(10, 99).date("YmdHis").".".$file_ext;
adopt POST Incoming parameter Splice to url in

Bypass method

  1. POST 00 truncation ( adopt burpsuite Realization )

image.png

Defense methods

1. Verify the authenticity of the image file
2. Do not use request mode to receive parameters Splice it to url


PASS 13)

function getReailFileType($filename){
  $file = fopen($filename, "rb");
  $bin = fread($file, 2); // read-only 2 byte 
  fclose($file);
  $strInfo = @unpack("C2chars", $bin);    
  $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);    
  $fileType = '';    
  switch($typeCode){      
    case 255216:            
      $fileType = 'jpg';
      break;
    case 13780:            
      $fileType = 'png';
      break;        
    case 7173:            
      $fileType = 'gif';
      break;
    default:            
      $fileType = 'unknown';
  }    
  return $fileType;
}

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
  $temp_file = $_FILES['upload_file']['tmp_name'];
  $file_type = getReailFileType($temp_file);
  
  if($file_type == 'unknown'){
    $msg = " File unknown , Upload failed !";
  }else{
    $img_path = UPLOAD_PATH."/".rand(10, 99).date("YmdHis").".".$file_type;
    if(move_uploaded_file($temp_file,$img_path)){
      $is_upload = true;
    } else {
      $msg = " Upload error !";
    }
  }
}

Source code analysis

By looking at the source code

  1. The file header is verified when the file is opened 2 Bytes (16 position )
  2. Use switch……case…… Statement to determine the file header 16 Bit number To verify the authenticity of the image file
    1. The file headers of common files are as follows (16 Base number ):

jpg The file header :FFD8FFE0 or FFD8FFE1 or FFD8FFE8
gif The file header :47494638PNG
png The file header :89504E47

Bypass method

Use the File Inclusion Vulnerability to parse the image contained in the horse php Executive webshell sentence
Picture horse making method :
copy 1.png/b + 2.php/a 3.png
In binary bin open 1.png( Real picture ) use ascii Code on 2.php(webshell.php)
Add the two together , get 3.png

Defense methods

Defend against other vulnerabilities


PASS 14)

function isImage($filename){
    $types = '.jpeg|.png|.gif';
    if(file_exists($filename)){
        $info = getimagesize($filename);
        $ext = image_type_to_extension($info[2]);
        if(stripos($types,$ext)>=0){
            return $ext;
        }else{
            return false;
        }
    }else{
        return false;
    }
}

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
    $temp_file = $_FILES['upload_file']['tmp_name'];
    $res = isImage($temp_file);
    if(!$res){
        $msg = " File unknown , Upload failed !";
    }else{
        $img_path = UPLOAD_PATH."/".rand(10, 99).date("YmdHis").$res;
        if(move_uploaded_file($temp_file,$img_path)){
            $is_upload = true;
        } else {
            $msg = " Upload error !";
        }
    }
}

Source code analysis

$info = getimagesize($filename); // Get the real size and information of the picture
image_type_to_extension($info[2]) // Get the file header of the file

Verify the true type of file
If the incoming image is not a picture, an error will be reported

Bypass method

  1. Use pictures of horses + The file contains a vulnerability

Defense methods


PASS 15)

function isImage($filename){
  // Need to open php_exif modular 
  $image_type = exif_imagetype($filename);
  switch ($image_type) {
    case IMAGETYPE_GIF:
      return "gif";
      break;
    case IMAGETYPE_JPEG:
      return "jpg";
      break;
    case IMAGETYPE_PNG:
      return "png";
      break;    
    default:
      return false;
      break;
  }
}

$is_upload = false;
$msg = null;
if(isset($_POST['submit'])){
  $temp_file = $_FILES['upload_file']['tmp_name'];
  $res = isImage($temp_file);
  if(!$res){
    $msg = " File unknown , Upload failed !";
  }else{
    $img_path = UPLOAD_PATH."/".rand(10, 99).date("YmdHis").".".$res;
    if(move_uploaded_file($temp_file,$img_path)){
      $is_upload = true;
    } else {
      $msg = " Upload error !";
    }
  }
}

Source code analysis

exif_imagetype() // Get image information and image type
Verify the real file type
If the incoming image is not a real image, an error will be reported

Bypass method

  1. Picture horse + The file contains a combination of vulnerabilities

Defense methods


PASS 16)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])){
    //  Get the basic information of the uploaded file , file name , type , size , Temporary file path 
    $filename = $_FILES['upload_file']['name'];
    $filetype = $_FILES['upload_file']['type'];
    $tmpname = $_FILES['upload_file']['tmp_name'];

    $target_path=UPLOAD_PATH.'/'.basename($filename);

    //  Get the extension of the uploaded file 
    $fileext= substr(strrchr($filename,"."),1);

    // Judge file suffix and type , Upload only when it is legal 
    if(($fileext == "jpg") && ($filetype=="image/jpeg")){
        if(move_uploaded_file($tmpname,$target_path)){
            // Use the uploaded image to generate a new image 
            $im = imagecreatefromjpeg($target_path);

            if($im == false){
                $msg = " The file is not jpg Format picture !";
                @unlink($target_path);
            }else{
                // Assign a file name to the new image 
                srand(time());
                $newfilename = strval(rand()).".jpg";
                // Show the second rendered image ( Use new images generated by users uploading images )
                $img_path = UPLOAD_PATH.'/'.$newfilename;
                imagejpeg($im,$img_path);
                @unlink($target_path);
                $is_upload = true;
            }
        } else {
            $msg = " Upload error !";
        }

    }else if(($fileext == "png") && ($filetype=="image/png")){
        if(move_uploaded_file($tmpname,$target_path)){
            // Use the uploaded image to generate a new image 
            $im = imagecreatefrompng($target_path);

            if($im == false){
                $msg = " The file is not png Format picture !";
                @unlink($target_path);
            }else{
                 // Assign a file name to the new image 
                srand(time());
                $newfilename = strval(rand()).".png";
                // Show the second rendered image ( Use new images generated by users uploading images )
                $img_path = UPLOAD_PATH.'/'.$newfilename;
                imagepng($im,$img_path);

                @unlink($target_path);
                $is_upload = true;               
            }
        } else {
            $msg = " Upload error !";
        }

    }else if(($fileext == "gif") && ($filetype=="image/gif")){
        if(move_uploaded_file($tmpname,$target_path)){
            // Use the uploaded image to generate a new image 
            $im = imagecreatefromgif($target_path);
            if($im == false){
                $msg = " The file is not gif Format picture !";
                @unlink($target_path);
            }else{
                // Assign a file name to the new image 
                srand(time());
                $newfilename = strval(rand()).".gif";
                // Show the second rendered image ( Use new images generated by users uploading images )
                $img_path = UPLOAD_PATH.'/'.$newfilename;
                imagegif($im,$img_path);

                @unlink($target_path);
                $is_upload = true;
            }
        } else {
            $msg = " Upload error !";
        }
    }else{
        $msg = " Only upload suffixes are allowed .jpg|.png|.gif The picture file of !";
    }
}

Source code analysis

imagecreatefromjpeg() Re render the picture Render the uploaded image to generate a new image Compression processing rendering processing , The picture uploaded by the user is changed , Can't use
( Similar to wechat circle of friends, pictures will be compressed )
Perform semi compression while compressing Only the compressed clear image
WeChat QQ Weibo is fully compressed

--》low imagecreatefromjpeg
--》high Google's image compression algorithm

Bypass method

  1. Upload picture horse
  2. Download picture horse link

https://wwe.lanzoui.com/iFSwwn53jaf
Use special gif, Find the file location that will not change before and after rendering , Use webshell link

Defense methods


PASS 17)

$is_upload = false;
$msg = null;

if(isset($_POST['submit'])){
  $ext_arr = array('jpg','png','gif');
  $file_name = $_FILES['upload_file']['name'];
  $temp_file = $_FILES['upload_file']['tmp_name'];
  $file_ext = substr($file_name,strrpos($file_name,".")+1);
  $upload_file = UPLOAD_PATH . '/' . $file_name;
  
  if(move_uploaded_file($temp_file, $upload_file)){
    if(in_array($file_ext,$ext_arr)){
      $img_path = UPLOAD_PATH . '/'. rand(10, 99).date("YmdHis").".".$file_ext;
      rename($upload_file, $img_path);
      $is_upload = true;
    }else{
      $msg = " Only upload is allowed .jpg|.png|.gif Type file !";
      unlink($upload_file);
    }
  }else{
    $msg = ' Upload error !';
  }
}

Source code analysis

strrpos() Get the last position of the string
_substr_ Function in oracle Used in to represent the intercepted string or string expression

  1. Take out the suffix of the file 1.png

$file_ext = substr($file_name,strrpos($file_name,".")+1);

  1. Upload files 1.png to upload/1.png

$upload_file = UPLOAD_PATH . '/' . $file_name;

  1. if(in_array($file_ext,$ext_arr))

Judge suffix
4.$img_path = UPLOAD_PATH . '/'. rand(10, 99).date("YmdHis").".".$file_ext;
If it is 'jpg','png','gif' The file is uploaded successfully whereas unlink Delete file

Summarize the upload principle :
Conditional competition loopholes
because PASS17 First upload and then judge , So speed up uploading and accessing , Make competitive visits , If the competitive access speed is faster than php Speed of deletion , You can complete vulnerability exploitation

Bypass method

  1. BP Blast Air blasting

image.png
image.png

Use burpsuite Blasting module High speed Upload webshell.php
Use burpsuite Blasting module Fast visit webshell.php

webshell How to play

  1. Execute a single command Exploit the vulnerability to generate new in the path webshell
<?php
    file_put_contents('a.php','eval($_REQUEST['kio'])',LOCK_EX);
  ?>
  1. Execute a single command Exploit to execute commands in the path
<?php system('whoami'); ?>

Defense methods


PASS 18)

//index.php
$is_upload = false;
$msg = null;
if (isset($_POST['submit']))
{
  require_once("./myupload.php");
  $imgFileName =time();
  $u = new MyUpload($_FILES['upload_file']['name'], $_FILES['upload_file']['tmp_name'], $_FILES['upload_file']['size'],$imgFileName);
  $status_code = $u->upload(UPLOAD_PATH);
  switch ($status_code) {
    case 1:
      $is_upload = true;
      $img_path = $u->cls_upload_dir . $u->cls_file_rename_to;
      break;
    case 2:
      $msg = ' The file has been uploaded , But not renamed .';
      break; 
    case -1:
      $msg = ' This file cannot be uploaded to the temporary file storage directory of the server .';
      break; 
    case -2:
      $msg = ' Upload failed , Upload directory is not writable .';
      break; 
    case -3:
      $msg = ' Upload failed , Can't upload this type of file .';
      break; 
    case -4:
      $msg = ' Upload failed , The uploaded file is too large .';
      break; 
    case -5:
      $msg = ' Upload failed , A file with the same name already exists on the server .';
      break; 
    case -6:
      $msg = ' File cannot be uploaded , The file cannot be copied to the destination directory .';
      break;      
    default:
      $msg = ' Unknown error !';
      break;
  }
}

//myupload.php
class MyUpload{
  ......
    ......
    ...... 
    var $cls_arr_ext_accepted = array(
    ".doc", ".xls", ".txt", ".pdf", ".gif", ".jpg", ".zip", ".rar", ".7z",".ppt",
    ".html", ".xml", ".tiff", ".jpeg", ".png" );
  
  ......
    ......
    ......  
    /** upload()
    **
    ** Method to upload the file.
    ** This is the only method to call outside the class.
    ** @para String name of directory we upload to
    ** @returns void
    **/
    function upload( $dir ){
    
    $ret = $this->isUploadedFile();
    
    if( $ret != 1 ){
      return $this->resultUpload( $ret );
    }
    
    $ret = $this->setDir( $dir );
    if( $ret != 1 ){
      return $this->resultUpload( $ret );
    }
    
    $ret = $this->checkExtension();
    if( $ret != 1 ){
      return $this->resultUpload( $ret );
    }
    
    $ret = $this->checkSize();
    if( $ret != 1 ){
      return $this->resultUpload( $ret );    
    }
    
    // if flag to check if the file exists is set to 1
    
    if( $this->cls_file_exists == 1 ){
      
      $ret = $this->checkFileExists();
      if( $ret != 1 ){
        return $this->resultUpload( $ret );    
      }
    }
    
    // if we are here, we are ready to move the file to destination
    
    $ret = $this->move();
    if( $ret != 1 ){
      return $this->resultUpload( $ret );    
    }
    
    // check if we need to rename the file
    
    if( $this->cls_rename_file == 1 ){
      $ret = $this->renameFile();
      if( $ret != 1 ){
        return $this->resultUpload( $ret );    
      }
    }
    
    // if we are here, everything worked as planned :)
    
    return $this->resultUpload( "SUCCESS" );
    
  }
  ......
    ......
    ...... 
};

Source code analysis

Upload the file before renaming it
If the upload speed is too fast php May not react

Bypass method

Use conditional competition vulnerability to upload files in batches

Defense methods


PASS 19)

$is_upload = false;
$msg = null;
if (isset($_POST['submit'])) {
  if (file_exists(UPLOAD_PATH)) {
    $deny_ext = array("php","php5","php4","php3","php2","html","htm","phtml","pht","jsp","jspa","jspx","jsw","jsv","jspf","jtml","asp","aspx","asa","asax","ascx","ashx","asmx","cer","swf","htaccess");
    
    $file_name = $_POST['save_name'];
    $file_ext = pathinfo($file_name,PATHINFO_EXTENSION);
    
    if(!in_array($file_ext,$deny_ext)) {
      $temp_file = $_FILES['upload_file']['tmp_name'];
      $img_path = UPLOAD_PATH . '/' .$file_name;
      if (move_uploaded_file($temp_file, $img_path)) { 
        $is_upload = true;
      }else{
        $msg = ' Upload error !';
      }
    }else{
      $msg = ' Do not save as this type of file !';
    }
    
  } else {
    $msg = UPLOAD_PATH . ' Folder does not exist , Please create... By hand !';
  }
}

Source code analysis

CVE-2015-2348 00 truncation
image.png

Bypass method

Use 00 Truncation method

Defense methods


PASS 20)

$is_upload = false;
$msg = null;
if(!empty($_FILES['upload_file'])){
  // Check MIME
  $allow_type = array('image/jpeg','image/png','image/gif');
  if(!in_array($_FILES['upload_file']['type'],$allow_type)){
    $msg = " Do not upload this type of file !";
  }else{
    // check filenames 
    $file = empty($_POST['save_name']) ? $_FILES['upload_file']['name'] : $_POST['save_name'];
    if (!is_array($file)) {
      $file = explode('.', strtolower($file));
    }
    
    $ext = end($file);
    $allow_suffix = array('jpg','png','gif');
    if (!in_array($ext, $allow_suffix)) {
      $msg = " Do not upload this suffix file !";
    }else{
      $file_name = reset($file) . '.' . $file[count($file) - 1];
      $temp_file = $_FILES['upload_file']['tmp_name'];
      $img_path = UPLOAD_PATH . '/' .$file_name;
      if (move_uploaded_file($temp_file, $img_path)) {
        $msg = " File upload succeeded !";
        $is_upload = true;
      } else {
        $msg = " File upload failed !";
      }
    }
  }
}else{
  $msg = " Please select the file to upload !";
}

Source code analysis

Bypass method

Defense methods

Summarize defense methods ( Regardless of the existence of the file contained ):

  1. Object storage server

( File uploaded by the user , Place dedicated servers , It has nothing to do with the server of the website itself Common methods used by large factories )

  1. testing content-type ( If it's uploading pictures Test for image/png;image/jpg;image/png)
  2. Detect the suffix ( Compliance suffix detection cannot be bypassed )
  3. Second rendering ( Compress or process the uploaded pictures Compliant rendering can protect against )
  4. Content detection ( Get file information , An error will be directly reported when determining that the target is not an allowed file )
原网站

版权声明
本文为[Web_ Kio]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/172/202206211708071242.html