Wiki Search

CS 352 Wiki Web Development 3

| edit page | page history | Sign in |

Day 38 Wiki Notes main content

Notes Index

Security and PHP

Security basically falls into two categories, dealt with by either network administrators or programmers. Since this is a computer science course, we will deal with vulnerabilities that programmers can address.

In earlier versions of PHP, the language itself was susceptible to buffer overflow attacks through the use of strings. However, such vulnerabilities have been fixed and most, if not all, flaws are due to poor programming. Common programming errors can be broken down into the following categories:

Unvalidated Data

As discussed in class, no user input should be trusted. User input can come to the web site in the following ways:

Therefore, when using any of these, you must be sure to validate the data. This can be done with the PHP functions addslashes(), which escapes quotes, and htmlspecialchars(), which converts potentially dangerous characters such as > to their save equivalent.

addslashes() Example:

He said, "What's the problem?"
becomes:
He said, \"What\'s the problem?\"

htmlspecialchars() example:

<a href='test'>Test</a>
becomes:
&lt;a href='test'&gt;Test&lt;/a&gt;

Note that htmlspecialcahrs didn't remove the single quotes. Therefore, it becomes important to also use addslashes() after you use hmtlspecialchars();

Regular Expressions

As discussed previously, validating by rejecting harmful data is, in most cases, not the best approach. Using regular expressions to only allow valid data is preferred.

In PHP, we can use ereg or preg_match to validate strings

For example, if we only want to accept strings comprised of letters and numbers, we can write:

$pattern = "Joe23 ";
$regex = "^[a-zA-Z0-9]+$";
if(ereg( stripslashes(trim($pattern)), $regex)){

        //we're okay
        print "yay!";
}
else{
        //problem
        print "boo!";
}

Here is an example used to validate input on a form field

<?php
//validates a string, returns an error message if it doesn't validate

function validate($userInput, $regex, $error)
{
   $errorMessage = "";

   if(!ereg($regex, stripslashes(trim($userInput))))
   {
      //problem
      $validates = false;
     //create the error message
     $errorMessage = "<span style=\"color:Red;\">" . $error . "</span>";
   }

   //return the message
   return $errorMessage;
}
?>

<form method="post" action="<?php print $_SERVER['PHP_SELF']; ?>">
<p>
<label for="firstName">Please enter your first name:</label>
<input  type="text" id="firstName" name="firstName" value="<?php if(isset($_POST['firstName'])) print $_POST['firstName']; ?>" />
<?php
   if(isset($_POST['firstName']))
      print validate($_POST['firstName'], "^[a-zA-Z]+$", "Only characters are allowed");
?>
</p>
<p>
<input type="submit" value="submit" name="submit"/>
</p>
</form>
 

Defensive Programming

Even though a programmer may have written code to secure the software, the way in which it was written can lead to other security vulnerabilities. For example, examine the following code:

$sql = "SELECT userID FROM users WHERE username='user' AND password='pass'";

$result = sqlite_query($sql, $db);

If (sqlite_num_rows($result) > 0)
{
   //do the work
}

On the surface, this code looks fine: it checks to make sure that our database returned at least one row. It is much easier for a hacker to fake multiple entries than it is for him/her to fake one correct entry. Thus, it would be much better to write the IF statement as:

if (sqlite_num_rows($result) == 1)
{
   //do the work
}

Cross Site Scripting

Cross site scripting (XSS) is a term referring to the use of scripts to perform malicious actions on a user’s computer by using known vulnerabilities in the user’s browser or host server. According to Wikipedia.org there are three types of XSS.

DOM-based or Local XSS
This type of XSS exists because of how certain browsers treat JavaScript. For example: A malicious email is sent out and the recipient clicks the link provided in the email. After the link is clicked the recipient is sent to a web site that executes the JavaScript locally on the recipients’ machine. The script can take anything, from cookies to personal information and run other scripts while holding command over the recipients’ computer.
Non-persistent XSS
Another type of XSS exists when a malicious user finds a web page that takes invalidated user input. The malicious user can then create a URL that can then execute on a non-malicious users browser that frequents a vulnerable website. The executed code could steal information or give the malicious user access to the viewed web pages.
Persistent XSS
The final type of XSS is also the most powerful. This type of attack can occur when a website does not sanitize publicly viewed user input. A malicious user can log into the web site, post a malicious script with a inflammatory subject line, and get many other users to view, and subsequently run the scripts without knowing it. The malicious user can then take personal information from the users that viewed the script and do whatever he/she desires.

How to avoid XSS

Make sure that all your data is HTML encoded. Most of the time, you should check the HTML before it is displayed in a web application. This will ensure that the code will be filtered properly and no malicious code can make it through.

SQL Injection

SQL injection is a common form of web based attacks. SQL Injection consists of using text boxes to insert malicious or deceptive code into a SQL statement. After "injecting" the code into the textbox, the server then runs the code.

SQL Injection is an easy means to blindly attack a website. The attacker needs limited knowledge of the database in order to do malicious things to it. There are many ways to protect against SQL injection: sanitizing input data, using mysql_real_escape_string(), and using parameters and stored procedures.

Magic Quotes

When command injection first became an issue when PHP was devised, a simple and sometimes frustrating solution was implemented. Magic quotes is a function used in PHP to add slashes to any quotes found in user input. Adding slashes to any quotes in the user input can help prevent against malicious user data, but the detriment to the non-experienced web developer is frustrating also.

For example if the user wanted to enter "Billy Bob's First Blog" into a text field with magic quotes turned on, he would get this error message.

You have an error in your SQL syntax near /'s First Blog'

You can see that the magic quotes have placed a slash before the apostrophe, thus turning this innocent line of text into a non usable string.

Another downside to magic quotes is that an attacker that knows what he/she is doing can easily get past the magic quotes function by entering a correct escape string.

PHP magic quotes has been deprecated and removed as of PHP 6.0.

| Return to top | | Site Management | Find Broken Links | edit | attr | Documentation Index | PmWiki.org |

Page last modified on May 29, 2008, at 09:12 AM