Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
JavaScript Security
JavaScript Security

JavaScript Security: Learn JavaScript security to make your web applications more secure

eBook
€10.99 €16.99
Paperback
€20.99
Subscription
Free Trial
Renews at €18.99p/m

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

JavaScript Security

Chapter 1. JavaScript and the Web

First of all, welcome to the book! In this chapter, I will give a very high-level overview of JavaScript, such as some of the basic things it can do on the Web both on the client side and on the server side. After that, I will dive into some of the basic examples of JavaScript security issues.

Here's what we will learn in this chapter:

  • The relationship of JavaScript with HTML/CSS
  • Some basic usage of jQuery, a popular JavaScript library
  • A high-level overview of JavaScript security

JavaScript and your HTML/CSS elements

JavaScript provides behavior to your web pages. From changing your HTML elements' positioning to performing Ajax operations, there are many things that JavaScript can do now compared to just a few years ago. Here's just a basic list of things that JavaScript can do:

  • Perform animation
  • Add in content
  • Create single-page applications
  • Use third-party JavaScript widgets, such as Google Analytics and Facebook's social plugins

Most importantly, with the rise of JavaScript libraries, such as jQuery, AngularJS, ReactJS, and more, achieving all this has never been easier. We'll see multiple examples of JavaScript with the use of jQuery just to give you a taste of some of the code we will see and use throughout this book.

jQuery effects

For this section, we'll start with some basic animation effects before moving on to the topics that may be of concern in security-related topics. You will also need a text editor and a browser in order to test the code.

We'll start off with simple hide/show effects.

Note

We are using jQuery for this section (and the remainder of the book) for things such as Ajax, animation, and so forth, due to its widespread use and ease of understanding. The important thing is to take note of the lessons/concepts associated with JavaScript.

Hide/Show

To perform hide/show actions, we can make use of jQuery's hide() and show() functions. For example, consider the following code:

<html>
<head>
  <style>
  #item {
    display: block;
    height:100px;
    width:100px;
    border:1px solid black;
    background-color: yellow
  }
  </style>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
  $(document).ready(function() {
    $("#hide").click(function(){
      $("#item").hide();
    });

    $("#show").click(function(){
      $("#item").show();
    });    
  });
  </script>
</head>
<body>
  <button id="show">Show Me</button>
  <button id="hide">Hide Me</button>
  <div id="item">I am item</div>
</body>
</html>

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/ support and register to have the files e-mailed directly to you.

Copy-and-paste this code to the hide_show.html function, and open it in your favorite browser. You should get something like this:

Hide/Show

Simple show and hide actions

Clicking on Show Me and Hide Me will show and hide the yellow box. You can do the same thing using the toggle() function, which we will quickly cover in the next section.

Toggle

The toggle() function allows you to display and hide elements. Going back to the code we used in the previous section, create a new file and call it toggle.html. Replace the code within $(document).ready() with the following code:

    $("#toggle_button").click(function(){
      $("#item").toggle();
    });

Feel free to make some changes to your button IDs and item contents. In my case, this is how my code looks:

<html>
<head>
  <style>
  #item {
    display: block;
    height:100px;
    width:100px;
    border:1px solid black;
    background-color: yellow
  }
  </style>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
  $(document).ready(function() {
    $("#toggle_button").click(function(){
      $("#item").toggle();
    });  
  })
  </script>
  
</head>
<body>
  <button id="toggle_button">Toggle Button</button>
  <div id="item">Toggle Toggle Toggle</div>
</body>
</html>

This is what you will see when you open the file in your web browser:

Toggle

Simple toggle action

Clicking on Toggle Button will allow you to hide and show the yellow box as expected.

Animation

jQuery also provides easy methods to perform animations via the animate() method. Copy the previous example (toggle.html) and name it animation.html. In animation.html, make the following changes as shown in the highlighted lines of code:

<html>
<head>
  <style>
  #item {
    display: block;
    position: relative;
    left:0px;
    height:100px;
    width:100px;
    border:1px solid black;
    background-color: yellow
  }
  </style>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
  $(document).ready(function() {
    $("#animate_button").click(function(){
      $("#item").animate({
        opacity: 0.5,
        left: "+=50",
      }, 1000);
    });  
  })
  </script>
  
</head>
<body>
  <button id="animate_button">Animate Button</button>
  <div id="item">Animate me</div>
   </body>
</html>

