Php security code audit summary

Source: Internet
Author: User
Tags php file upload

This article is just a Summary of the notes that have been prepared for a period of time. It is an analysis framework without instantiation analysis.


0x01 tools
Editor (notepad ++, editplus, UE, etc)
TommSearch (string SEARCH) | grep
HttpProtocolDebugger (http debugger)
Fiddler (analysis package, Change Package)
Seay PHP code audit tool (assisted by php-code-audit Analysis)
Several interesting projects
Dvwa (Code audit test platform)
Phpmvs
Php security audit check
PHP Vulnerability Hunter

0x02 Functions
Addslashed () Add a backslash
Stripslashed () Remove the backslash
Get_magic_quotes_gpc () determines whether to enable gpc
Expode (".", $ array) is split into Arrays
Is_numeric () determines whether it is a number
Sizeof () Judge Length
Trim () removes spaces or other characters at the beginning and end of a string.
System () Outputs and returns the last shell result.
Exec () does not output results. The last shell result is returned. All results can be saved to a returned array.
Passthru () only calls the command and directly outputs the command running result to the standard output device.
EscapeShellCmd (), which escapes all characters in a string that may bypass Shell and execute another command. These characters have special meanings in Shell, such as semicolons (;), redirection (>), and reading from a file (<.
EscapeShellArg (). Add single quotation marks on both sides of the given string and escape the single quotation marks in the string, so that the string can be safely used as a command parameter.
Use the popen () function to open a process
The preceding method can only execute commands, but cannot interact with commands. However, sometimes you must enter something into the command. For example, when adding a Linux system user, you must call su to change the current user to the root user, the su command must enter the root password on the command line. In this case, it is obviously not feasible to use the method mentioned above.
The popen () function opens a process pipeline to execute the given command and returns a file handle. Since a file handle is returned, you can read and write it. In PHP3, you can only perform a single operation mode on the handle, either write or read. From PHP4, you can read and write the handle at the same time. Unless this handle is opened in a mode (read or write), you must call the pclose () function to close it.
Example 1:
/* Add a system user in PHP
The following is a routine. Add a user named james,
The root password is verygood. For reference only
*/
$ Sucommand = "su -- login root -- command ";
$ Useradd = "useradd ";
$ Rootpasswd = "verygood ";
$ User = "james ";
$ User_add = sprintf ("% s" % s "", $ sucommand, $ useradd, $ user );
$ Fp = @ popen ($ user_add, "w ");
@ Fputs ($ fp, $ rootpasswd );
@ Pclose ($ fp );

Require will not execute any more when there is an error code in the contained File
Include is still executed when there is an error code in the contained File

The htmlspecialchars () function converts some predefined characters into HTML objects.
The predefined characters are:
& (And number) become &
"(Double quotation marks)"
'(Single quotes)'
<(Less than) becomes <
> (Greater than) become>

The move_uploaded_file () function moves the uploaded file to the new location.

The extract () function imports variables from the array to the current symbol table.
For each element in the array, the key name is used for the variable name, and the key value is used for the variable value.
The second parameter type is used to specify how the extract () function treats such conflicts when a variable already exists and an element with the same name exists in the array.
This function returns the number of successfully set variables.
Syntax
Extract (array, extract_rules, prefix)

The parse_str () function parses the query string to a variable (common in the variable overwrite vulnerability)
Syntax
Parse_str (string, array)
Parameter description
String is required. Specifies the string to be parsed.
Array is optional. Specifies the name of the array that stores the variable. This parameter indicates that the variable is stored in the array.

Specify attacks against Variables
Use $ _ GET [(index)] instead of using foreach to traverse the $ _ GET variable.

The eval () function calculates the string according to the PHP code. The string must be a valid PHP code and must end with a semicolon.
If the return statement is not called in the code string, NULL is returned. If a parsing error exists in the Code, the eval () function returns false.

Preg_replace: search and replace a regular expression.
/E parameter Execution Code

0x03 Vulnerabilities
-----------------------------------------------
[1]. SQL-Injection
Note: cookie and x-forward-for, wide byte, error injection, etc.
Vulnerability mining reference
Variable
$ _ GET [""], $ _ POST [""], $ _ COOKIE [""], $ SERVER [""]
Database operation functions
Mysql_query ()
Digital Injection prevention:
1. is_numeric () ctype_digit () intval ()
2. str_length () determines the length.
Injection prevention:
1. mysql_real_escape_string ()
2. @ explosion-proof error added before the database query statement
3. str_length () determines the length.
-----------------------------------------------
[2]. Command-Execution
Function:
System (), passthru (), popen (), exec ()
Database operation functions:
Exec, system, popen, passthru, proc_open, shell_exec
Execute Command Pipeline character % |>
Test: 0 | dir c:
| Double vertical bars. If the preceding statement is incorrectly executed, the following statement is executed.
For example, xx "+ | + whoami + | + echo
-----------------------------------------------
[3]. File-transfer sion
Function:
Include (), require (), include_once (), require_once ()
Remote File Inclusion Vulnerability requirements
Allow_url_fopen () allow_url_include () file_get_contents ()
Bypass: zlib: // and ogg ://
Versions later than 5.2.0
Data: // text/plain; base64, PD9waHAgcGhwaW5mbygpOz8 + //
@ Eval (file_get_contents ('php: // input'); // POST phpinfo ();
With % 00 truncation, the new version automatically escapes \ 0
-----------------------------------------------
[4]. CSRF
CSRF Protection Policy
1> verify the http-referer Field
Low Security and easy to forge
2> Add and verify the token in the request address
The token can be stored in the session after the user logs on. During each request, the token is taken out of the session, and the requested token is compared to prevent CSRF
GET method: http: // url /? = Token


If a website receives many requests, the entire dom tree is traversed every time the page is loaded, and the token is added after each a and form tag in the dom.
However, the html code generated after loading the dynamic page must be manually added as hard-coded.
The security weakness of this method is that, for example, hacker can construct an environment to steal tokens and construct csrf attacks in areas with frequent interactions such as forums.
Therefore, manually disable referer
3> customize attributes in the HTTP header and verify the attributes. Use the XMLHttpRequest class.
This method is usually used for asynchronous page refreshing by Ajax.
However, it is adaptable and has great limitations on the existing website architecture.
-----------------------------------------------
[5]. XSS (Cross Site Script)
Reflective and storage
Control various input variables of $ _ GET, $ _ POST, and $ _ COOKIE
Use the htmlspecialchars () function for basic filtering
Automated exploitation with CSRF
-----------------------------------------------
[6]. File_Upload
Function: move_uploaded_file ()
Variable: $ _ FILES
PHP File Upload using form for file upload must use multipart/form-data for post to complete file data transfer
Php uses the $ _ FILES system function parameters and the move_upload_file function to upload temporary FILES generated by the $ _ FILES global variable to the specified directory.
$ _ FILES ['files'] ['name'] original name of the client file
$ _ FILES ['files'] ['type'] MIME type of the file
$ _ FILES ['files'] ['SIZE'] size of the uploaded file
$ _ FILES ['files'] ['tmp _ name'] indicates the temporary file name stored, which is generally the default file name.
$ _ FILES ['files'] ['error'] error code used to upload the file
Defense methods:
1> determine the mime type file type, such as $ _ FILES ['files'] ['type'] = "image/jpeg", and determine the file size, for example, $ _ FILES ['files'] ['SIZE'] <10000 & $ _ files ['files'] ['SIZE']> 100
2> specifies the upload file name, such as the time-dependent generation of hash(time).jpg, etc.
3> determine the file based on the file suffix
For example, file_ext = substr ($ filename, $ strrpos ($ filename, '.') + 1 );
Check whether there may be logic problems such as dual-extension and secondary upload breakthrough.
4> the server tries to render the file to determine whether it is an image.
5> File Upload types are not subject to client js script restrictions
6> whitelist rules
FAQs about apache Server Upload Security
1> upload with. htaccess
AllOverride ALL allows child rules to overwrite parent rules
Add AddType Application/x-httpd-php. jpg to. htaccess
2> file name resolution Vulnerability
*. Php.123
In. htaccess add AddHandler php5-script. php, the file name with PHP extension name can be PHP script execution, such as x.php.jpg
. Php3. php4 Extension

0x04 Configuration
1> pay attention to vulnerability information and update versions in a timely manner
2> php. ini httpd. conf. htaccess file configuration
1) safe_mode Configuration
2) Disable register_globals.
3) open_basedir configuration to prevent Directory Traversal
4) Close allow_url_fopen
5) disable_functions Configuration
6) Open magic_quotes_gpc
7) error_reporting = E_ALL &~ E_NOTICE
8) display_errors = Off to prevent attackers from obtaining more information.
9) expose_php = Off hide version information
3> minimize other account permissions on the server
4> third-party security reinforcement Software Installation
5> call a third-party security protection file to configure php. ini
Include_path = ".:/php/shortdes"
Auto_pretend_file = "anti-inj.php"
Auto_appent_file =

0x05 ideas
When I first started practicing auditing, I got a set of source code. What I did right away was to drop it into the tool, scan sensitive functions, trace it one by one, and find the entry point. However, auditing is a waste of time. Every time we trace back, we constantly look for some common functions defined in the source code. Without understanding the entire source code process, it wastes a lot of time and effort in the process of finding these general functions.
So I adjusted my audit process again. After obtaining the source code, read the code from where it starts (usually the index file under the root directory) in the executed order until it initializes the content, and the basic functions. In this way, you can clearly understand the structure of the entire source code, which function file is placed in which folder, and which file the common function is placed in. This is helpful when we read the code that is "suspected" and has a problem later. For example, when we see a common function, we can quickly switch to the common function file, find the implementation code of this function.
Note: here we will reference the article "PHP code audit learning summary", which is a reference for modifying the document of Tang men sanshao.

0x06 Summary
Code auditing, like reverse engineering, requires patience and care.
In addition, focusing on the latest vulnerabilities on the vulnerability release platform and tracking and analyzing them is also a way to quickly improve your capabilities.

Related Article

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.