Static code analysis tools (such as ESLint security plugins)
Basic Concepts of Static Code Analysis Tools
Static code analysis tools identify potential issues by examining source code without actually executing the program. These tools can detect security vulnerabilities early in the development phase, preventing problems from reaching production environments. ESLint, one of the most popular static analysis tools in the JavaScript ecosystem, allows for extending security checks through its plugin mechanism.
// A typical ESLint configuration example
module.exports = {
extends: ['eslint:recommended', 'plugin:security/recommended'],
plugins: ['security'],
rules: {
'security/detect-buffer-noassert': 'error',
'security/detect-child-process': 'warn'
}
};
How ESLint Security Plugins Work
Security plugins analyze the Abstract Syntax Tree (AST) using predefined rule sets. They trigger alerts when code patterns match known vulnerability signatures. For example, eslint-plugin-security
includes 38 security rules for Node.js and frontend development, covering risks from prototype pollution to unsafe regular expressions.
// Detecting unsafe eval usage
function processInput(input) {
// The security plugin will flag this risk
eval(input); // Error: Unsafe use of eval
}
Common Security Issue Detection
1. XSS Protection
Security plugins can identify unescaped HTML output. For example, they warn when innerHTML
is directly assigned:
// Unsafe DOM operation
document.getElementById('output').innerHTML = userInput; // Warning: Unsafe HTML assignment
// Secure alternative
document.getElementById('output').textContent = userInput;
2. Sensitive Data Leakage
Detecting hardcoded credentials and keys:
// Code that will be flagged
const dbPassword = 'root123'; // Error: Hardcoded sensitive data
3. Insecure Dependency Calls
Identifying dangerous child_process
call patterns:
const { exec } = require('child_process');
exec('ls ' + userInput); // Warning: Unsafe command concatenation
Advanced Configuration Techniques
Custom rules can extend detection capabilities. The following example creates a rule to detect sensitive localStorage
operations:
// custom-security-rules.js
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Disallow sensitive localStorage operations'
}
},
create(context) {
return {
MemberExpression(node) {
if (node.object.name === 'localStorage' &&
node.property.name === 'setItem') {
context.report({
node,
message: 'Avoid storing sensitive data in localStorage'
});
}
}
};
}
};
Integration with CI/CD Pipelines
Adding static analysis to the build pipeline can block unsafe code merges. Below is a GitHub Actions configuration example:
name: Security Scan
on: [push, pull_request]
jobs:
eslint-security:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- run: npm install
- run: npx eslint --ext .js,.jsx,.ts,.tsx src/ --max-warnings 0
Performance Optimization Practices
Large projects require adjusted analysis strategies:
- Enable ignoring for
node_modules
directories - Use the
--cache
option to speed up repeated checks - Split checks by directory
# Optimized check command
eslint src/ --ext .js,.jsx --cache --ignore-pattern "**/node_modules/**"
Collaboration with Other Tools
Combining SAST tools like Semgrep creates multi-layered protection. For example:
// Combining multiple rule sets
module.exports = {
extends: [
'plugin:security/recommended',
'semgrep:recommended'
],
overrides: [
{
files: ['**/*.ts'],
extends: ['@typescript-eslint/recommended']
}
]
};
Real-World Case Studies
An e-commerce project discovered a price calculation vulnerability through static analysis:
// Original problematic code
function calculateTotal(price, discount) {
return eval(price + discountFormula[discount]); // Dynamic execution risk
}
// Fixed solution
const formulaMap = {
'WELCOME': p => p * 0.9,
'VIP': p => p * 0.7
};
function calculateTotal(price, discount) {
return formulaMap[discount]?.(price) ?? price;
}
Guide to Custom Rule Development
Example of creating a rule to detect SSRF vulnerabilities:
module.exports = {
meta: {
type: 'problem',
docs: {
description: 'Detect potential SSRF vulnerabilities'
}
},
create(context) {
return {
CallExpression(node) {
if (node.callee.name === 'fetch') {
const urlArg = node.arguments[0];
if (urlArg && urlArg.type === 'Literal' &&
urlArg.value.includes('internal.api')) {
context.report({
node,
message: 'Restrict access to internal APIs'
});
}
}
}
};
}
};
False Positive Handling Strategies
Suppress alerts for specific cases using comments:
// eslint-disable-next-line security/detect-non-literal-fs-filename
const file = fs.readFileSync(dynamicPath);
Also document suppression reasons in .eslintrc
:
{
"rules": {
"security/detect-non-literal-fs-filename": [
"error",
{
"ignorePatterns": ["^/var/secure/"]
}
]
}
}
Extensions for Modern Frontend Frameworks
Example Vue-specific security rule configuration:
module.exports = {
extends: [
'plugin:vue/recommended',
'plugin:security/recommended'
],
rules: {
'vue/no-v-html': 'error',
'security/detect-bidi-characters': 'error'
}
};
React dangerous property detection:
// Flagged JSX
<div dangerouslySetInnerHTML={{ __html: userContent }} />; // Error: Dangerous property usage
Rule Severity Grading Strategy
Recommended three-tier classification system:
- High risk (error): e.g., eval usage, SQL concatenation
- Medium risk (warn): e.g., unsafe URL construction
- Low risk (off): e.g., console.log usage
{
"rules": {
"security/detect-eval-with-expression": "error",
"security/detect-unsafe-regex": "warn",
"no-console": "off"
}
}
Team Collaboration Best Practices
- Version-controlled shared configuration:
npm install --save-dev eslint-config-security
- Pre-commit hook configuration:
// package.json
{
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"*.js": "eslint --fix"
}
}
Security Rule Update Mechanism
Recommended update process:
- Check plugin updates monthly
- Test new rules in an isolated branch
- Use breaking change logs
# Check for outdated plugins
npm outdated eslint-plugin-security
# Safe update command
npm update eslint-plugin-security --save-dev
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn
上一篇:前端安全测试的基本流程