A ramble on PHP security

Source: Internet
Author: User
Tags ereg execution connect sql mysql sprintf sql injection file permissions

The security environment discussed in this article is in linux+apache+mysql+php. Security issues beyond this range are outside the scope of this article.

First, Apache server security settings

1, to nobody users to run

In general, Apache is installed and run by root. If the Apache server process has root privileges, it poses a significant threat to the security of the system and should ensure that the Apache server process runs with the most likely user privileges. By modifying the following options in the httpd.conf file, nobody the user to run Apache for relative security purposes.
User Nobody
group#-1

2, the ServerRoot directory permissions

To ensure that all configurations are appropriate and secure, it is necessary to strictly control the access rights of the Apache home directory so that non-superuser users cannot modify the contents of the directory. The Apache home directory corresponds to the server root control of the Apache server configuration file httpd.conf, which should be:
Server Root/usr/local/apache

3. SSI Configuration

The includes NO exec option is added to the options directive in the configuration file access.conf or httpd.conf to disable executive function in Apache Server. To avoid the user directly execute the Apache server execution program, resulting in the public server system.

Options Includes noexec


4. Prevent users from modifying system settings

The following settings are made in the Apache server configuration file to prevent users from creating, modifying, and htaccess files to prevent users from exceeding the defined system security features.

Allowoveride None
Options None
Allow from all

The appropriate configuration is then made to the specific directory separately.

5, change the Apache server's default access characteristics

Apache's default settings guarantee only a certain degree of security, if the server can find the file through the normal mapping rules, then the client will get the file, such as Http://local host/~ root/will allow users to access the entire file system. Add the following in the server file:

Order Deny,ellow
Deny from all

Default access to the file system is blocked.

6. Security Considerations for CGI scripts

A CGI script is a series of programs that can be run through a Web server. To ensure the security of the system, it should be ensured that the CGI author is trustworthy. In the case of CGI, it is best to limit it to a specific directory, such as Cgi-bin, for ease of management, and to ensure that the files in the CGI directory are not writable and that some deceptive programs reside or are involved; If you can provide a security-friendly CGI program module as a reference, It may reduce the number of unnecessary problems and security risks, and remove all the non-business application scripts in the CGI directory to prevent abnormal information leaks.

7, SSL link encryption

These commonly used measures can give Apache Server a basic safe operating environment, obviously in the implementation of the further refinement of the decomposition, to develop a practical application of the Security Configuration scheme.

Second, PHP security settings

The server does not prevent all security issues, such as program vulnerabilities, user input form issues, PHP file permissions issues, and so on.
You can also use some means to confuse hackers or those with ulterior motives.
1. Program code vulnerabilities

Many PHP programs have a major weakness is not the problem of PHP language itself, but the programmer's security awareness is not high. Therefore, you must always pay attention to the possible problems of each piece of code to discover the possible impact of incorrect data submission.

?
1 2 3 4 5 6 <?php unlink ($evil _var); Fwrite ($fp, $evil _var); System ($evil _var); EXEC ($evil _var);?>

You must always be aware of your code to ensure that every variable submitted from the client is properly checked, and then ask yourself the following questions:

    • Does this script affect only the files that you expect?
    • Can the abnormal data be brought into effect after being submitted?
    • Can this script be used for unplanned purposes?
    • Can this script be combined with other scripts to do bad things?
    • Are all the transactions fully documented?

Ask yourself these questions while writing the code, or you might want to rewrite the code for added security later. If you pay attention to these problems, you may not be able to guarantee the security of the system, but at least it will improve security.

You can also consider turning off register_globals,magic_quotes or other settings that make programming easier but will cause the legality, source, and value of a variable to be messed up.


