Thursday, December 1, 2011

Node.JS Security - the good, bad and ugly

At the moment, dev world is full of rave about Node and server side JavaScript (databases like MongoDB and the likes). There hasn't been a better time for front-end and JS developers. On the first look - it appears great, promising and exciting.

On the down side, as with most upcoming technologies, there isn't enough security analysis, consideration and advisory to reference and understand gotchas with server side JS. Nothing wrong with that - it's functions, coolness and innovation that brings business and not security (history/economics is a testimony).

In this post, I will share my security view point as I see it. This could be an ever growing list and the kind of things you can achieve with server side JavaScript - there is no early end to this.

Let's start with the good things. Node inherently introduces a great security benefit over
traditional server side programming paradigms and that is "secure by default" (reminds me of my NetBSD days). As highlighted in white below, your create your web server - a bare bone types and not a full blown with bells and whistles like Apache.

And then chose and pick what you want. Like define what your doc root will have - unlike anything and everything in a traditional web doc root. Like highlighted in yellow below - that is what your web server will respond to for requests. Rest needs to be caught by a 404.

Summarizing - your web server isn't configured and capable more than what you want it to be unlike Apache, Tomcat or IIS. I recall countless instances of Tomcat compromises due to default admin and manager apps that come installed and running with default passwords. And IIS getting exploited with WebDAV buffer overflow when in reality the web app never really needed it in first place. Typically web servers sent a false sense of security where developers mostly considered them to be secure. And we all know, more features, bigger the attack surface. Bigger the attack surface more chances of things going wrong. And something that can go wrong will go wrong!

On the flip side - the bad parts. Node carries over the known dangerous JavaScript APIs like the eval that can be trivially exploited to do server side injection (that were earlier only client side exploits like XSS).

Let's look at a PoC exploit where app evaluates the input and returns  an output like below

Abusing eval on client side would result an XSS but on server-side it induces a server side injection alike SQL Injection as seen below where we inject an HTTP response.

 The screenshot below highlights execution of server side injection.

To best of my knowledge, this issue was first brought to notice in context of Node by Bryan Sullivan at BlackHat. Not a brand new exploit. We know eval is evil. What is worth note here is most developers wouldn't imagine this happening at the first go. From that perspective this exploit vector server side is novel.

What do I see ugly? The ugly parts are the ones that introduce new attack vectors. There should have been default protection built-in ideally. The event driven single threaded programming model is not what web developers are used to. Node is single threaded and a simple error can create a denial of service condition as highlighted in the screenshot below.

As highlighted, hitting submit crashes the node server.

Similar DoS condition would result when messing with global variables - intentionally or unintentionally. Above scenarios are quite likely considering JS developers are usually quite used to errors. I see thousands of live sites day in and out that have a number of errors showing up in Firebug console and running absolutely ok which will not be the case as you go server side.

Another  ugly part is that web developers are not quite used to service permissioning. Web developers had it outsourced to Apache/IIS, would now end up running their node services as root, that earlier ran as nobody.

A 1000 feet high apple to apple comparison between let's say PHP and Node tells me - it took a step back in security. At least, you would come to expect a sanitization/validation library for a new programming language, if not a fancy new auto-sanitization module like PHP Filter (aah yes - Filter isn't a complete auto sanitization in PHP but you get what I mean).

An honest look and I feel node isn't meant to be used as is.  With a strong framework, is how it should be used. There are many in the fray right now - Express probably is the most widely used. I haven't tried it yet but from what I see, security in node is a work in progress.

Being a Yahoo, how can I end without not mentioning Yahoo Cocktails. Haven't played around with it yet, but this is something I have super high hopes with. The engineers I met there are fabulous. Come Q1 2012 it would be there for all of us to play around. Yahoo is a great company, the best  I have worked for - no doubt I would love to see it scoring high.