We've basically changed #item to display as block with position:relative. Now, the button ID is animate_button. Notice that the animate() function works on the item when the button is clicked. The following is what you will get when you click on Animate Button:

Animation

Animation

The animation looks like the following:

Animation

Animation part 2

Chaining

One of the more interesting uses of jQuery is the chaining of functions. We'll do a basic example using the chaining of built-in animations. Go back to your text editor, create a new file called chained.html, and paste the following code:

<html>
<head>
  <style>
  #item {
    display: none;
    position: relative;
    left:0px;
    height:100px;
    width:100px;
    border:1px solid black;
    background-color: yellow
  }
  </style>
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
  <script>
  $(document).ready(function() {
    $('#chain_button').click(function() {
      $("#item").fadeIn('slow').fadeOut('slow').fadeIn('slow').
       fadeOut('slow').slideDown('slow').slideUp('slow');
    })
  })
  </script>
  
</head>
<body>
  <button id="chain_button">Chained Button</button>
  <div id="item">Chain me</div>
</body>
</html>

The main thing to notice in this example is the use of the fadeIn(), fadeout(), slideDown(), and slideUp() functions. We chain the built-in animations together such that we see a series of effects when we click on the button.

jQuery Ajax

Now, we focus on the jQuery Ajax operations. The basic concepts discussed here will be used in the next chapter, where we will talk about secure RESTful APIs. For a start, Ajax typically refers to Asynchronous JavaScript and XML, where your web page performs data operations with a server to get new data, create or update data, or delete data. During the past few years, with the rise in popularity of APIs (such as the Facebook Graph API and others), data is increasingly being exchanged using JSON instead of XML. Such actions typically require the cooperation of a backend server. We will not cover the server details here; for the moment, we will just focus on the jQuery operations.

In any Ajax application, single page or not, you will most likely be required to perform the basic HTTP operations, such as GET, POST, and so on. In this section, we will deal with the basic operations that you will most likely use in coding Ajax apps. Most importantly, you will use variants of this code in the later chapters.

jQuery GET

A jQuery .get() request simply performs a GET request from a server. To perform a .get() request, you will need the following code:

var jqxhr = $.get("http://example.com/data", function() {
  alert( "success" );
})
  .done(function() {
    alert( "second success" );
  })
  .fail(function() {
    alert( "error" );
  })
  .always(function() {
    alert( "finished" );
  });

The hypothetical endpoint in this example, http://example.com/data, can return either XML or JSON.

jQuery getJSON

A jQuery .getJSON() request simply performs a GET request from a server. But this time around, we are attempting to retrieve JSON data from our server. To perform a .getJSON() request, here's what we do:

var jqxhr = $.getJSON( "http://example.com/json", function(data) {
  console.log( "success" );
})
  .done(function(data) {
    console.log( "second success" );
  })
  .fail(function(data) {
    console.log( "error" );
  })
  .always(function(data) {
    console.log( "complete" );
  });

In this example, we perform a getJSON() request from http://example.com/json; the endpoint should return a JSON response.

jQuery POST

If you want to change the data source of your data or create a new one, you will need to perform a POST operation on your server. In this example, we perform a .post() operation to http://example.com/endpoint, and depending on whether our Ajax request is successful or not, we create an alert with different messages. This is done with the following code:

var jqxhr = $.post( "http://example.com/endpoint", function(data) {
  alert( "success" );
})
  .done(function(data) {
    alert( "second success" );
  })
  .fail(function(data) {
    alert( "error" );
  })
  .always(function(data) {
    alert( "finished" );
});

JavaScript beyond the client

JavaScript now not only runs on browsers, but is also used in servers. In this section, we'll take a very brief look as to where JavaScript is being used at this point in time.

JavaScript on the server side

JavaScript is increasingly used on the server side as well—most notably Node.js and increasingly Meteor.js.

Full-stack JavaScript

JavaScript is also used as a full-stack programming language, from the server side, client side, and so on. In fact, there are now full-stack frameworks, such as MEAN, where JavaScript is based on MongoDB, Express.js, AngularJS, and Node.js.

JavaScript security issues

JavaScript is becoming ubiquitous and more popular now. However, it has some security issues if not used properly. Two of the most commonly known examples are cross-site request forgery (CSRF) and cross-site scripting. I'll touch very briefly upon these two topics as a way to prepare you for the remainder of the book.

Cross-site request forgery

