OWasp NodeJS Security Cheat Sheet Flashcards
Real time AJAX security evaluation for learners based on content at https://cheatsheetseries.owasp.org/cheatsheets/Nodejs_Security_Cheat_Sheet
Use Flat Promise Chains
What problem does excessive nesting in asynchronous callbacks cause?
It leads to a “Pyramid of Doom” or “Callback Hell,” making code harder to maintain and track errors or results.
Use Flat Promise Chains
How do Promises help avoid “Callback Hell”?
Promises provide a top-down execution flow and automatically skip to the first .catch function when an error occurs, simplifying error handling.
Use Flat Promise Chains
What approach should be used to further reduce complexity in Promises?
Use flat Promise chains to maintain readability and avoid nested structures.
Use Flat Promise Chains
How can nested callbacks be rewritten using a flat Promise chain?
Example:
```javascript
func1(“input1”)
.then(result => func2(“input2”))
.then(result => func3(“input3”))
.then(result => func4(“input4”))
.catch(error => {
// error handling
});
~~~
Use Flat Promise Chains
How can nested callbacks be avoided using async/await?
Example:
```javascript
(async () => {
try {
const res1 = await func1(“input1”);
const res2 = await func2(“input2”);
const res3 = await func3(“input3”);
const res4 = await func4(“input4”);
} catch (err) {
// error handling
}
})();
~~~
Best Practices
What are best practices for using Promises?
Use Promises for asynchronous code instead of deeply nested callbacks.
Convert non-Promise-based modules using Promise.promisifyAll() if needed.
Use async/await for further simplification and readability.
Set Request Size Limits
Why should request size limits be set?
Without limits, attackers can send large request bodies, exhausting server memory or disk space.
Set Request Size Limits
How can request size limits be set for all requests?
Using the raw-body package in Express with a specified limit:
```javascript
getRawBody(req, { length: req.headers[‘content-length’], limit: ‘1kb’ }, callback);
~~~
Set Request Size Limits
Why should limits differ by content type?
JSON payloads are blocking operations and riskier than multipart inputs; setting appropriate limits per type prevents performance issues.
Set Request Size Limits
How can Express middleware enforce content-specific limits?
Example:
```javascript
app.use(express.urlencoded({ extended: true, limit: ‘1kb’ }));
app.use(express.json({ limit: ‘1kb’ }));
~~~
Set Request Size Limits
How should Content-Type headers be handled to prevent bypassing limits?
Validate request data against the stated Content-Type header and prioritize checking large requests or specific types.
Do Not Block the Event Loop
What architecture does Node.js use?
A single-thread, non-blocking, event-driven architecture.
Do Not Block the Event Loop
What happens during CPU-intensive JavaScript operations?
The event loop becomes blocked, waiting for the operation to finish.
Do Not Block the Event Loop
Why are asynchronous operations important in Node.js?
They allow the main application to remain unblocked, improving performance.
Avoiding Race Conditions
What issue arises when synchronous code depends on asynchronous callbacks?
Race conditions, where operations may execute out of order, leading to potential errors or security issues.
Avoiding Race Conditions
How can race conditions be avoided?
Ensure dependent operations are written within the same callback or non-blocking function:
```javascript
fs.readFile(‘/file.txt’, (err, data) => {
// perform actions
fs.unlink(‘/file.txt’, (err) => { if (err) throw err; });
});
~~~
Input Validation
Why is input validation essential for application security?
To prevent various attacks like SQL Injection, XSS, Command Injection, Denial of Service, Directory Traversal, and more.
Input Validation
What is the best input validation technique?
Use an allow-list of accepted inputs.
Input Validation
What should be done if an allow-list cannot be used?
Validate inputs against expected schemes and escape dangerous inputs.
Input Validation
Which Node.js modules simplify input validation?
validator and express-mongo-sanitize.
Input Validation
Why is JavaScript parsing of URLs a challenge for input validation?
The dynamic nature of JavaScript allows query strings to take on various forms, which can lead to inconsistencies.
Output Escaping
Why is output escaping important?
To prevent Cross-Site Scripting (XSS) attacks by sanitizing HTML and JavaScript content shown to users.
Output Escaping
Which libraries can be used for output escaping in Node.js?
escape-html and node-esapi.
Activity Logging
Why is logging application activity a good practice?
It aids in debugging, enhances security through incident response, and supports IDS/IPS tools.
Activity Logging
Which Node.js modules can be used for logging?
Winston, Bunyan, and Pino.
Activity Logging
How can you log activities to both console and a file?
Example:
```javascript
const logger = new (Winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: ‘application.log’ })
],
level: ‘verbose’
});
~~~
Activity Logging
How can errors and general logs be separated?
Configure different transports to save errors in one log file and general logs in another.
Monitor the Event Loop
What type of attack can overwhelm the event loop?
A Denial of Service (DoS) attack, caused by heavy network traffic.
Monitor the Event Loop
How does the toobusy-js module help during heavy traffic?
It monitors response times and sends a 503 ‘Server Too Busy’ message when the server is under load.
Example of toobusy-js usage in Express:
```javascript
app.use(function(req, res, next) {
if (toobusy()) {
res.status(503).send(‘Server Too Busy’);
} else {
next();
}
});
~~~
Take Precautions Against Brute-Forcing
Why are brute-forcing attacks common?
Attackers use brute-forcing to guess passwords or other sensitive information, especially on login pages.
Take Precautions Against Brute-Forcing
Which Node.js modules help defend against brute-forcing?
express-bouncer, express-brute, and rate-limiter.
Take Precautions Against Brute-Forcing
How does a CAPTCHA help against brute-forcing?
It requires solving a challenge before proceeding, slowing down automated attacks.
Example:
```javascript
const svgCaptcha = require(‘svg-captcha’);
app.get(‘/captcha’, function (req, res) {
const captcha = svgCaptcha.create();
req.session.captcha = captcha.text;
res.type(‘svg’);
res.status(200).send(captcha.data);
});
~~~
Take Precautions Against Brute-Forcing
What is an account lockout?
A mechanism that locks an account after multiple failed login attempts, preventing further brute-force attempts.
Use Anti-CSRF Tokens
What is Cross-Site Request Forgery (CSRF)?
An attack where an authenticated user unknowingly performs actions on behalf of an attacker.
Use Anti-CSRF Tokens
Why is csurf no longer recommended?
It has a known security vulnerability and has been deprecated. Consider alternative CSRF protection packages.
Remove Unnecessary Routes
Why should unused API routes be disabled?
They increase the application’s attack surface and may lead to issues like information leakage or command execution.
Remove Unnecessary Routes
Which frameworks automatically generate routes that may need removal?
Frameworks like Sails and Feathers.
Prevent HTTP Parameter Pollution (HPP)
What is HTTP Parameter Pollution?
An attack where multiple HTTP parameters with the same name are sent, causing unpredictable application behavior.
Prevent HTTP Parameter Pollution (HPP)
How can HPP be mitigated in Express?
Use the hpp module to ensure only the last parameter value is processed:
Example:
```javascript
const hpp = require(‘hpp’);
app.use(hpp());
~~~
Only Return What Is Necessary
Why should applications limit the data returned in responses?
To avoid personal information disclosure, such as returning sensitive fields like email addresses or social security numbers.
Use Object Property Descriptors
What are the three hidden attributes of object properties?
writable: Determines if the property value can be changed.
enumerable: Specifies if the property can be used in for-loops.
configurable: Indicates if the property can be deleted.
Use Object Property Descriptors
How can you define object property attributes?
Use Object.defineProperty():
```javascript
Object.defineProperty(o, “a”, {
writable: true,
enumerable: true,
configurable: true,
value: “A”
});
~~~
Use Object Property Descriptors
What does Object.preventExtensions() do?
It prevents new properties from being added to an object.
Use Access Control Lists (ACL)
How can ACLs enforce authorization in Node.js applications?
By defining roles and assigning users to those roles using modules like acl.
Error and Exception Handling
How should uncaughtException events be handled?
Bind to the uncaughtException event to log error details, clean up resources, and terminate the process:
```javascript
process.on(“uncaughtException”, function(err) {
// cleanup and logging
process.exit(); // avoid unknown state
});
~~~
Error and Exception Handling
What happens if errors are unhandled in an EventEmitter?
They become uncaught exceptions, potentially crashing the application. Always attach listeners for error events:
```javascript
emitter.on(‘error’, function(err) {
// Handle error
});
~~~
Server Security
How should errors in asynchronous calls be handled?
Always propagate the error as the first argument to callbacks or explicitly handle it in express routes.
Server Security
How can you improve session cookie security?
Set the following flags:
httpOnly: Prevents client-side JavaScript access, mitigating XSS attacks.
secure: Ensures cookies are sent only over HTTPS.
SameSite: Protects against CSRF attacks by restricting cross-site requests.
Server Security
Example of setting cookie flags:
```javascript
const session = require(‘express-session’);
app.use(session({
secret: ‘your-secret-key’,
name: ‘cookieName’,
cookie: { secure: true, httpOnly: true, path: ‘/user’, sameSite: true }
}));
~~~
Use Appropriate Security Headers
What package helps set HTTP security headers in Express?
The helmet package.
Example usage:
```javascript
app.use(helmet());
~~~
Use Appropriate Security Headers
What does the Strict-Transport-Security header do?
Ensures browsers access the application only over HTTPS.
Example usage:
```javascript
app.use(helmet.hsts({ maxAge: 123456, includeSubDomains: false }));
~~~
Use Appropriate Security Headers
How does X-Frame-Options protect against Clickjacking attacks?
It restricts whether a page can be loaded in <frame> or <iframe> elements.</frame>
Example usage:
```javascript
app.use(helmet.frameguard());
~~~
Use Appropriate Security Headers
Why is X-XSS-Protection discouraged?
It has been deprecated due to potential security issues.
Example usage:
```javascript
app.use(helmet.xssFilter()); // Sets “X-XSS-Protection: 0”
~~~
Use Appropriate Security Headers
What is the role of Content-Security-Policy (CSP)?
Reduces XSS and Clickjacking risks by controlling allowed content.
Example usage:
```javascript
app.use(helmet.contentSecurityPolicy({
directives: {
defaultSrc: [“‘self’”],
scriptSrc: [“‘self’”],
frameAncestors: [“‘none’”],
imgSrc: [“‘self’”, “http://imgexample.com”],
}
}));
~~~
Use Appropriate Security Headers
How does X-Content-Type-Options improve security?
Prevents browsers from MIME type sniffing.
Example usage:
```javascript
app.use(helmet.noSniff());
~~~
Use Appropriate Security Headers
When should Cache-Control headers be used?
To prevent caching of sensitive information.
Example usage:
```javascript
app.use(nocache());
~~~
Use Appropriate Security Headers
What does X-Powered-By reveal, and how can it be hidden?
It discloses server technology.
Example usage:
```javascript
app.use(helmet.hidePoweredBy());
~~~
Platform Security
How can you ensure your third-party packages are up-to-date?
Use tools like npm audit, OWASP Dependency-Check, or Retire.js to identify vulnerabilities.
Example usage:
```bash
npm audit
npm audit fix
~~~
Avoid Dangerous Functions
Why is eval() dangerous?
It executes strings as JavaScript, enabling remote code execution when combined with user input.
Avoid Dangerous Functions
What risks do child_process.exec functions present?
They can execute arbitrary commands, leading to command injection vulnerabilities.
Avoid Dangerous Functions
How should risky modules like fs and vm be used?
With sanitized inputs and, in the case of vm, within a sandboxed context.
Stay Away from Evil Regexes
What is a ReDoS attack?
Regular Expression Denial of Service (ReDoS) exploits slow Regex implementations to make applications hang with crafted input.
Stay Away from Evil Regexes
What are ‘evil’ regexes?
Regexes that group repetition and alternation with overlapping, leading to extreme slowdowns on specific input.
Stay Away from Evil Regexes
How can you test if a Regex is vulnerable?
Use tools like vuln-regex-detector.
Example: The regex ^(([a-z])+.)+A-Z+$ may hang on long input strings like aaaa…aaaaAaaaaa…aaaa.
Run Security Linters
Why are linting tools essential in JavaScript?
They ensure secure code by flagging patterns with potential risks in the development lifecycle.
Run Security Linters
Which tools are commonly used for JavaScript linting?
ESLint and JSHint.
Run Security Linters
How can you improve linting effectiveness?
Regularly review and audit linting rules, and add custom rules for application-specific risks.
Use Strict Mode
What is the purpose of strict mode in JavaScript?
It removes unsafe legacy features, makes errors visible, and optimizes JavaScript engines.
Use Strict Mode
How do you enable strict mode?
Add “use strict”; at the top of your code file or function.
Example (without strict mode):
```javascript
func();
function func() {
y = 3.14; // No error; y is undefined
}
~~~
Example (with strict mode):
```javascript
“use strict”;
func();
function func() {
y = 3.14; // ReferenceError: y is not defined
}
~~~