Learning more and more of Node, I keep reminding myself "Node is powerful, and with power comes responsibility".


  1. Great article. We are actually writing a new enterprise app, and now the front-end team are suggesting using node. We have very big clients who always pen-test our current site and security is a big issue! We have actually had to get the team to slow down and consider the security aspects before rushing into this new architecture. I am spending a lot of time researching node from a security and performance/scaling perspective as this is the prime concern from a business angle. Your point about the JS error leading to DOS was a classic example of what we could end up with! The single threaded model has always worried me.

    Please do give us more updates on node.

  2. Thanks, Zahir.

    I have had these concerns coming from several folks I meet at conferences and communities.

    NodeJS as it is, is not the way to go from what I learn so far. It has to be handled by a framework which should also provide most desired security controls with minimum developer interference especially on things that developers did not expect in other development paradigms and things that were implicit.

    Did you experiment with Express? I would be looking into the security aspects of it soon. At the moment, it is Cocktails what I am playing around with.

    OVERALL - I would be very cautious for an enterprise app with the maturity of security features available on Node.

    If the business decision is hard and you go to use Node, here are some things I think would work but it isn't a complete list:

    1. Use a templating framework. I like Ctemplate. Mustache is a derivative of Ctemplate and available for Node. It autoencodes HTML context (not the JS and other contexts like Ctemplate) user input in templates to protect against XSS primarily

    2. Hack the HTTP module of Node and auto some filtering there if you could via C module. Esp for SQLi and related input validation issues

    3. Use a framework that handles Node errors to avoid DoS

    4. CODE DEFENSIVELY. This is the best bet. Like audit usage of eval and the likes.

    5. This is not a Node specific issue but watch out for DOM XSS. It is on the rise everyday. Again - code defensively. Avoid document.write and innerHTML instead use innerText or filter user input. Encoding won't save always though due to browser decoding which can again trigger DOM XSS.

    I will publish more things along the way. Share some my way if you have any recommendations.

    Good luck!

  3. I'm using Node a lot, and I have never used Eval in my code. It seems the whole point here is: do not use eval()! Beyond that, is the security really that bad? If you setup your server with a firewall and you're not a completely ignorant software engineer, it seems your server should be pretty robust.

  4. Hi Brian - Thanks for sharing your opinion.

    I think it is much much more than eval. Today I wrote 3 new posts on exactly that.

    #1 Global Namespace Pollution

    #2 with is evil

    #3 switch is evil

    #1 is something that non JS developers aren't used to. #2 and #3 were probably not that serious in the context of client side JS with Node they are really dangerous.

    I will be posting more stuff soon. BTW there are also eval cousins like setInterval that are equally dangerous. There is lot more that I worry about on Node.

    Do share if you come across something. This is an active area of research.

    1. theese are the *basics* of js gotchas and good practices

    2. do you have an email address?

    3. please send your email to if you don't mind.

  5. Any webserver can be insecure if you code like a dufus.

    1. ++++
      Anyone who uses with or eval is an idiot. The only correct eval() use-case is superseded in Node by the VM module.
      Switch isn't terrible if you understand how to program.

  6. Please do some research into Node.js. Counterpoints:

    XSS - This is true of ANY serverside technology. The key here is to escape inputs. Templating systems like express.js handle this for you. If you don't escape input you will see this in ANY serverside stack, java, php, etc.

    Crashing - All you need is a global exception handler or to escape input and you are good to go.

    1. XSS:

      Are you sure express.js can defend against XSS in contexts other than HTML? It does not.

      i did not find any templating system in Node that does context sensitive output escaping. HTML escaping is simple. And that's what Mu and other engines in Node achieve.

      What we need is something like Google Ctemplate

      We did a hack to make it work on Node. So it isn't that difficult. We might OS it after some fine tuning down the line. As of now, it's just a hack

      You said it. "All you need" - why should I need to do that. It's got to be the default config. History is full of instances where systems that are secure by default are more resilient than ones that have opt-in security. Worse, this is a break down of paradigm for traditional server side programmers.

    2. XSS is *only* an HTML problem. HTML allows for JavaScript execution inline via script tags and event attributes. Injecting JS into a file served up with any non-HTML & non-JS mimetype is not XSS, as it can't be made to execute without user consent.

      NodeJS is a runtime and an API. There is no reason to bundle a bunch of crap like templating into Node. If you absolutely must use node core for this, use sprintf.

      Complaining that Node *allows* you to be a fool when programming is like complaining that your operating system doesn't write your code for you. You are a developer, its your JOB to understand the things required to be good at what you do. No amount of babysitting will fix that.

    3. Crashing: Do not use global exception handler. Use forever or similar tool. When unhandled exception happens application is in undetermined state. If restarting service does not solve anything there is error outside of node script (database etc)

    4. @\0/ bish \0/ - Node isnt just used as a webserver hence no need for that "default config". Besides if u plan to use node.js as a webserver, there are tonnes of modules out there.

    5. "XSS is *only* an HTML problem. HTML allows for JavaScript execution inline via script tags and event attributes. Injecting JS into a file served up with any non-HTML & non-JS mimetype is not XSS, as it can't be made to execute without user consent."

      Incorrect. CSS is surprisingly powerful. Attacks may also be inserted in html attributes, json, url references, practically anywhere including targeting the DOM parser itself.

      It all depends on the attack surface. Just because you're coding a reset server which runs on server side javascript and only outputs json, for example, doesn't mean it's safe against injection.

  7. I visited your blog for the first time and just been your fan. Keep posting as I am gonna come to read it everyday.

  8. @washington security systems - thanks for the appreciation. This kind of spurs me to write more often. Another one should be coming soon.

  9. You can leverage a lot of the security issues you mentionned by adding
    'use strict'
    at the top of every js files of your project like you would add <?php for a PHP file. Basically, strict mode prevents a lot of common JS mistakes and might even improve performacnes in some situations. Part of the things it prevents :
    - with keyword: it is disabled in strict mode and throws an exception if you try to use it
    - global namespace pollution: you can't use a variable that has not been declared using var first

    It also add a lot of exceptions where before JS code was silently doing nothing. If you write, let's say "delete Object.prototype", withotu strict mode, it was doing nothing (it would be disastrous to remove this prototype right? so it was impossible, but this line was also not doing anything... now you get a nice TypeError if you try this).

    If you want more documentation on this :

    To make it shorter : use strict mode. That's a HUGE benefit. There was some talk about activating it by default on NodeJS but for some reason it has not been done. So you have to add it as the first line of code in every file. That's a shame but still it leverage a lot of the language biggest issues.

    I also want to tell that 'use strict'; also works in browsers. If you want to write clean code, you can. Still, on browser side, since there are old broken browsers, you should not rely on the nice new exceptions for your code to work properly and still tests things out before.

  10. I also forgot to tell one important thing. You don't run NodeJS as root. That's a bad idea. You just don't. Then you will ask me "But how do I listen on port 80?". That's a good one. User land softwares can't listen on ports numbered lower than 1024. So what? It's easy as pie. You just add a nat rule (on Linux using ipnat) to forward port 80 on your internal port xxxx (eg 8000). That would look like:
    sudo iptables -t nat -A PREROUTING -p tcp --dport 80 -j REDIRECT --to-ports 8000

    Then if it works as intended, save the change in conf:
    sudo service iptables save
    sudo chkconfig iptables on

    Hope this might help people here address their biggest security issues with NodeJS. I believe there is a lot of good practices to got used to but it will make a better web in the end. I believe NodeJS is a piece of technology that as a great future. Still needs some refining but still... It looks very very promising.

    1. You stole my words. Really.
      But you forgot to say, another common practice is to have
      a reverse-proxy that listens to 80, then drops privileges.

      Moreover, you can drop privileges with Node by calling
      process.setuid(...), something you can't
      normally do with other languages without native extensions.

  11. The whole point of your post should be.. don't use Node.js, if you're an amateur. It's clear that you should use STRICT ECMAScript with Node.js. Don't generalize. If you are a professional, you know where weak points of ECMAScript are. Don't directly interpret input, don't use global variables, unless caching or immediate memory-databases are the actual case.

    The most important is: don't use Node.js, if you're an ECMAScript amateur. You'll fuck it up.

  12. Yet another blog post warning about eval(), this is just what the world needed. People have been warning about eval() since before JavaScript's inception; Perl for example.

  13. I was gonna give this post +1, but I was rickroll'd after seeing the eval code..

  14. Your toy it's so beautiful, I like it vey much, I also bought one at cheap prada handbags
    , If you want one too. can visit this address, The backpacks are beautiful at there. I think you will be love it too.

  15. Your toy it's so beautiful, I like it vey much, I also bought one at hermes handbags online
    , If you want one too. can visit this address, The backpacks are beautiful at there. I think you will be love it too.

  16. I don't understand why anyone would eval() the contents of any variable that was sent from a form (or URL or any other susceptible location)? Am I reading the code wrong? I'm new to server-side JS using Node and I'm trying to understand some of the security aspects I need to consider.

    1. You are right. This isn't a good example. And some people hated it. I don't blame them. Quite honestly, in my experience I have seen worst (ab)uses of 'eval'

      To your question, the whole point is - use 'eval' with extreme caution on the server side.

    2. "To your question, the whole point is - don't use 'eval' on the server side" - FTFY

  17. You are comparing apples and oranges. You are comparing using node to the benefits fully featured application framework. If you wanted to comare apples to apples you'd compare node to a Java app opening up a socket to listen on a port (no Tomcat, Spring, JBoss etc) which has all of the same problems listed here (some are easier some are harder)

    1. +1 - I totally agree that it's not a fair comparison.

      I would add that IMHO it's pretty well known that using node.js to write a web server is not really a smart move. I'm aware the article is old, however it should be made clear that if you want to provide a webserver then use the correct tools. Personally I like node.js for Websockets or other types of custom communications. I wouldn't choose to use it for a webserver, no matter what the form. If your using it for web services, then I believe others have posted comments about appropriate modules to use for this.

  18. Check out:

  19. Given PHP has eval and even most other languages have equivalents I completely fail to see what you mean. SQL injections are the same. SANITIZE INPUTS. Doesn't even matter if there's an eval or not.

    Saying JavaScript is the bad part of Node basically means the Node engineers did a perfect job. They didn't design Javascript, that was other people.

    The spartanism of node by default is what makes it so much more secure. Using a heavy framework will make you lose understanding and simplicity and replace it for the usual mess.

    This isn't just about "javascript on the client side". Javascript being expressive/strong enough to be confusing is the only security argument against it. Node itself is small and has so far been very secure.

    An operational details like not running as root can also not be blamed upon Node itself. Apache can be run as root just as easily.

    Post finds no attachment with me.

  20. I find it highly hillarious that JS developers think having a complete conceptual map of their JS code shitfest means it's secure. How many js parsers have you implemented in a browser? None I'm sure. If you don't understand your platform, you don't understand shit. Ditch this garbage and learn to program in a real language with a real platform if you want to write backend code. Coding defensively only gives you a false sense of security.

    1. Let me guess, javascript is for script kiddies. 'Real programmers use butterflies'. Rabble rabble rabble, hurr durr.

      What you're really trying to say is, you know very little about Javascript.

      How many of your 'real platforms' have been able to pass the C10k test. IIS, with a async add-on that's mimics Node? Apache with a similar async addon? How secure are those secondary plug-in branches of development that will only be adopted in exceptional use cases versus Node's mainline async development branch.

      Or, are you one of those idealists who still refuses to believe that JSP is anything more than a deprecated language in the web-developer domain.

      The only inherent security flaw of Node is using eval on code that gets passed back to the server. Eval just converts string text to code the same way SQL does and -- as a result -- suffers from the same inherent security flaws. It's well-known that eval should be avoided.

      Note: Only newbs and idiots use eval and it takes a special kind of idiot to take raw input from the client and eval it on the server.

  21. Best Security Services and security consultants for your business protection and domestic security. Morpheus security company provides efficient, cost effective and reliable security Service 24/7.

    1. Haha, because internet security starts with a good foundation of housekeeping, garbage disposal, and janitorial services.

      I think you should invest in some resources in hiring more intelligent web spammers.

  22. Morpheus Security | Morpheus Security Services in Delhi
    The wide range of Morpheus Security services offered by us includes guarding Morpheus Security Services in Delhi, Guard Services, Security Guards Company, Security Guard Services in India and Indian Security Guards.

  23. This comment has been removed by the author.

  24. The issues with "eval" is more related to bad programming practices than to bad programming language.

  25. So what you're REALLY trying to say is Node should use more regular expressions /s.

    Your main point that 'eval is bad' is common knowledge. Pretty low-hanging fruit if you ask me.

    This post title should read. "Node.js security = bad; Yahoo Cocktails = good: Because I said so".

    Try to consider that when you're writing for an audience of developers -- not the typical luddite -- using FUD to market a new product just makes you look disingenuous. Plus TechNet already dominates the market on FUD.

  26. Morpheus security services offers security services in delhi, best security agencies in Delhi/NCR. Security we provide a comprehensive spectrum of manned security services and security Guard Solutions.

  27. Security Services in Delhi | Best Security Service in Delhi
    Morpheus security services offers best security services in delhi, best security agencies in Delhi/NCR. Security we provide a comprehensive spectrum of manned security services and security Guard Solutions.

  28. I have a strong background in writing backend software and totally appreciate node.js. ES5 has it's flaws, yes. But there's ES6 which fixes a lot. Regarding speed: the V8 Compiler used in node.js lately whiped out pretty much every other dynamic language implementation and slowly reaches performance areas where only Java or C++ are present. Async is so important these days and node.js makes it dead simple, the callback hell can be solved by using promises (ES6 even supports yield for coroutines).

    @"real" programmers: Alright, you know C and Java, so you think you know software engineering, right ? ES is much more complex than Java or C together. It is far more expressive and has much higher level abstractions. I can only take you guys seriously if you would have 5+ years experience with Haskell/similar. Beyond that all imperative languages are kind of equal, but I would never write again network code in Java or C, it's just a mess, and C is far more insecure than node.js will ever be: C has pointers, yes, when writing drivers they are useful, but totally useless in application code.

    A real programmer chooses the tool which fits best, and if I can write productive and safe software 10x times faster than you, than obviously you choose the wrong tool ;)

  29. Morpheus is a Private Security Guards Service provider in India. If you imagine about how to get Security services in Delhi? Then contact us  or come to our online website. Morpheus Security is the famous name in the security fields. We provide you fully trained security guards and gunmen, bouncer in anytime and anywhere for only your security purpose.

  30. The wide range of Morpheus Security services offered by us includes guarding Morpheus Security Services in Delhi, Security Services in Delhi.

  31. Event Security Services London is the best firm providing the well trained Professional Security Guard for Personal Security.

  32. Protection Concepts provide you with customized solutions designed for your specific needs, monitor home security systems and commercial security systems,requirements and budget AND remember, our base monitoring starting at just $14.95 per month .
    Commercial Security

  33. Security contractor installs and helps monitor home security systems and commercial security systems with monitoring starting at just $14.95 Protection Concepts ,Atlanta security contractor, Atlanta Security provider.
    Atlanta Home Security Systems

  34. Protection Concepts provide you with customized solutions designed for your specific needs, monitor home security systems and commercial security systems,requirements and budget AND remember, our base monitoring starting at just $14.95 per month .
    Commercial Security

  35. Interactive home security systems from Protection Concepts based in Marietta and serving Atlanta, Georgia. Monitoring starts at $14.95 a month.

    Atlanta Security provider

  36. Protection Concepts began in 1998 with one simple principle…To offer excellent customer service, quality equipment and monitoring all at an affordable price while conducting business with honesty and integrity.

    Atlanta security contractor

  37. Commercial video surveillance systems from Protection Concepts based in Marietta, serving the Atlanta area. Monitoring starts at $14.95 a month.
    security systems

  38. Lloyd Security Offers innovative, affordable solutions that deliver greater safety, awareness, control, convenience, and efficiency inside the home and wherever you go.
    Minnesota commercial security

  39. Minneapolis-based security contractor Lloyd Security works with security systems of your choosing including Residential and Commercial Security.
    Minnesota contracted surveillance

  40. Replacing batteries in smoke and carbon monoxide detectors is a simple task to provide protection for your family’s security. If you need help with a more sophisticated fire alarm system, give us a call, Lloyd Security can help provide the additional security you want for your home and family.
    Minneapolis 612.874.9295 | St.paul 651.646.0131 | Toll Free 800.330.0911
    Commercial Security Options

  41. Protection Concepts provide you with customized solutions designed for your specific needs, monitor home security systems and commercial security systems, requirements and budget AND remember, our base monitoring starting at just $14.95 per month.
    Personal Emergency Response System (PERS)

  42. Very happy with my security system Lloyd Security was great to work with. They provided a reasonable quote, installed the system within a few days and immediately I could sleep better. Everybody has been great to work with especially Ben the installer, her was very professional, knowledgeable and was very patient showing me how to use my system. I would highly recommend.
    Home security systems MN

  43. top home security systems
    Great blog post! I don’t understand how long it will require me to obtain through all of them!

  44. This is a nice and informative, containing all information and also has a great impact on the new technology. web development company pakistan

  45. The main idea of Node.js, development is use of non-blocking and event-driven I/O to remain insubstantial and efficient in the face of data-intensive real-time applications which run across distributed devices.

  46. Nice blog...Morpheus security in uttrakhand are the best security service provider in uttrakhand we have ensured to leave no stone unturned to provide world-class safety and security support. Our security guard services in Uttarakhand provides a whole host of top security services.

  47. This is very essential blog; it helped me a lot whatever you have provided.

    adt security reviews

  48. Nice blog...Mobitsolutions in USA is the best security service provider in USA. We have ensured to our clients to provide them, excellent safety and Security Solutions.

    Work from home theory is fast gaining popularity because of the freedom and flexibility that comes with it. Since one is not bound by fixed working hours, they can schedule their work at the time when they feel most productive and convenient to them. Women & Men benefit a lot from this concept of work since they can balance their home and work perfectly. People mostly find that in this situation, their productivity is higher and stress levels lower. Those who like isolation and a tranquil work environment also tend to prefer this way of working. Today, with the kind of communication networks available, millions of people worldwide are considering this option.

    Women & Men who want to be independent but cannot afford to leave their responsibilities at home aside will benefit a lot from this concept of work. It makes it easier to maintain a healthy balance between home and work. The family doesn't get neglected and you can get your work done too. You can thus effectively juggle home responsibilities with your career. Working from home is definitely a viable option but it also needs a lot of hard work and discipline. You have to make a time schedule for yourself and stick to it. There will be a time frame of course for any job you take up and you have to fulfill that project within that time frame.

    There are many things that can be done working from home. A few of them is listed below that will give you a general idea about the benefits of this concept.

    This is the most common and highly preferred job that Women & Men like doing. Since in today's competitive world both the parents have to work they need a secure place to leave behind their children who will take care of them and parents can also relax without being worried all the time. In this job you don't require any degree or qualifications. You only have to know how to take care of children. Parents are happy to pay handsome salary and you can also earn a lot without putting too much of an effort.

    For those who have a garden or an open space at your disposal and are also interested in gardening can go for this method of earning money. If given proper time and efforts nursery business can flourish very well and you will earn handsomely. But just as all jobs establishing it will be a bit difficult but the end results are outstanding.

    Freelance can be in different wings. Either you can be a freelance reporter or a freelance photographer. You can also do designing or be in the advertising field doing project on your own. Being independent and working independently will depend on your field of work and the availability of its worth in the market. If you like doing jewellery designing you can do that at home totally independently. You can also work on freelancing as a marketing executive working from home. Wanna know more, email us on and we will send you information on how you can actually work as a marketing freelancer.

    Internet related work
    This is a very vast field and here sky is the limit. All you need is a computer and Internet facility. Whatever field you are into work at home is perfect match in the software field. You can match your time according to your convenience and complete whatever projects you get. To learn more about how to work from home, contact us today on workfromhome.otr@gmail.comand our team will get you started on some excellent work from home projects.

    Diet food
    Since now a days Women & Men are more conscious of the food that they eat hence they prefer to have homemade low cal food and if you can start supplying low cal food to various offices then it will be a very good source of income and not too much of efforts. You can hire a few ladies who will help you out and this can be a good business.

    Thus think over this concept and go ahead.

  50. stas são dicas de investimento muito úteis. Vou recomendar aos meus amigos para ler este blog. Jogos de carros

  51. This is my very first time that I am visiting here and I’m truly pleasurable to see everything at one place.
    surveillance camera pole

  52. Superb posts with lots of information!!! This is really the most miraculous blog site dude….
    security camera system for business

  53. A web development company can offer your business not only web development services but, also a range of other services which can take your company to the very top. However, most importantly, these companies can offer you with a team of highly skilled web designers who can design the very best page for your company.

  54. Invictus Security Services is the best security company providing the well trained Professional Security Guard for Personal Security & Event Security.

  55. This post refers effective information about internet marketing. I have also a website where included online marketing tips. Have something to sell, a cause to promote, a service to provide? To know more information, you can visit the links……
    email marketing

  56. You have really selected the suitable topic; this is one of my favorite blogs. the owner

  57. This is very essential blog about Security Services it helped me a lot whatever you have provided. This is very interpreting post Thanks for sharing.