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
Q

Activity Logging

Which Node.js modules can be used for logging?

A

Winston, Bunyan, and Pino.

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

Activity Logging

How can you log activities to both console and a file?

A

Example:

```javascript
const logger = new (Winston.Logger)({
transports: [
new (winston.transports.Console)(),
new (winston.transports.File)({ filename: ‘application.log’ })
],
level: ‘verbose’
});
~~~

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

Activity Logging

How can errors and general logs be separated?

A

Configure different transports to save errors in one log file and general logs in another.

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

Monitor the Event Loop

What type of attack can overwhelm the event loop?

A

A Denial of Service (DoS) attack, caused by heavy network traffic.

29
Q

Monitor the Event Loop

How does the toobusy-js module help during heavy traffic?

A

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

30
Q

Take Precautions Against Brute-Forcing

Why are brute-forcing attacks common?

A

Attackers use brute-forcing to guess passwords or other sensitive information, especially on login pages.

31
Q

Take Precautions Against Brute-Forcing

Which Node.js modules help defend against brute-forcing?

A

express-bouncer, express-brute, and rate-limiter.

32
Q

Take Precautions Against Brute-Forcing

How does a CAPTCHA help against brute-forcing?

A

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

33
Q

Take Precautions Against Brute-Forcing

What is an account lockout?

A

A mechanism that locks an account after multiple failed login attempts, preventing further brute-force attempts.

34
Q

Use Anti-CSRF Tokens

What is Cross-Site Request Forgery (CSRF)?

A

An attack where an authenticated user unknowingly performs actions on behalf of an attacker.

35
Q

Use Anti-CSRF Tokens

Why is csurf no longer recommended?

A

It has a known security vulnerability and has been deprecated. Consider alternative CSRF protection packages.

36
Q

Remove Unnecessary Routes

Why should unused API routes be disabled?

A

They increase the application’s attack surface and may lead to issues like information leakage or command execution.

37
Q

Remove Unnecessary Routes

Which frameworks automatically generate routes that may need removal?

A

Frameworks like Sails and Feathers.

38
Q

Prevent HTTP Parameter Pollution (HPP)

What is HTTP Parameter Pollution?

A

An attack where multiple HTTP parameters with the same name are sent, causing unpredictable application behavior.

39
Q

Prevent HTTP Parameter Pollution (HPP)

How can HPP be mitigated in Express?

A

Use the hpp module to ensure only the last parameter value is processed:

Example:

```javascript
const hpp = require(‘hpp’);
app.use(hpp());
~~~

40
Q

Only Return What Is Necessary

Why should applications limit the data returned in responses?

A

To avoid personal information disclosure, such as returning sensitive fields like email addresses or social security numbers.

41
Q

Use Object Property Descriptors

What are the three hidden attributes of object properties?

A

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
Q

Use Object Property Descriptors

How can you define object property attributes?

A

Use Object.defineProperty():

```javascript
Object.defineProperty(o, “a”, {
writable: true,
enumerable: true,
configurable: true,
value: “A”
});
~~~

43
Q

Use Object Property Descriptors

What does Object.preventExtensions() do?

A

It prevents new properties from being added to an object.

44
Q

Use Access Control Lists (ACL)

How can ACLs enforce authorization in Node.js applications?

A

By defining roles and assigning users to those roles using modules like acl.

45
Q

Error and Exception Handling

How should uncaughtException events be handled?

A

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
Q

Error and Exception Handling

What happens if errors are unhandled in an EventEmitter?

A

They become uncaught exceptions, potentially crashing the application. Always attach listeners for error events:

```javascript
emitter.on(‘error’, function(err) {
// Handle error
});
~~~

47
Q

Server Security

How should errors in asynchronous calls be handled?

A

Always propagate the error as the first argument to callbacks or explicitly handle it in express routes.

48
Q

Server Security

How can you improve session cookie security?

A

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
Q

Server Security

Example of setting cookie flags:

A

```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
Q

Use Appropriate Security Headers

What package helps set HTTP security headers in Express?

A

The helmet package.

Example usage:

```javascript
app.use(helmet());
~~~

51
Q

Use Appropriate Security Headers

What does the Strict-Transport-Security header do?

A

Ensures browsers access the application only over HTTPS.

Example usage:

```javascript
app.use(helmet.hsts({ maxAge: 123456, includeSubDomains: false }));
~~~

52
Q

Use Appropriate Security Headers

How does X-Frame-Options protect against Clickjacking attacks?

A

It restricts whether a page can be loaded in <frame> or <iframe> elements.</frame>

Example usage:

```javascript
app.use(helmet.frameguard());
~~~

53
Q

Use Appropriate Security Headers

Why is X-XSS-Protection discouraged?

A

It has been deprecated due to potential security issues.

Example usage:

```javascript
app.use(helmet.xssFilter()); // Sets “X-XSS-Protection: 0”
~~~

54
Q

Use Appropriate Security Headers

What is the role of Content-Security-Policy (CSP)?

A

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

55
Q

Use Appropriate Security Headers

How does X-Content-Type-Options improve security?

A

Prevents browsers from MIME type sniffing.

Example usage:

```javascript
app.use(helmet.noSniff());
~~~

56
Q

Use Appropriate Security Headers

When should Cache-Control headers be used?

A

To prevent caching of sensitive information.

Example usage:

```javascript
app.use(nocache());
~~~

57
Q

Use Appropriate Security Headers

What does X-Powered-By reveal, and how can it be hidden?

A

It discloses server technology.

Example usage:

```javascript
app.use(helmet.hidePoweredBy());
~~~

58
Q

Platform Security

How can you ensure your third-party packages are up-to-date?

A

Use tools like npm audit, OWASP Dependency-Check, or Retire.js to identify vulnerabilities.

Example usage:

```bash
npm audit
npm audit fix
~~~

59
Q

Avoid Dangerous Functions

Why is eval() dangerous?

A

It executes strings as JavaScript, enabling remote code execution when combined with user input.

60
Q

Avoid Dangerous Functions

What risks do child_process.exec functions present?

A

They can execute arbitrary commands, leading to command injection vulnerabilities.

61
Q

Avoid Dangerous Functions

How should risky modules like fs and vm be used?

A

With sanitized inputs and, in the case of vm, within a sandboxed context.

62
Q

Stay Away from Evil Regexes

What is a ReDoS attack?

A

Regular Expression Denial of Service (ReDoS) exploits slow Regex implementations to make applications hang with crafted input.

63
Q

Stay Away from Evil Regexes

What are ‘evil’ regexes?

A

Regexes that group repetition and alternation with overlapping, leading to extreme slowdowns on specific input.

64
Q

Stay Away from Evil Regexes

How can you test if a Regex is vulnerable?

A

Use tools like vuln-regex-detector.

Example: The regex ^(([a-z])+.)+A-Z+$ may hang on long input strings like aaaa…aaaaAaaaaa…aaaa.

65
Q

Run Security Linters

Why are linting tools essential in JavaScript?

A

They ensure secure code by flagging patterns with potential risks in the development lifecycle.

66
Q

Run Security Linters

Which tools are commonly used for JavaScript linting?

A

ESLint and JSHint.

67
Q

Run Security Linters

How can you improve linting effectiveness?

A

Regularly review and audit linting rules, and add custom rules for application-specific risks.

68
Q

Use Strict Mode

What is the purpose of strict mode in JavaScript?

A

It removes unsafe legacy features, makes errors visible, and optimizes JavaScript engines.

69
Q

Use Strict Mode

How do you enable strict mode?

A

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