Get Started
- CodeAnt AI
- Control Center
- Pull Request Review
- IDE
- Compliance
- Anti-Patterns
- Code Governance
- Infrastructure Security Database
- Application Security Database
Security
Detects trojan source attacks that employ unicode bidi attacks to inject malicious code.
// Example with a potentially harmful bidi character
const username = "user"; // This string contains a unicode bidi character that flips text direction
console.log("Logged in as: " + username);
-
This ESLint rule specifically targets the prevention of trojan source attacks by identifying the presence of unicode bidi (bidirectional) characters in the code, which could potentially be used to alter the flow of the program in a malicious manner, thereby enhancing the security of the codebase.
-
By automatically detecting and flagging the use of bidi characters, both in the code and comments, it ensures that developers are immediately made aware of potential security risks, allowing for rapid remediation and significantly reducing the risk of malicious code injection through seemingly benign text manipulation.
-
The rule is particularly relevant for projects with multiple contributors, including open-source projects, where the introduction of bidi characters can occur either unintentionally or through deliberate malicious activity. It acts as an early warning system, ensuring the integrity of the code before it’s merged into the main codebase.
-
The detailed message provided by this rule, pointing out the exact location and nature of the potential trojan source attack, empowers developers to understand the specific security concern and rectifies the issue efficiently without needing to manually search for the problematic bidi characters, thus streamlining the debugging and code review process.
Detects calls to “buffer” with “noAssert” flag set.
const buffer = Buffer.from([1, 2, 3, 4, 5]);
const value = buffer.readInt32LE(0, true); // 'true' is the noAssert flag
-
The rule targets prevention of potential security vulnerabilities that can arise from bypassing built-in validation checks by setting the “noAssert” flag to true when calling “buffer” methods. This validation is crucial for ensuring data integrity and avoiding buffer overflow or underflow scenarios.
-
It enforces best practices in code quality by encouraging developers to rely on Node.js’s inherent checks within Buffer manipulation methods. These checks are designed to catch errors and misuse of the Buffer API, contributing to more robust and reliable code.
-
Specifically addresses a common pitfall in Node.js applications related to the misuse of the Buffer API, thereby providing a targeted solution to a specific class of bugs. Improper handling of Buffers can lead to inconsistencies in application behavior or even security breaches.
-
Enhances code maintainability and readability by discouraging the use of deprecated or discouraged features, such as the “noAssert” flag. This aligns with modern Node.js development practices, as newer versions of Node.js have deprecated the use of the “noAssert” argument due to its implications on security and application stability.
Detects instances of “child_process” & non-literal “exec()” calls.
const { exec } = require('child_process');
let userProvided = 'user input here'; // This could be user-controlled input
exec(userProvided, (error, stdout, stderr) => {
if (error) {
console.error(`exec error: ${error}`);
return;
}
console.log(`stdout: ${stdout}`);
console.error(`stderr: ${stderr}`);
});
-
This ESLint rule targets the detection of “child_process” module usage with a focus on
exec()
function calls where the command passed toexec()
is not a literal string. This is crucial because dynamic commands based on user input can lead to arbitrary code execution, a severe security vulnerability. -
It immediately flags any
require
expressions that load the “child_process” module unless these are part of a variable declaration, assignment, or a member expression. This narrow focus helps in pinpointing potentially hazardous code patterns where the module is imported without being directly assigned or used, which could indicate indirect or concealed usage. -
The rule is specifically designed to catch non-literal first arguments passed to the
exec()
function. Since literals are static and their content is known at the time of code writing, enforcing their use greatly reduces the risk of executing untrusted code. This constraint ensures that developers explicitly state command strings, making code inspection and auditing for insecure practices more straightforward. -
Additionally, this ESLint rule serves as an educational tool for developers, particularly those new to Node.js or unaware of the security implications associated with executing shell commands. By flagging unsafe practices, it encourages the adoption of secure coding patterns and raises awareness about the necessity of validating and sanitizing external input, especially in scenarios involving command execution.
Detects “object.escapeMarkup = false”, which can be used with some template engines to disable escaping of HTML entities.
// Example of a configuration that disables markup escaping in a template engine context
var templateEngine = {
escapeMarkup: false // Disabling HTML escaping
};
// Usage of the template engine in rendering data, posing a potential XSS risk if user-controlled data is included
templateEngine.render('<div>User content: ${userContent}</div>');
-
It specifically targets the risky practice of disabling HTML entity escaping within template engines by identifying the exact pattern
object.escapeMarkup = false
, which directly corresponds with turning off automatic escaping mechanisms. This is crucial because automatic escaping is a primary defense against XSS (Cross-Site Scripting) attacks. -
The rule ensures that developers are immediately alerted to any instances where markup escaping is disabled, promoting swift rectification. This immediate feedback loop helps in maintaining secure coding practices and helps prevent insecure code from progressing through the development lifecycle, potentially reaching production environments where it could be exploited.
-
The rule aids in the enforcement of secure default configurations within template engines. By detecting and discouraging the explicit disabling of escaping, it implicitly encourages the practice of keeping or enabling these security features, aligning with the principle of secure defaults in software development.
-
The rule’s specificity in looking for the
escapeMarkup
property assignment tofalse
means that it is highly focused and is less likely to produce false positives. This focus helps maintain developer productivity by ensuring that only genuinely risky configurations are flagged for review and correction, without overwhelming developers with irrelevant warnings.
Detects “eval(variable)” which can allow an attacker to run arbitrary code inside your process.
let userInput = "console.log('Hello World!');"; // This could be an input from an external source
eval(userInput); // Unsafe use of eval with a variable
-
This rule helps in pinpointing the use of
eval()
with non-literal arguments within the code, which are typically susceptible to code injection attacks. By explicitly identifying calls whereeval()
is invoked with variables or expressions possibly controlled by user input, developers are reminded to scrutinize and ideally avoid such usage patterns. -
By detecting
eval(variable)
, it encourages developers to look for safer alternatives to dynamic code evaluation based on untrusted inputs. The rule not only highlights dangerous patterns but implicitly guides towards safer coding practices by making developers aware of the risks associated with usingeval()
in this manner. -
The provided “fix” example demonstrates a safer approach to handling dynamic inputs by using
JSON.parse()
for parsing JSON strings from untrusted sources instead of evaluating them as code. This specific guidance helps in reducing the security vulnerabilities associated with dynamic code execution, steering developers towards more secure methods of handling untrusted data. -
Implementing this rule within a project’s ESLint configuration acts as an automated guardrail against introducing potentially exploitable vulnerabilities through the misuse of
eval()
. By enforcing its detection at the code analysis stage, it aids in preemptively mitigating risks associated with arbitrary code execution vulnerabilities, thereby contributing to the overall security posture of the application.
Detects instances of new Buffer(argument) where argument is any non-literal value.
// Assuming user input is coming from somewhere untrusted
const userInput = getUserInput();
// Using the deprecated and unsafe Buffer constructor
const buffer = new Buffer(userInput);
- The rule detects usage of
new Buffer(argument)
with non-literal values, which is deprecated due to security vulnerabilities. Using non-literal values can lead to vulnerabilities where user input might be used to manipulate data or cause unintended behavior in the application. - It encourages developers to replace the deprecated
new Buffer(argument)
calls with the recommendedBuffer.from(argument)
syntax, which is designed to handle data more safely, thereby reducing the potential for security vulnerabilities such as buffer overflow attacks. - By automatically identifying places in the code where the deprecated constructor is used, it helps in maintaining code quality and ensures that the codebase utilizes the current best practices for handling binary data in Node.js.
- The rule aids in automatic code review processes by flagging potentially unsafe code patterns, thereby saving time during code reviews and improving the security posture of the application without relying entirely on manual code reviews to catch such issues.
Detects Express “csrf” middleware setup before “method-override” middleware.
const express = require('express');
const csrf = require('csurf');
const methodOverride = require('method-override');
const app = express();
// Incorrect order
app.use(csrf());
app.use(methodOverride());
app.get('/', (req, res) => {
res.send('Hello, world!');
});
app.listen(3000, () => console.log('Server running on port 3000'));
- This ESLint rule specifically ensures that the CSRF (Cross-Site Request Forgery) middleware is set up after the method-override middleware in Express applications, which is crucial for maintaining the correct order of middleware execution to ensure security measures are effective.
- By detecting the incorrect setup of
express.csrf()
beforeexpress.methodOverride()
, this rule helps prevent potential security vulnerabilities where an attacker might exploit the ability to override HTTP methods in a way that bypasses CSRF protection mechanisms, potentially leading to CSRF attacks. - The rule aids in maintaining best practices in middleware setup for Express applications by programmatically enforcing the sequence in which middleware functions should be used, thus reducing the risk of developer oversight or misunderstandings about the importance of middleware order for security.
- Automatically identifying and reporting the incorrect order of middleware setup as evidenced by the provided code snippets (
app.use(csrf());
beforeapp.use(methodOverride());
) assists in early detection and correction during development, contributing to a more secure codebase by preventing deployment of Express applications with configuration that could be exploited for CSRF attacks.
Detects variable in filename argument of “fs” calls, which might allow an attacker to access anything on your system.
const fs = require('fs');
let userInput = 'path/to/user/file.txt';
// Vulnerable to arbitrary file access if userInput is controlled by an attacker
fs.readFile(userInput, 'utf8', (err, data) => {
if (err) throw err;
console.log(data);
});
- It specifically targets potential security vulnerabilities linked with the use of variable file names in filesystem (
fs
) module operations. By detecting non-literal filename arguments, it reduces the risk of arbitrary file access, where an attacker could potentially navigate the filesystem or access restricted files. - The rule prevents a common attack vector called “Directory Traversal” by ensuring that
fs
operations do not inadvertently process user-controlled input without validation, thus safeguarding against unauthorized access to the filesystem. - It encourages better coding practices by prompting developers to validate or sanitize input data before it is used in file system operations. This is exemplified in the provided ‘fix’ snippet where user input is checked against a predefined list of allowed files before access is permitted.
- By identifying instances where the filename argument of
fs
calls is dynamically generated, this rule helps maintain a stronger security posture within Node.js applications, making it harder for attackers to exploit vulnerabilities related to file access.
Detects “RegExp(variable)”, which might allow an attacker to DOS your server with a long-running regular expression.
function testRegex(input) {
const pattern = new RegExp(input);
const testString = "example test string";
return pattern.test(testString);
}
const userInput = ".*";
testRegex(userInput);
-
Prevents the use of dynamically generated regular expressions, which reduces the risk of Regular Expression Denial of Service (ReDoS) attacks. These attacks can overload the server by causing it to process long-running regular expressions.
-
Enhances security by ensuring that all regular expressions are literal. This way, attackers cannot inject malicious patterns into the regular expressions which might be used to extract sensitive information or manipulate the application’s logic.
-
Promotes best practices in handling user input by discouraging the direct use of user-controlled data in critical functions like regular expressions, thereby encouraging developers to sanitize and validate user input.
-
Facilitates the maintenance and readability of code by ensuring that regular expressions are defined explicitly within the code. This not only helps in understanding the purpose of the regular expression but also makes it easier to review and audit the code for potential security issues.
Detects “require(variable)”, which might allow an attacker to load and run arbitrary code, or access arbitrary files on disk.
const moduleName = "someDynamicValue";
const myModule = require(moduleName);
-
Ensures the arguments passed to
require
are static literals, mitigating the risk of executing dynamically constructed module paths which can be manipulated by attackers to execute arbitrary code. This directly targets and reduces a significant vector for remote code execution vulnerabilities. -
Increases code maintainability and readability by encouraging the use of static module names. This makes the dependency graph more predictable and easier to understand, as opposed to dynamic requires that could load any number of modules based on runtime conditions.
-
Helps in static analysis and tooling by making the modules required by a piece of code more apparent. Tools that analyze dependencies, bundle applications, or detect unused modules rely on static analysis, which is more effective with literal require paths.
-
Assists in compliance with secure coding standards that forbid or discourage the use of dynamic expressions in critical functions like module loading. By enforcing this rule, developers are guided towards practices that are generally considered safer and are often a requirement in security-sensitive environments.
Detects “variable[key]” as a left- or right-hand assignment operand.
function getUserData(userInput) {
const userData = {
id: 123,
username: 'Alice',
email: 'alice@example.com',
};
// BAD: Using variable to access property dynamically could lead
// to unsafe object property access.
return userData[userInput];
}
-
This ESLint rule is invaluable for detecting potential security vulnerabilities related to object property access where keys are dynamically generated or user-controlled. By highlighting instances where variables are used to access object properties (
variable[key]
), it draws attention to code patterns that could be exploited for property injection attacks, thereby preventing possible security breaches. -
It emphasizes the importance of validating or sanitizing input used to access object properties. The rule illustrates a common mistake in handling user input directly without checks, which could lead to unauthorized access to object properties or even execution of unintended code paths. Following this rule’s guidance encourages the implementation of validation mechanisms, such as whitelists, to ensure only safe property access.
-
The rule not only highlights the potential vulnerability but also suggests a remediation approach by demonstrating how to replace unsafe dynamic property access with a secure pattern that explicitly checks the input against a list of allowed keys. This educative aspect helps developers understand not just what to avoid but also how to correct their approach, fostering more secure coding practices.
-
By categorizing object injection points based on their usage context (e.g., variable assignment, function call, or generic usage), this ESLint rule offers tailored feedback that can help developers more precisely identify and address the different ways in which unsafe dynamic property access could be manifested in their code. This nuanced approach to reporting vulnerabilities makes it easier for developers to understand the context and severity of the potential security flaw, leading to more effective and targeted fixes.
Detects insecure comparisons (==
, !=
, !==
and ===
), which check input sequentially.
function checkPassword(inputPassword, userPassword) {
if (inputPassword === userPassword) {
// Process the login
return true;
}
return false;
}
- The rule specifically targets the prevention of timing attacks by detecting comparisons using
==
,!=
,!==
, and===
. These operations can leak timing information because they exit early as soon as a mismatch is found, potentially allowing attackers to deduce a correct value based on the time taken to evaluate the condition. - By identifying insecure binary expressions in conditionals, the rule helps developers spot places where sensitive comparisons are made, such as password or token comparisons, directing them to implement time-constant comparisons instead.
- The rule encourages the adoption of secure coding practices by promoting the use of cryptographic functions, like
crypto.timingSafeEqual
in Node.js, which are designed to compare data in a way that protects against timing attacks by ensuring that the operation takes the same amount of time regardless of the input. - By providing clear feedback on the exact location within the code where a potential timing attack could be exploited (either on the left or right side of the comparison), the rule enables developers to quickly identify and rectify vulnerabilities, thus enhancing the overall security posture of the application.
Detects if “pseudoRandomBytes()” is in use, which might not give you the randomness you need and expect.
const crypto = require('crypto');
function generateRandomBytes() {
return crypto.pseudoRandomBytes(256).toString('hex');
}
console.log(generateRandomBytes());
-
This rule specifically targets the use of the
pseudoRandomBytes()
function from the Node.jscrypto
module, which does not generate cryptographically secure random values. This is crucial for applications requiring high levels of security, such as in cryptographic operations, token generations, etc., where the predictability of random values could be exploited. -
By detecting the usage of
pseudoRandomBytes()
, the rule encourages developers to replace it withrandomBytes()
, a function that generates cryptographically strong randomness. This simple switch considerably enhances the security posture of the application without requiring significant changes to the codebase. -
This ESLint rule aids in the early detection of potentially insecure code during the development phase, reducing the likelihood of introducing vulnerabilities into production environments. Early detection means lower costs and less effort associated with remediation.
-
It also serves an educational purpose by highlighting a common pitfall among developers who might not be aware of the difference between pseudo-random and cryptographically secure random numbers. By flagging this in the development process, it helps in raising awareness and knowledge about implementing secure coding practices.
Detects potentially unsafe regular expressions, which may take a very long time to run, blocking the event loop.
// Potentially unsafe regular expression due to nested quantifiers
const regex = /.*(a+)+$/;
- Helps in identifying and preventing the use of potentially catastrophic regular expressions, which could lead to ReDoS (Regular Expression Denial of Service) by flagging expressions with exponential or polynomial time complexity for certain inputs.
- Enhances application performance and responsiveness by ensuring that regular expressions do not block the event loop, thereby preventing the server from becoming unresponsive to other incoming requests due to CPU-intensive regex evaluation.
- Increases code safety and security by automatically detecting and prompting the developer to refactor unsafe regular expressions that could be exploited by malicious users to cause application hangs or crashes.
- Supports both literal and constructor-created regular expressions by checking both static and dynamically created
RegExp
objects, thus providing comprehensive coverage across different use cases and patterns in the codebase.