Giter Club home page Giter Club logo

eslint-plugin-security-node's Introduction

eslint-plugin-security-node's People

Contributors

cherniavskii avatar dependabot[bot] avatar fdawgs avatar gkouziik avatar karlhorky avatar nf997 avatar paumacasaet avatar tmlaughlinjr avatar wcatron avatar zhammami avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

eslint-plugin-security-node's Issues

NoSQL Injection - MongoDb, $where operator

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.

Fix for rules

Do a research for which of those rules can be fixed,and implement the fix funtion!

window.open() attack

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!

Is this project deprecated?

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.

eval(),setTimeout(),setInterval()

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!

Broken on eslint v8.9.0+

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

fs calls with non-literal arguments

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!

Eslint 6.6 output when this plugin is connected

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.

Security Missconfiguration <helmet>

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

Release?

Hi, could you please release new version after fixing #46?

CRLF from console.log()

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

  1. Log Forging(CRLF)
    Lets consider an example where an application logs a failed attempt to login to the system.A very common example for this is as follows:
    var userName = req.body.userName; console.log('Error: attempt to login with invalid user: ', userName);
    When user input is unsanitized and the output machanism is an ordinary terminal stdout facility then the application will be vulnerable to CRLF injection,where an attacker can create a malicious payload as follows:
    curl http://localhost:4000/login -X POST --data 'userName=vyva%0aError: alert moldovan failed $1.000.000 transaction&password=Admin_123&_csrf='
    where the username is encoded parameter is encoding in the request the LF symbol which will result in a new line to begin.Resulting log output will look as follows:
    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!

Create a new working (base) Branch

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!

detect-html-Injection

RULE 13
try to find non-literal arguments in the following methods!
document.write(variable)
document.writeln(variable)
Element.innerHTML = variable;
Element.outerHTML = variable;

SQL Injection

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!

Security Missconfiguration express cookie

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

Modify the already existed rule for command injection in security-eslint-existed-plugin

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 !

Force the user to use 'use strict' in the beggining of every File

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:

  1. Eliminates some JAvascript silent errors by changing them to throw errors
  2. Fixes mistakes that make it difficult for Javascript engines to perform optimizations:strict mode code can sometimes be made to run faster than identical code thats not strict mode.
  3. Prohibits some syntax likely to be defined in future versions of ECMASprit
    See the documentation (list of rules.odt) file for more information

Eslint first rule

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!

DOS(Denial Of Service)

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

Dangerous redirects via res.redirect()

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!

Insecure Randomness

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!

Missing 'detect-helmet-without-nocache' in 1.0.13

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'

Missing documentation

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

implementation of the first rule

#3 After creation of the first rule try to make the rule work!

  1. fill the document file with information about that rule docs/rules/no-ugly-buttons.md

  2. write the impementation of the rule no-ugly-buttons in lib/rules/no-ugly-buttons.js.
    Use https://astexplorer.net/ to write the rule!

  3. 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!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.