Node.js Security🚀and Best Pratices 👨💻
Best Security tips and Best pratices to make your Nodejs Api More Secure and hack proof.
Compromised Database
Compromised database is dangerous. If any unauthorized user get access to such database can create serious damage. To prevent this we can do the following
- Strongly Encrypting passwords and password reset tokens with salt and hash
Options:
a. Bcrypt (recommended)
b. Crypto (Nodejs native Module)
Brute Force Attacks
A Brute Force Attack is the simplest method to gain access to a site or server . It tries various combinations of usernames and passwords again and again until it gets in. To prevent this in your node js API we can do following
- Use bcrypt to make login request slow
- Implement rate limiting with express-rate-limit
- Implement maximum login attempts
Cross Site Scripting (XSS) Attacks
XSS attacks enable attackers to inject client-side scripts into web pages viewed by other users. A cross-site scripting vulnerability may be used by attackers to bypass access controls such as the same-origin policy. To prevent this we can do following:
Denial Of Service (DOS) Attack
Denial Of Service attack is a cyber-attack in which the perpetrator seeks to make a machine or network resource unavailable to its intended users by temporarily or indefinitely disrupting services of a host connected to the Internet. This can be prevented by:
- Implementing rate limiting (by express-rate-limit)
- limiting body payload size
const express = require("express");
const app = express();/*
* restrict the req.body size to be less then 10mb
*/
app.use(express.bodyparser({ limit: '10mb'}));
3. Avoid 😈 regular expression (regular expression with take lot of computation)
NoSql query 💉
NoSQL Injection is security vulnerability that lets attackers take control of database queries through the unsafe use of user input. It can be used by an attacker to Expose unauthorized information. To prevent this we can take following precaution:
- Use mongoose for mongodb( because of schema type)
- Sanitize user input data
Some other Best Pratices and Suggestions
- Always use HTTPS for encrypting request and responses.
- Create random password 🔑 reset tokens with expire dates
- Deny access to JWT after password is changed
- Dont commit sensitive config data to git
- Dont send error details to client
- Prevent cross-site request forgery:
Cross-site request forgery, also known as one-click attack or session riding and abbreviated as CSRF or XSRF, is a type of malicious exploit of a website where unauthorized commands are transmitted from a user that the web application trusts. This can be prevented by csurf.
7. Do reauthentication before a high value action
8. Implement blacklist for untrusted jwt
9. Confirm user email after first creating account.
10. Keep user login with refresh token
11. Implement two factor authentation
12. Prevent parameter pollution causing uncaught exception
Referenced from master nodejs