Security Articles

Sort by:


  1. Inspecting Security and Privacy Settings of a Website

    Inspecting the Content Security Policy of a Website

    Starting in Firefox 41, Mozilla provides a developer tool that allows users to inspect the security settings of a website. Using GCLI (Graphic Command Line Interface) a user can inspect the Content Security Policy (CSP) of a website. CSP is a security concept that allows websites to protect themselves against cross-site scripting (XSS) and related attacks. CSP allows website authors to whitelist approved sources from which content can be loaded safely. Browsers enforce that Content Security Policy header and only allow whitelisted resources to be loaded into that website. The CSP inspection tool » security csp lists all whitelisted sources.

    The main intention behind CSP is to protect websites against XSS attacks, but the protection needs to be deployed in a way that allows support for legacy code on these sites. For example, the keyword ‘unsafe-inline’ was originally introduced to support legacy inline scripts while transitioning sites to use CSP. This keyword whitelists all inline scripts for a site, but it also allows attacker-injected scripts to execute, making CSP ineffective against most XSS attacks. Hence, the CSP devtool not only lists all whitelisted sources, but also provides a rating for each whitelisted source, to indicate the level of protection.

    Inspecting the referrer policy of a website

    Starting in Firefox 43, Mozilla exposes more website privacy settings and also allows users to inspect the Referrer Policy » security referrer. The referrer policy allows websites to exercise more control over the browser’s referrer header. Specifically it allows website authors to instruct the browser to strip the referrer completely, reveal it only when navigating within the same origin, etc. The referrer devtool provides an example of what referrer will be used when visiting different websites, allowing the user and developer to inspect what information is sent when following a link.

    Inspecting the Content Security Policy as well as the Referrer Policy is only the starting point to providing end users with more feedback about the security and privacy settings a web page uses. We hope to add more tools in the future to give users more transparency and control over the security and privacy of the websites they visit.

  2. Do not let your CDN betray you: Use Subresource Integrity

    Mozilla Firefox Developer Edition 43 and other modern browsers help websites to control third-party JavaScript loads and prevent unexpected or malicious modifications. Using a new specification called Subresource Integrity, a website can include JavaScript that will stop working if it has been modified. With this technology, developers can benefit from the performance gains of using Content Delivery Networks (CDNs) without having to fear that a third-party compromise can harm their website.

    Using Subresource Integrity is rather simple:

    <script src=""

    The idea is to include the script along with its cryptographic hash (e.g. SHA-384) when creating the web page. The browser can then download the script and compute the hash over the downloaded file. The script will only be executed if both hashes match. The security properties of a collision resistant hash function, ensure that a modification results in a very different hash. This helps the site owner detect and prevent any changes, whether they come from a compromised CDN or an evil administrator.

    An important side note is that for Subresource Integrity to work, the CDN must support Cross-Origin Resource Sharing (CORS). The crossorigin attribute in the above code snippet enforces a CORS-enabled load. The anonymous value means that the browser should omit any cookies or authentication that the user may have associated with the domain. This prevents cross-origin data leaks, and also makes the request smaller.

    Integrity syntax

    As you may have noticed, the integrity attribute does not just include the hash value. It also contains the digest name. The syntax for the integrity attribute allows multiple tokens of this name-value format. This allows site owners to specify hashes of different strengths as well as the values of multiple scripts that may be behind a URL. This is useful for browser sniffing or content negotiation.

    <script src=""


    For the best performance, users would load all resources from the CDN, but if integrity cannot be verified, you don’t want your users to be trapped on a non-working web page. To make failover work, we recommend hosting a copy of the script on your own origin. To recover from failure one could then extend the previous snippet with the following code:

    <script>window.jQuery || /* reload from own domain here */;</script>

    This code will check if jQuery has been defined and could otherwise insert a script tag that loads the same origin version of the script.

    Please note that many scripts update regularly, especially if they do not come with a version number. If you want to secure your CDN-loaded scripts, it is best to stick to a specific version and not use filenames with the word ‘latest’ in them.

    HTTP or HTTPS?

    Subresource Integrity works on both HTTP and HTTPS. If you are serving your page over plain HTTP, the browser can still figure out if the script was modified on the CDN, but it is not protected against active network attackers, as they would be able to just remove the integrity attribute from your HTML. It is, however, in the interest of your users to provide confidentiality, integrity, and authenticity of your web applications by using HTTPS for the entirety of your website.

    Stylesheet support

    While we are working on adding support for subresources other than scripts, you can also use Subresource Integrity for CSS. Just use the integrity attribute that you now know so well on your <link> tag!

    Try Subresource Integrity Now!

    If you want to test browser support or toy with examples, take a look at, which can do all the grunt work of computing hashes as well as checking if your CDN already supports HTTPS. A few early adopters like BootstrapCDN, CloudFlare and GitHub are already experimenting with it.
    There is some additional documentation of Subresource Integrity on MDN. But if you want to read all the fine details of Subresource Integrity, take a look at the specification.

    To conclude, Subresource Integrity can make your website safer when using a CDN that you do not fully control. It’s as simple as adding just a few extra attributes to your script tags.

  3. Passwordless authentication: Secure, simple, and fast to deploy

    Passwordless is an authentication middleware for Node.js that improves security for your users while being fast and easy to deploy.

    The last months were very exciting for everyone interested in web security and privacy: Fantastic articles, discussions, and talks but also plenty of incidents that raised awareness.

    Most websites are, however, still stuck with the same authentication mechanism as from the earliest days of the web: username and password.

    While username and password have their place, we should be much more challenging if they are the right solution for our projects. We know that most people use the same password on all the sites they visit. For projects without dedicated security experts, should we really open up our users to the risk that a breach of our site also compromises their Amazon account? Also, the classic mechanism has by default at least two attack vectors: the login page and the password recovery page. Especially the latter is often implemented hurried and hence inherently more risky.

    We’ve seen quite a bit of great ideas recently and I got particularly excited by one very straightforward and low-tech solution: one-time passwords. They are fast to implement, have a small attack surface, and require neither QR codes nor JavaScript. Whenever a user wants to login or has her session invalidated, she receives a short-lived one-time link with a token via email or text message. If you want to give it a spin, feel free to test the demo on

    Unfortunately—depending on your technology stack—there are few to none ready-made solutions out there. Passwordless changes this for Node.js.

    Getting started with Node.js & Express

    Getting started with Passwordless is straight-forward and you’ll be able to deploy a fully fledged and secure authentication solution for a small project within two hours:

    $ npm install passwordless --save

    gets you the basic framework. You’ll also want to install one of the existing storage interfaces such as MongoStore which store the tokens securely:

    $ npm install passwordless-mongostore --save

    To deliver the tokens to the users, email would be the most common option (but text message is also feasible) and you’re free to pick any of the existing email frameworks such as:

    $ npm install emailjs --save

    Setting up the basics

    Let’s require all of the above mentioned modules in the same file that you use to initialise Express:

    var passwordless = require('passwordless');
    var MongoStore = require('passwordless-mongostore');
    var email   = require("emailjs");

    If you’ve chosen emailjs for delivery that would also be a great moment to connect it to your email account (e.g. a Gmail account):

    var smtpServer  = email.server.connect({
       user:    yourEmail,
       password: yourPwd,
       host:    yourSmtp,
       ssl:     true

    The final preliminary step would be to tell Passwordless which storage interface you’ve chosen above and to initialise it:

    // Your MongoDB TokenStore
    var pathToMongoDb = 'mongodb://localhost/passwordless-simple-mail';
    passwordless.init(new MongoStore(pathToMongoDb));

    Delivering a token

    passwordless.addDelivery(deliver) adds a new delivery mechanism. deliver is called whenever a token has to be sent. By default, the mechanism you choose should provide the user with a link in the following format:{TOKEN}&amp;uid={UID}

    deliver will be called with all the needed details. Hence, the delivery of the token (in this case with emailjs) can be as easy as:

        function(tokenToSend, uidToSend, recipient, callback) {
            var host = 'localhost:3000';
                text:    'Hello!nAccess your account here: http://'
                + host + '?token=' + tokenToSend + '&amp;uid='
                + encodeURIComponent(uidToSend),
                from:    yourEmail,
                to:      recipient,
                subject: 'Token for ' + host
            }, function(err, message) {
                if(err) {

    Initialising the Express middleware

    app.use(passwordless.acceptToken({ successRedirect: '/'}));

    sessionSupport() makes the login persistent, so the user will stay logged in while browsing your site. Please make sure that you’ve already prepared your session middleware (such as express-session) beforehand.

    acceptToken() will intercept any incoming tokens, authenticate users, and redirect them to the correct page. While the option successRedirect is not strictly needed, it is strongly recommended to use it to avoid leaking valid tokens via the referrer header of outgoing HTTP links on your site.

    Routing & Authenticating

    The following takes for granted that you’ve already setup your router var router = express.Router(); as explained in the express docs

    You will need at least two URLs to:

    • Display a page asking for the user’s email
    • Accept the form details (via POST)
    /* GET: login screen */
    router.get('/login', function(req, res) {
    /* POST: login details */'/sendtoken',
        function(req, res, next) {
            // TODO: Input validation
        // Turn the email address into a user ID
            function(user, delivery, callback) {
                // E.g. if you have a User model:
                User.findUser(email, function(error, user) {
                    if(error) {
                    } else if(user) {
                        // return the user ID to Passwordless
                    } else {
                        // If the user couldn’t be found: Create it!
                        // You can also implement a dedicated route
                        // to e.g. capture more user details
                        User.createUser(email, '', '',
                            function(error, user) {
                                if(error) {
                                } else {
        function(req, res) {
            // Success! Tell your users that their token is on its way

    What happens here? passwordless.requestToken(getUserId) has two tasks: Making sure the email address exists and transforming it into a unique user ID that can be sent out via email and can be used for identifying users later on. Usually, you’ll already have a model that is taking care of storing your user details and you can simply interact with it as shown in the example above.

    In some cases (think of a blog edited by just a couple of users) you can also skip the user model entirely and just hardwire valid email addresses with their respective IDs:

    var users = [
        { id: 1, email: '' },
        { id: 2, email: '' }
    /* POST: login details */'/sendtoken',
            function(user, delivery, callback) {
                for (var i = users.length - 1; i >= 0; i--) {
                    if(users[i].email === user.toLowerCase()) {
                        return callback(null, users[i].id);
                callback(null, null);
            // Same as above…

    HTML pages

    All it needs is a simple HTML form capturing the user’s email address. By default, Passwordless will look for an input field called user:

            <form action="/sendtoken" method="POST">
                <br /><input name="user" type="text">
                <br /><input type="submit" value="Login">

    Protecting your pages

    Passwordless offers middleware to ensure only authenticated users get to see certain pages:

    /* Protect a single page */
    router.get('/restricted', passwordless.restricted(),
     function(req, res) {
      // render the secret page
    /* Protect a path with all its children */
    router.use('/admin', passwordless.restricted());

    Who is logged in?

    By default, Passwordless makes the user ID available through the request object: req.user. To display or reuse the ID it to pull further details from the database you can do the following:

    router.get('/admin', passwordless.restricted(),
        function(req, res) {
            res.render('admin', { user: req.user });

    Or, more generally, you can add another middleware that pulls the whole user record from your model and makes it available to any route on your site:

    app.use(function(req, res, next) {
        if(req.user) {
            User.findById(req.user, function(error, user) {
                res.locals.user = user;
        } else {

    That’s it!

    That’s all it takes to let your users authenticate securely and easily. For more details you should check out the deep dive which explains all the options and the example that will show you how to integrate all of the things above into a working solution.


    As mentioned earlier, all authentication systems have their tradeoffs and you should pick the right system for your needs. Token-based channels share one risk with the majority of other solutions incl. the classic username/password scheme: If the user’s email account is compromised and/or the channel between your SMTP server and the user’s, the user’s account on your site will be compromised as well. Two default options help mitigate (but not entirely eliminate!) this risk: short-lived tokens and automatic invalidation of the tokens after they’ve been used once.

    For most sites token-based authentication represents a step up in security: users don’t have to think of new passwords (which are usually too simple) and there is no risk of users reusing passwords. For us as developers, Passwordless offers a solution that has only one (and simple!) path of authentication that is easier to understand and hence to protect. Also, we don’t have to touch any user passwords.

    Another point is usability. We should consider both, the first time usage of your site and the following logons. For first-time users, token-based authentication couldn’t be more straight-forward: They will still have to validate their email address as they have to with classic login mechanisms, but in the best-case scenario there will be no additional details required. No creativity needed to come up with a password that fulfils all restrictions and nothing to memorise. If the user logins again, the experience depends on the specific use case. Most websites have relatively long session timeouts and logins are relatively rare. Or, people’s visits to the website are actually so infrequent that they will have difficulties recounting if they already had an account and if so what the password could have been. In those cases Passwordless presents a clear advantage in terms of usability. Also, there are few steps to take and those can be explained very clearly along the process. Websites that users visit frequently and/or that have conditioned people to login several times a week (think of Amazon) might however benefit from a classic (or even better: two-factor) approach as people will likely be aware of their passwords and there might be more opportunity to convince users about the importance of good passwords.

    While Passwordless is considered stable, I would love your comments and contributions on GitHub or your questions on Twitter: @thesumofall

  4. Firefox and FireCAT as a Platform for Ethical Hacking

    Some years ago – in early 2007, while working as freelancers – we were challenged to do a penetration test on a web application. It was really simple but had a condition-based methodology, and therefore was impossible to use any automated tool; we could only use a web browser.

    Our solution was to convert Firefox into a Platform for Ethical Hacking.

    How did we do it?

    We searched the Web, looking for a solution that satisfied the requirements and obligations to not use automated tools. We found many, a lot of them being add-ons and extensions. Many of them were unknown, unnoticed and unofficial.

    Having compiled some useful findings, our next challenge was to create something that maintained the essence of Mozilla Firefox: open, free and easy for everyone. The project was named FireCAT (Firefox Catalog of Auditing exTensions)

    What is FireCAT?

    FireCAT is a mind map organized into different categories and subcategories with a variety of add-ons available. These are themed around application security auditing and assessment, adding news functionality, customizing your browser and providing the ability to adapt it to different user’s need.

    Current Status

    The latest version is 2.0, and was presented at Black Hat Arsenal during 2011. From the web site it is possible to list the content and browse the categories, directly accessing the add-ons on Mozilla Add-ons; you can also download the entire mind map with the categories:

    What’s New?

    • Current Version: 2.0
    • Add-ons: > 90
    • Categories: 7
    • Subcategories: 19

    FireCAT v2.0 – Firefox Catalog of Auditing exTensions

    • Information Gathering
      • Whois
      • Location Info
      • Enumeration & Fingerprint
      • Data Mining
      • Googling & Spidering
    • Proxies & Web Utilities
    • Editors
    • Network Utilities
      • Intrusion Detection System
      • Sniffers
      • Wireless
      • Passwords
      • Protocols & Applications
    • Misc
      • Tweaks & Hacks
      • Encryption / Hashing
      • Antivirus & Malware Scanner
      • Anti Spoof
      • Anti-phishing / Pharming / Jacking
      • Automation
      • Logs / History
      • Backup & Synchronization
      • Protection
    • IT Security Related
    • Application Auditing

    What can we find in the categories?

    The 7 main categories are as follows:

    Information Gathering

    An important part of the process of conducting vulnerability assessment or penetration testing is related to obtaining information in a passive or active way about our objective, to be analyzed later.

    From the Firefox platform, we could identify IP addresses, query DNS, verify HTTP headers, generate reports of domains via Whois, use different search engines, and identify applications and versions from Web Server, modules, etc.


    “Show IP” shows the IP address(es) of the current page in the status bar. It also allows querying of custom services by IP (right mouse button) and hostname (left mouse button), like whois, netcraft, etc.

    Proxies & Web Utilities

    Sometimes it’s necessary to use proxies to connect with different hosts or through networks for exaple using TOR to hide our real IP, analyze time responses, detect load balancer, etc.


    The User Agent Switcher extension adds a menu and a toolbar button to switch the user agent of the browser:


    From the ubiquitous FireBug to different JavaScript or XML editors, the available editors can help us to visualize and modify content as required.


    The JavaScript Deobfuscator will show you what JavaScript gets to run on a web page, even if it is obfuscated and generated on the fly.

    Network Utilities

    In this section you can use and connect with applications and services such as FTP, DNS and databases in real time.


    This section contains a lot of useful add-ons, for example tools to convert your ASCII into md5, sha1, base64, hex, etc., and methods to identify the WOT (Web of Trust) in a web site, guage reputation and ratings, modify your HTTP Referer, automate actions through Macros, and make backups of your configuration and installed addons.


    The Certificate Patrol add-on reveals when certificates are updated, so you can ensure it was a legitimate change.

    IT Security Related

    Sometimes it is necessary to use search engines to find information within some Web sites, content related to errors, configurations, and news vulnerabilities by CVE.

    Application Auditing

    The HackBar is probably the best known addon in this group, but I recommend you take a deeper look because many of them are useful. For example, Exploit-Me’s suite to perform vulnerability analysis of cross-site scripting and SQL Injection.


    The SQLite Manager allows you to manage any SQLite database on your computer.

    Recommended add-ons

    The top ten recommended add-ons would be:

    Final Words

    I invite you to explore the different add-ons and extensions available, identifying which ones are most interesting and helpful for your work, and their relative performance and compatibilities. Firefox was a great help during our work!

    If you decide to install a large amount of add-ons, memory usage might be a problem: consider this carefully.

    Feel free to send us your comments and recommendations for new options to add to the mind map!

  5. Firefox OS Security: Part 2 – User Experience and Security Updates

    When presenting Firefox OS to people, security is a big topic. Can an operating system built on web technologies be secure? What has Mozilla built in to avoid drive-by downloads and malware? How can a browser-based app be secure without making the UX suffer by asking the user to react to a lot of “do you want to allow this?”. In this, the second of a two part video series Christian Heilmann (@codepo8), principal evangelist of Mozilla, talks to Michael Coates (@_mwc), chair of @OWASP Board about the user experience when it comes to installing and using apps and the security update model for Firefox OS.

    You can watch the video on YouTube.

    Firefox OS was built on top of the technologies that power the Web. Following Mozilla’s security practices and knowledge from over 10 years of securing Firefox, Firefox OS is engineered as a multi-tiered system that protects users while delivering the power of the mobile web. The design ensures users are in control of their data and developers have APIs and technologies at their disposal to unlock the power of the Web.

    Additional links for more information:

  6. Firefox OS Security: Part 1 – The Web Security Model

    When presenting Firefox OS to people, security is a big topic. Can an operating system built on web technologies be secure? What has Mozilla built in to avoid drive-by downloads and malware? In this two part video series Christian Heilmann (@codepo8), principal evangelist of Mozilla, talks to Michael Coates (@_mwc), chair of @OWASP Board about all things security in Firefox OS.

    Firefox OS was built on top of the technologies that power the Web. Following Mozilla’s security practices and knowledge from over 10 years of securing Firefox, Firefox OS is engineered as a multi-tiered system that protects users while delivering the power of the mobile web. The design ensures users are in control of their data and developers have APIs and technologies at their disposal to unlock the power of the Web.

    Watch the following video where we talk more about the security design and controls present in Firefox OS. In this, the first of two videos on Firefox OS security, we’ll cover items such as the multi-tiered architecture, the permission model, run time decision making, protection of users data and the update model. You can watch the video on YouTube.

    Additional links for more information:

  7. Content Security Policy 1.0 lands in Firefox Aurora

    The information in this article is based on work together with Ian Melven, Kailas Patil and Tanvi Vyas.

    We have just landed support for the Content Security Policy (CSP) 1.0
    in Firefox Aurora (Firefox 23), available as of tomorrow (May 30th). CSP is a security mechanism that aims to protect a website against content injection attacks by providing a whitelist of known-good domain names to accept JavaScript (and other content) from. CSP does this by sending a Content-Security-Policy header with the document it protects (yes, we lost the X prefix with the 1.0 version of the spec).

    To effectively protect against XSS, a few JavaScript features have to be

    • All inline JavaScript is disallowed. This means, that all the JavaScript code must be placed in a separate file that is linked via <script src=... >
    • All calls to functions which allow JavaScript code being executed from strings (e.g., eval) are disabled

    CSP now more intuitive and consistent

    While Firefox has had support for CSP since its invention here at Mozilla, things have been changing a lot. The streamlined development of a specification within the W3C has made the concept more intuitive and consistent. Most directives in a CSP header are now of a unified form which explicitly specifies the type of content you want to restrict:

    • img-src
    • object-src
    • script-src
    • style-src and so on.

    Oh and if you feel like you must allow less secure JavaScript coding styles, you can add the values unsafe-inline or unsafe-eval to your list of script sources. (This used to be inline-script and eval-script before).

    Start protecting your website by implementing CSP now!

    But wait – isn’t that a bit tedious… Writing a complex policy and making sure that you remembered all the resources that your website requires? Don’t fret! Here comes UserCSP again!

    Generate your Content Security Policies with UserCSP!

    During the last few months, Kailas Patil, a student in our Security Mentorship Program has continued his GSoC work from last year to update UserCSP.

    UserCSP is a Firefox add-on that helps web developers and security-minded users use CSP. Web developers can create a Content Security Policy (CSP) for their site by using UserCSP’s infer CSP feature. This feature can list required resource URLs and turn them into a policy ready to plug into a CSP header.

    In addition, UserCSP is the first step to expose a policy enforcement mechanism directly to web users. Furthermore, users can enforce a stricter policy than a page supplies through the add-on or apply a policy to certain websites that don’t currently support CSP.

    While earlier versions of UserCSP were more aligned to content security policies as originally invented at Mozilla, this version is updated to be in compliance with the CSP 1.0 specification. This means that policies derived with this add-on may work in all browsers as soon as they support the specification. Hooray!

    As this evolves and ships, our MDN documentation on Content Security Policy (CSP) will keep on evolving, and we also plan to write more about this in the Mozilla Security Blog in the next few weeks, so stay tuned!

  8. Privacy policy guidelines and Template for web apps

    Privacy Releasing an app is much more than just coding it. You are providing a service to people and they trust you with their data. With the amount of reports of apps “calling home” and storing and sending your data to third parties without your consent rising it is important to make it plain and obvious what you do. An easy to understand and plain Privacy Policy is not only a good service but it can make it easier for investors and users to choose your product over another.

    Ramping up developers to submit and publish their apps to the Mozilla Marketplace we just released a few simple to understand Privacy policy guidelines complete with an HTML/CSS/RSS Privacy Policy Template on GitHub.

    Whilst the guidelines are not a substitute for a real lawyer and don’t provide legal advice they have some very simple and powerful tips to get you going:

    • Design your app or add-on so that what you actually do with user data is what users think you are doing with it.
    • Try to give the user as much control over their data as you can, such as giving them the choice to opt-in to or opt-out of data collection whenever possible.
    • Try to limit your data collection and use to only the data that you need.
    • Design your app and service to protect the security of your user’s data in its collection, storage, and use.
    • Respond to user questions and concerns about your privacy practices.
    • Avoid ‘secret’ updates.
    • Make your use of social features transparent, so that users are aware of when they’re sharing data socially.
    • Give people a way to turn off automatic sharing or make more granular choices about sharing data.
    • Obtain consent from users when necessary, especially for location and other sensitive information.
    • Put a link to your privacy policy and, if you have them, your “terms of use” somewhere in your app.

    Avoid confusion and problems in the future by getting the basics right – and that very much includes privacy concerns in your app.

  9. An interesting way to determine if you are logged into social web sites

    Do you remember the trick how to find out that you went to certain web sites by analysing link colour (now patched in Firefox)? There is much your browser tells about you if you just create a few HTML elements.

    Mike Cardwell has found an interesting way to detect if you are logged into social web sites. The easiest trick lies with GMail. Mike created a photo and uploaded it to Google. If you add this image to an HTML document and add event handlers for the success and failure case you can check if the visitor is logged in or not – as the photo gets delivered when you are and GMail delivers a 404 document when you are not:

    <img style="display:none;"

    This works in all browsers and can be used to for example send mailto: links to GMail directly. Notice that this just checks that you are logged in, it doesn’t mean you get access to content.

    For Facebook and Twitter, this doesn’t quite work. Instead, Mike tries to read content with the APIs and relies on errors to be thrown on 404 responses:

    <script type="text/javascript"
    <script type="text/javascript"

    This fails to work in Internet Explorer and Opera, but still works nicely for the other browsers. In Firefox you can work around this using the Request Policy add-on.

    It’d be interesting to see what other social web sites can be detected with some simple onload and onerror handlers. Know any others?

  10. ECMAScript 5 strict mode in Firefox 4

    Editor’s note: This article is posted by Chris Heilmann but authored by Jeff Walden – credit where credit is due.

    Developers in the Mozilla community have made major improvements to the JavaScript engine in Firefox 4. We have devoted much effort to improving performance, but we’ve also worked on new features. We have particularly focused on ECMAScript 5, the latest update to the standard underlying JavaScript.

    Strict mode is arguably the most interesting new feature in ECMAScript 5. It’s a way to opt in to a restricted variant of JavaScript. Strict mode isn’t just a subset: it intentionally has different semantics from normal code. Browsers not supporting strict mode will run strict mode code with different behavior from browsers that do, so don’t rely on strict mode without feature-testing for support for the relevant aspects of strict mode.

    Strict mode code and non-strict mode code can coexist, so scripts can opt into strict mode incrementally. Strict mode blazes a path to future ECMAScript editions where new code with a particular <script type="..."> will likely automatically be executed in strict mode.

    What does strict mode do? First, it eliminates some JavaScript pitfalls that didn’t cause errors by changing them to produce errors. Second, it fixes mistakes that make it difficult for JavaScript engines to perform optimizations: strict mode code can sometimes be made to run faster than identical code that’s not strict mode. Firefox 4 generally hasn’t optimized strict mode yet, but subsequent versions will. Third, it prohibits some syntax likely to be defined in future versions of ECMAScript.

    Invoking strict mode

    Strict mode applies to entire scripts or to individual functions. It doesn’t apply to block statements enclosed in {} braces; attempting to apply it to such contexts does nothing. eval code, event handler attributes, strings passed to setTimeout, and the like are entire scripts, and invoking strict mode in them works as expected.

    Strict mode for scripts

    To invoke strict mode for an entire script, put the exact statement "use strict"; (or 'use strict';) before any other statements.

    // Whole-script strict mode syntax
    "use strict";
    var v = "Hi!  I'm a strict mode script!";

    This syntax has a trap that has already bitten a major site: it isn’t possible to blindly concatenate non-conflicting scripts. Consider concatenating a strict mode script with a non-strict mode script: the entire concatenation looks strict! The inverse is also true: non-strict plus strict looks non-strict. Concatenation of strict mode scripts with each other is fine, and concatenation of non-strict mode scripts is fine. Only crossing the streams by concatenating strict and non-strict scripts is problematic.

    Strict mode for functions

    Likewise, to invoke strict mode for a function, put the exact statement "use strict"; (or 'use strict';) in the function’s body before any other statements.

    function strict()
      // Function-level strict mode syntax
      'use strict';
      function nested() { return "And so am I!"; }
      return "Hi!  I'm a strict mode function!  " + nested();
    function notStrict() { return "I'm not strict."; }

    Changes in strict mode

    Strict mode changes both syntax and runtime behavior. Changes generally fall into these categories:

    • Converting mistakes into errors (as syntax errors or at runtime)
    • Simplifying how the particular variable for a given use of a name is computed
    • Simplifying eval and arguments
    • Making it easier to write “secure” JavaScript
    • Anticipating future ECMAScript evolution

    Converting mistakes into errors

    Strict mode changes some previously-accepted mistakes into errors. JavaScript was designed to be easy for novice developers, and sometimes it gives operations which should be errors non-error semantics. Sometimes this fixes the immediate problem, but sometimes this creates worse problems in the future. Strict mode treats these mistakes as errors so that they’re discovered and promptly fixed.

    First, strict mode makes it impossible to accidentally create global variables. In normal JavaScript, mistyping a variable in an assignment creates a new property on the global object and continues to “work” (although future failure is possible: likely, in modern JavaScript). Assignments which would accidentally create global variables instead throw errors in strict mode:

    "use strict";
    mistypedVaraible = 17; // throws a ReferenceError

    Second, strict mode makes assignments which would otherwise silently fail throw an exception. For example, NaN is a non-writable global variable. In normal code assigning to NaN does nothing; the developer receives no failure feedback. In strict mode assigning to NaN throws an exception. Any assignment that silently fails in normal code will throw errors in strict mode:

    "use strict";
    NaN = 42; // throws a TypeError
    var obj = { get x() { return 17; } };
    obj.x = 5; // throws a TypeError
    var fixed = {};
    fixed.newProp = "ohai"; // throws a TypeError

    Third, if you attempt to delete undeletable properties, strict mode throws errors (where before the attempt would simply have no effect):

    "use strict";
    delete Object.prototype; // throws a TypeError

    Fourth, strict mode requires that all properties named in an object literal be unique. Normal code may duplicate property names, with the last one determining the property’s value. But since only the last one does anything, the duplication is simply a vector for bugs, if the code is modified to change the property value other than by changing the last instance. Duplicate property names are a syntax error in strict mode:

    "use strict";
    var o = { p: 1, p: 2 }; // !!! syntax error

    Fifth, strict mode requires that function argument names be unique. In normal code the last duplicated argument hides previous identically-named arguments. Those previous arguments remain available through arguments[i], so they’re not completely inaccessible. Still, this hiding makes little sense and is probably undesirable (it might hide a typo, for example), so in strict mode duplicate argument names are a syntax error:

    function sum(a, a, c) // !!! syntax error
      "use strict";
      return a + b + c; // wrong if this code ran

    Sixth, strict mode forbids octal syntax. Octal syntax isn’t part of ECMAScript, but it’s supported in all browsers by prefixing the octal number with a zero: 0644 === 420 and "\045" === "%". Novice developers sometimes believe a leading zero prefix has no semantic meaning, so they use it as an alignment device — but this changes the number’s meaning! Octal syntax is rarely useful and can be mistakenly used, so strict mode makes octal a syntax error:

    "use strict";
    var sum = 015 + // !!! syntax error
              197 +

    Simplifying variable uses

    Strict mode simplifies how variable uses map to particular variable definitions in the code. Many compiler optimizations rely on the ability to say that this variable is stored in this location: this is critical to fully optimizing JavaScript code. JavaScript sometimes makes this basic mapping of name to variable definition in the code impossible to perform except at runtime. Strict mode removes most cases where this happens, so the compiler can better optimize strict mode code.

    First, strict mode prohibits with. The problem with with is that any name in it might map either to a property of the object passed to it, or to a variable in surrounding code, at runtime: it’s impossible to know which beforehand. Strict mode makes with a syntax error, so there’s no chance for a name in a with to refer to an unknown location at runtime:

    "use strict";
    var x = 17;
    with (obj) // !!! syntax error
      // If this weren't strict mode, would this be var x, or
      // would it instead be obj.x?  It's impossible in general
      // to say without running the code, so the name can't be
      // optimized.

    The simple alternative of assigning the object to a variable, then accessing the corresponding property on that variable, stands ready to replace with.

    Second, eval of strict mode code does not introduce new variables into the surrounding code. In normal code eval("var x;") introduces a variable x into the surrounding function or the global scope. This means that, in general, in a function containing a call to eval, every name not referring to an argument or local variable must be mapped to a particular definition at runtime (because that eval might have introduced a new variable that would hide the outer variable). In strict mode eval creates variables only for the code being evaluated, so eval can’t affect whether a name refers to an outer variable or some local variable:

    var x = 17;
    var evalX = eval("'use strict'; var x = 42; x");
    assert(x === 17);
    assert(evalX === 42);

    Relatedly, if the function eval is invoked by an expression of the form eval(...) in strict mode code, the code will be evaluated as strict mode code. The code may explicitly invoke strict mode, but it’s unnecessary to do so.

    function strict1(str)
      "use strict";
      return eval(str); // str will be treated as strict mode code
    function strict2(f, str)
      "use strict";
      return f(str); // not eval(...): str is strict iff it invokes strict mode
    function nonstrict(str)
      return eval(str); // str is strict iff it invokes strict mode
    strict1("'Strict mode code!'");
    strict1("'use strict'; 'Strict mode code!'");
    strict2(eval, "'Non-strict code.'");
    strict2(eval, "'use strict'; 'Strict mode code!'");
    nonstrict("'Non-strict code.'");
    nonstrict("'use strict'; 'Strict mode code!'");

    Third, strict mode forbids deleting plain names. Thus names in strict mode eval code behave identically to names in strict mode code not being evaluated as the result of eval. Using delete name in strict mode is a syntax error:

    "use strict";
    eval("var x; delete x;"); // !!! syntax error

    Making eval and arguments simpler

    Strict mode makes arguments and eval less bizarrely magical. Both involve a considerable amount of magical behavior in normal code: eval to add or remove bindings and to change binding values, and arguments by its indexed properties aliasing named arguments. Strict mode makes great strides toward treating eval and arguments as keywords, although full fixes will not come until a future edition of ECMAScript.

    First, the names eval and arguments can’t be bound or assigned in language syntax. All these attempts to do so are syntax errors:

    "use strict";
    eval = 17;
    var obj = { set p(arguments) { } };
    var eval;
    try { } catch (arguments) { }
    function x(eval) { }
    function arguments() { }
    var y = function eval() { };
    var f = new Function("arguments", "'use strict'; return 17;");

    Second, strict mode code doesn’t alias properties of arguments objects created within it. In normal code within a function whose first argument is arg, setting arg also sets arguments[0], and vice versa (unless no arguments were provided or arguments[0] is deleted). For strict mode functions, arguments objects store the original arguments when the function was invoked. The value of arguments[i] does not track the value of the corresponding named argument, nor does a named argument track the value in the corresponding arguments[i].

    function f(a)
      "use strict";
      a = 42;
      return [a, arguments[0]];
    var pair = f(17);
    assert(pair[0] === 42);
    assert(pair[1] === 17);

    Third, arguments.callee is no longer supported. In normal code arguments.callee refers to the enclosing function. This use case is weak: simply name the enclosing function! Moreover, arguments.callee substantially hinders optimizations like inlining functions, because it must be made possible to provide a reference to the un-inlined function if arguments.callee is accessed. For strict mode functions, arguments.callee is a non-deletable property which throws an error when set or retrieved:

    "use strict";
    var f = function() { return arguments.callee; };
    f(); // throws a TypeError

    “Securing” JavaScript

    Strict mode makes it easier to write “secure” JavaScript. Some websites now provide ways for users to write JavaScript which will be run by the website on behalf of other users. JavaScript in browsers can access the user’s private information, so such JavaScript must be partially transformed before it is run, to censor access to forbidden functionality. JavaScript’s flexibility makes it effectively impossible to do this without many runtime checks. Certain language functions are so pervasive that performing runtime checks has considerable performance cost. A few strict mode tweaks, plus requiring that user-submitted JavaScript be strict mode code and that it be invoked in a certain manner, substantially reduce the need for those runtime checks.

    First, the value passed as this to a function in strict mode isn’t boxed into an object. For a normal function, this is always an object: the provided object if called with an object-valued this; the value, boxed, if called with a Boolean, string, or number this; or the global object if called with an undefined or null this. (Use call, apply, or bind to specify a particular this.) Automatic boxing is a performance cost, but exposing the global object in browsers is a security hazard, because the global object provides access to functionality “secure” JavaScript environments must invariably. Thus for a strict mode function, the specified this is used unchanged:

    "use strict";
    function fun() { return this; }
    assert(fun() === undefined);
    assert( === 2);
    assert(fun.apply(null) === null);
    assert( === undefined);
    assert(fun.bind(true)() === true);

    (Tangentially, built-in methods also now won’t box this if it is null or undefined. [This change is independent of strict mode but is motivated by the same concern about exposing the global object.] Historically, passing null or undefined to a built-in method like Array.prototype.sort() would act as if the global object had been specified. Now passing either value as this to most built-in methods throws a TypeError. Booleans, numbers, and strings are still boxed by these methods: it’s only when these methods would otherwise act on the global object that they’ve been changed.)

    Second, in strict mode it’s no longer possible to “walk” the JavaScript stack via commonly-implemented extensions to ECMAScript. In normal code with these extensions, when a function fun is in the middle of being called, fun.caller is the function that most recently called fun, and fun.arguments is the arguments for that invocation of fun. Both extensions are problematic for “secure” JavaScript, because they allow “secured” code to access “privileged” functions and their (potentially unsecured) arguments. If fun is in strict mode, both fun.caller and fun.arguments are non-deletable properties which throw an error when set or retrieved:

    function restricted()
      "use strict";
      restricted.caller;    // throws a TypeError
      restricted.arguments; // throws a TypeError
    function privilegedInvoker()
      return restricted();

    Third, arguments for strict mode functions no longer provide access to the corresponding function call’s variables. In some old ECMAScript implementations arguments.caller was an object whose properties aliased variables in that function. This is a security hazard because it breaks the ability to hide privileged values via function abstraction; it also precludes most optimizations. For these reasons no recent browsers implement it. Yet because of its historical functionality, arguments.caller for a strict mode function is also a non-deletable property which throws an error when set or retrieved:

    "use strict";
    function fun(a, b)
      "use strict";
      var v = 12;
      return arguments.caller; // throws a TypeError
    fun(1, 2); // doesn't expose v (or a or b)

    Paving the way for future ECMAScript versions

    Future ECMAScript versions will likely introduce new syntax, and strict mode in ECMAScript 5 applies some restrictions to ease the transition. It will be easier to make some changes if the foundations of those changes are prohibited in strict mode.

    First, in strict mode a short list of identifiers become reserved keywords. These words are implements, interface, let, package, private, protected, public, static, and yield. In strict mode, then, you can’t name or use variables or arguments with these names. A Mozilla-specific caveat: if your code is JavaScript 1.7 or greater (you’re chrome code, or you’ve used the right <script type="">) and is strict mode code, let and yield have the functionality they’ve had since those keywords were first introduced. But strict mode code on the web, loaded with <script src=""> or <script>...</script>, won’t be able to use let/yield as identifiers.

    Second, strict mode prohibits function statements not at the top level of a script or function. In normal code in browsers, function statements are permitted “everywhere”. This is not part of ES5! It’s an extension with incompatible semantics in different browsers. Future ECMAScript editions hope to specify new semantics for function statements not at the top level of a script or function. Prohibiting such function statements in strict mode “clears the deck” for specification in a future ECMAScript release:

    "use strict";
    if (true)
      function f() { } // !!! syntax error
    for (var i = 0; i &lt; 5; i++)
      function f2() { } // !!! syntax error
    function baz() // kosher
      function eit() { } // also kosher

    This prohibition isn’t strict mode proper, because such function statements are an extension. But it is the recommendation of the ECMAScript committee, and browsers will implement it.

    Strict mode in browsers

    Firefox 4 is the first browser to fully implement strict mode. The Nitro engine found in many WebKit browsers isn’t far behind with nearly-complete strict mode support. Chrome has also started to implement strict mode. Internet Explorer and Opera haven’t started to implement strict mode; feel free to send those browser makers feedback requesting strict mode support.

    Browsers don’t reliably implement strict mode, so don’t blindly depend on it. Strict mode changes semantics. Relying on those changes will cause mistakes and errors in browsers which don’t implement strict mode. Exercise caution in using strict mode, and back up reliance on strict mode with feature tests that check whether relevant features of strict mode are implemented.

    To test out strict mode, download a Firefox nightly and start playing. Also consider its restrictions when writing new code and when updating existing code. (To be absolutely safe, however, it’s probably best to wait to use it in production until it’s shipped in browsers.)