2, user input form problem
Verify any data entered by the user to ensure the security of the PHP code.
Note that 1:JS is only created to improve the experience of the visiting user, not the validated tool. This layer of validation can be skipped because any visiting user may or may not accidentally disable client script execution. So we have to test this data on the PHP server-side program.
Note 2: Do not use the $_server[' Http_referer ' as the super variable to check the source address of the data, a very small novice hacker will use tools to forge this variable data, as far as possible using MD5, or Rand functions such as to produce a token, verify the source, Verify that this token matches.

3, PHP file permissions issues

PHP is designed to access the file system at the user level, so it is entirely possible to write a section of PHP code to read system files such as/etc/passwd, change network connections, and send a large number of print tasks, and so on. Therefore, you must ensure that the PHP code reads and writes the appropriate files. Take a look at the code below, where the user wants to delete a file in their home directory. Suppose this scenario is to manage the file system through the Web interface, so the Apache user has the right to delete files in the user directory.

?
1 2 3 4 5 6 7 <?php $username = $_post[' user_submitted_name ']; $homedir = "/home/$username"; $file _to_delete = "$userfile"; Unlink ("$homedir/$userfile"); echo "$file _to_delete has been deleted!"; ?>

Since the username variable can be committed through the user table forms, it is possible to submit someone else's username and file name and delete the file. In this case, consider other forms of authentication:

    • Only a limited number of permissions are given to PHP's web users.
    • Check all the submitted variables.

The following are more secure file names and variables for validation and checking:

?
1 2 3 4 5 6 7 8 9 10 <?php $username = $_server[' Remote_user '];   $homedir = "/home/$username";   if (!ereg (' ^[^./][^/]*$ ', $userfile)) die (' bad filename '); if (!ereg (' ^[^./][^/]*$ ', $username)) Die (' bad username ');?>


4. Hide php Extension

In general, improving security by means of concealment is considered a less useful practice. But in some cases, it is worthwhile to add as much security as possible.

Some simple ways to help hide PHP can make it more difficult for attackers to discover system vulnerabilities. Setting expose_php = off in the php.ini file can reduce the useful information they can get.

Another strategy is to have the Web server parse different extensions in PHP. Either through the. htaccess file or the Apache configuration file, you can set a file extension that can mislead an attacker:

# make PHP look like any other programming language
AddType application/x-httpd-php. asp. py. pl

# make PHP look like an unknown file type
AddType application/x-httpd-php. Bop. Foo. 133t

# make PHP code look like an HTML page
AddType application/x-httpd-php. htm. html

For this method to take effect, you must change the extension of the PHP file to the extension above. This improves security by hiding, albeit with low defense and some drawbacks.


Third, MySQL database security settings

PHP itself does not protect the security of the database. The following sections simply describe how to use PHP scripts for basic access and manipulation of a database. Remember a simple rule: deep defense. The more measures are taken to protect the database, the more difficult it is for an attacker to obtain and use information within the database. The proper design and application of databases can reduce the fear of being attacked.

1, Database design problems

Applications should never use the database owner or Superuser account to connect to the database because they can perform arbitrary actions, such as modifying the database structure (such as deleting a table) or emptying the contents of the entire database. The user settings for the screenshot below are dangerous.

You should create different database accounts for each aspect of your program and give you very limited permissions on database objects. Assign only the permissions that are required to complete its function, and avoid the same user being able to accomplish another user's business. This way, even if an attacker exploits a program vulnerability to gain access to the database, it can only be as affected as the program.

2. Database Connectivity Issues

Establishing a connection on SSL encryption can increase the security of client and server-side communication, or SSH can also be used to encrypt the connection between the client and the database. If these techniques are used, it is difficult for an attacker to monitor the server's communications or get information about the database.

3. Encryption of database data

Ssl/ssh can protect data exchanged between client and server, but Ssl/ssh does not protect the data already in the database. SSL is just a protocol that encrypts network data streams.

If an attacker obtains permission to access the database directly (bypassing the Web server), sensitive data may be exposed or misused unless the database itself protects the information. Encrypting data within a database is an effective way to reduce this type of risk, but only a few databases provide these encryption capabilities.

For this problem, there is a simple solution is to create their own encryption mechanism, and then use it in the PHP program, the most common example is the password after MD5 encrypted hash into the database to replace the original plaintext password.

?
1 2 3 4, 5 6 7 8 9 10 11 12 13 14 15 <?php $query = sprintf ("INSERT into Users (name,pwd) VALUES ('%s ', '%s ');", Addslashes ($username), MD5 ($password));   $result = Pg_query ($connection, $query); $query = sprintf ("Select 1 from Users WHERE name= '%s ' and pwd= '%s ';", Addslashes ($username), MD5 ($password));   $result = Pg_query ($connection, $query); if (Pg_num_rows ($result) > 0) {echo ' Welcome, $username! '} else {echo ' Authentication failed for $username. '}? &G T

4, SQL injection problem

Direct SQL command injection is a technique commonly used by attackers to create or modify existing SQL statements to achieve hidden data, or to overwrite critical values, or even to execute database host operating system commands. This is accomplished by using the application to obtain user input and combining static parameters into SQL queries. Some real examples will be given below.

?
1 2 3 4 5 6 7 8 <?php $query = "SELECT ID, name, inserted, size from products WHERE size = ' $size ' ORDER by $order LIMIT $limit, $off set; ";   $result = Odbc_exec ($conn, $query); ?>

You can add another SELECT query based on the original query to get the password:

Union select ' 1 ', concat (uname '-' passwd) as name, ' 1971-01-01 ', ' 0 ' from usertable;

If the above statement (using ' and--) is added to any variable in the $query, then it is troublesome.


These attacks are always based on the discovery of code that is not strong in security sense. Therefore, never trust data entered by the outside world, especially from clients, including selection boxes, form hiding fields, and cookies. As the first example above, even a normal query can cause disaster.

    • Never use a superuser or owner account to connect to a database. The account to be strictly restricted with permissions.
    • Checks whether the data entered has the desired data format. PHP has a number of functions that can be used to check input, from simple variable functions and character type functions (such as is_numeric (), Ctype_digit ()) to complex Perl-compatible regular expression functions to do this work.
    • If the program waits for a number to be entered, consider using Is_numeric () to check it, or use Settype () to convert its type, or use sprintf () to format it as a number.

A more secure way to prevent SQL injection from paging:
?
1 2 3 4 5 6 7 8 <?php Settype ($offset, ' Integer '); $query = "SELECT ID, name from [Order by name LIMIT OFFSET $offset;";   $query = sprintf ("Select ID, name from [] LIMIT OFFSET%d;", $offset); ?>


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.