PHP Security Talk_PHP Tutorial

WBOY
Release: 2016-07-21 15:18:27
Original
838 people have browsed it

1. Apache server security settings

1. Run as Nobody user

Generally, Apache is installed and run by Root. If the Apache Server process has Root user privileges, it will pose a great threat to system security. You should ensure that the Apache Server process runs as the user with the lowest possible privileges. By modifying the following options in the httpd.conf file, you can run Apache as the Nobody user to achieve relative security.
User nobody
Group# -1

2. Permissions of the ServerRoot directory

In order to ensure that all configurations are appropriate and secure, access to the Apache home directory needs to be strictly controlled Permissions so that non-superusers cannot modify the contents of the directory. The home directory of Apache corresponds to the Server Root control item in the Apache Server configuration file httpd.conf, which should be:
Server Root /usr/local/apache

3. SSI configuration

Add the Includes NO EXEC option to the Options directive in the configuration file access.conf or httpd.conf to disable the execution function in Apache Server. Prevent users from directly executing the execution program in the Apache server, which will cause the server system to be exposed.

Options Includes Noexec


4. Prevent users from modifying system settings

Make the following settings in the configuration file of the Apache server to prevent users from creating and modifying .htaccess file to prevent users from overriding definable system security features.

AllowOveride None
Options None
Allow from all

Then configure the specific directories appropriately.

5. Change the default access characteristics of the Apache server

The default settings of Apache can only guarantee a certain degree of security. If the server can find the file through normal mapping rules, the client will Obtaining this file such as http://local host/~root/ will allow the user to access the entire file system. Add the following content to the server file:

order deny,ellow
Deny from all

will disable default access to the file system.

6. Security considerations of CGI scripts

CGI scripts are a series of programs that can be run through a web server. In order to ensure the security of the system, you should ensure that the author of the CGI is trustworthy. For CGI, it is best to limit it to a specific directory, such as cgi-bin, for easy management; in addition, you should ensure that the files in the CGI directory are not writable to avoid some deceptive programs from residing or mixing. Among them; if you can provide users with a module of a CGI program with good security as a reference, it may reduce many unnecessary troubles and security risks; remove all non-business application scripts in the CGI directory to prevent abnormal information leakage.

7. SSL link encryption

The above common measures can give Apache Server a basic safe operating environment. Obviously, further refinement and decomposition are needed in the specific implementation to formulate a suitable Security configuration solutions for practical applications.

2. PHP security settings

The server cannot prevent all security issues, such as program vulnerabilities, user input form issues, PHP file permission issues, etc.
You can also use some means to confuse hackers or people with ulterior motives.
1. Program code vulnerabilities

The major weaknesses in many PHP programs are not problems with the PHP language itself, but are caused by programmers' low security awareness. Therefore, you must always pay attention to possible problems in each piece of code to discover the possible impact of incorrect data submission.

Copy code The code is as follows:

unlink ($evil_var);
fwrite ( $fp, $evil_var);
system ($evil_var);
exec ($evil_var);
?>

Always pay attention to your code to ensure that every variable submitted from the client is properly checked, and then ask yourself some questions:

Does this script only affect the files it is expected to have?
Can abnormal data have any effect after being submitted?
Can this script be used for unintended purposes?
Can this script be combined with other scripts to do bad things?
Are all transactions adequately documented?
Ask yourself these questions when writing code, otherwise you may have to rewrite your code to increase security in the future. If you pay attention to these problems, you may not be able to completely guarantee the security of the system, but you can at least improve the security.

Also consider turning off register_globals, magic_quotes or other settings that make programming more convenient but will mess up the legality, source and value of a variable.

2. User input form issues

Verify any data entered by the user to ensure the security of the PHP code.
Note 1: JS is only produced to improve the experience of visiting users, not a verification tool. Because any visiting user may or may inadvertently disable the execution of client scripts, thereby skipping this layer of verification. So we must verify this data on the PHP server-side program.
Note 2: Do not use the super variable $_SERVER['HTTP_REFERER'] to check the source address of the data. A small novice hacker will use tools to forge the data of this variable. Use Md5, rand and other functions as much as possible. To generate a token, when verifying the source, verify whether the token matches.

3. PHP file permission issues

PHP is designed to access the file system at the user level, so it is entirely possible to read system files such as /etc/passwd by writing a piece of PHP code. Change network connections, send large print jobs, and more. So you have to make sure that your PHP code is reading and writing the appropriate files. Please look at the code below. The user wants to delete a file in his home directory. Assume this scenario is that the file system is managed through the web interface, so the Apache user has permission to delete files in the user directory.
Copy code The code is as follows:

