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

1
Q

Use Flat Promise Chains

What problem does excessive nesting in asynchronous callbacks cause?

A

It leads to a “Pyramid of Doom” or “Callback Hell,” making code harder to maintain and track errors or results.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Use Flat Promise Chains

How do Promises help avoid “Callback Hell”?

A

Promises provide a top-down execution flow and automatically skip to the first .catch function when an error occurs, simplifying error handling.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Use Flat Promise Chains

What approach should be used to further reduce complexity in Promises?

A

Use flat Promise chains to maintain readability and avoid nested structures.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Use Flat Promise Chains

How can nested callbacks be rewritten using a flat Promise chain?

A

Example:

```javascript
func1(“input1”)
.then(result => func2(“input2”))
.then(result => func3(“input3”))
.then(result => func4(“input4”))
.catch(error => {
// error handling
});
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Use Flat Promise Chains

How can nested callbacks be avoided using async/await?

A

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
}
})();
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Best Practices

What are best practices for using Promises?

A

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.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Set Request Size Limits

Why should request size limits be set?

A

Without limits, attackers can send large request bodies, exhausting server memory or disk space.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Set Request Size Limits

How can request size limits be set for all requests?

A

Using the raw-body package in Express with a specified limit:

```javascript
getRawBody(req, { length: req.headers[‘content-length’], limit: ‘1kb’ }, callback);
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Set Request Size Limits

Why should limits differ by content type?

A

JSON payloads are blocking operations and riskier than multipart inputs; setting appropriate limits per type prevents performance issues.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Set Request Size Limits

How can Express middleware enforce content-specific limits?

A

Example:

```javascript
app.use(express.urlencoded({ extended: true, limit: ‘1kb’ }));
app.use(express.json({ limit: ‘1kb’ }));
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Set Request Size Limits

How should Content-Type headers be handled to prevent bypassing limits?

A

Validate request data against the stated Content-Type header and prioritize checking large requests or specific types.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Do Not Block the Event Loop

What architecture does Node.js use?

A

A single-thread, non-blocking, event-driven architecture.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Do Not Block the Event Loop

What happens during CPU-intensive JavaScript operations?

A

The event loop becomes blocked, waiting for the operation to finish.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Do Not Block the Event Loop

Why are asynchronous operations important in Node.js?

A

They allow the main application to remain unblocked, improving performance.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Avoiding Race Conditions

What issue arises when synchronous code depends on asynchronous callbacks?

A

Race conditions, where operations may execute out of order, leading to potential errors or security issues.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Avoiding Race Conditions

How can race conditions be avoided?

A

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; });
});
~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Input Validation

Why is input validation essential for application security?

A

To prevent various attacks like SQL Injection, XSS, Command Injection, Denial of Service, Directory Traversal, and more.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

Input Validation

What is the best input validation technique?

A

Use an allow-list of accepted inputs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Input Validation

What should be done if an allow-list cannot be used?

A

Validate inputs against expected schemes and escape dangerous inputs.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

Input Validation

Which Node.js modules simplify input validation?

A

validator and express-mongo-sanitize.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Input Validation

Why is JavaScript parsing of URLs a challenge for input validation?

A

The dynamic nature of JavaScript allows query strings to take on various forms, which can lead to inconsistencies.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

Output Escaping

Why is output escaping important?

A

To prevent Cross-Site Scripting (XSS) attacks by sanitizing HTML and JavaScript content shown to users.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

Output Escaping

Which libraries can be used for output escaping in Node.js?

A

escape-html and node-esapi.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Activity Logging

Why is logging application activity a good practice?

A

It aids in debugging, enhances security through incident response, and supports IDS/IPS tools.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
# Activity Logging Which Node.js modules can be used for logging?
Winston, Bunyan, and Pino.
26
# 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' }); ```
27
# 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.
28
# Monitor the Event Loop What type of attack can overwhelm the event loop?
A Denial of Service (DoS) attack, caused by heavy network traffic.
29
# 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. ## Footnote 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(); } }); ```
30
# 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.
31
# Take Precautions Against Brute-Forcing Which Node.js modules help defend against brute-forcing?
express-bouncer, express-brute, and rate-limiter.
32
# Take Precautions Against Brute-Forcing How does a CAPTCHA help against brute-forcing?
It requires solving a challenge before proceeding, slowing down automated attacks. ## Footnote 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); }); ```
33
# 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.
34
# 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.
35
# 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.
36
# 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.
37
# Remove Unnecessary Routes Which frameworks automatically generate routes that may need removal?
Frameworks like Sails and Feathers.
38
# 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.
39
# 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: ## Footnote Example: ```javascript const hpp = require('hpp'); app.use(hpp()); ```
40
# 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.
41
# 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.
42
# 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" }); ```
43
# Use Object Property Descriptors What does Object.preventExtensions() do?
It prevents new properties from being added to an object.
44
# 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.
45
# 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 }); ```
46
# 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 }); ```
47
# 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.
48
# 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.
49
# 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 } })); ```
50
# Use Appropriate Security Headers What package helps set HTTP security headers in Express?
The helmet package. ## Footnote Example usage: ```javascript app.use(helmet()); ```
51
# Use Appropriate Security Headers What does the Strict-Transport-Security header do?
Ensures browsers access the application only over HTTPS. ## Footnote Example usage: ```javascript app.use(helmet.hsts({ maxAge: 123456, includeSubDomains: false })); ```
52
# Use Appropriate Security Headers How does X-Frame-Options protect against Clickjacking attacks?
It restricts whether a page can be loaded in or