Publishers of technology books, eBooks, and videos for creative people

Home > Articles > Web Design & Development > Ajax and JavaScript

This chapter is from the book

This chapter is from the book

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.

  1. 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.
  2. 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>
  3. Save the file as chap4/4-8.php .
  4. 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;
  5. Declare a function called errorCount:
    function errorCount(errors) {
  6. Set the argument variable errors to be equal to the submitErrors variable:
    errors = submitErrors;
  7. 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');
  8. 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');
        }
  9. 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.

  1. 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--);
  2. 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

    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.

  1. 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.
  2. 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");
          
  3. 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.

  4. 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;
  5. 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();
        }
  6. 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

    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.

  1. Using email validations as an example, open peRegister.php (chap4/inc/peRegister.php) to modify it.
  2. 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.

  3. Test the value posted against the regular expression with PHP's preg_match function:
    preg_match($regexEmail, $_POST['email'], $match);
  4. 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">&nbsp;</label>
    <input type="submit" value="Search" />
    <input type="reset" value="Clear" />
</form>

The PHP htmlspecialchars function replaces certain characters and returns:

&lt;form name=&quot;search&quot; action=&quot;inc/search.php&quot; method=&quot;post&quot;&gt;&lt;label class=&quot;label&quot; for=&quot;pesearch&quot;&gt;Search For: &lt;/label&gt;&lt;input type=&quot;text&quot; name=&quot;pesearch&quot; id=&quot;pesearch&quot; size=&quot;64&quot; /&gt;&lt;br /&gt;&lt;label class=&quot;label&quot;&gt;&amp;nbsp;&lt;/label&gt;&lt;input type=&quot;submit&quot; value=&quot;Search&quot; /&gt;&lt;input type=&quot;reset&quot; value=&quot;Clear&quot; /&gt;&lt;/form&gt;

The following characters have been changed:

  • Ampersand (&) becomes '&amp;'
  • Double quote (") becomes '&quot;'
  • Single quote (') becomes '&#039;'
  • The less than bracket (<) becomes '&lt;'
  • The greater than bracket (>) becomes '&gt;'

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.

Peachpit Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from Peachpit and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about Peachpit products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites; develop new products and services; conduct educational research; and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email ask@peachpit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by Adobe Press. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.peachpit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020