Skip to content

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

License

Notifications You must be signed in to change notification settings

NodeSecure/js-x-ray

Repository files navigation

@nodesecure/js-x-ray

npm version license ossf scorecard github ci workflow

JavaScript AST analysis. This package has been created to export the NodeSecure 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 basic knowledge of secure coding.

Goals

The objective of the project is to detect potentially suspicious JavaScript code. The target is code that is added or injected for malicious purposes.

Most of the time hackers will try to hide the behaviour of their code 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.

Feature Highlight

  • Retrieve required dependencies and files for Node.js
  • Detect unsafe regular expressions
  • Get warnings when the AST analysis detects a problem or is unable to follow a statement
  • Highlight common attack patterns and API usages
  • Follow the usage of dangerous Node.js globals
  • Detect obfuscated code and, when possible, the tool that has been used
  • Detect potential performance issues related to usage of synchronous API from Node.js core.

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 { AstAnalyser } from "@nodesecure/js-x-ray";
import { readFileSync } from "node:fs";

const scanner = new AstAnalyser();

const { warnings, dependencies } = await scanner.analyseFile(
  "./file.js"
);

console.log(dependencies);
console.dir(warnings, { depth: null });

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

Tip

There are also a lot of suspicious code examples in the ./workspaces/js-x-ray/examples directory. Feel free to try the tool on these files.

Scanning a complete project

By itself, JS-X-Ray does not provide utilities to walk and scan a complete project. However, NodeSecure has packages to achieve that:

import { ManifestManager } from "@nodesecure/mama";
import { NpmTarball } from "@nodesecure/tarball";

const mama = await ManifestManager.fromPackageJSON(
  "./path/to/package.json"
);
const extractor = new NpmTarball(mama);

const {
  composition, // Project composition (files, dependencies, extensions)
  conformance, // License conformance (SPDX)
  code         // JS-X-Ray analysis results
} = await extractor.scanFiles();

console.log(code);

The NpmTarball class uses JS-X-Ray under the hood, and ManifestManager locates entry (input) files for analysis.

Alternatively, you can use EntryFilesAnalyser directly for multi-file analysis. See the EntryFilesAnalyser API documentation for more details.

API

Warnings

type OptionalWarningName =
  | "synchronous-io"
  | "log-usage";

type WarningName =
  | "parsing-error"
  | "encoded-literal"
  | "unsafe-regex"
  | "unsafe-stmt"
  | "short-identifiers"
  | "suspicious-literal"
  | "suspicious-file"
  | "obfuscated-code"
  | "weak-crypto"
  | "shady-link"
  | "unsafe-command"
  | "unsafe-import"
  | "serialize-environment"
  | "data-exfiltration"
  | "sql-injection"
  | "monkey-patch"
  | OptionalWarningName;

interface Warning<T = WarningName> {
  kind: T | (string & {});
  file?: string;
  value: string | null;
  source: string;
  location: null | SourceArrayLocation | SourceArrayLocation[];
  i18n: string;
  severity: "Information" | "Warning" | "Critical";
  experimental?: boolean;
}

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

Optional Warnings

Some warnings are not included by default and must be explicitly requested through the AstAnalyser API.

import { AstAnalyser } from "@nodesecure/js-x-ray";

// Enable all optional warnings
const scanner = new AstAnalyser({
  optionalWarnings: true
});

// Or enable specific optional warnings
const scannerSpecific = new AstAnalyser({
  optionalWarnings: ["synchronous-io", "log-usage"]
});

The following warnings are optional:

  • synchronous-io - Detects synchronous I/O operations that could impact performance
  • log-usage - Tracks usage of logging functions (console.log, logger.info, etc.)

Internationalization (i18n)

Warnings support internationalization through the @nodesecure/i18n package. Each warning has an i18n key that can be used to retrieve localized descriptions.

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

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

Warning Catalog

Click on the warning name for detailed documentation and examples.

Critical Severity

Name Experimental Description
suspicious-file No Suspicious file containing more than ten encoded literals
obfuscated-code Yes High probability of code obfuscation detected

Warning Severity

Name Experimental Description
unsafe-import No Unable to follow an import (require, require.resolve) statement
unsafe-regex No Unsafe regular expression that may be vulnerable to ReDoS attacks
unsafe-stmt No Usage of dangerous statements like eval() or Function("")
unsafe-command Yes Suspicious commands detected in spawn() or exec()
short-identifiers No Average identifier length below 1.5 characters (possible obfuscation)
suspicious-literal No Suspicious literal values detected in source code
weak-crypto No Usage of weak cryptographic algorithms (MD5, SHA1, etc.)
shady-link No Suspicious or potentially malicious URLs detected
synchronous-io ⚠️ Yes Synchronous I/O operations that may impact performance
serialize-environment No Attempts to serialize process.env (potential data exfiltration)
data-exfiltration No Potential unauthorized transfer of sensitive data
sql-injection No Potential SQL injection vulnerability detected
monkey-patch No Modification of built-in JavaScript prototype properties

Information Severity

Name Experimental Description
parsing-error No AST parser encountered an error while analyzing the code
encoded-literal No Encoded literal detected (hexadecimal, Unicode, base64)
log-usage ⚠️ No Usage of logging functions (console.log, logger methods, etc.)

Note

Warnings marked with ⚠️ are optional and must be explicitly enabled (see Optional Warnings section).

Workspaces

Click on one of the links to access the documentation of the workspace:

name package and link
js-x-ray @nodesecure/js-x-ray
estree-ast-utils @nodesecure/estree-ast-utils
tracer @nodesecure/tracer
sec-literal @nodesecure/sec-literal
ts-source-parser @nodesecure/ts-source-parser

These packages are available in the Node package repository and can be easily installed with npm or yarn.

$ npm i @nodesecure/estree-ast-util
# or
$ yarn add @nodesecure/estree-ast-util

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

πŸ’» πŸ›
Kouadio Fabrice Nguessan
Kouadio Fabrice Nguessan

🚧 πŸ’»
Jean
Jean

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

πŸ’» ⚠️
mkarkkainen
mkarkkainen

πŸ’»
FredGuiou
FredGuiou

πŸ“– πŸ’»
Madina
Madina

πŸ’»
SairussDev
SairussDev

πŸ’»
Abdou-Raouf ATARMLA
Abdou-Raouf ATARMLA

πŸ’»
Clement Gombauld
Clement Gombauld

πŸ’» ⚠️
Ajāy
Ajāy

πŸ’»
Michael Mior
Michael Mior

πŸ“–
Hamed Mohamed
Hamed Mohamed

πŸ’»

License

MIT

About

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

Topics

Resources

License

Contributing

Security policy

Stars

Watchers

Forks

Contributors 31