• Stars
    star
    228
  • Rank 175,267 (Top 4 %)
  • Language
    JavaScript
  • License
    MIT License
  • Created over 4 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

JavaScript & Node.js open-source SAST scanner. A static analyser for detecting most common malicious patterns πŸ”¬.

@nodesecure/js-x-ray

npm version license ossf scorecard github ci workflow codecov

JavaScript AST analysis. This package has been created to export the Node-Secure AST Analysis to enable better code evolution and allow better access to developers and researchers.

The goal is to quickly identify dangerous code and patterns for developers and Security researchers. Interpreting the results of this tool will still require you to have a set of security notions.

Note I have no particular background in security. I'm simply becoming more and more interested and passionate about static code analysis. But I would be more than happy to learn that my work can help prevent potential future attacks (or leaks).

Goals

The objective of the project is to successfully detect all potentially suspicious JavaScript codes.. The target is obviously codes that are added or injected for malicious purposes..

Most of the time these hackers will try to hide the behaviour of their codes as much as possible to avoid being spotted or easily understood... The work of the library is to understand and analyze these patterns that will allow us to detect malicious code..

Features Highlight

  • Retrieve required dependencies and files for Node.js.
  • Detect unsafe RegEx.
  • Get warnings when the AST Analysis as a problem or when not able to follow a statement.
  • Highlight common attack patterns and API usages.
  • Capable to follow the usage of dangerous Node.js globals.
  • Detect obfuscated code and when possible the tool that has been used.

Getting Started

This package is available in the Node Package Repository and can be easily installed with npm or yarn.

$ npm i @nodesecure/js-x-ray
# or
$ yarn add @nodesecure/js-x-ray

Usage example

Create a local .js file with the following content:

try  {
    require("http");
}
catch (err) {
    // do nothing
}
const lib = "crypto";
require(lib);
require("util");
require(Buffer.from("6673", "hex").toString());

Then use js-x-ray to run an analysis of the JavaScript code:

import { runASTAnalysis } from "@nodesecure/js-x-ray";
import { readFileSync } from "fs";

const str = readFileSync("./file.js", "utf-8");
const { warnings, dependencies } = runASTAnalysis(str);

const dependenciesName = [...dependencies];
const inTryDeps = [...dependencies.getDependenciesInTryStatement()];

console.log(dependenciesName);
console.log(inTryDeps);
console.log(warnings);

The analysis will return: http (in try), crypto, util and fs.

Warning There is also a lot of suspicious code example in the ./examples cases directory. Feel free to try the tool on these files.

Warnings

This section describes how use warnings export.

type WarningName = "parsing-error"
| "encoded-literal"
| "unsafe-regex"
| "unsafe-stmt"
| "short-identifiers"
| "suspicious-literal"
| "suspicious-file"
| "obfuscated-code"
| "weak-crypto"
| "unsafe-import"
| "shady-link";

declare const warnings: Record<WarningName, {
  i18n: string;
  severity: "Information" | "Warning" | "Critical";
  experimental?: boolean;
}>;

We make a call to i18n through the package NodeSecure/i18n to get the translation.

import * as jsxray from "@nodesecure/js-x-ray";
import * as i18n from "@nodesecure/i18n";

console.log(i18n.getTokenSync(jsxray.warnings["parsing-error"].i18n));

Warnings Legends

Warning versions of NodeSecure greather than v0.7.0 are no longer compatible with the warnings table below.

This section describe all the possible warnings returned by JSXRay. Click on the warning name for additional information and examples.

name experimental description
parsing-error ❌ The AST parser throw an error
unsafe-import ❌ Unable to follow an import (require, require.resolve) statement/expr.
unsafe-regex ❌ A RegEx as been detected as unsafe and may be used for a ReDoS Attack.
unsafe-stmt ❌ Usage of dangerous statement like eval() or Function("").
encoded-literal ❌ An encoded literal has been detected (it can be an hexa value, unicode sequence or a base64 string)
short-identifiers ❌ This mean that all identifiers has an average length below 1.5.
suspicious-literal ❌ A suspicious literal has been found in the source code.
suspicious-file βœ”οΈ A suspicious file with more than ten encoded-literal in it
obfuscated-code βœ”οΈ There's a very high probability that the code is obfuscated.
weak-crypto βœ”οΈ The code probably contains a weak crypto algorithm (md5, sha1...)
shady-link βœ”οΈ The code contains shady/unsafe link

