PHP code Audit

Source: Internet
Author: User
Tags account security

 
The document was updated last year. It was not well written, and some were not fully written. I have referenced many documents.

The owasp codereview should also be 2.0.

Let's give some suggestions.

Directory

1. Overview 3

2. input verification and output display 3

2.1 command injection 4

2.2 XSS 4

2.3 file contains 5

2.4 code injection 5

2.5 SQL Injection 6

2.6 XPath injection 6

2.7 HTTP Response Splitting 6

2.8 File Management 6

2.9 File Upload 7

2.10 variable overwrite 7

2.11 dynamic functions 7

3. Session Security 8

3.1 HTTPOnly setting 8

3.2 domain settings 8

3.3 path setting 8

3.4 cookie duration 8

3.5 secure settings 8

3.6 session fixed 9

3.7 CSRF 9

4. Encryption 9

4.1 plaintext storage password 9

4.2 weak password encryption 9

4.3 passwords are stored in files accessible to attackers 9

5. authentication and authorization 10

5.1 user authentication 10

5.2 unauthenticated calls to functions or files 10

5.3 password hard-coded 10

6. Random Function 10

6.1 rand () 10

6.2 mt_srand () and mt_rand () 11

7. special characters and multi-byte encoding 11

7.1 multi-byte encoding 11

8. PHP dangerous functions 11

8.1 Buffer Overflow 11

8.2 session_destroy () File Deletion vulnerability 12

8.3 unset ()-zend_hash_del_key_or_index vulnerability 12

9. Information Leakage 13

9.1 phpinfo 13

10. PHP Environment 13

10.1 open_basedir settings 13

10.2 allow_url_fopen settings 13

10.3 set allow_url_include 13

10.4 set safe_mode_exec_dir to 14

10.5 magic_quote_gpc settings 14

10.6 register_globals settings 14

10.7 safe_mode settings 14

10.8 session_use_trans_sid settings 14

10.9 display_errors settings 14

10.10 expose_php settings 14

 


Overview
Code review is a systematic check of the application source code. It aims to find and fix some vulnerabilities or program logic errors in the application development stage, so as to prevent the illegal exploitation of program vulnerabilities from bringing unnecessary risks to the Enterprise.

Code review is not a simple code check. The reason for reviewing the Code is to ensure that the code can be securely protected by sufficient information and resources, therefore, it is very important to be familiar with the business process of the entire application to control potential risks. Reviewers can use questions similar to the following to interview developers to collect application information.

What types of sensitive information does an application contain and how does the application protect it?

Does an application provide internal services or external services? Who will use it? Are they all trusted users?

Where is the application deployed?

What is the importance of applications for enterprises?

The best way is to make a checklist for developers to fill in. Checklist can intuitively reflect application information and coding Security done by developers. It should cover modules that may have severe vulnerabilities, such: data verification, identity authentication, session management, authorization, encryption, error processing, logs, security configuration, and network architecture.

Input verification and output display
Most vulnerabilities are caused by the absence of security verification on input data or the absence of Security Processing on output data. Strict data verification methods are as follows:

Exact data matching

Accept data from the whitelist

Reject blacklist data

Encode the data that matches the blacklist

In PHP, the list of variables that users can enter is as follows:

$ _ SERVER

$ _ GET

$ _ POST

$ _ COOKIE

$ _ REQUEST

$ _ FILES

$ _ ENV

$ _ HTTP_COOKIE_VARS

$ _ HTTP_ENV_VARS

$ _ HTTP_GET_VARS

$ _ HTTP_POST_FILES

$ _ HTTP_POST_VARS

$ _ HTTP_SERVER_VARS

We should check these input variables

Command Injection
PHP can use the following functions to execute system commands: system, exec, passthru, '', shell_exec, popen, proc_open, and pcntl_exec.

By searching for these functions in all program files, we can determine whether the function parameters will change due to external submissions and check whether these parameters have been safely processed.

Defense methods:

Use a user-defined function or function library to replace the functions of External commands

Use the escapeshellarg function to process Command Parameters

Use safe_mode_exec_dir to specify the path of the executable file

XSS
Reflected cross-site variables are often processed after they are submitted by the user, and are directly output to the client. Stored cross-site variables are often processed after they are submitted by the user, stored in the database, and then read the information from the database and output it to the client. Output functions are often used: echo, print, printf, vprintf, <% = $ test %>

For cross-site reflection, because the output is immediately displayed to the client, check whether the variable is immediately displayed after the client submits the variable on the current php page, whether the variables have been checked for security during this process.

