PHP Security: Rekindle your PHP security fire

Source: Internet
Author: User
Tags empty eval execution functions mysql update variables split sql injection

The topic of scripting security seems to last forever, and if you often go to a variety of bugtraq abroad, you will find that more than half of them are related to scripts, such as SQL Injection,xss,path disclosure,remote commands Execution such words abound, we looked after the use is only to catch chickens? For those of us who want to do web security, it is best to learn, but the root of all things, we do not want fish but fishing. In the domestic, a variety of PHP Program version 1.0, 2.0 version springing up like mushrooms, but, we are concerned about a number of well-known CMS, forum, blog program, very few people in those not well-known programs do security testing, for more and more PHP programmers and webmaster, In addition to relying on the server's fortress settings, the PHP program itself how much security you have to understand a little bit.

Some people say you do PHP security is nothing more than to engage in injection and cross station what what, wrong, if so, a MAGIC_QUOTES_GPC or server security settings let us all live: (. What I'm going to say today is not the injection, not the cross-site, but the security detail that exists in the PHP program. Ok! cut to the chase.

Note the filtering of some functions

Some functions are often used in programs, such as include (), require (), fopen (), fwrite (), ReadFile (), unlink (), eval (), and their variant functions, and so on. These functions are very practical, practical does not mean that you worry more, you have to pay for them more snacks. :)

1.include (), require (), and fopen (), include_once (), require_once () can call files remotely, and for their harm, Google searches you will be very clear, for the contained call variables are not filtered well, You can optionally include files to execute them. For instance, look at print.php

...

