Difference between revisions of "Web Application Security, Part 2"

From CSE330 Wiki
Jump to: navigation, search
m (Solution)
(Solution)
Line 52: Line 52:
 
</source>
 
</source>
  
However, the better solution is to use prepared queries.  For more information on prepared queries, see [[MySQL and PHP]].
+
However, the better solution is to use prepared queries.  For more information on prepared queries, see [[PHP and MySQL]].
  
 
=== Real-Life Examples ===
 
=== Real-Life Examples ===

Revision as of 14:11, 1 September 2012

This is Part 2 of the Web Application Security article, geared toward the material covered in Module 3. For material covered in Module 2 (HTML, CSS, and PHP), see Web Application Security, Part 1. For material covered in Module 4 (JavaScript), see Web Application Security, Part 3.

SQL Injection

Exploits of a mom.png

SQL injection occurs when an attacker submits specially-crafted input into your server, which is then included in an SQL query. The input modifies the query to perform additional actions on the database or to access unwanted information.

For instance, suppose you had the following code:

<?php
require 'database.php';

/* DISCLAIMER: THIS CODE IS BAD IN MANY MORE WAYS THAN JUST
BEING VULNERABLE TO SQL INJECTION! IT IS FOR DEMONSTRATION OF
CONCEPT ONLY. DO NOT USE THIS CODE IN YOUR OWN PROJECTS! */

$res = $mysqli->query("SELECT id FROM users WHERE username='".$_POST['username']."' AND password='".$_POST['password']."'");

if( $res->num_rows==1 ){
    $row = $res->fetch_assoc();
    $_SESSION['user_id'] = $row["id"];
}else{
    echo "Login failed.";
    exit;
}
?>

This code is vulnerable to SQL injection. For example, suppose the attacker used the following string of text for his username:

mother-goose' --

Here's what the resulting query would look like:

SELECT id FROM users WHERE username='mother-goose' --' AND password=''

Since -- is the start of a comment in SQL, when MySQL interprets this query, it will completely ignore the password-checking part of the query! Dr. Evil can log in using anyone's username and steal all of their money!

Solution

If you write your queries manually (as in the example above), you need to use $mysqli->real_escape_string() to sanitize your input:

<?php
$safe_username = $mysqli->real_escape_string($_POST['username']);
// ...
?>

However, the better solution is to use prepared queries. For more information on prepared queries, see PHP and MySQL.

Real-Life Examples

Password Security

Let's assume for a moment that despite all of your efforts in the other fronts of web security, an attacker was still able to extract information from your database. If you store your passwords as plain text, not only will the attacker be able to log in as whomever he chooses, but the attacker will also likely be able to log in as the users of your site on different sites (since many users employ the same password on several different web sites).

Encryption

The types of encryption and encryption algorithms is a whole class to itself.

In CSE330 and future web application development, you should always use one-way encryption to encrypt your passwords. What this means is that you feed a string of text (a password) to an encryption function, and that encryption function returns another string of text that is a digest of the password. It is impossible to mathematically convert a digest back to its associated password, but encrypting the same password will always yield the same digest.

One-way encryption algorithms can also be salted. What this means is that the string to be encrypted is modified by a salt before the encryption occurs. The same salt and the same password will always yield the same digest. Using a salted hashing algorithm is preferable to a non-salted hashing algorithm for passwords because although digests cannot be reversed, non-salted digests can be looked up in a rainbow table.

Solution

So, the solution is to store salted, one-way-encrypted passwords in your database. PHP provides the crypt() function to do this for you.

<?php
// This is a *good* example of how you can implement password-based user authentication in your web application.

require 'database.php';

// Use a prepared statement
$stmt = $mysqli->prepare("SELECT COUNT(*), id, crypted_password FROM users WHERE username=?");

// Bind the parameter
$stmt->bind_param('s', $user);
$user = $_POST['username'];
$stmt->execute();

// Bind the results
$stmt->bind_result($cnt, $user_id, $pwd_hash);
$stmt->fetch();

$pwd_guess = $_POST['password'];
// Compare the submitted password to the actual password hash
if( $cnt == 1 && crypt($pwd_guess, $pwd_hash)==$pwd_hash){
	// Login succeeded!
	$_SESSION['user_id'] = $user_id;
	// Redirect to your target page
}else{
	// Login failed; redirect back to the login screen
}
?>

Note: You may sometimes see functions like md5() used to encrypt passwords. md5() does indeed perform one-way encryption, but it does so without a salt. THIS IS BAD PRACTICE, because unsalted md5 hashes can be trivially reversed using a rainbow table. (Just Google for "md5 decrypter".) Using a salt prevents the effective use of a rainbow table.

OpenID

One other solution that will solve all issues related to password security is to not have passwords at all. This can be achieved using OpenID, which allows end users to use their accounts from other sites (e.g. Google, Yahoo, and Twitter) to authenticate on your site. Not only does this make your life easier in the security realm, but it also eliminates the need for password recovery, etc.

