Search icon
Arrow left icon
All Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletters
Free Learning
Arrow right icon
JavaScript Security
JavaScript Security

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

By Eugene Liang
$15.99 per month
Book Nov 2014 112 pages 1st Edition
eBook
$16.99 $10.99
Print
$26.99
Subscription
$15.99 Monthly
eBook
$16.99 $10.99
Print
$26.99
Subscription
$15.99 Monthly

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details


Publication date : Nov 22, 2014
Length 112 pages
Edition : 1st Edition
Language : English
ISBN-13 : 9781783988006
Category :
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:

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:

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

The animation looks like the following:

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

Key benefits

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

What do you get with a Packt Subscription?

Free for first 7 days. $15.99 p/m after that. Cancel any time!
Product feature icon Unlimited ad-free access to the largest independent learning library in tech. Access this title and thousands more!
Product feature icon 50+ new titles added per month, including many first-to-market concepts and exclusive early access to books as they are being written.
Product feature icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Product feature icon Thousands of reference materials covering every tech concept you need to stay up to date.
Subscribe now
View plans & pricing

Product Details


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

Table of Contents

13 Chapters
JavaScript Security Chevron down icon Chevron up icon
Credits Chevron down icon Chevron up icon
About the Author Chevron down icon Chevron up icon
About the Reviewers Chevron down icon Chevron up icon
www.PacktPub.com Chevron down icon Chevron up icon
Preface Chevron down icon Chevron up icon
JavaScript and the Web Chevron down icon Chevron up icon
Secure Ajax RESTful APIs Chevron down icon Chevron up icon
Cross-site Scripting Chevron down icon Chevron up icon
Cross-site Request Forgery Chevron down icon Chevron up icon
Misplaced Trust in the Client Chevron down icon Chevron up icon
JavaScript Phishing Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Filter icon Filter
Top Reviews
Rating distribution
Empty star icon Empty star icon Empty star icon Empty star icon Empty star icon 0
(0 Ratings)
5 star 0%
4 star 0%
3 star 0%
2 star 0%
1 star 0%

Filter reviews by


No reviews found
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is included in a Packt subscription? Chevron down icon Chevron up icon

A subscription provides you with full access to view all Packt and licnesed content online, this includes exclusive access to Early Access titles. Depending on the tier chosen you can also earn credits and discounts to use for owning content

How can I cancel my subscription? Chevron down icon Chevron up icon

To cancel your subscription with us simply go to the account page - found in the top right of the page or at https://subscription.packtpub.com/my-account/subscription - From here you will see the ‘cancel subscription’ button in the grey box with your subscription information in.

What are credits? Chevron down icon Chevron up icon

Credits can be earned from reading 40 section of any title within the payment cycle - a month starting from the day of subscription payment. You also earn a Credit every month if you subscribe to our annual or 18 month plans. Credits can be used to buy books DRM free, the same way that you would pay for a book. Your credits can be found in the subscription homepage - subscription.packtpub.com - clicking on ‘the my’ library dropdown and selecting ‘credits’.

What happens if an Early Access Course is cancelled? Chevron down icon Chevron up icon

Projects are rarely cancelled, but sometimes it's unavoidable. If an Early Access course is cancelled or excessively delayed, you can exchange your purchase for another course. For further details, please contact us here.

Where can I send feedback about an Early Access title? Chevron down icon Chevron up icon

If you have any feedback about the product you're reading, or Early Access in general, then please fill out a contact form here and we'll make sure the feedback gets to the right team. 

Can I download the code files for Early Access titles? Chevron down icon Chevron up icon

We try to ensure that all books in Early Access have code available to use, download, and fork on GitHub. This helps us be more agile in the development of the book, and helps keep the often changing code base of new versions and new technologies as up to date as possible. Unfortunately, however, there will be rare cases when it is not possible for us to have downloadable code samples available until publication.

When we publish the book, the code files will also be available to download from the Packt website.

How accurate is the publication date? Chevron down icon Chevron up icon

The publication date is as accurate as we can be at any point in the project. Unfortunately, delays can happen. Often those delays are out of our control, such as changes to the technology code base or delays in the tech release. We do our best to give you an accurate estimate of the publication date at any given time, and as more chapters are delivered, the more accurate the delivery date will become.

How will I know when new chapters are ready? Chevron down icon Chevron up icon

We'll let you know every time there has been an update to a course that you've bought in Early Access. You'll get an email to let you know there has been a new chapter, or a change to a previous chapter. The new chapters are automatically added to your account, so you can also check back there any time you're ready and download or read them online.

I am a Packt subscriber, do I get Early Access? Chevron down icon Chevron up icon

Yes, all Early Access content is fully available through your subscription. You will need to have a paid for or active trial subscription in order to access all titles.

How is Early Access delivered? Chevron down icon Chevron up icon

Early Access is currently only available as a PDF or through our online reader. As we make changes or add new chapters, the files in your Packt account will be updated so you can download them again or view them online immediately.

How do I buy Early Access content? Chevron down icon Chevron up icon

Early Access is a way of us getting our content to you quicker, but the method of buying the Early Access course is still the same. Just find the course you want to buy, go through the check-out steps, and you’ll get a confirmation email from us with information and a link to the relevant Early Access courses.

What is Early Access? Chevron down icon Chevron up icon

Keeping up to date with the latest technology is difficult; new versions, new frameworks, new techniques. This feature gives you a head-start to our content, as it's being created. With Early Access you'll receive each chapter as it's written, and get regular updates throughout the product's development, as well as the final course as soon as it's ready.We created Early Access as a means of giving you the information you need, as soon as it's available. As we go through the process of developing a course, 99% of it can be ready but we can't publish until that last 1% falls in to place. Early Access helps to unlock the potential of our content early, to help you start your learning when you need it most. You not only get access to every chapter as it's delivered, edited, and updated, but you'll also get the finalized, DRM-free product to download in any format you want when it's published. As a member of Packt, you'll also be eligible for our exclusive offers, including a free course every day, and discounts on new and popular titles.