if (empty ($bn)) {//check whether the variable $bn is empty

Include ("$cfg _dir/site_${site}.php"); To include the site_${site}.php in the $cfg_dir path.

...

Regardless of the existence of the $cfg_dir directory, $site this variable you can naturally use, because he did not check the $site variable AH. You can specify a remote file to call the variable $site, or it can be a local file, you specify the file to write the PHP statement, and then it will include the execution of the file containing the PHP statement. Like this.

Listing file Directories

It can even be extended to include some admin files and elevate permissions, typically like a previously phpwind,bo-blog vulnerability. In addition to relying on the allow_url_fopen in php.ini to disable remote use of files and Open_base_dir prohibit the use of files outside the directory, you have to declare in advance what documents can only be included, there is no more nonsense here.

2.fopen (), file (), ReadFile (), OpenFile (), and so on, are the places to pay special attention to. The function itself is nothing, their role is to open the file, but if the variable filtering is not complete, it will reveal the source code. There will be a lot of such functions in the text forum.

...

$articlearray =openfile ("$dbpath/$fid/$tid. php"); Open the $tid.php file for $dbpath/$fid this path

$topic _detail=explode ("|", $articlearray [0]); Read the contents of a post with a split character |

...

Look familiar, this is Ofstar previous version of the read.php, $fid and $tid did not have any filtering, $tid designated as a file submission, the original code leak occurred. Just like this.

Http://explame.com/ofstar/read.php?fid=123&tid=.. /index

$tid will be added to the PHP suffix, so write the index directly. This is just an example, then look at it.

3.fwrite () and its variant function this vulnerability is to think that the user submitted characters do not filter, write a PHP back door is not not.

4.unlink () function, some time ago, phpwind in any delete file is the use of this function, for the determination of whether to delete the variables are not filtered, variable can be designated as arbitrary files, of course, can delete arbitrary file variables.

5.eval (), preg_replace () function, their function is to execute PHP code, if the string has not been filtered by any, what will happen, I often see some of the CMS inside use, think, a word of the PHP Trojan is not based on the eval () Principle of production?

6. For system functions, you would say that a system function is prohibited in the php.ini, which is a good way to do it, but like some programs, is that not necessary? Just like the last time I saw a nice set of PHP albums. In addition, for Popen (), Proc_open (), Proc_close () functions you also have to pay special attention to, although they execute the command and there is no direct output, but you think this is not the use of hackers. Again here PHP provides two functions, Escapeshellarg (), Escapeshellcmd (), which are used to counter call attacks on system functions, that is, filtering.

For the harm, for example, let's take a look at a forum prod.php

Modified $doubleApp = Isset ($argv [1]); Initialize variable $doubleapp

...

An if ($DOUBLEAPP)//if statement

15 {

$appDir = $argv [1]; Initialize $appdir

System ("mkdir $prodDir/$appDir"); Use system function systems to create a directory $proddir/$appDir

It was originally used to create the $proddir/$appDir directory, and then it appears that the program only detects the existence of $argv[1], lacks the necessary filtering of $argv[1], then you can

/prod.php?argv[1]=|ls%20-la or/PROD.PHP?ARGV[1]=|CAT%20/ETC/PASSWD.

(Split character | This is the pipeline parameter for UNIX, and you can execute multiple commands. )

Here, the common types of vulnerabilities should know the point.

Attention to special characters

For special characters, there is a phrase called All puts is invalid. This sentence is very common in foreigners ' articles. All input is harmful. You should never worry about what users have entered, in order to deal with these hazards, programmers are busy filtering a lot of characters, lest something be missed. And some programmers? Never seem to notice these problems, always open the door of loopholes. Don't talk nonsense, or look at the following things first.

1. In fact, the most critical flaw in the program, the most let developers worry about is with the $ symbol of the dollar symbol, variable, for the people who find the loophole, grasping the variable two words is everything. Like directory traversal of this bug, a lot of mail programs exist, developers consider very comprehensive, and some even add a network hard this thing, good is good, like

http://mail.com/file.php?id=1&put=list&tid=1&file=./

If we change the file variable to./. /Even more? The directory is then traversed.

2. Angle bracket "<>" Cross station You don't know, some search bar, articles, messages, like the previous time Phpwind attachment where the cross station and so on. Of course, you have to filter far more than the angle brackets for the cross station problem. Not afraid to filter out what is missing, but afraid you can't think of to filter.

3. Oblique rod and Reverse tilt rod: for/And filter, remember the Magic Forum attachment download The original code leaked?

Attachment.php?id=684&u=3096&extension=gif&attach=.\.. \.. \.. \.. \.. \.. \includes\config.php&filename=1.gif

For filtering. /\ Issues like Windows host not only to filter ... /also to filter. \,windows host to \ will resolve to/, these details compared with SQL injection, what is called depth?

4. For inverted quotes ('), inverted quotes are powerful in PHP, it can execute system commands, just like system () functions, if the user's malicious statements are executed by it will harm the server, I think in addition to the server settings is very good, for them, you still honest filtering.

5. For line breaks, null characters, and so on, such as "\t,\x0b,\n,\r,\0 these, these are very useful, like the previous upload vulnerability is due to the upload of the null () character, for these can be arbitrarily truncated program flow characters, How careful do you think we should be in the test?

6. Semicolons (;) and delimiters (|)

Semicolons truncate the program flow, just like this

Shell_exec ("del/yourpath/$file"); To delete a file using the system function Shell_exec $file

Variable $file not specified, then write directly Zizzy.php;del/yourpath, so that your Yourpath directory will be Del.

Split Character (|) is a self-contained pipe function in Unix that can be executed with a few commands connected to it. Sometimes it is performed in a system function that is not tightly filtered.

Logical error

Validation is not complete and some of the logic errors in the program is also easy to find, especially the current programmer, only in-depth learning, and logic errors and so on security awareness is not the awareness of training, in fact, it is to cultivate themselves, rather than waiting for people to report bugs to you. The logic of the wrong judgment, we can only say that more practice, experience is the most important.

1. For landing verification problems. For example: We look at a admin.php fragment of a forum

It here username and password seems to be wrong, there are Administrator's username and password directly through verification, which means that there is no user name, no password is OK. 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 data packet that we forged (you asked me how to forge it?) Grab the bag and modify it again, we use get to submit the data, and the principle is to construct the spoofing statement in the cookie.

Then the entire SQL statement becomes this way

SELECT * from users WHERE username= ' or IsNull (1/0) and level=3/* ' and password= '

Here only a ' or ' = ' or ' principle, the detection of username and password is bypassed, and Level=3 is a forged grade. Thus spared the detection, into the management backstage.

For the background of the validation can not be so sloppy, two lines of code, even if done, you have to from the session (sessions), cookies these places to enhance validation.

2. Upload Vulnerability

There's a time when I see the restrictions on uploading file types in a program config.php.

$IllegalExtentions = Array (' exe ', ' asp ', ' php ', ' php3 ', ' bat ', ' CGI ', ' pl ', ' com ', ' vbs ', ' Reg ', ' PCD ', ' pif ', ' SCR ', ' bas ', ' Inf ', ' VB ', ' vbe ', ' WSC ', ' wsf ', ' WSH '); For uploading file restrictions, only allow uploading of exe,asp,php,php3,bat,cgi,pl,com,vbs,reg,pcd,pif,scr,bas,inf,vb,vbe,wsc,wsf,ws ' these files.

The rules are not allowed to upload what files, other can upload, this logic is good? What if I upload. Inc,,. PHP4 phtml,. html,. pwml such types? Why don't you turn this logic into a rule that the user can pass all but one of these files, and all the others are not allowed to upload. Like this, the array is changed to the reverse thinking.

$IllegalExtentions = Array (' rar ', ' gif ', ' jpg ', ' bmp ', ' PDF ')//can only upload rar,gif,jpg,bmp,pdf several formats

Actually this and you upload Cer,asa is a truth.

3. A typical logical error

In some CMS (whole station program) casually registered users, you will find that the modification of the information is not required to enter the original password, only by judging the user ID or email, you save the page to the local, the ID or email to the administrator, action changed to change the address, submit you become an administrator. The solution is not too difficult, as long as we increase the password verification, enhance the MySQL UPDATE statement filter is OK.

These we have no way, most programmers do not care about security at all, originally a person can do, why should be divided into Web security and web development two kinds of people?

Length problem

Don't think the loophole is to get an administrator password or Webshell, there are some restless people, that is, ddoser (denial of service attackers), they have a lot of tricks, but for programmers, the key is filtering. The length problem I'm talking about, not only the length of a character, but also the length of time, you must have seen someone write a script, register tens of thousands of users, or simply write garbage data to drag the database to death. At this point, restricting data submission time and verification code will work. But to really encounter a vicious person, a variable filtering problem can paralyze the site, which is faster than using any of the network zombie software.

A minor problem.

1. The leak of the absolute path

This is a very moderate problem, a lot of programs have, which is also part of the security. At least you play with loadfile () need it. Of course, the display_errors in the php.ini can also work.

2. Validation of the background

Do not say no, I have seen some programs like this, you go to test, register a user, submit the administrator to edit the user's URL, such as Admin_member.php?action=edit&id=55&level=4&username= Zizzy&power=1 This corresponding Add admin URL, you will find almost no verification, direct success. So, for the background of the detection, but also very necessary, just like the discuz of the loophole.

The filtration problem unconsciously said so much, wrote a lot of the reminder of the filter, now also say how to filter.

1. When users enter any data, that is, submit variables into the database, we must use Addslashes () to filter, like our injection problem, a addslashes () is done. In fact, when it comes to variable values, the Intval () function is a good choice for string filtering.

2. Open MAGIC_QUOTES_GPC and Magic_quotes_runtime in php.ini. MAGIC_QUOTES_GPC can turn the quotes in the Get,post,cookie into slashes. Magic_quotes_runtime data that goes in and out of a database can play a role in formatting. In fact, this parameter is very popular as long ago when the injection was crazy.

3. When using system functions, you must use the Escapeshellarg (), escapeshellcmd () parameters to filter, so you can rest assured that the use of system functions.

4. For cross stations, Strip_tags (), Htmlspecialchars () Two parameters are good, and for user-submitted tags with HTML and PHP will be converted. For example, the angle bracket "<" will be converted to "<" such harmless characters.

5. For filtering related functions, just like the previous include (), Unlink,fopen (), and so on, as long as you specify the variables you want to perform the operation or filter the relevant characters closely, I think this is perfect.

Server security Settings

On the server security settings, I think it is not practical, most of us use virtual host, for PHP.ini How to set, that only network management itself to do. But I'm just saying,

1. Set "Safe_mode" to "on"

This is a great option for the vast space business, and it can greatly improve the security of PHP.

2. Prohibit "Open_basedir", this option can prohibit the specified directory file operations, but also effectively eliminate local files or remote files are include () and other functions of the call attack.

3.expose_php is set to off so that PHP does not disclose information in the HTTP file header.

4. Set "Allow_url_fopen" to "off" this option can prohibit remote file features, highly recommended

5 "Log_errors" to "on" Error day to bring it.

6. For "Display_errors,register_globals" two items to depend on the situation, display_errors too negative, the error is all off, want to debug scripts are not. As for register_globals (global variable) to open it up, it will be very troublesome, and now most programs do not have it to support the use of it.

These are the most necessary settings. The higher security settings for PHP servers are a learning discipline and are not covered in this article.

This article is coming to an end, perhaps you will say, you say these are to open source of the program is useful, to those Zend encryption program can not be made? In fact, for security, solid it is the important thing, how can you encrypt the black box test? It's going to be discovered someday.

Limited to space is here, we have a preliminary exploration of PHP program security. For the vast number of readers to consider, the example is also considered very easy to understand, of course, the premise is that you have to point PHP, otherwise it is to see the heavenly book (Wow, don't see here just ask me what is PHP?). The whole article is not about hacking, but for beginners and PHP programmers who want to develop PHP security. If you hear from anyone again what loophole, then how to change is the basic things. I hope this article can broaden your thinking and develop better. Drinking into a stupid sword is also crazy, rekindle your PHP security fire, with the persistence of PHP on the road.



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.