- Using AJAX for Validation
- Using AJAX to Update Content
- Securing AJAX Requests
- Wrapping Up
Securing AJAX Requests
One of the vexing problems with Web sites and applications is that users will either inadvertently or purposely submit data through your Web site that can cause harm to your databases and servers. It is important that you take as many steps as possible to guard against the input and transmission of bad or malformed data.
Several of these steps have been covered already, including using regular expressions to guide the user to input the right kind of data and making sure that cookies are set uniquely for each Web visitor. As an older, and much wiser, mentor said to me, "Locking the gate in this way only keeps the honest people from climbing the fence."
Even with regular expressions in place for form fields, you cannot stop the transmission of the data because the form can still be submitted. So, what are some of the measures you can take to prevent users from submitting potentially harmful data?
- Prevent form submission by "graying" out the Submit button on forms until all of the regular expression rules for each form field have been met.
- Use cookies to uniquely identify the user (more precisely, the user's computer) based on registration information and check cookie data against a database during transmission of user-supplied data.
- Clean user-supplied data when it arrives at the back-end process to make sure the data doesn't contain harmful statements or characters.
- Transmit the data over a secure connection (HTTPS [HyperText Transfer Protocol Secure]) to prevent outsiders from "sniffing" information traveling from and to the Web browser.
These techniques should be used in conjunction with each other to present the safest experience for the user and the Web-site owner. Let's walk through some of these techniques.
Preventing Form Submission
Let's return to the Photographer's Exchange Web site and make some changes to the HTML file containing the registration form as well as the jQuery script that supports the form.
- Open chap4/4-2.php and locate the section of the script where jQuery scripts are included. You'll find these include declarations between the head tags.
Change the following highlighted line to point to the updated jqpe.js file:
<script type="text/javascript" src="inc/jquery-1.5.min.js"></script> <script type="text/javascript" src="inc/jquery.ez-bg-resize.js"></script> <script type="text/javascript" src="inc/spritenav.js"></script> <script type="text/javascript" src="inc/carousel.js"></script> <script type="text/javascript" src="inc/jqpe.js"></script> <script type="text/javascript" src="inc/peAjax.js"></script>
After the change, the line will look like this:
<script type="text/javascript" src="inc/jqpeUpdated.js"></script>
- Save the file as chap4/4-8.php .
- Open chap4/inc/jqpe.js and save it as
chap4/inc/jqpeUpdated.js
. Add the code for the error count function. Start by initializing the $submitErrors variable:
var submitErrors = 0;
- Declare a function called errorCount:
function errorCount(errors) {
- Set the argument variable errors to be equal to the submitErrors variable:
errors = submitErrors;
- If the error count is zero, you want to enable the submit button. So, remove the disabled attribute from the button. Use the jQuery attribute selectors to select the proper button:
if(0 == errors){ $('input[type="submit"][value="Register"]').removeAttr('disabled');
- If the error count is not zero, the submit button will be disabled. Use the same selector syntax and add the disabled attribute to the button:
} else { $('input[type="submit"][value="Register"]').attr('disabled','disabled'); }
- Close out the function:
}
Once the function is in place, you'll need to make some changes to the password and email validation functions that were created previously.
In jqpeUpdated.js locate the password validation function that begins with the comment /*make sure password is not blank */. Insert the two new lines of code highlighted here:
/* make sure that password is not blank */ $(function() { var passwordLength = $('#penewpass').val().length; if(passwordLength == 0){ $('#penewpass').next('.error').css('display', 'inline'); errorCount(submitErrors++); $('#penewpass').change(function() { $(this).next('.error').css('display', 'none'); errorCount(submitErrors--); }); } });
If the password is blank (having a length of zero), the errorCount function is called and the submitErrors variable is incremented by a count of one.
errorCount(submitErrors++);
After a password has been entered, the error is cleared and the error count can be reduced by decrementing submitErrors:
errorCount(submitErrors--);
Locate the email validation function. It begins with the comment /* validate e-mail address in register form */. Add the same calls to the errorCount function where indicated by the following highlights:
/* validate e-mail address in register form */ $(function(){ var emailLength = $('#email').val().length; if(emailLength == 0){ $('#email').next('.error').css('display', 'inline'); errorCount(submitErrors++); $('#email').change(function() { var regexEmail = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/; var inputEmail = $(this).val(); var resultEmail = regexEmail.test(inputEmail); if(resultEmail){ $(this).next('.error').css('display', 'none'); errorCount(submitErrors--); } }); } });
When the page first loads, submitErrors gets incremented twice—once by each of the validation functions. The total error count prior to the form being filled out is two. Because the submitErrors has a value of two, the submit button is disabled, as illustrated in Figure 4.14.
Figure 4.14 The Register button is grayed out. It is not available to the user until all errors are cleared.
As each function is cleared of its error, the submitErrors variable is decremented until it finally attains a value of zero. When the value of submitErrors is zero, the errorCount function removes the disabled attribute from the submit button and the form can be submitted normally.
This technique can be applied to any number of form fields that you need to validate, but it really isn't enough to prevent malicious users from trying to hack your site. Let's take a look at another technique you can add to your Web-site application model, giving each user cookies.
Using Cookies to Identify Users
Giving users cookies sounds very pleasant. But it really means that you want to identify users to make sure they are allowed to use the forms and data on your Web site. What you don't want to do is put sensitive information into cookies. Cookies can be stolen, read, and used.
Personally, I'm not a big fan of "remember me cookies" because the longer it takes a cookie to expire, the longer the potentially malicious user has to grab and use information in the cookie. I'd rather cookies expire when the user closes the browser. This would reduce the chance that someone could log in to the user's computer and visit the same sites to gain information or copy the cookies to another location.
What should you store in the cookie? One technique that you can employ that is very effective is storing a unique token in the cookie that can be matched to the user during the user's current session. Let's modify the Photographer's Exchange login process to store a token in the user's database record. The token will be changed each time the user logs in to the site, and you will use the token to retrieve other data about the user as needed.
- Open chap4/inc/peRegister.php and locate the section that starts with the comment /* if the login is good */. You will insert new code to create and save the token into the newly created database column.
- The first line that you need to add creates a unique value to tokenize. Concatenate the user name contained in $_POST['pename'] with a time stamp from PHP's time function. PHP's time function returns the time in seconds since January 1, 1970. Store that in the variable $tokenValue, as shown in the following highlighted line:
/* if the login is good */ if(1 == $loginCount){ if(isset($_POST['remember'])){ $tokenValue = $_POST['pename'].time("now");
Modify the information to be stored in $peCookieValue by hashing the $tokenValue with an MD5 (Message Digest Algorithm) hash:
$peCookieValue = hash('md5', $tokenValue); $peCookieExpire = time()+(60*60*24*365); $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; setcookie('photoex', $peCookieValue, $peCookieExpire, '/', $domain, false); echo $loginCount; } else {
The MD5 hash algorithm is a cryptographic hash that takes a string and converts it to a 32-bit hexadecimal number. The hexadecimal number is typically very unique and is made more so here by the use of the time function combined with the user's name.
- Make the same modifications in the section of the code where no "remember me" value is set:
$tokenValue = $_POST['pename'].time("now"); $peCookieValue = hash('md5', $tokenValue); $peCookieExpire = 0; $domain = ($_SERVER['HTTP_HOST'] != 'localhost') ? $_SERVER['HTTP_HOST'] : false; setcookie('photoex', $peCookieValue, $peCookieExpire, '/', $domain, false); echo $loginCount;
- Add the code that will update the database with the new value:
$updateUser = "UPDATE `photoex`.`peuser` "; $updateUser .= "SET `token` = '".$peCookieValue."' "; $updateUser .= "WHERE `username` = '".$_POST['pename']."' "; if(!($updateData = mysql_query($updateUser, $dbc))){ echo mysql_errno(); exit(); }
- Open chap4/4-8.php and log in to the site with a known good user name and password. The cookie will be set with the token, and the token information will be set in the database. You can use your browser's built-in cookie viewer (for Figure 4.15, I used Tools > Page Info > Security > View Cookies in the Firefox browser) to examine the value stored in the cookie.
Figure 4.15 The content of the cookie is circled and would-be cookie thieves are foiled!
Using the value of the token, you can retrieve needed information about the user so that the data can be entered into forms or the appropriate photographs can be displayed. Next, let's take a look at cleaning up user-supplied data.
Cleansing User-supplied Data
One additional step that you can take to make sure that user-supplied data is safe once it reaches the server is to use your client-side scripting language to ensure that the data is handled safely and securely.
A less than savory visitor may visit your site and copy your visible Web pages and functions. Once copied, modifications can be made to your jQuery scripts to remove some of the controls (regular expressions for instance) that you have placed around data. Your first line of defense against that is to replicate those controls in your server-side scripts.
- Using email validations as an example, open peRegister.php (chap4/inc/peRegister.php) to modify it.
Locate the section of the code that begins with the comment /* if the registration form has a valid username & password insert the data */ and supply this regular expression:
$regexEmail = '/^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/';
This is the same regular expression used in the jQuery function to validate email addresses into the registration form.
- Test the value posted against the regular expression with PHP's preg_match function:
preg_match($regexEmail, $_POST['email'], $match);
The test result, a 1 if there is a match or a 0 if there isn't a match, is placed into the variable $match that is declared in the preg_match function. Use this result to modify the $_POST['email'] variable:
if(1 == $match){ $_POST['email'] = $_POST['email']; } else { $_POST['email'] = 'E-MAIL ADDRESS NOT VALID'; }
The data from the $_POST['email'] variable is used in the SQL query that inserts the data into the database.
Many languages, such as PHP, include specific functions for data cleansing. Let's take a look at two PHP functions that you can use to clean up data before it is entered into a database: htmlspecialchars() and mysql_real_escape_string().
Cleaning up information submitted in HTML format is a simple matter of wrapping the data in PHP's htmlspecialchars function. Given a form like this:
<form name="search" action="inc/search.php" method="post"> <label class="label" for="pesearch">Search For: </label> <input type="text" name="pesearch" id="pesearch" size="64" /><br /> <label class="label"> </label> <input type="submit" value="Search" /> <input type="reset" value="Clear" /> </form>
The PHP htmlspecialchars function replaces certain characters and returns:
<form name="search" action="inc/search.php" method="post"><label class="label" for="pesearch">Search For: </label><input type="text" name="pesearch" id="pesearch" size="64" /><br /><label class="label">&nbsp;</label><input type="submit" value="Search" /><input type="reset" value="Clear" /></form>
The following characters have been changed:
- Ampersand (&) becomes '&'
- Double quote (") becomes '"'
- Single quote (') becomes '''
- The less than bracket (<) becomes '<'
- The greater than bracket (>) becomes '>'
Using PHP's htmlspecialchars function makes user-supplied HTML data much safer to use in your Web sites and databases. PHP does provide a function to reverse the effect, which is htmlspecialchars_decode().
Also just as simple is preventing possible SQL injection attacks by using PHP's mysql_real_escape_string function. This function works by escaping certain characters in any string. A malicious visitor may try to enter a SQL query into a form field in hopes that it will be executed. Look at the following example in which the visitor is trying to attempt to gain admin rights to the database by changing the database admin password. The hacker has also assumed some common words to try to determine table names:
UPDATE `user` SET `pwd`='gotcha!' WHERE `uid`='' OR `uid` LIKE '%admin%'; --
If this SQL query was entered into the user name field, you could keep it from running by using mysql_real_escape_string:
$_POST['username'] = mysql_real_escape_string($_POST['username']);
This sets the value of $_POST['username'] to:
UPDATE `user` SET `pwd`=\'gotcha!\' WHERE `uid`=\'\' or `uid` like \'%admin%\'; --
Because the query is properly handled and certain characters are escaped, it is inserted into the database and will do no harm.
One other technique that you can use is securing the transmission of data between the client and the server. Let's focus on that next.
Transmitting Data Securely
Another option that you can consider is getting a security certificate for your site or application and then putting your site into an HTTPS security protocol. This is very useful because data traveling between the client and server cannot be read by potential attackers as easily, but it can be costly.
All of the Web site data is encrypted according to keys provided by the security certificate. The Web-site information is transmitted back and forth in a Secure Sockets Layer (SSL). The SSL is a cryptographic communications protocol for the Web. Once the data reaches either end of the transmission, it is decrypted properly for use. If you have used a Web site where the URL begins with https:// or you have seen the lock icon on your Web browser, you have used a Web site protected in this manner. Many financial institutions and business Web sites use HTTPS to ensure that their data travels securely.