Secure JavaScript

JavaScript sometimes gets knocked for being an everything-goes language with lots of WAT. But does that mean it is by nature insecure? How can we write secure JavaScript?

Background

These notes will assume you’re a fairly capable JavaScript programmer. In particular, you should already know:

JavaScript and Security

JavaScript is a memory-managed language, meaning you don’t have to allocate and deallocate memory on your own. You simply ask to create new objects and space is found for them on the heap. When objects are no longer accessible, a garbage collector will reclaim the memory.

You do not get the classic buffer overflows possible in C and C++, but there are still many ways JavaScript code can be vulnerable.

JavaScript Language Security

Like any modern language, poorly written JavaScript can be susceptible to exploits around:

Exercise: Do some research on strict mode. Read and study, carefully and in detail, the entire excellent MDN article on strict mode. Produce, as you study, a table of strict mode features versus sloppy mode features.

There is also the very old (not updated since 2015) JavaScript Best Practices Guide from the W3C that has a curious mix of browser-based guidelines and language-independent ideas. You can read it with the understanding that many of the JavaScript-specific guidelines might have been addressed in more modern iterations of the language.

Node.js Security

JavaScript is a massively popular language on the server-side of web and mobile applications, because it is so event-friendly and async-friendly. Node.js is the most popular server-side JavaScript runtime, used almost everywhere. There are a few things to do to secure your Node.js applications.

What can we do? Well, good news! You can start with the Node.js Cheat Sheet from OWASP!

Also, the NPM ecosystem (the largest in the world, perhaps) allows you to run:

npm audit

Audit frequently!

For more on Node.js security, read this Best Practices article, and checkout this summary from a really comprehensive best practices repository on GitHub.

Browser Security

Browsers place severe restrictions on what the JavaScript engine running in your browser can do. Your browser’s JavaScript can’t read your files, can’t access content such as cookies or variables from different sites (at least by default), and so on.

But it doesn’t stop everything bad. There are still security problems unique to writing code poorly in browser-side JavaScript. Examples are XSS, Not handling cookies securely, CSRF, abusing innerHTML, and many more. We’ll cover these later in a unit on Web Security.

In the meantime, here’s a video:

Summary

We’ve covered:

  • Things to keep in mind about JavaScript and Security
  • Sources of vulnerabilities
  • Strict mode
  • Node.js Security
  • Browser security issues