API

runASTAnalysis(str: string, options?: RuntimeOptions): Report
interface RuntimeOptions {
  module?: boolean;
  isMinified?: boolean;
  removeHTMLComments?: boolean;
}

The method take a first argument which is the code you want to analyse. It will return a Report Object:

interface Report {
  dependencies: ASTDeps;
  warnings: Warning[];
  idsLengthAvg: number;
  stringScore: number;
  isOneLineRequire: boolean;
}
runASTAnalysisOnFile(pathToFile: string, options?: RuntimeFileOptions): Promise< ReportOnFile >
interface RuntimeOptions {
  module?: boolean;
  isMinified?: boolean;
  removeHTMLComments?: boolean;
}

Run the SAST scanner on a given JavaScript file.

export type ReportOnFile = {
  ok: true,
  warnings: Warning[];
  dependencies: ASTDeps;
  isMinified: boolean;
} | {
  ok: false,
  warnings: Warning[];
}

Contributors ✨

All Contributors

Thanks goes to these wonderful people (emoji key):

Gentilhomme
Gentilhomme

πŸ’» πŸ“– πŸ‘€ πŸ›‘οΈ πŸ›
Nicolas Hallaert
Nicolas Hallaert

πŸ“–
Antoine
Antoine

πŸ’»
Mathieu
Mathieu

πŸ’»
Vincent Dhennin
Vincent Dhennin

πŸ’» ⚠️
Tony Gorez
Tony Gorez

πŸ’» πŸ“– ⚠️
PierreD
PierreD

⚠️ πŸ’»
Franck Hallaert
Franck Hallaert

πŸ’»
Maji
Maji

πŸ’»
MichaΓ«l Zasso
MichaΓ«l Zasso

πŸ’» πŸ›

License

MIT

More Repositories

1

cli

JavaScript security CLI that allow you to deeply analyze the dependency tree of a given package or local Node.js project.
JavaScript
368
star
2

vulnera

Programmatically fetch security vulnerabilities with one or many strategies (NPM Audit, Sonatype, Snyk, Node.js DB).
TypeScript
30
star
3

scanner

⚑️ A package API to run a static analysis of your module's dependencies. This is the CLI engine!
TypeScript
28
star
4

ci

NodeSecure tool enabling secured continuous integration
TypeScript
21
star
5

report

NodeSecure HTML & PDF report generator for any public and/or private git repositories.
JavaScript
14
star
6

Governance

NodeSecure Governance (Code of conduct & Contribution guidelines)
13
star
7

ci-action

The official GitHub action of the @nodesecure/ci package
JavaScript
9
star
8

npm-registry-sdk

Node.js SDK to fetch data from the npm API.
TypeScript
9
star
9

domain-check

Node.js module which helps you to check informations about domains
JavaScript
9
star
10

rc

NodeSecure runtime configuration
TypeScript
7
star
11

eslint-config

NodeSecure ESLint configuration (Work for both JavaScript and TypeScript projects).
JavaScript
6
star
12

ossf-scorecard-sdk

Node.js SDK for OpenSSF scorecard
TypeScript
5
star
13

Dependency-Analyser

Draw a graphic network of a given Github or Gitlab organization
JavaScript
4
star
14

github

Download and Extract Github repository
TypeScript
4
star
15

dependa

Identitfy and categorize Node.js dependencies (builtins, third parties..)
JavaScript
4
star
16

sec-literal

Security utilities to analyze ESTree Literal and JavaScript string primitive. Detect Hexadecimal, Base64, suffix and prefix patterns etc..
JavaScript
4
star
17

preview

Scan your node packages in your browser!
TypeScript
4
star
18

gitlab

Download and extract gitlab repository
TypeScript
3
star
19

vis-network

NodeSecure vis.js network front-end module
JavaScript
3
star
20

npm-security-fetcher

a Node.js CLI created to simplify the analysis of npm registry packages.
TypeScript
3
star
21

flags

NodeSecure security flags 🚩 (configuration and documentation)
HTML
2
star
22

estree-ast-utils

Utilities for AST (ESTree compliant)
JavaScript
2
star
23

i18n

NodeSecure Internationalization
JavaScript
1
star
24

database

NodeSecure Security Database
1
star
25

authors

DEPRECATED (replaced by @nodesecure/contact)
JavaScript
1
star
26

licenses-conformance

Parse spdx license expressions into structured object
TypeScript
1
star