For the storage-type cross-site, check whether the variables have passed the security check during the input and output of the input variables.

Defense methods:

If the input data only contains letters and numbers, any special characters should be blocked.

The entered data is strictly matched by the line, such as the mail format. The user name can only contain English letters, Chinese characters, underscores, and hyphens.

Encode the output in HTML Format

<& Lt;

> & Gt;

(& Amp; #40;

) & #41;

#&# 35;

& Amp;

"& Quot;

& Apos;

'% 60

File Inclusion
PHP may contain functions including include, include_once, require, require_once, show_source, highlight_file, readfile, file_get_contents, fopen, and file.

Defense methods:

Accurately match the input data, for example, determining the language en based on the value of the variable. php, cn. php, then the two files are placed in the same directory 'language /'. $ _ POST ['lang ']. '. php ', check whether the submitted data is en or cn is the strictest, and check whether it only contains letters.

Filter the/,..., and other characters in the parameter.

Code Injection
PHP may have code injection functions: eval, preg_replace +/e, assert, call_user_func, call_user_func_array, create_function

Find the places where these functions are used in the program, and check whether the submission variables are controllable and whether input verification is performed.

Defense methods:

Exact match of input data

Filter executable functions by whitelist

SQL Injection
Because SQL injection is required to operate the database, it generally finds Keywords of SQL statements: insert, delete, update, and select to check whether the passed variable parameters are controllable and whether they have been safely processed.

Defense methods:

Use parameterized Query

XPath Injection
Xpath is used to operate xml. we search for xpath to analyze whether the parameters submitted to the xpath function are processed safely.

Defense methods:

Exact data matching

HTTP Response Splitting
In PHP, the HTTP Response Splitting may be caused by the use of the header function and the $ _ SERVER variable. Note that PHP later versions will disable line breaks in the HTTP header. You can skip this test directly.

Defense methods:

Exact match of input data

Check if any or is in the input.

File Management
PHP functions for file management. If the input variables can be submitted by the user, no data verification is performed in the program, which may become a high-risk vulnerability. We should search for the following functions in the program: copy, rmdir, unlink, delete, fwrite, chmod, fgetc, fgetcsv, fgets, fgetss, file, file_get_contents, fread, readfile, ftruncate, file_put_contents, fputcsv, fputs, however, every file operation function in PHP may be dangerous.

Http://ir.php.net/manual/en/ref.filesystem.php

Defense methods:

Strictly match submitted data

Limits the accessible directories of Files

File Upload
For PHP file uploads, move_uploaded_file is usually used. You can also find the file upload program for detailed analysis.

Defense methods:

Use whitelist to detect file suffixes

Generate file names by Algorithm Based on Time after upload

The uploaded directory script file cannot be executed.

Note: % 00 Truncation

Variable Overwrite
PHP variable overwrite may occur in the following situations:

Traverse initialization Variables

Example:

Foreach ($ _ GET as $ key => $ value)

$ Key = $ value;

Function override variables: parse_str, mb_parse_str, and import_request_variables

When Register_globals = ON, the variables submitted in GET mode will be overwritten directly.

Defense methods:

Set Register_globals = OFF

Do not use these functions to obtain variables.

Dynamic Functions
When dynamic functions are used, attackers can execute arbitrary functions if the variables are controllable.

Example:

<? Php

$ Myfunc = $ _ GET [myfunc];

$ Myfunc ();

?>

Defense method:

Do not use functions like this

Session Security
HTTPOnly settings
Session. cookie_httponly = ON, the client script (JavaScript, etc.) cannot access this cookie. Enabling this command can effectively prevent session ID hijacking through XSS attacks.

Domain settings
Check whether session. cookie_domain only contains this domain. If it is a parent domain, other subdomains can obtain cookies of this domain.

Path settings
Check session. cookie_path. If the website is applied to/app, the path must be set to/app/to ensure security.

Cookie duration
Check session. cookie_lifetime. If the time setting process is too long, even if the user closes the browser, attackers may also endanger account security.

Secure Settings
If HTTPS is used, set session. cookie_secure = ON to ensure that HTTPS is used to transmit cookies.

Fixed session
If the permission level changes (for example, after verifying the user name and password, the common user is promoted to the Administrator), we should modify the session ID to be re-generated, otherwise, the program may face the risk of Session Fixation attacks.

CSRF
Cross-Site Request Forgery Attack: attackers forge a malicious request link to allow normal user access in various ways

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.