Giter Site home page Giter Site logo

tslint-config-security's Introduction

tslint-config-security

Build Status npm npm npm

TSLint security rules

Inspired by eslint-plugin-security

How to use

  • Install package:
npm i tslint-config-security --save-dev  --production
  • Update your tslint.json:
{
  "extends": ["tslint-config-security"]
}

By default tslint-config-security enables all rules, but you may disable any of them (not recommended):

{
  "extends": ["tslint-config-security"],
  "rules": {
    "tsr-detect-html-injection": false,
    "tsr-detect-unsafe-regexp": false
  }
}

Rules

All rules start from the prefix tsr- (TSLint Security Rule) to prevent name collisions.

tsr-detect-unsafe-regexp

Locates potentially unsafe regular expressions, which may take a very long time to run, blocking the event loop.

Examples: test/rules/tsr-detect-unsafe-regexp/default/test.ts.lint

More information:

tsr-detect-non-literal-buffer

Detects variable in new Buffer argument

Examples: test/rules/tsr-detect-non-literal-buffer/default/test.ts.lint

tsr-detect-buffer-noassert

Detects calls to Buffer with noAssert flag set

From the Node.js API docs: "Setting noAssert to true skips validation of the offset. This allows the offset to be beyond the end of the Buffer."

Examples: test/rules/tsr-detect-buffer-noassert/default/test.ts.lint

tsr-detect-child-process

Detects instances of child_process & non-literal exec()

More information: https://web.archive.org/web/20170129010544/https://blog.liftsecurity.io/2014/08/19/Avoid-Command-Injection-Node.js#avoiding-command-injection-in-nodejs

Examples: test/rules/tsr-detect-child-process/default/test.ts.lint

tsr-disable-mustache-escape

Detects object.escapeMarkup = false, which can be used with some template engines to disable escaping of HTML entities. This can lead to Cross-Site Scripting (XSS) vulnerabilities.

More information: https://www.owasp.org/index.php/Cross-site_Scripting_(XSS)

Examples: test/rules/tsr-disable-mustache-escape/default/test.ts.lint

tsr-detect-eval-with-expression

Detects eval(variable) which can allow an attacker to run arbitrary code inside your process.

More information: http://security.stackexchange.com/questions/94017/what-are-the-security-issues-with-eval-in-javascript

Examples: test/rules/tsr-detect-eval-with-expression/default/test.ts.lint

tsr-detect-no-csrf-before-method-override

Detects Express csrf middleware setup before method-override middleware. This can allow GET requests (which are not checked by csrf) to turn into POST requests later.

More information: http://blog.nibblesec.org/2014/05/nodejs-connect-csrf-bypass-abusing.html

Examples: test/rules/tsr-detect-no-csrf-before-method-override/default/test.ts.lint

tsr-detect-non-literal-fs-filename

Detects variable in filename argument of fs calls, which might allow an attacker to access anything on your system.

More information: https://www.owasp.org/index.php/Path_Traversal

Known limitations

Due to the known issues in the typed TSLint rules:

tslint-config-security module will analyze methods only on fs variable or on 'fs' module. E.g.:

const fs = require('fs');

fs.open(somePath); // triggers the error
require('fs').symlink(path1, path2); // triggers the error
require("fs").symlink(path1, path2); // triggers the error

const myFs = require('fs');

myFs.open(somePath); // no error

More examples: test/rules/tsr-detect-non-literal-fs-filename/default/test.ts.lint

tsr-detect-non-literal-regexp

Detects RegExp(variable), which might allow an attacker to DOS your server with a long-running regular expression.

More information:

Examples: test/rules/tsr-detect-non-literal-regexp/default/test.ts.lint

tsr-detect-non-literal-require

Detects require(variable), which might allow an attacker to load and run arbitrary code, or access arbitrary files on disk.

More information:

Examples: test/rules/tsr-detect-non-literal-require/default/test.ts.lint

tsr-detect-possible-timing-attacks

Detects insecure comparisons (==, !=, !== and ===), which check input sequentially.

More information: https://snyk.io/blog/node-js-timing-attack-ccc-ctf/

Examples: test/rules/tsr-detect-possible-timing-attacks/default/test.ts.lint

tsr-detect-pseudo-random-bytes

Detects if pseudoRandomBytes() is in use, which might not give you the randomness you need and expect.

More information: http://stackoverflow.com/questions/18130254/randombytes-vs-pseudorandombytes

Examples: test/rules/tsr-detect-pseudo-random-bytes/default/test.ts.lint

tsr-detect-html-injection

