28 ms·
NodeJS security cheat sheet
- eyelidlessness 5y agoPosted when? Recommending Promise chains is a security (and bug/defect) nightmare. I’m currently working in several codebases that do this and you can’t get a call stack to anything that matters. Good luck finding a vulnerability or bug with no trace of what actually happened. Edit: “posted when” because I don’t know if this is outdated advice, but async/await introduced after Promise standardization addresses the problem.
- Normal_gaussian 5y agoThe main points are 2 years old, with newer edits: https://github.com/OWASP/CheatSheetSeries/blame/master/cheatsheets/Nodejs_Security_Cheat_Sheet.md https://github.com/OWASP/CheatSheetSeries/blame/master/cheat... Catch-log-new error-rethrow or catch-annotate-rethrow is (unfortunately) an important part of using Promises that isn't widely taught. I've also seen some Promise replacements with better debugging (often call site carry through, so more like a stack trace) - though I like to keep it vanilla.
- eyelidlessness 5y ago> Catch-log-new error-rethrow or catch-annotate-rethrow is (unfortunately) an important part of using Promises that isn't widely taught And horribly unwieldy to have to do everywhere, causes code bloat, is easy to forget. > I've also seen some Promise replacements with better debugging (often call site carry through, so more like a stack trace) - though I like to keep it vanilla. I remembered Bluebird has call stack support so I looked into that yesterday. Unfortunately it doesn’t play well with sourcemaps so it’s barely an improvement. I really think this is all a lot of trouble for very little benefit when async/await is supported basically everywhere and doesn’t have these problems. It’s not just a huge ergonomic improvement, though it’s also that.
- bigiain 5y agoNodeJS "security". Recommendations: 1) Don't. Just don't. 2) See point 1, it's important. 3) Maybe transpile Rust into WASM instead? </snark>
- bigiain 5y agoMore reasonably... Most of these are fundamental server side web app best practice that we learnt decades ago and used Perl libraries that mitigated them back in the 90s. "Validate your inputs", "escape your outputs", "have good logging", "have brute force protection", "use anti CSRF tokens", "take care parsing http headers" - those are all bits of advice you could find in the comp.lang.perl.misc archives from the late '90s. None of them are NodeJS specific, they're all "inexperienced backend developer" specific bits of advice. Which is scary...
- cwilby 5y agoQuestion the requirements, they're almost always wrong. Question them even more if you think a smart person wrote them.
- bigiain 5y ago... especially if that smart person was you. Find someone smarter than the requirements writer to review them. Even if they only have time to do a quick skim over them, it'll help. (Yep. I've made that mistake often enough to believe that advice.)
- chakkepolja 5y agoMany people learn web development from short crash courses and half baked youtube videos these days. They are often often don't pay much attention to these. So many times I have seen people concatenate strings to do SQL than use prepared statements or whatever language analog its scary. For HN audience, It sure sounds very old knowledge but for some document intended as cheat sheet / checklist it has place.
- 5y ago
- junon 5y agoThis post is wildly outdated. I was scratching my head over their mention of callbacks, trying to figure out what they meant in modern JavaScript terms.
- arcturus17 5y agoCallbacks are still widely used in JavaScript. The "callback pyramid of doom" was horrible and we're all glad that it's sorted out through Promises and Async/Await, but functions as first-class language members remains one of the best features of JavaScript, and if a dev is not passing around functions somewhat frequently I would really question their credentials as a "modern" JS developer. Callbacks remain some of the best and most elegant solutions to a range of problems that are not at all uncommon.
- BeefWellington 5y agoIn practical terms Promises just moved callbacks into .then() instead of a function parameter and encouraged the use of pre-written functions instead of anonymous inline functions. It solves a lot of legibility problems. It was entirely possible to write nice-looking Javascript before Promises were a thing; people just didn't.
- Oras 5y agoI was looking at the code of bouncer and found it weird that the used middleware does not match the defined function [bouncer.blocked => bouncer.block] ``` bouncer.blocked = function (req, res, next, remaining) { res.send(429, "Too many requests have been made. Please wait " + remaining/1000 + " seconds."); }; // route to protect app.post("/login", bouncer.block, function(req, res) { if (LoginFailed){ } else { bouncer.reset( req ); } }); ``` So I went to check the library to understand why. The library hasn't been updated since 5 years! https://www.npmjs.com/package/express-bouncer https://www.npmjs.com/package/express-bouncer I'm not sure if these security measures are up to date.
- yesbabyyes 5y agoMaybe you're right in your conclusion, but for the wrong reasons. `bouncer.block` and `bouncer.blocked` are two different things. The first is the middleware, which tracks whether the user should be blocked. The second is an optionally defined custom error function, informing the user that they have indeed been blocked. Perhaps the library hasn't been updated simply because it's complete?
- gregoriol 5y agoAs always very good content from owasp. However, I'm a bit confused by the first one, "use flat Promise chains": it doesn't feel like a question about security, but more about code readability. While a good practice to use promises (and maybe async/await instead of then), it feels much like saying use switch instead of if/then/else because it's less prone to errors.
- lucideer 5y agoThe implication here seems to be that comprehensive error handling & logging improves security. Silently swallowing errors is a common issue in async code and that can be a major risk if those errors are indicative of security holes (or even active attack attempts). The author seems to believe flat chains make it easier / more likely that errors will be caught and handled. That's probably true, it does seem easier to insert error handling code with flat promises, but it's certainly not done automatically. Would be good if it was clearer on that point and to see more hard examples of actual error handling.
- dgb23 5y agoThere are also: https://nodejs.org/api/process.html#process_event_unhandledrejection https://nodejs.org/api/process.html#process_event_unhandledr... And for the browser: https://developer.mozilla.org/en-US/docs/Web/API/Window/unhandledrejection_event https://developer.mozilla.org/en-US/docs/Web/API/Window/unha... Not entirely sure of their utility though. But can be elegant or robust if applied correctly.
- capableweb 5y agoAlthough I think it's a weak argument, the argument they seem to make is that it's easier to screw up doing callbacks in a nested way when it comes to correct flow + error handling, as compared to a flat flow of promises to execute. At least that's what I understood from "Promises provide a higher assurance of capturing and handling errors" which seems to be the only argument in that snippet.
- joshxyz 5y agoi think custom error types (extended from Error) wrapped in try catch is a good alternative kn that.
- vinnymac 5y agoI wouldn’t recommend NPM audit. You’ll spend more time dealing with false positives, than fixing anything of significance. When everything is urgent, nothing is.
- pimterry 5y agoThere's some ongoing work to improve this, by reducing noise & false positives: https://github.com/npm/rfcs/pull/422 https://github.com/npm/rfcs/pull/422
- vinnymac 5y agoThis work is very exciting. Thanks for sending me the link, greatly appreciate it!
- dane-pgp 5y agoFiltering out a few false positives is easier than auditing every dependency from scratch by yourself, and probably less effort than explaining to your users why your site didn't include a fix for a known vulnerability. I take your point about "npm audit" being an annoying tool to use, though, and would recommend the package better-npm-audit in its place, which allows developers to ignore specific vulnerabilities by adding entries to a config file that can be committed to the repo. https://www.npmjs.com/package/better-npm-audit https://www.npmjs.com/package/better-npm-audit
- kilburn 5y agoI find the "Do not block the event loop" example terrible: const fs = require('fs'); fs.readFile('/file.txt', (err, data) => { // perform actions on file content fs.unlink('/file.txt', (err) => { if (err) throw err; }); }); This comes right after a section about "use flat promise chains" and is also vulnerable to leaving file.txt behind if the "perform actions" part throws. Much better example imho: const fs = require('fs/promises'); const data = await fs.readFile('/file.txt'); try { // Do something with the data } finally { await fs.unlink('/file.txt'); }
- siproprio 5y agoYes! Thank you! This reminded example reminded me why I hated working with node!
- bcoates 5y agoThis advice is not great! From the top: Flat promise chains aren't fully general (you'll need a lot of trivial helper functions to do anything other than sequence of single operations). This is fine because you shouldn't be using nontrivial .then()s outside of utility code. Alternate advice: always use async/await for asynchronous control flow. Request limits, toobusy, and several other pieces of advice assume you're throwing a single node process on the internet directly. Do not do this, you probably want at least an nginx or other battle-ready front end proxy, and probably want a CDN and/or load-balancer too. Configure these correctly to not send overlarge, weird, slowloris, etc., requests through to the node processes. The thing about express letting API attackers create exotic objects is genuinely scary, and if true makes me want to not use express anymore or at least install a middleware to drop requests that try it. Describing anti-XSS measures as 'escaping' is a little questionable, you should be using proper tools for generating machine-readable information, not string concatenation or (shudder) interpolation. Build a DOM, convert it to text, send it out unmodified. IP level rate limiting simply doesn't work, at least not in the trivial "just use bouncer" way described. It's unexplained what you could possibly use object property descriptors for to obtain security benefits. They are not, in general, a security perimeter. If attacker is running code in your context, attacker has won. uncaughtException is difficult to use correctly, error prone, and has little to offer in general. The default behavior does the right thing. uncaughtExceptionMonitor lets you do a little extra logging before crashing if you like and is less of a footgun. Much of the rest of the advice is generic web application security recommendations.
- polishdude20 5y agoWhy is up level rate limiting bad?
- bcoates 5y agoAttackers have a practically unlimited number of IPs to use if they want to do a brute force password attack.
- polishdude20 5y ago
- Aldipower 5y agoThey also suggest "Account lockout". > The most common protection against these attacks is to implement account lockout, which prevents any more login attempts for a period after a certain number of failed logins. Imho account lockout has a huge downside. It reveals the username to attackers, because only on correct usernames the account lockout hooks in. I just would keep it silent and throttle the requests down on any false attemp.
- SixDouble5321 5y agoLock out fake users too? Seems simple enough.
- Aldipower 5y agoHmm, sounds easy! :-D But isn't, you need to keep track of fake users somewhere, which is another attack vector for DoS.