@nodesecure/js-x-ray
TypeScript icon, indicating that this package has built-in type declarations

7.0.0 • Public • Published

@nodesecure/js-x-ray

npm version license ossf scorecard github ci workflow codecov

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 a set of security notions.

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 "node:fs";

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

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

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

[!TIP] 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

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

Custom Probes

You can also create custom probes to detect specific pattern in the code you are analyzing.

A probe is a pair of two functions (validateNode and main) that will be called on each node of the AST. It will return a warning if the pattern is detected. Below a basic probe that detect a string assignation to danger:

export const customProbes = [
  {
    name: "customProbeUnsafeDanger",
    validateNode: (node, sourceFile) => [
      node.type === "VariableDeclaration" && node.declarations[0].init.value === "danger"
    ],
    main: (node, options) => {
      const { sourceFile, data: calleeName } = options;
      if (node.declarations[0].init.value === "danger") {
        sourceFile.addWarning("unsafe-danger", calleeName, node.loc);

        return ProbeSignals.Skip;
      }

      return null;
    }
  }
];

You can pass an array of probes to the runASTAnalysis/runASTAnalysisOnFile functions as options, or directly to the AstAnalyser constructor.

Name Type Description Default Value
customParser SourceParser | undefined An optional custom parser to be used for parsing the source code. JsSourceParser
customProbes Probe[] | undefined An array of custom probes to be used during AST analysis. []
skipDefaultProbes boolean | undefined If true, default probes will be skipped and only custom probes will be used. false

Here using the example probe upper:

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

// add your customProbes here (see example above)

const result = runASTAnalysis("const danger = 'danger';", { customProbes, skipDefaultProbes: true });

console.log(result);

Result:

✗ node example.js
{
  idsLengthAvg: 0,
  stringScore: 0,
  warnings: [ { kind: 'unsafe-danger', location: [Array], source: 'JS-X-Ray' } ],
  dependencies: Map(0) {},
  isOneLineRequire: false
}

Congrats, you have created your first custom probe! 🎉

[!TIP] Check the types in index.d.ts and types/api.d.ts for more details about the options

API

runASTAnalysis(str: string, options?: RuntimeOptions & AstAnalyserOptions): Report
interface RuntimeOptions {
  module?: boolean;
  removeHTMLComments?: boolean;
  isMinified?: boolean;
}
interface AstAnalyserOptions {
  customParser?: SourceParser;
  customProbes?: Probe[];
  skipDefaultProbes?: 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 & AstAnalyserOptions): Promise< ReportOnFile >
interface RuntimeFileOptions {
  module?: boolean;
  removeHTMLComments?: boolean;
  packageName?: string;
}
interface AstAnalyserOptions {
  customParser?: SourceParser;
  customProbes?: Probe[];
  skipDefaultProbes?: 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[];
}

Workspaces

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

name package and link
estree-ast-utils @nodesecure/estree-ast-utils
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

💻

License

MIT

Package Sidebar

Install

npm i @nodesecure/js-x-ray

Weekly Downloads

98

Version

7.0.0

License

MIT

Unpacked Size

69.9 kB

Total Files

38

Last publish

Collaborators

  • pierred
  • antoine-coulon
  • kawacrepe
  • fraxken
  • tonygo