Detects HTML injections:

  • document.write(variable)
  • document.writeln(variable)
  • Element.innerHTML = variable;
  • Element.outerHTML = variable;
  • el.insertAdjacentHTML(variable);

More examples: test/rules/tsr-detect-html-injection/default/test.ts.lint

tsr-detect-sql-literal-injection

Detects possible SQL injections in string literals:

// invalid
const userId = 1;
const query1 = `SELECT * FROM users WHERE id = ${userId}`;
const query2 = `SELECT * FROM users WHERE id = ` + userId;
const query3 = 'SELECT * FROM users WHERE id =' + userId;

const columns = 'id, name';
Users.query(`SELECT ${columns} FROM users`);

// valid
const userId = 1;
const query = sql`SELECT * FROM users WHERE id = ${userId}`;
db.query(query);

// See https://github.com/mysqljs/mysql
db.query('SELECT * FROM `books` WHERE `author` = ?', ['David'], function (error, results, fields) {
  //...
});

More examples: test/rules/tsr-detect-sql-literal-injection/default/test.ts.lint

tsr-detect-unsafe-cross-origin-communication

Detects when all windows & frames on your page (including ones that were injected by 3rd-party scripts) may receive your data.

Always provide a specific targetOrigin, not *, if you know where the other window's document should be located. Failing to provide a specific target discloses the data you send to any interested malicious site. https://developer.mozilla.org/en-US/docs/Web/API/Window/postMessage

const myWindow = document.getElementById('myIFrame').contentWindow;

myWindow.postMessage(message, "*"); // Noncompliant

tsr-detect-unsafe-properties-access

Detects a potential unsafe access to the object properties

/* 

It equals to `new Function(prop3)`

const a = {};

a["constructor"]["constructor"]("alert(1)")()
 */
 
// unsafe
obj[prop1][prop2](prop3)

// unsafe
obj[prop1][prop2](prop3)()  
 

More information:

Solutions:

  • use Map
  • use .hasOwnProperty check
  • use Content-Security-Policy on your page

tslint-config-security's People

Contributors

g-marconet avatar theoretick avatar webschik 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

Watchers

 avatar  avatar  avatar

tslint-config-security's Issues

[bug] tsr-detect-non-literal-fs-filename false positives

const s = 'test';
const o = {
  open(a: string) {},
};
o.open(s);

will trigger on the last line

[tslint] Found fs.open with non-literal argument as index 0 (tsr-detect-non-literal-fs-filename)

I tried one, two and three arguments for method (I personally has open method with three arguments) – any of these cases triggers rule.

TypeScript 3.x Support

Hi,

first: thanks for this great TSLint plugin.

My question is if this plugin is (fully) compatible with Typescript 3.x? The package.json specifies ^2.9.1 as requested version.

[New feature] Add more info links to the output

It will be really useful to have "more info about the issue" field in the output.

Maybe you don't want to overwhelm the default human-readable output of TSLint but maybe you can add this into the JSON output?

I see that the JSON output provides a lot of information then more info information will be really cool.

You already have good documentation about every rule so it won't be hard to do.

PS: I have seen a few linters that do that - Bandit for Python is one example and I am helping with the Gosec for golang to do just that.

[New Feature] Confidence level for the issues

There are different issues - some are more concrete others are problems only in specific situations and easily can produce many false-positives.

Like tsr-detect-non-literal-fs-filename rule is a problem when there is a user input which is not checked. This is a narrow case from all possible uses of fs.open/fs.read/fs.write and can easily produce many false-positives.

Having a confidence level will give an understanding of how possible is a false-positive from a concrete rule.

Many static code analysis tools for security vulnerabilities like Bandit and Gosec are using "confidence" level in their output.

Typescript 3.x Support

Hi,

I noticed #4, but I am having issues getting the plugin to work with Typescript 3. The rules seem to be loaded just fine, but they never actually execute.

Steps to reproduce:

  • Generate new project with typescript 3.0.3 and tslint 5.11.0. Write a file that blatantly goes against one of the rules in tslint-config-security. Make sure tslint.json extends tslint-config-security.
  • Clone tslint-config-security in an adjacent directory
  • npm install in tslint-config-security
  • npm link in tslint-config-security
  • npm link tslint-config-security in your project
  • Run tslint. Notice no errors are present (or at least, none from tslint-config-security)
  • Go into the local clone of tslint-config-security, change the typescript version to 3.1.2
  • npm install in tslint-config-security
  • Run tslint. Notice it now shows errors from tslint-config-security

