My Linkedin profile
gkouziik / eslint-plugin-security-node Goto Github PK
View Code? Open in Web Editor NEWESLint security plugin for Node.js
ESLint security plugin for Node.js
My Linkedin profile
RULE 15
Buffer.allocUnsafe(10)
creates the buffer with unitialized data!
RULE 12
Check if $where
operator is used by user in mongo's db queries, and hit a warning!
Changed in version 3.6: The $expr operator allows the use of aggregation expressions within the query language. $expr is faster than $where because it does not execute JavaScript and should be preferred where possible.
Do a research for which of those rules can be fixed,and implement the fix funtion!
Rule 8
When user uses window.open();
to open a new window check if he is reseting the opener property!
e.g
var newWind = window.open(); newWind.opener = null;
If this feature is set,the newly-opned window will open as normal,except that it will not have access back to the originating window.This is useful for preventing untrusted sites opened via window.open() for tampering with the originating window,and vice versa!
In eslint-custom-plugin/docs/rules
write the documentation file for detect-child-process Rule
Hey @gkouziik, I saw that there are some PRs that could be very important and some bugs related to the new eslint. Is this project deprecated/dead? If it's, I would like to contribute this to the public.
Rule 6
Check if user, useseval()
with string concat that denotes possible user input
For more info check the documentation (list of rules.odt) file!
Hi @grouzliik
Thank you for this nice plugin. I found bug while using your plugin, it works on older eslint fine, but i need some nice features from latest eslint
✖ eslint --color:
Oops! Something went wrong! :(
ESLint: 8.13.0
TypeError: Cannot read properties of undefined (reading 'hasOwnProperty')
Occurred while linting /Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/src/polyfills/http-response.ts:100
Rule: "security-node/detect-unhandled-event-errors"
at CallExpression (/Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/node_modules/eslint-plugin-security-node/lib/rules/detect-unhandled-event-errors.js:99:54)
at ruleErrorHandler (/Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/node_modules/eslint/lib/linter/linter.js:1114:28)
at /Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/node_modules/eslint/lib/linter/safe-emitter.js:45:58
at Array.forEach (<anonymous>)
at Object.emit (/Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/node_modules/eslint/lib/linter/safe-emitter.js:45:38)
at NodeEventGenerator.applySelector (/Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/node_modules/eslint/lib/linter/node-event-generator.js:297:26)
at NodeEventGenerator.applySelectors (/Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/node_modules/eslint/lib/linter/node-event-generator.js:326:22)
at NodeEventGenerator.enterNode (/Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/node_modules/eslint/lib/linter/node-event-generator.js:340:14)
at CodePathAnalyzer.enterNode (/Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/node_modules/eslint/lib/linter/code-path-analysis/code-path-analyzer.js:795:23)
at /Users/dalisoft/Desktop/Open_Source/nanoexpress/ultimate/node_modules/eslint/lib/linter/linter.js:1145:32
error Command failed with exit code 1.
Related issue: #64
RULE 19
Try to detect calls to fs
functions that take a non Literal value as the filename parameter!
For more info check documentation file!
I connect the plugin:
{
"plugins": ["security-node"],
"extends": ["plugin:security-node/recommended"],
}
I get this output like:
{ type: 'CallExpression',
callee:
{ type: 'Identifier',
name: 'expect',
range: [ 293, 299 ],
loc: { start: [Object], end: [Object] },
parent: [Circular] },
arguments:
[ { type: 'CallExpression',
callee: [Object],
arguments: [Array],
optional: false,
range: [Array],
loc: [Object],
parent: [Circular] } ],
optional: false,
range: [ 293, 332 ],
loc:
{ start: { line: 8, column: 4 }, end: { line: 8, column: 43 } },
parent:
{ type: 'MemberExpression',
object: [Circular],
property:
{ type: 'Identifier',
name: 'toBe',
range: [Array],
loc: [Object],
parent: [Circular] },
computed: false,
optional: false,
range: [ 293, 337 ],
loc: { start: [Object], end: [Object] },
parent:
{ type: 'CallExpression',
callee: [Circular],
arguments: [Array],
optional: false,
range: [Array],
loc: [Object],
parent: [Object] } } }
If I remove the plugin from the config, then there is no such problem.
RULE 20
Try to detect non literal reg exprs arguments!
Create or Modify all the appropriate documentation files!
Rule 10
when user adds helmet,try to find if he 'requires' helmet and if he uses app.use(helmet())
, then try to find if he is using also the 'must' middlewares which they ship with helmet!
Middlewares:
//Prevent opening page in frame or iframe to protect from clickjacking
app.disable("x-powered-by");
//Prevent opening page in frame or iframe to protect from clickjacking
app.use(helmet.xframe());
//Prevent browser from caching and storing page
app.use(helmet.noCache());
//Allow loading resources only from white-listed domains
app.use(helmet.csp());
//Allow communication only on HTTPS
app.use(helmet.hsts());
//Forces browser to only use the Content-Type set in the resource header instead of sniffing or guessing it
app.use(nosniff());
RULE 18
detect require
calls with not LIteral argument!
After upgrading to latest [email protected]
, linting the project now fails with:
Cannot read property 'type' of null Occurred while linting /path/to/project/some-file.js:15 Rule: "security-node/detect-unhandled-async-errors"
EDIT: Just noted that there's an outstanding PR that would fix this issue.
@gkouziik Any chance we could get that merged? Many thanks!
Write a list with rules that we need to focus on from snyk!
Create all the rules via yo and write all the documentations
Hi, could you please release new version after fixing #46?
Rule 7
Warn user when uses console.log()
with string concat!
An attacker may craft a malicious request that may deliberately fail,which the application will log,and when attacker input is sanitized,the payload is sent as-is to the logging facility.Vulnerabilities may vary depending on the
var userName = req.body.userName; console.log('Error: attempt to login with invalid user: ', userName);
curl http://localhost:4000/login -X POST --data 'userName=vyva%0aError: alert moldovan failed $1.000.000 transaction&password=Admin_123&_csrf='
Error: attempt to login with invalid user: vyva Error: alex moldovan failed $1.00.000 transcation
Do not allow user input into logs.
For more info check the documentation (list of rules.odt) file!
The Helmet noCache helmet.noCache
has been removed as a functionality from the helmet package in august https://github.com/helmetjs/helmet/blob/d491d281eb1cc55380046532d24fbc314af836e0/CHANGELOG.md#400---2020-08-02 and this is the issue that is related to the removal reason helmetjs/helmet#215
A suggestion would be to also remove it as a rule. If you don't mind I can create a PR for this.
RULE 14
Warn the user when postMessage()
API is used with the target "*"
Create the working base branch and install the eslint locally! Merge it with master and after that install the allready existed security plugin in the base working branch!
RULE 13
try to find non-literal arguments in the following methods!
document.write(variable)
document.writeln(variable)
Element.innerHTML = variable;
Element.outerHTML = variable;
Rule 3
Dynamically constructed SQL queries that include user-supplied inputs are vulnerable to SQL injection! When malicious data is concatenated to a SQL query,the SQL interpreter fails to distinguish between the intended command and input data,resulting in the execution of the malicious data at SQL commands.
e.g vunlurable SQL query:
connection.query{ 'SELECT * FROM accounts WHERE + req.body.username + '" AND password = " ' + passwordHash + '"', function(err,rows,fields){ console.log("Result = " + JSON.stringify(rows)); }};
Preventing SQL Injection
Use Parameterized Queries To bind all user-supplied data!
For more Info check the documentation (list of rules.odt) file!
RULE 17
For more info check links in documentation (list_of_rules.odt) file!
Rule 11
The user has to add httpOnly:true
and secure:true
properties in express cookie configuration!
HttpOnly
HTTP header preventing cookies beeing accessed by scripts.The application used HTTPS secure connections,and cookies are configured to sent only on Secure HTTPS connections be Secure
flag!
app.use(express.session({ secret: "s3Cur3", cookie: { httpOnly: true, secure: true } }));
In tests/lib/rules
Implement the test.js file for detect-child-process Rule
RULE 16
Check if user requires node's vm and warn him!
For more info check the documentation (List_of_rules.odt) file!
Modify the already existed rule(command injection) from the existed eslint-security-plugin! the existed rule doesnt permit to user to even require(child_process)!So he cant even use child_process functions! Let user to use use child_prcess functions but forbid him to use child_proces.exec() with string concatenation and .spawn(), .execFile() , .execFileSync() , .spawnSync() with option shell:true !
Rule 2
Force the user to use 'use strict'
at the top of his file or at the beggining of a function,which enables the strict mode within the enclosing function scope
Info:
Strict mode makes several changes to normal Javascript semantincs:
intitialize eslint plugin through Yeoman Generator!
Create a first rule for Eslint!
Create a rule that enforces that s have at least a btn class because default button styling really has not kept up over the years!
Instructions:
Invoke yo eslint:rule
and the Yeoman generator will generate 3 files
docs/rules/<rule-name>.md
This is a Markdown file that documents your rule
lib/rules/<rule-name>.js
This is where we’ll write the logic to implement the rule
tests/lib/rules/<rule-name>.js
This is a scaffold of a test suite with an example of a test of some invalid code
Write the rule file and the test,pass the tests and after that delete the branch!
Rule 5
Instead of readFile() from fs lib,use createReadStream(). Since the process thread is shared among all the clients,memory is also shared! You should storing much information in memory per request because it can accumulate over concurrent clients and your process can die simply because it runs out of memory.In threaded servers,a thread usually has a seperate memory limit that's reached long before the whole server process runs out of memory,so the only thread gets terminated instead of the whole process.However Node.js being in a single ,will kill the whole process.
Let's look an example:
'use strict'; var express = require('express') ; var app = express(); var fs = require('fs'); app.get('/getfile', function(req,res) { fs.readFile(_dirname + '/directory.txt' 'utf8', function(err, content){ res.send(err ? 500 : content); //send an error or content of file }); }); app.listen(3000);
It looks perfevtly finedoesnt it? When the client requests a file, the application reads it from the file system (asynchronoysly) and then sends it to the client! The problem is that the whole file is read into memory before it's sent to the client.In our example, the file is small, so it doesnt really matter.But if the file was larger - a few hundred MB, for example- then it could create a memory issue!
How do you fix this?Streams!
A basic building block in Node.js and a type of EventEmmiter,stremas are widely used.Streams allow us to transmit the file to the client application bit by bit as it becomes available so that we dont hog memory no matter how big the file.Let's look at how to fix the previous example with streams:
'use strict'; var express = require('express'); var app = express(); var fs = require('fs'); app.get('/getfile', function (req,res){ fs.createReadStream(_dirname + '/directory.txt', 'utf8').pipe(res); }); app.listen(3000);
Rule 9
Check if user uses res.redirect()
with string concat that may denotes user input!
Or at least make sure that he is sanitizing input via encodeURI()
.
For more info check in documentation (list of rles.odt) file!
Rule 4
The Math.random()
method is often used to generate nonpredictable values such as random tokens,resource IDs,or UUIDs,.However Math.random()
is cryptographically indecure.It can produce predictable values and is therefore not safe to use in security-sensitive context.
For more info check the documentation (list of rules.odt) file!
It seems that since the 'detect-helmet-without-nocache' rule has been removed, but it is still present in the rules config and in the recommended rules causing our builds to fail;
'Failed to load plugin 'security-node' declared in '.eslintrc.json': Cannot find module './lib/rules/detect-helmet-without-nocache'
Just to keep track of it, the following rules miss documentation (there is currently only a placeholder file):
detect-helmet-without-nocache
detect-option-multiplestatements-in-mysql
detect-option-rejectunauthorized-in-nodejs-httpsrequest
detect-possible-timing-attacks
disable-ssl-across-node-server
Construct the final report file (based on list of rules.odt)!
The following code should not cause detect-crlf
console.log(`test`);
#3 After creation of the first rule try to make the rule work!
fill the document file with information about that rule docs/rules/no-ugly-buttons.md
write the impementation of the rule no-ugly-buttons in lib/rules/no-ugly-buttons.js
.
Use https://astexplorer.net/ to write the rule!
Write the test in tests/lib/rules/no-ugly-buttons.js
Be sure that test will pass and push the changes in branch first-rule-branch!
A declarative, efficient, and flexible JavaScript library for building user interfaces.
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google ❤️ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.