There are many PHP libraries available for OpenID authentication; one such library is the creatively named OpenID, which you can install using PEAR. You will need to install some other packages first, some from yum (if using RHEL) and some from pear. (If you don't install them, PEAR will yell at you.) These are the commands you need to run in order to install the correct packages (make sure you understand what they do before running them!):

sudo yum install php-mbstring php-bcmath # not necessary on Debian
sudo apachectl graceful
sudo pear install Crypt_DiffieHellman-0.2.6 Validate-0.8.5 Services_Yadis-0.5.1 OpenID-0.3.3

Here's an example implementation that uses the PEAR package.

Login Page:

<nowiki>
<form action="process_openid.php" method="post">
	<input id="start" name="start" type="hidden" value="true" />
	<fieldset>
		<legend>Sign in using OpenID</legend>
		<div id="openid_choice">
			<p>Please select your account provider:</p>
			<select name="identifier">
				<option value="https://www.google.com/accounts/o8/id">Google</option>
				<option value="http://yahoo.com/">Yahoo</option>
			</select>
		</div>
		<p>
			<input type="submit" value="Sign In"/>
		</p>
	</fieldset>
</form>
</nowiki>

process_openid.php:

<nowiki>
<?php
require_once 'OpenID/RelyingParty.php';
require_once 'OpenID/Message.php';
require_once 'Net/URL2.php';

session_start();

$realm = "http://www.yoursite.com/";
$returnTo = $realm . "path/to/process_openid.php";

$identifier = @$_POST['identifier'] ?: @$_SESSION['identifier'] ?: null; // note: the @ signs suppress "undefined" notices

$o = new OpenID_RelyingParty($returnTo, $realm, $identifier);

// Part 1: We are processing a login request before visiting the OpenID provider
if(@$_POST['start']) {
	$authRequest = $o->prepare();
	$url = $authRequest->getAuthorizeURL();
	
	header("Location: ".$url);
	exit;
}

// Part 2: The user is returning to our site after visiting the OpenID provider's site
else {
	$usid = @$_SESSION['identifier'] ?: null;
	unset($_SESSION['identifier']);

	$queryString = count($_POST) ? file_get_contents('php://input') : $_SERVER['QUERY_STRING'];
	
	$message = new OpenID_Message($queryString, OpenID_Message::FORMAT_HTTP);

	$result = $o->verify(new Net_URL2($returnTo . '?' . $queryString), $message);
	
	if($result->success()){
		// Login Success!
		
		// Get the OpenID identifier, which is unique to every OpenID user (i.e. you can use it in your database to
		// keep track of people between logins), and save it in the session:
		$_SESSION["openid.identity"] = $message->get("openid.identity");
		
		// Now redirect to the target page for logged-in users
	}else{
		// Login Failed.  You can redirect back to the login page or whatever
	}
}
?>
</nowiki>

Disclaimer: OpenID does have security issues in its own right, especially phishing-type vulnerabilities, but they are almost exclusively tied to the OpenID identity providers (Google, Yahoo, etc), not the OpenID relying party (you). Using an SSL connection will help to solve many of these security issues. And ultimately, it's safe to rest assured that profit-driven OpenID providers are quick to respond when such security vulnerabilities are reported.

Real-Life Examples

Here is a constantly-updated list of sites that do not use proper password security: http://plaintextoffenders.com/

Abuse of Functionality

Abuse of Functionality is a general term that refers to when an attacker exploits vulnerabilities in the logic of your application.

For example, suppose you were a banking site, and you had the following code to perform a transaction:

<?php
$mysqli->autocommit(false); // start transaction
$mysqli->query("UPDATE users SET balance=balance-".$amount."
	WHERE id=".$_SESSION['user_id']);
$mysqli->query("UPDATE users SET balance=balance+".$amount."
	WHERE username='".$destination_username."'");
$mysqli->commit(); // commit transaction
?>

It may not be obvious, but if you don't filter your input, it is trivial for an attacker to insert a negative number into the "amount" field and transfer money from anyone's account to his account! The solution here is to simply filter amount for what you expect (in this case, a positive number that is not greater than the user's current balance).

Filtering on the Client Side is Never Enough

Suppose you have an e-mail field in a form in HTML, and you use some JavaScript function (or HTML5) to check it for form as an e-mail address:

<input type="text" name="email" onchange="checkEmail(this);" /> <!-- HTML versions ≤ XHTML 1.0 -->

<input type="email" name="email" /> <!-- HTML versions ≥ 5 -->

With this filter in place, any layperson using your form is now required to submit an e-mail address in that field. However, it is trivial for an attacker to bypass this client-side filtering (e.g., by using web developer tools like Firebug) and still submit non-email text to your server. This is why IT IS ESSENTIAL THAT YOU FILTER INPUT ON THE SERVER SIDE! Any sort of filtering on the client side are just bells and whistles for the end user.

Information Leakage

Information Leakage is a noteworthy type of Abuse of Functionality attack that involves unprivileged users accessing privileged information. In fact, Information Leakage accounts for a significant percentage of all recorded web application vulnerabilities (second only to Cross-Site Scripting).

The concept is relatively simple. Suppose you have an administration page that loads an image containing a graph of all activity on your site:

admin.php

<?php
if($_SESSION['admin']) echo '<img src="stats.php?day=2012-08-19" alt="Stats for 2012-08-19" />';
?>

stats.php

<?php
// query the database, and save the results in $result

$im = new PNGraph();
$im->takeData($result);

header("Content-Type: image/png");
print $im->toString();
?>

Notice how you check for admin credentials in admin.php. However, you forgot to do this in stats.php itself. An attacker could simply load stats.php directly to see all of the sensitive admin-only information!

Solution

Information Leakage is an attack that requires the developer to see the big picture and really keep track of what's going on in his or her application. As a rule of thumb, whenever you query the database to access sensitive information, check the permissions of the user first.

A Note about Frameworks

Web frameworks are designed to make web development more agile, but they in turn have security weaknesses of their own. For instance, the infamous mass-assignment vulnerability in Ruby on Rails-type MVC frameworks is an abuse of functionality vulnerability that enables attackers to save arbitrary information in your database (!).

The important thing to know is that if you use a web framework, be familiar with the security considerations with that framework. Most of the time, frameworks will have articles on their web sites that discuss these concerns. (If your framework doesn't have a guide like this, you should probably be using a different framework!)

Real-Life Examples