I decided to start off with this topic as it is generally easier to explain and understand. To put it simply, cross-site request forgery refers to a type of malicious exploitation of a website where unauthorized commands are transmitted from an unknowing user that the website trusts.

The following straightforward example involves Ajax requests: go back to earlier sections where we talked about POST requests. Imagine that your server endpoint does not defend itself against an Ajax request made outside of your domain name, and somehow, malicious POST requests are made. That particular request can somehow be made to alter your database information and more.

You may argue that we can make use of CSRF tokens (a common technique to prevent cross-domain requests and a way to provide greater security to the site) as a security measure, but it is not entirely safe. For instance, the script that is performing the attack could be residing in the website itself; the site could have been hijacked with malicious script in the first place.

In addition, if some of the following conditions are met, CSRF can be achieved:

  • The defending websites do not check the referrer header
  • The attacker will need to:
    • Find a form submission endpoint (that typically has important side effects, such as monetary exchange or exchange of highly personal information)
    • Guess the right values for the form inputs in order to carry out the attack

Cross-site scripting

Cross-site scripting (XSS) enables attackers to inject a client-side script (usually JavaScript) into web pages that are used by users. The general idea is that attackers use the known vulnerabilities of web-based applications, servers, plugin systems (such as WordPress), or even third-party JavaScript plugins to serve malicious scripts or content from the compromised site. The end result is that the compromised site ends up sending content that contains the malicious content/script.

If the content happens to be a piece of malicious JavaScript, then the results can be disastrous: since we know that JavaScript has global access to the web page, such as the DOM, and given the fact that that piece of JavaScript can have access to the cookies issued by the site (thus allowing the attacker to gain access to potentially useful information), that piece of JavaScript can do the following:

  • Make changes on the DOM so that it creates links, malicious content, and more
  • Perform actions on behalf of the user, such as performing web form submissions or Ajax operations straight from the site

If you are new to all this, all you need to remember at this point in time is that such security flaws come from both server-side and client-side weaknesses. We'll be touching upon them in the next chapter.

Summary

To summarize, we went through some basic jQuery and JavaScript. We've also learned some basic ideas on how JavaScript security issues occur and what they are. From this chapter onwards, we'll go into deeper detail on individual topics introduced in this chapter. We'll start with writing secure Ajax RESTful APIs in the next chapter.

Left arrow icon Right arrow icon

Description

This book is for JavaScript developers having basic web development knowledge and also for those who want to explore the security issues that arise from the use of JavaScript. Prior knowledge of how JavaScript is used, such as for DOM manipulation or to perform Ajax operations, is assumed.

What you will learn

  • Review the features of JavaScript and its vulnerabilities
  • Use JavaScript in tandem with Ajax RESTful APIs
  • Deal with crosssite scripting
  • Make basic GET and POST calls to an endpoint
  • Explore what crosssite forgery is and how to deal with it
  • Avoid misplaced trust in the client and explore various examples
  • Understand JavaScript phishing
Estimated delivery fee Deliver to Belgium

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 22, 2014
Length: 112 pages
Edition : 1st
Language : English
ISBN-13 : 9781783988006
Category :
Languages :
Tools :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Estimated delivery fee Deliver to Belgium

Premium delivery 7 - 10 business days

€17.95
(Includes tracking information)

Product Details

Publication date : Nov 22, 2014
Length: 112 pages
Edition : 1st
Language : English
ISBN-13 : 9781783988006
Category :
Languages :
Tools :

Packt Subscriptions

See our plans and pricing
Modal Close icon
€18.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
€189.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts
€264.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just €5 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 94.97
JavaScript Security
€20.99
Mastering JavaScript Design Patterns
€36.99
Learning JavaScript Data Structures and Algorithms
€36.99
Total 94.97 Stars icon

Table of Contents

7 Chapters
1. JavaScript and the Web Chevron down icon Chevron up icon
2. Secure Ajax RESTful APIs Chevron down icon Chevron up icon
3. Cross-site Scripting Chevron down icon Chevron up icon
4. Cross-site Request Forgery Chevron down icon Chevron up icon
5. Misplaced Trust in the Client Chevron down icon Chevron up icon
6. JavaScript Phishing Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
(1 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 100%
1 star 0%
Guillermo Snipe May 07, 2015
Full star icon Full star icon Empty star icon Empty star icon Empty star icon 2
I didn't learn anything new. You can find almost all the content in the web. Fairly basic examples.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela