Getting started with code auditing-php Tutorial

Source: Internet
Author: User
Introduction to code auditing 0x00

I have read all the PHP code auditing books written by seay. as a little bit of code auditing, I hope to provide my gains to some people who are just like me, as well as an overall framework and common vulnerability functions. This is also a learning note for this book. you can take a look at this book based on my thought. :)

0x01 overall

The objective of learning code audit is to independently monitor the code security of a CMS. Its general ideas include:

  • Read the full-text code from the functional function code, such as common_fun.php in the include folder or a file with a keyword similar to this.
  • Check the configuration file, the file with the config keyword, find the connect () function of the mysql. class. php file, and check whether there is a vulnerability during database connection.
  • Continue to read the home page file, index. php: understand which functions and files are called when the program is running using index. the PHP file is used as the benchmark. you can expand and read the included files on a layer-by-layer basis to understand the functions of the files. then, you can access the homepage file of the functional folder for additional reading.
0x02 various holes a. File operation vulnerabilities
  • You do not need to control the file name parameters.
  • Parallel user permission administrator permission operation permission
  • Prohibit input parameters like this ..,/, \ check passed parameters, make restrictions, stop the program to execute
1. file inclusion vulnerability:

(1) Local files include:

  • It usually exists in module loading, template loading, and cache calling.
  • Include functions: include ()/include_once (), require ()/require_once () to find controllable variables

(2) remote files include:

  • Prerequisites: allow_url_include = on
  • Appear less frequently than local inclusion

(3) file inclusion truncation:

  • % 00 truncation (php version less than 5.3)
  • Question mark truncation (which is equivalent to the request parameter after the question mark)
  • English (.) backslash (/) truncation
2. file read (download) vulnerability:

Search for key functions:

File_get_contents (), highlight_file (), fopen (), read file (), fread (), fgetss (), fgets (), parse_ini_file (), show_source (), file () and so on

3. file Upload vulnerability:

Search for key functions:

Move_uploaded_file () then checks whether the code that calls this function is in a restricted Upload format or can be bypassed.

(1) unfiltered or local filtering: files in PHP format can be directly uploaded without being filtered by the server.

(2) blacklist extension filtering:

  • Incomplete restrictions: IIS supports parsing. asp,. cdx,. asa,. cer, and so on by default.
  • The extension can be bypassed:

The file format is not allowed. php, but we can upload the file name as 1.php (note that there is a space behind it)

(3) file header content-type verification bypass:

  • Getimagesize () function: verifies that the file header is GIF89a and returns true.
  • To limit the value of $ _ FILES ["file"] ["type"] is to manually limit content-type to controllable variables.

(4) Prevention:

  • Use in_array () or use third-party equal to = to compare the extension.
  • To save the uploaded file, rename it. The rule uses the timestamp to splice the random number: md5 (time () + rand )).
4. file deletion vulnerability:

Search for key functions:

  • Unlink () uses backtracing variables
  • In earlier versions, session_destroy () can be used to delete files, which are now basically fixed.
Metinfo arbitrary file deletion vulnerability:

$ Action = delete: delete the. SQL file. if the file is not an SQL file, delete the submitted file name.

Target.com/recovery.php? & Action = delete & filename =.../../index. php

B. code execution vulnerability 1. code execution function:

Key search functions: eval (), assert (), preg_replace (), call_user_func (), call_user_func_array (), array_map ()

(1) preg_replace () function:

Mixed preg_replace (mixed $ pattern, mixed $ replacement, mixed $ subject [, int $ limit =-1 [, int & $ count])

When the e modifier exists at $ pattern, $ replacement is executed as php code.

(2) mixed call_user_func (callable $ callbank [, mixed $ parameter [, mixed $ ...) :

The first parameter is the callback function, and the second parameter is the callback function parameter.

(3) eval () and assert ():

PHP code can be executed when the assert () parameter is a string

[Differentiation ]:

eval(" phpinfo(); ");【√】 eval(" phpinfo() ");【X】assert(" phpinfo(); ");【√】 assert(" phpinfo() ");【√】
2. dynamic function execution:

Dynamic function backdoor:

#!php
 

3. command execution function:

Key search functions: system (), exec (), shell_exec (), passthru (), pcntl_exec (), popen (), proc_open ()

(1) popen and proc_open ():

#!php
 > /Users/bingdaojueai/Desktop/1.txt', 'r' ); ?>

Then, the content in 1.txt is the result after the command is executed.

(2) run the command against quotation marks:

  • Echo whoami; you can directly execute the command

  • Difference between double quotation marks and single quotation marks:

    #!php$a = 1echo " $a "    output:1echo ' $a '    output:$a
When using double quotation marks, variables can be parsed directly, resulting in code execution vulnerability. C. variable overwrite vulnerability 1. improper use of functions:
  • Int extract (array & $ var_array, int $ extract_type = EXTR_OVERWRITE, string $ prefix = null)
  • Void parse_str (string $ str, array & $ arr)
  • Bool import_request_variables (string $ type, string $ prefix)
2. $ variable overwrite:

D. logical vulnerabilities

Questions to consider:

  • Can the program be installed repeatedly?
  • Changing the password does not allow unauthorized modification of other user passwords
  • Can I retrieve the password verification code for brute force cracking?
  • Whether the cookie can be predicted and verified to bypass
1. equals to bypassing the existing judgment:

(1) in_array ():The type is automatically converted before comparison.

(2) is_numeric (): When the input parameter is hex, it directly passes and returns true. MYSQL can directly use hex encoding to replace string plaintext and can be injected twice, which may cause XSS vulnerability.

(3) double equals = and third equals AT =:

  • Double equals performs class conversion during variable comparison, which is the same as in_array.
  • Level 3TypeAndValueIn comparison, it is more secure.
2. excessive permissions in the account system:
  • Horizontal unauthorized operation: User A can perform all permissions of user B as user B. If user A and User B have the same permissions.
  • Vertical unauthorized operation: User A is able to perform all permissions on user C as user C, provided that user C has higher permissions than user.

(1) No exit/return/die:

#!php
 

Test will still be output, replaced with the installation process, and PHP will continue.

(2) payment vulnerability:

  • Client unit price modification
  • Change the total price and purchase quantity of the client
  • Strict Server Verification
  • Time difference of repeated packet sending:

    #! Php
       

Vulnerability function: str_replace ()

#!php
 $b
";$c = str_replace($a,'',$b);echo trim($c);?>

E. session authentication vulnerability
  • COOKIE verification: no SESSION verification is used to save the information directly in the COOKIE.

    1. Find the passing process of the parameters passed in the SQL statement and trace back the variables to the original function to check whether the algorithm stored in the cookie is reversible.
    2. And MD5 are less secure than sha1 in decryption of sha1.
    3. Only one user can log on to one IP address at the same time.
  • When auditing code, view the logon code

F. secondary vulnerability 1. type:
  • It is not a logic issue, but a credibility issue.
  • The complexity of business logic is proportional to the trigger rate of secondary vulnerabilities.
  • Shopping cart/order/Reference Data/article editing/draft ==> SQL injection/XSS

2. tips:

(1) drill the space escape characters such as GPC:

  • $ _ SERVER variable not protected by GPC: after PHP5, the headers obtained by $ _ SERVER are no longer affected by GPC. even if special characters are enabled, they are not escaped and injected.
  • Encoding problem conversion:

    1. Wide byte injection of GBK: % df 'single quotes are automatically converted to (% 5c), and % df and % 5c are combined to form a single quotation mark, which is closed successfully. [Encoding conversion problem during php interaction with mysql]
    2. Mb_convert_encoding ():

      #!php
            
           

(2) string problems:

  • Use the error message to find sensitive information
  • String truncation:

    1. % 00 null character truncation: [PHP version less than 5.3]

      #! Php
           ?>
    2. Iconv function character encoding truncation: [required for PHP version]

      #! Phpchr (128)-chr (255) can be truncated
           "; // 1 �2 echo iconv (" UTF-8 "," GBK ", $ a); // 1?>
  • Php: // input/output stream:

    #! Php
       1. php? File = php: // filter/convert. base64-encode (the content is base64 encoded)/resource1_example.txt (remote file)
  • Php code parsing tag:

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.