$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 submitted through the user form, you can submit other people's username and file name and delete the file. In this case, other methods of authentication should be considered:

Only give PHP web users very limited permissions.
Check all submitted variables.
The following is a more secure verification and check of file names and variables:
Copy the code The code is as follows:

< ?php
$username = $_SERVER['REMOTE_USER'];
$homedir = "/home/$username";

if (!ereg('^[^./][^ /]*$', $userfile))
die('bad filename');

if (!ereg('^[^./][^/]*$', $username) )
die('bad username');
?>


4. Hide PHP extension

Generally speaking, improving security through hidden means is considered to be of little effect. But in some cases, adding as much security as possible is worth it.

Some simple methods can help hide PHP and in doing so make it more difficult for attackers to discover system weaknesses. Setting expose_php = off in the php.ini file reduces the amount of useful information they can obtain.

Another strategy is to have the web server parse the different extensions using PHP. Whether through .htaccess files or Apache configuration files, you can set file extensions that can mislead attackers:



# Make PHP look like other programming languages ​​
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 the PHP code look like an HTML page
AddType application/x-httpd-php .htm .html

For this method to take effect, the extension of the PHP file must be changed to The above extension. This improves security through concealment, although defense capabilities are low and have some drawbacks.

3. Mysql database security settings

PHP itself cannot protect the security of the database. The following chapters only describe how to use PHP scripts to perform basic access and operations on the database. Remember one simple rule: defend in depth. The more measures you take to protect your database, the harder it will be for attackers to obtain and use the information within the database. Properly designing and implementing your database can reduce the worry of being attacked.

1. Database design issues

Applications should never use the database owner or superuser account to connect to the database, because these accounts can perform arbitrary operations, such as modifying the database structure (such as deleting a table) or clear the contents of the entire database. The user settings in the screenshot below are dangerous.


Separate database accounts should be created for each aspect of the program and given very limited permissions on database objects. Assign only the permissions required to complete their function to prevent the same user from being able to complete another user's tasks. In this way, even if an attacker exploits a program vulnerability to gain access to the database, he or she can only have the same scope of impact as the program.

2. Database connection issues
Establishing the connection based on SSL encryption technology can increase the security of client-server communication, or SSH can also be used to encrypt the connection between the client and the database. If these techniques are used, it will be difficult for an attacker to monitor server communications or obtain database information.

3. Encryption of database data

SSL/SSH can protect the data exchanged between the client and the server, but SSL/SSH cannot protect the data already in the database. SSL is simply a protocol that encrypts network data streams.

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

For this problem, there is a simple solution, which is to create your own encryption mechanism and then use it in the PHP program. The most common example is to store the MD5 encrypted hash of the password into the database. to replace the original clear text password.

Copy code The code is as follows:

$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.';
}
?>


4. SQL injection problem

Direct SQL command injection is commonly used by attackers A technique for creating or modifying existing SQL statements to obtain hidden data, overwrite key values, or even execute database host operating system commands. This is accomplished by the application taking user input and combining it with static parameters into an SQL query. Some real examples will be given below.

Copy code The code is as follows:

$query = "SELECT id, name , inserted, size FROM products
WHERE size = '$size'
ORDER BY $order LIMIT $limit, $offset;";
$result = odbc_exec($conn, $query);
?>


You can add another SELECT query to 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 $query, then there will be trouble.

These attacks are always based on exploiting code with weak security awareness. Therefore, never trust data entered from the outside, especially from the client, including select boxes, form hidden fields, and cookies. As in the first example above, even a normal query can cause disaster.

Never use a superuser or owner account to connect to a database. Use an account with strictly restricted permissions.
Check whether the input data has the expected data format. PHP has many functions that can be used to check input, ranging from simple variable functions and character type functions (such as is_numeric(), ctype_digit()) to complex Perl-compatible regular expression functions that can do this job.

If the program is waiting for a number to be entered, consider using is_numeric() to check, or directly use settype() to convert its type, or use sprintf() to format it as a number.

A safer paging display method to prevent SQL injection:

Copy the code The code is as follows:

settype($offset, 'integer');
$query = "SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET $offset;";
$query = sprintf("SELECT id, name FROM products ORDER BY name LIMIT 20 OFFSET %d;",
$offset);
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/325517.htmlTechArticle1. Apache server security settings 1. Run as Nobody user. Under normal circumstances, Apache is installed and installed by Root. running. If the Apache Server process has Root user privileges, then it will...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template