PHP security configuration

Source: Internet
Author: User
Tags mysql update administrator password

Recently, my company's servers have been marked for a while. I have never found a good solution. Now, I find some useful personal information for the moment. I also hope that some of my friends will offer a better solution. Solve the problem

//////////////////////////////////////// //////////////////////////////////////// /////////////////////////////////////////

 

Pay attention to the filtering of some functions.

Some functions areProgramIs frequently used, such as include (), require (), fopen (), fwrite (), readfile (), unlink (), Eval () and their variant functions. These functions are very practical, and they do not mean that you have to worry about them. You have to pay more for them.

1. include (), require (), fopen (), include_once (), and require_once () can all remotely call files. If you search for these files, you will be very clear about the harm they cause, if you do not filter out the variables that contain the call, you can include any file and execute it. For example, let's look at print. php.

...
If (empty ($ bn) {// check whether the variable $ BN is null
Include
("$ Cmd_dir/Site _ $ {site}. php"); // include site _ $ {site}. php In the $ cmd_dir path
...

No matter the $ external _dir directory does not exist, you can use the $ site variable naturally because it does not check the $ site variable. You can specify a remote file to call the variable $ site or a local file. Write the PHP statement in the specified file, then it will include the file that executes this PHP statement. just like this

List file directories

It can even be expanded to include some administrator files to improve permissions, typically like vulnerabilities in phpwind and Bo-blog. Besides relying on PHP. set allow_url_fopen in ini to off to prohibit Remote use of files and open_base_dir to prohibit files other than directories. You have to declare in advance which files can only be included, so I will not talk about it here.

2. fopen (), file (), readfile (), openfile (), and so on are also important points. The function itself has nothing to do. Its function is to open the file, but if the variable is not completely filtered, it will be leaked.Source code. There will be many such function text forums.

...
$ Articlearray = openfile ("$ dbpath/$ FID/$ tid. php ");
// Open the $ tid. php file in the $ dbpath/$ FID path.

$ Topic_detail = explode ("", $ articlearray [0]); // read the Post content with a delimiter
...

Familiar with this. This is the read. php version of ofStar, $ FID and $ TID are not filtered, and $ TID is specified as a file to be submitted.CodeLeakage. Just like this.

Http://explame.com/ofstar/read.php? FID = 123 & tid = ../Index

$ TID will be suffixed with PHP, so you can directly write the index. This is just an example. Let's take a look.

3. fwrite () and its variant functions. If you do not filter the characters submitted by the user, it is not impossible to write a PHP backdoor.

4. unlink () function. Some time ago, this function was used to delete any file in phpwind. If the variable to be deleted is not filtered, the variable can be specified as any file, of course, you can delete any file variable.

5. eval (), preg_replace () functions are used to execute PHP code. If the string is not filtered, what will happen? I often see some CMS functions used in it, think about it. Isn't a PHP Trojan built based on the eval () Principle?

6. for system (), you will say in PHP. this is also a good way to disable system functions in ini. But as some programs need it, isn't it necessary? Just like the beautiful PHP album I saw last time. In addition, you must pay special attention to the popen (), proc_open (), proc_close () functions, even though they do not directly output the output after executing the command, but do you think this is useful to hackers. Here, PHP provides two functions, escapeshellarg () and escapeshellcmd (), which are used to defend against system function call attacks, that is, filtering.

For hazards, let's take a look at a forum's prod. php.

07 $ doubleapp = isset ($ argv [1]);
// Initialize the variable $ doubleapp
...
14 if ($ doubleapp) // If statement
15 {
16
$ Appdir = $ argv [1]; // initialize $ appdir
17 system ("mkdir $ proddir/$ appdir ");
// Use the system function system to create the directory $ proddir/$ appdir

It was originally used to create the $ proddir/$ appdir directory. Then it looks like the program only checks whether $ argv [1] exists and does not need to filter $ argv [1, then you can

/Prod. php? Argv [1] = ls % 20-La or/prod. php? Argv [1] = cat % 20/etc/passwd

(The Delimiter is a UNIX pipeline parameter. You can run multiple commands .)

By now, you should know the common vulnerability types.

Special characters

A special character is called all puts is.
Invalid. ForeignerArticleThis sentence is very common. All inputs are harmful. You should never worry about what users enter. To deal with these dangers, programmers are busy filtering out a large number of characters, lest they miss something. What about some programmers? It seems that you have never paid attention to these issues and have always opened the door to vulnerabilities. Let's take a look at the following things.

1. In fact, the most critical component of a program's vulnerability is the dollar symbol with the $ symbol. variables are everything for those looking for vulnerabilities. Just like the directory traversal bug, many email programs exist, and developers have considered it very well. Some even add the network hard disk.

Http://mail.com/file.php? Id = 1 & put = List & tid = 1 & file = ./

What if we change the file variable to.../or even a higher level? The directory is traversed.

2. You don't know the cross-site support. Some articles and comments in the search bar, such as the cross-site support in the phpwind attachment some time ago. Of course, for Cross-Site problems, you need to filter far more than angle brackets. You are afraid of missing content when filtering, but you cannot remember to filter.

3. Diagonal bars and reverse Bars: Do you remember the original code leakage at the attachment Download Area of the magic forum for filtering/and?

Attachment. php? Id = 684 & U = 3096 & Extension = GIF & attach =. \... \ .. \ des \ config.php&filename=1.gif

For the issue of filtering ../\, for example, Windows host should not only filter ../but also filter .. \. Windows host will parse \ /.
Compared with injection, what is depth?

4. for backquotes (''), backquotes are very powerful in PHP. They can execute system commands, just like system functions, if a user's malicious statement is executed by it, the server will be compromised. I think you can filter the statements in a down-to-earth Manner in addition to setting the server well.

5. it is useful for line breaks, null characters, and so on, such as "\ t, \ x0b, \ n, \ r, \ 0, the previous Upload Vulnerability of IMG was caused by the null (\ 0) character in the upload. For those characters that can freely intercept the program flow, how careful should we be during the detection?

6. semicolon (;) and delimiter ()

The semicolon truncates the program flow, just like this

Shell_exec ("del
./Yourpath/$ File "); // use the system function shell_exec to delete the file $ File

If the variable $ file is not specified, write zizzy. php; del./yourpath directly, so that your yourpath directory will be Del.

The delimiter () is a built-in Pipeline Function in Unix. It can be connected to several commands for execution. Sometimes it is added to system functions that are not strictly filtered.

Logical error

Incomplete verification and some logical errors can be easily found in the program, especially for the current programmers, who only need to study in depth, but have no security awareness such as logical errors, in fact, this is based on your own training, rather than waiting for people to report bugs to you. For the determination of logical errors, we can only say that experience is the most important thing.

1. Questions about login verification. For example, let's look at the admin. php snippet of a forum.

Here, username and
There seems to be something wrong with the password. If there is an administrator's username and password, it will pass the verification directly. That means there is no user name, and there is no password. We submit

GET/BBS/admin/index. php? Page = General HTTP/1.1
Accept:
Image/GIF, image/X-xbitmap, image/JPEG, image/pjpeg,
Application/X-Shockwave-flash ,*/*
Accept-language: ZH-CN

Accept-encoding: gzip, deflate
User-Agent: Mozilla/4.0 (compatible;
MSIE 6.0; Windows NT 5.1; sv1; Maxthon)
HOST: 127.0.0.1
Connection:
Keep-alive
COOKIE: username = 'or isnull (1/0) and level = 3/*; Password =;

This is a counterfeit data packet (you asked me how to forge it? Packet Capture and modify). We use get to submit data. The principle is to construct a spoofing statement in the cookie.

Then, the entire SQL statement is like this.

Select * from users where username = ''or
Isnull (1/0) and level = 3/* 'and Password =''

Here we only use the principle of 'or' = 'or' to bypass the detection of username and password, while level = 3 is a forged level. This allows us to skip detection and go to the management background.

Verification on the background cannot be so sloppy. Even if two lines of code are finished, you have to enhance verification from sessions and cookies.

2. Upload Vulnerability

Once I saw that the restrictions on the types of uploaded files in config. php are as follows:

$ Illegalextentions =
Array ('exe ', 'asp', 'php', 'php3 ', 'bat', 'cgi ', 'pl', 'com ', 'vbs ', 'reg ', 'pcd', 'pif', 'Scr ', 'bas', 'inf ', 'vb', 'vbe ', 'wsc', 'wsf ', 'wsh ');
// For File Upload restrictions, only EXE, ASP, PHP, php3, bat, CGI, PL, COM, vbs, Reg, PCD, PIF, Scr, Bas, INF, VB, VBE, WSC, WSF, and ws' files.

It specifies that users are not allowed to upload any files, and other files can be uploaded. Is this logic good? If I upload. Inc,. PhP4. phtml,. html,. pwml
What about this type? Why don't you change this logic thinking to stipulate that users are not allowed to upload all of these files. In this way, the array is changed to reverse thinking.

$ Illegalextentions =
Array ('rar ', 'gif', 'jpg', 'bmp ', 'pdf') // only rar, GIF, JPG, BMP, and PDF files can be uploaded.

In fact, this is the same as uploading the CER to you. ASA is a truth.

3. Typical logical errors

Register a user in some CMS (whole site program). You will find that you do not need to enter the original password to modify the information, only by judging the user ID or email, you save the webpage locally and change the ID or email to the Administrator's, Action
Modify the submission address and you will become the administrator. The solution is not difficult. As long as we add password verification, it will be OK to enhance the filtering of the MySQL update statement.

There is no way for us. Most programmers don't care about security at all. Why do we need to separate Web security and web development from what one can do?

Length Problem

Don't think that the attacker is looking for a vulnerability to get an administrator password or webshell. There are also some disturbing people, that is, ddoser (DOS attackers). They have many tricks, but for programmers, the key is filtering. I am talking about the length problem, not only the length of characters, but also the length of time. You must have seen someone write a script and register thousands of users at once, or simply drag the database to death by writing junk data. At this time, it takes effect to restrict the data submission time and verification code. However, if you really encounter a virus, a variable filtering problem can paralyze the website, which is faster than what kind of BOT software is used.

Not a big problem

1. absolute path Leakage

This is not a big problem. Many programs have it, which is also a part of the security. At least you need to inject LoadFile. Of course, display_errors in PHP. INI also works.

2. backend Verification

Do not believe it or not, I have seen some programs like this. You should test, register a user, and submit the Administrator to edit the user URL, such as admin_member.php? Action = edit & id = 55 level = 4 & username = zizzy & Power = 1 and add the Administrator URL. You will find that the URL is almost unverified and has succeeded. Therefore, it is also necessary for background detection, just like the vulnerability of discuz.

The question of filtering has been said so much without knowing it. I wrote a lot of reminders about filtering. Now I should also talk about how to filter.

1. When a user inputs any data, that is, when submitting a variable to the database, we must use addslashes () for filtering. For example, if we have an injection problem, an addslashes () will be done. In fact, when variable values are involved, the intval () function is also a good choice for string filtering.

2. Enable magic_quotes_gpc and magic_quotes_runtime in PHP. ini. Magic_quotes_gpc can change the quotation marks in get, post, and cookie to a slash. Magic_quotes_runtime can be used as a format for inbound and outbound data. In fact, this parameter is very popular as early as the previous injection was crazy.

3. When using system functions, you must use the escapeshellarg () and escapeshellcmd () parameters to filter them out. In this way, you can safely use system functions.

4. For cross-site, strip_tags () and htmlspecialchars () parameters are both good. for user-submitted tags with HTML and PHP, they will be converted. For example, the angle brackets "<" are converted
"<" Is a harmless character.

5. filter related functions, such as the previous include (), unlink, and fopen () functions. As long as you specify the variables for the operation you want to perform or strictly filter the relevant characters, I think this will be impeccable.

Server Security Settings

I think it is very impractical to talk about server security settings. Most of us use virtual hosts. For how to set up PHP. ini, the only thing we can do is the network administrator. But let me talk about it,

1. Set "safe_mode" to "on"

This is a great option for a wide range of space vendors, which can greatly improve the security of PHP.

2. Disable "open_basedir"
This option can disable file operations outside the specified directory, and effectively eliminate attacks from calling local files or remote files by functions such as include.

3. Set expose_php to off, so that PHP will not leak information in the HTTP file header.

4. Setting "allow_url_fopen" to "off" can disable the remote file function. We strongly recommend that you

5. The "log_errors" is "ON". The error date must be included.

6. For "display_errors, register_globals", the two items are subject to the actual situation. display_errors is too negative and the error is completely disabled. You cannot debug the script. As for register_globals (global variable), it will be very troublesome to turn it off. Now most programs don't want to use it if they don't support it.

 

//////////////////////////////////////// /////////////////////

 

2. Reinforce PHP to enhance security.

Note: The following security depends on the situation, so I have clearly written their functions. If there is a problem, check whether the following restrictions are caused, you can comment it out.

Next we will start to reinforce PHP. We will edit the/etc/PhP5/apache2/PHP. ini file again. The reason why we haven't completed the change is mainly to give you a clear idea.

1. open security mode. The advantage of opening PHP files is that they can only access all the same files as the PHP file. Even in the chroot environment, they cannot access files with different masters in jail, similar to PHP files.
Shell is useless. phpshell is a popular PHP backdoor. It can execute system commands, just like his name. It is very similar to shell.

Safe_mode = on

2. The following settings limit fopen (),
File () and other functions can operate on the directory range, to avoid illegal file reading by intruders, you must add "/" after/var/WWW "/", otherwise, files under/var/wwww can also be accessed.
. This option will disable any PHP files that are not in the/var/www/directory, including any programs that are linked to the/var/www/directory through soft links, such as the phpMyAdmin package, it cannot run properly after this option is set.

Open_basedir =/var/www/

3. Disable the phpinfo and get_cmd_var functions to avoid service information leakage. Disable them after confirming that PHP works properly.

Disable_functions = phpinfo, get_assist_var

4. Set the PHP program error log

Error_reporting = e_all
Log_errors = on
Error_log =
/Var/log/php_err.log

5. If the PHP program does not specify that register_globals is required, it is best to set register_globals to off to avoid many security issues. NOTE: If your program requires register_globals, do not close it. Ubuntu is disabled by default.

Register_globals = off

6. Do not open the remote address. Remember the latest PHP address.
The include vulnerability? If a variable is included in a PHP program, the attacker can use this control server to execute a remote php program, such as phpshell, locally, so we can close this.

Allow_url_fopen = off

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.