This might also be an issue with tslint or with typescript. I haven't had an opportunity to dig much further into it.

Publish Version 2.0

Hey there,

i saw you accepted my pull request - thank you! :)
Could you publish the new version 2.0 to npm so I can use it in the libraries I'm currently updating?

tsr-detect-non-literal-fs-filename: TypeError when Linted Function Name Exists on Object.prototype

Hey! Thanks for making this set of rules, we're finding them really useful to have on our project.

We've run in to a tiny bug with the tsr-detect-non-literal-fs-filename rule when it runs on a toString call.

As toString exists as a function on the prototype of the fsModuleMethodsArgumentsInfo object, the rule thinks that it's found a match for fs and throws a TypeError: fsArgsInfo.filter is not a function error when it tries to lint it.

I guess more broadly this would affect any case where the name of the function being linted is a function on Object.prototype.

Code Reference

When methodName is toString, this returns the object's toString function rather than an entry from the fsModuleMethodsArgumentsInfo list:

https://github.com/webschik/tslint-config-security/blob/master/src/rules/tsrDetectNonLiteralFsFilenameRule.ts#L16

And then this tries to call filter on the object's toString function:

https://github.com/webschik/tslint-config-security/blob/master/src/rules/tsrDetectNonLiteralFsFilenameRule.ts#L20

[New feature] Add documentation webpage for every rule

There is really good documentation on projects GitHub webpage for the rules but it will be a lot nicer to have a specific webpage for every single rule.

One way to achieve this will be by using GitHub pages. GitHub pages are really easy to set up and provides you with different layout options.

Automatic Git hook installation is confusing and breaks Git related tooling.

I am working on a repo where I just introduced the tslint-config-security TSLint rules. Immediately afterwards, all my external Git tooling -- specifically, Tower -- started failing with this error message:

Husky requires Node 6, can't run Git hook.

Upon further investigation, this is what I believe happened:

  • My system Node version is 4.x. My NVM Node version is 10.x.
  • Upon installing tslint-config-security, the Git hooks were installed. I admit, I'm still unsure the exact mechanism by which this happened. I believe it was through Husky's post-install script, but I cannot confirm.
  • Tower -- per this docs page -- by default runs Git hooks with the user's default environment, as if they had started a new shell.
  • This means Tower runs this project's Git hooks under the system Node version of 4.x.
  • Husky breaks under Node 4.x.

This was difficult and confusing to deal with for a number of reasons:

  • I was not expecting any additional changes or side effects from installing the package.
  • The failure manifests far away from where it originated.
  • The error message refers to something different from and seemingly unrelated to the real root cause.

I would recommend instead, the Git hooks be included with the project, but opt-in rather than opt-out.

Please consider this change, as it could save a users quite a lot of confusion and frustration. If you agree that this is the correct course of action, I would be happy to contribute the change as a pull request. Thank you in advance.

EDIT:

I should clarify, I strongly suspect that there are many different ways to encounter analogous failures from these Git hooks, and they will be equally confusing. While an outdated system Node version, specifically, is probably not too common, I strongly suspect that the sum total of the ways in which this could break add up to reasonably common on the whole.

missing dependency on tslib and typescript in package json

Our build is failing because tslib is not noted as dependency in package json.

Also TypeScript is noted as devdependency, even though it is present in a js file (src/rules/tsrDetectBufferNoassertRule.js). It should be set as dependency or it should not be present in the js file. It is probably in the js file because of line 64 of src/rules/tsrDetectBufferNoassertRule.ts.

[bug] tsr-detect-html-injection false positives

tsr-detect-html-injection detects many false positives. For example my server contains this chunk of code:

import { Column, Entity, Generated, PrimaryColumn } from "typeorm";

@Entity()
export class User {
  @Column()
  @Generated("uuid")
  public uuid?: string;

  @PrimaryColumn() public sub: string;

  @Column({ nullable: true })
  public username?: string;

  constructor(sub: string) {
    this.sub = sub;
  }
}

Line 15 (this.sub = sub;) reports an error. While I see the idea of the rule, this will yield many false positives.

What is the future of the plugin?

I just read that issue Roadmap TSlint -> ESlint in which one of the maintainers of TSlint explains that TSlint will be deprecated and ESlint will scan TypeScript files in future.

As the maintainer points out this will require a lot of work but eventually will happen.

There is also a statement by the ESlint community:
https://eslint.org/blog/2019/01/future-typescript-eslint#the-future-of-typescript-on-eslint

What do you plan to do then with your project TSlint – config – security?

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.