@nodesecure/js-x-ray 4.1.2 → 4.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,147 +1,148 @@
1
- # js-x-ray
2
- ![version](https://img.shields.io/badge/dynamic/json.svg?url=https://raw.githubusercontent.com/NodeSecure/js-x-ray/master/package.json&query=$.version&label=Version)
3
- [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/NodeSecure/js-x-ray/commit-activity)
4
- [![Security Responsible Disclosure](https://img.shields.io/badge/Security-Responsible%20Disclosure-yellow.svg)](https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md
5
- )
6
- [![mit](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/NodeSecure/js-x-ray/blob/master/LICENSE)
7
- ![build](https://img.shields.io/github/workflow/status/NodeSecure/js-x-ray/Node.js%20CI)
8
-
9
- JavaScript AST analysis. This package has been created to export the [Node-Secure](https://github.com/ES-Community/nsecure) AST Analysis to enable better code evolution and allow better access to developers and researchers.
10
-
11
- 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.
12
-
13
- > 💖 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).
14
-
15
- ## Goals
16
- 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..
17
-
18
- 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..
19
-
20
- ## Features Highlight
21
- - Retrieve required dependencies and files for Node.js.
22
- - Detect unsafe RegEx.
23
- - Get warnings when the AST Analysis as a problem or when not able to follow a statement.
24
- - Highlight common attack patterns and API usages.
25
- - Capable to follow the usage of dangerous Node.js globals.
26
- - Detect obfuscated code and when possible the tool that has been used.
27
-
28
- ## Getting Started
29
-
30
- This package is available in the Node Package Repository and can be easily installed with [npm](https://docs.npmjs.com/getting-started/what-is-npm) or [yarn](https://yarnpkg.com).
31
-
32
- ```bash
33
- $ npm i @nodesecure/js-x-ray
34
- # or
35
- $ yarn add @nodesecure/js-x-ray
36
- ```
37
-
38
- ## Usage example
39
-
40
- Create a local `.js` file with the following content:
41
- ```js
42
- try {
43
- require("http");
44
- }
45
- catch (err) {
46
- // do nothing
47
- }
48
- const lib = "crypto";
49
- require(lib);
50
- require("util");
51
- require(Buffer.from("6673", "hex").toString());
52
- ```
53
-
54
- ---
55
-
56
- Then use `js-x-ray` to run an analysis of the JavaScript code:
57
- ```js
58
- import { runASTAnalysis } from "@nodesecure/js-x-ray";
59
- import { readFileSync } from "fs";
60
-
61
- const str = readFileSync("./file.js", "utf-8");
62
- const { warnings, dependencies } = runASTAnalysis(str);
63
-
64
- const dependenciesName = [...dependencies];
65
- const inTryDeps = [...dependencies.getDependenciesInTryStatement()];
66
-
67
- console.log(dependenciesName);
68
- console.log(inTryDeps);
69
- console.log(warnings);
70
- ```
71
-
72
- The analysis will return: `http` (in try), `crypto`, `util` and `fs`.
73
-
74
- > ⚠️ There is also a lot of suspicious code example in the root cases directory. Feel free to try the tool on these files.
75
-
76
- ## Warnings Legends (v2.0+)
77
-
78
- > Node-secure versions equal or lower than 0.7.0 are no longer compatible with the warnings table below.
79
-
80
- This section describe all the possible warnings returned by JSXRay.
81
-
82
- | name | description |
83
- | --- | --- |
84
- | parsing-error | An error occured when parsing the JavaScript code with meriyah. It mean that the conversion from string to AST as failed. If you encounter such an error, **please open an issue here**. |
85
- | unsafe-import | Unable to follow an import (require, require.resolve) statement/expr. |
86
- | unsafe-regex | A RegEx as been detected as unsafe and may be used for a ReDoS Attack. |
87
- | unsafe-stmt | Usage of dangerous statement like `eval()` or `Function("")`. |
88
- | unsafe-assign | Assignment of a protected global like `process` or `require`. |
89
- | encoded-literal | An encoded literal has been detected (it can be an hexa value, unicode sequence, base64 string etc) |
90
- | short-identifiers | This mean that all identifiers has an average length below 1.5. Only possible if the file contains more than 5 identifiers. |
91
- | suspicious-literal | This mean that the sum of suspicious score of all Literals is bigger than 3. |
92
- | obfuscated-code (**experimental**) | There's a very high probability that the code is obfuscated... |
93
-
94
- > 👀 More details on warnings and their implementations [here](./WARNINGS.md)
95
-
96
- ## API
97
-
98
- <details>
99
- <summary>runASTAnalysis(str: string, options?: RuntimeOptions): Report</summary>
100
-
101
- ```ts
102
- interface RuntimeOptions {
103
- module?: boolean;
104
- isMinified?: boolean;
105
- }
106
- ```
107
-
108
- The method take a first argument which is the code you want to analyse. It will return a Report Object:
109
-
110
- ```ts
111
- interface Report {
112
- dependencies: ASTDeps;
113
- warnings: Warning<BaseWarning>[];
114
- idsLengthAvg: number;
115
- stringScore: number;
116
- isOneLineRequire: boolean;
117
- }
118
- ```
119
-
120
- </details>
121
-
122
-
123
- ## Contributors ✨
124
-
125
- <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
126
- [![All Contributors](https://img.shields.io/badge/all_contributors-2-orange.svg?style=flat-square)](#contributors-)
127
- <!-- ALL-CONTRIBUTORS-BADGE:END -->
128
-
129
- Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
130
-
131
- <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
132
- <!-- prettier-ignore-start -->
133
- <!-- markdownlint-disable -->
134
- <table>
135
- <tr>
136
- <td align="center"><a href="https://www.linkedin.com/in/thomas-gentilhomme/"><img src="https://avatars.githubusercontent.com/u/4438263?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Gentilhomme</b></sub></a><br /><a href="https://github.com/NodeSecure/js-x-ray/commits?author=fraxken" title="Code">💻</a> <a href="https://github.com/NodeSecure/js-x-ray/commits?author=fraxken" title="Documentation">📖</a> <a href="https://github.com/NodeSecure/js-x-ray/pulls?q=is%3Apr+reviewed-by%3Afraxken" title="Reviewed Pull Requests">👀</a> <a href="#security-fraxken" title="Security">🛡️</a> <a href="https://github.com/NodeSecure/js-x-ray/issues?q=author%3Afraxken" title="Bug reports">🐛</a></td>
137
- <td align="center"><a href="https://github.com/Rossb0b"><img src="https://avatars.githubusercontent.com/u/39910164?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Nicolas Hallaert</b></sub></a><br /><a href="https://github.com/NodeSecure/js-x-ray/commits?author=Rossb0b" title="Documentation">📖</a></td>
138
- </tr>
139
- </table>
140
-
141
- <!-- markdownlint-restore -->
142
- <!-- prettier-ignore-end -->
143
-
144
- <!-- ALL-CONTRIBUTORS-LIST:END -->
145
-
146
- ## License
147
- MIT
1
+ # js-x-ray
2
+ ![version](https://img.shields.io/badge/dynamic/json.svg?url=https://raw.githubusercontent.com/NodeSecure/js-x-ray/master/package.json&query=$.version&label=Version)
3
+ [![Maintenance](https://img.shields.io/badge/Maintained%3F-yes-green.svg)](https://github.com/NodeSecure/js-x-ray/commit-activity)
4
+ [![Security Responsible Disclosure](https://img.shields.io/badge/Security-Responsible%20Disclosure-yellow.svg)](https://github.com/nodejs/security-wg/blob/master/processes/responsible_disclosure_template.md
5
+ )
6
+ [![mit](https://img.shields.io/github/license/Naereen/StrapDown.js.svg)](https://github.com/NodeSecure/js-x-ray/blob/master/LICENSE)
7
+ ![build](https://img.shields.io/github/workflow/status/NodeSecure/js-x-ray/Node.js%20CI)
8
+
9
+ JavaScript AST analysis. This package has been created to export the [Node-Secure](https://github.com/ES-Community/nsecure) AST Analysis to enable better code evolution and allow better access to developers and researchers.
10
+
11
+ 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.
12
+
13
+ > 💖 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).
14
+
15
+ ## Goals
16
+ 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..
17
+
18
+ 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..
19
+
20
+ ## Features Highlight
21
+ - Retrieve required dependencies and files for Node.js.
22
+ - Detect unsafe RegEx.
23
+ - Get warnings when the AST Analysis as a problem or when not able to follow a statement.
24
+ - Highlight common attack patterns and API usages.
25
+ - Capable to follow the usage of dangerous Node.js globals.
26
+ - Detect obfuscated code and when possible the tool that has been used.
27
+
28
+ ## Getting Started
29
+
30
+ This package is available in the Node Package Repository and can be easily installed with [npm](https://docs.npmjs.com/getting-started/what-is-npm) or [yarn](https://yarnpkg.com).
31
+
32
+ ```bash
33
+ $ npm i @nodesecure/js-x-ray
34
+ # or
35
+ $ yarn add @nodesecure/js-x-ray
36
+ ```
37
+
38
+ ## Usage example
39
+
40
+ Create a local `.js` file with the following content:
41
+ ```js
42
+ try {
43
+ require("http");
44
+ }
45
+ catch (err) {
46
+ // do nothing
47
+ }
48
+ const lib = "crypto";
49
+ require(lib);
50
+ require("util");
51
+ require(Buffer.from("6673", "hex").toString());
52
+ ```
53
+
54
+ ---
55
+
56
+ Then use `js-x-ray` to run an analysis of the JavaScript code:
57
+ ```js
58
+ import { runASTAnalysis } from "@nodesecure/js-x-ray";
59
+ import { readFileSync } from "fs";
60
+
61
+ const str = readFileSync("./file.js", "utf-8");
62
+ const { warnings, dependencies } = runASTAnalysis(str);
63
+
64
+ const dependenciesName = [...dependencies];
65
+ const inTryDeps = [...dependencies.getDependenciesInTryStatement()];
66
+
67
+ console.log(dependenciesName);
68
+ console.log(inTryDeps);
69
+ console.log(warnings);
70
+ ```
71
+
72
+ The analysis will return: `http` (in try), `crypto`, `util` and `fs`.
73
+
74
+ > ⚠️ There is also a lot of suspicious code example in the root cases directory. Feel free to try the tool on these files.
75
+
76
+ ## Warnings Legends (v2.0+)
77
+
78
+ > Node-secure versions equal or lower than 0.7.0 are no longer compatible with the warnings table below.
79
+
80
+ This section describe all the possible warnings returned by JSXRay.
81
+
82
+ | name | description |
83
+ | --- | --- |
84
+ | parsing-error | An error occured when parsing the JavaScript code with meriyah. It mean that the conversion from string to AST as failed. If you encounter such an error, **please open an issue here**. |
85
+ | unsafe-import | Unable to follow an import (require, require.resolve) statement/expr. |
86
+ | unsafe-regex | A RegEx as been detected as unsafe and may be used for a ReDoS Attack. |
87
+ | unsafe-stmt | Usage of dangerous statement like `eval()` or `Function("")`. |
88
+ | unsafe-assign | Assignment of a protected global like `process` or `require`. |
89
+ | encoded-literal | An encoded literal has been detected (it can be an hexa value, unicode sequence, base64 string etc) |
90
+ | short-identifiers | This mean that all identifiers has an average length below 1.5. Only possible if the file contains more than 5 identifiers. |
91
+ | suspicious-literal | This mean that the sum of suspicious score of all Literals is bigger than 3. |
92
+ | obfuscated-code (**experimental**) | There's a very high probability that the code is obfuscated... |
93
+
94
+ > 👀 More details on warnings and their implementations [here](./WARNINGS.md)
95
+
96
+ ## API
97
+
98
+ <details>
99
+ <summary>runASTAnalysis(str: string, options?: RuntimeOptions): Report</summary>
100
+
101
+ ```ts
102
+ interface RuntimeOptions {
103
+ module?: boolean;
104
+ isMinified?: boolean;
105
+ }
106
+ ```
107
+
108
+ The method take a first argument which is the code you want to analyse. It will return a Report Object:
109
+
110
+ ```ts
111
+ interface Report {
112
+ dependencies: ASTDeps;
113
+ warnings: Warning<BaseWarning>[];
114
+ idsLengthAvg: number;
115
+ stringScore: number;
116
+ isOneLineRequire: boolean;
117
+ }
118
+ ```
119
+
120
+ </details>
121
+
122
+
123
+ ## Contributors ✨
124
+
125
+ <!-- ALL-CONTRIBUTORS-BADGE:START - Do not remove or modify this section -->
126
+ [![All Contributors](https://img.shields.io/badge/all_contributors-3-orange.svg?style=flat-square)](#contributors-)
127
+ <!-- ALL-CONTRIBUTORS-BADGE:END -->
128
+
129
+ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/docs/en/emoji-key)):
130
+
131
+ <!-- ALL-CONTRIBUTORS-LIST:START - Do not remove or modify this section -->
132
+ <!-- prettier-ignore-start -->
133
+ <!-- markdownlint-disable -->
134
+ <table>
135
+ <tr>
136
+ <td align="center"><a href="https://www.linkedin.com/in/thomas-gentilhomme/"><img src="https://avatars.githubusercontent.com/u/4438263?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Gentilhomme</b></sub></a><br /><a href="https://github.com/NodeSecure/js-x-ray/commits?author=fraxken" title="Code">💻</a> <a href="https://github.com/NodeSecure/js-x-ray/commits?author=fraxken" title="Documentation">📖</a> <a href="https://github.com/NodeSecure/js-x-ray/pulls?q=is%3Apr+reviewed-by%3Afraxken" title="Reviewed Pull Requests">👀</a> <a href="#security-fraxken" title="Security">🛡️</a> <a href="https://github.com/NodeSecure/js-x-ray/issues?q=author%3Afraxken" title="Bug reports">🐛</a></td>
137
+ <td align="center"><a href="https://github.com/Rossb0b"><img src="https://avatars.githubusercontent.com/u/39910164?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Nicolas Hallaert</b></sub></a><br /><a href="https://github.com/NodeSecure/js-x-ray/commits?author=Rossb0b" title="Documentation">📖</a></td>
138
+ <td align="center"><a href="https://github.com/antoine-coulon"><img src="https://avatars.githubusercontent.com/u/43391199?v=4?s=100" width="100px;" alt=""/><br /><sub><b>Antoine</b></sub></a><br /><a href="https://github.com/NodeSecure/js-x-ray/commits?author=antoine-coulon" title="Code">💻</a></td>
139
+ </tr>
140
+ </table>
141
+
142
+ <!-- markdownlint-restore -->
143
+ <!-- prettier-ignore-end -->
144
+
145
+ <!-- ALL-CONTRIBUTORS-LIST:END -->
146
+
147
+ ## License
148
+ MIT
package/index.js CHANGED
@@ -1,92 +1,93 @@
1
- // Import Node.js Dependencies
2
- import fs from "fs/promises";
3
- import path from "path";
4
-
5
- // Import Third-party Dependencies
6
- import { walk } from "estree-walker";
7
- import * as meriyah from "meriyah";
8
- import isMinified from "is-minified-code";
9
-
10
- // Import Internal Dependencies
11
- import Analysis from "./src/Analysis.js";
12
-
13
- export function runASTAnalysis(str, options = Object.create(null)) {
14
- const { module = true, isMinified = false } = options;
15
-
16
- // Note: if the file start with a shebang then we remove it because 'parseScript' may fail to parse it.
17
- // Example: #!/usr/bin/env node
18
- const strToAnalyze = str.charAt(0) === "#" ? str.slice(str.indexOf("\n")) : str;
19
- const { body } = meriyah.parseScript(strToAnalyze, {
20
- next: true, loc: true, raw: true, module: Boolean(module)
21
- });
22
-
23
- const sastAnalysis = new Analysis();
24
-
25
- // we walk each AST Nodes, this is a purely synchronous I/O
26
- walk(body, {
27
- enter(node) {
28
- // Skip the root of the AST.
29
- if (Array.isArray(node)) {
30
- return;
31
- }
32
-
33
- const action = sastAnalysis.walk(node);
34
- if (action === "skip") {
35
- this.skip();
36
- }
37
- }
38
- });
39
-
40
- const dependencies = sastAnalysis.dependencies;
41
- const { idsLengthAvg, stringScore, warnings } = sastAnalysis.getResult(isMinified);
42
- const isOneLineRequire = body.length <= 1 && dependencies.size <= 1;
43
-
44
- return {
45
- dependencies, warnings, idsLengthAvg, stringScore, isOneLineRequire
46
- };
47
- }
48
-
49
- export async function runASTAnalysisOnFile(pathToFile, options = {}) {
50
- try {
51
- const { packageName = null, module = true } = options;
52
- const str = await fs.readFile(pathToFile, "utf-8");
53
-
54
- const isMin = pathToFile.includes(".min") || isMinified(str);
55
- const data = runASTAnalysis(str, {
56
- isMinified: isMin,
57
- module: path.extname(pathToFile) === ".mjs" ? true : module
58
- });
59
- if (packageName !== null) {
60
- data.dependencies.removeByName(packageName);
61
- }
62
-
63
- return {
64
- ok: true,
65
- dependencies: data.dependencies,
66
- warnings: data.warnings,
67
- isMinified: !data.isOneLineRequire && isMin
68
- };
69
- }
70
- catch (error) {
71
- return {
72
- ok: false,
73
- warnings: [
74
- { kind: "parsing-error", value: error.message, location: [[0, 0], [0, 0]] }
75
- ]
76
- };
77
- }
78
- }
79
-
80
- export const CONSTANTS = {
81
- Warnings: Object.freeze({
82
- parsingError: "ast-error",
83
- unsafeImport: "unsafe-import",
84
- unsafeRegex: "unsafe-regex",
85
- unsafeStmt: "unsafe-stmt",
86
- unsafeAssign: "unsafe-assign",
87
- encodedLiteral: "encoded-literal",
88
- shortIdentifiers: "short-identifiers",
89
- suspiciousLiteral: "suspicious-literal",
90
- obfuscatedCode: "obfuscated-code"
91
- })
92
- };
1
+ // Import Node.js Dependencies
2
+ import fs from "fs/promises";
3
+ import path from "path";
4
+
5
+ // Import Third-party Dependencies
6
+ import { walk } from "estree-walker";
7
+ import * as meriyah from "meriyah";
8
+ import isMinified from "is-minified-code";
9
+
10
+ // Import Internal Dependencies
11
+ import Analysis from "./src/Analysis.js";
12
+
13
+ export function runASTAnalysis(str, options = Object.create(null)) {
14
+ const { module = true, isMinified = false } = options;
15
+
16
+ // Note: if the file start with a shebang then we remove it because 'parseScript' may fail to parse it.
17
+ // Example: #!/usr/bin/env node
18
+ const strToAnalyze = str.charAt(0) === "#" ? str.slice(str.indexOf("\n")) : str;
19
+ const { body } = meriyah.parseScript(strToAnalyze, {
20
+ next: true, loc: true, raw: true, module: Boolean(module)
21
+ });
22
+
23
+ const sastAnalysis = new Analysis();
24
+ sastAnalysis.analyzeSourceString(str);
25
+
26
+ // we walk each AST Nodes, this is a purely synchronous I/O
27
+ walk(body, {
28
+ enter(node) {
29
+ // Skip the root of the AST.
30
+ if (Array.isArray(node)) {
31
+ return;
32
+ }
33
+
34
+ const action = sastAnalysis.walk(node);
35
+ if (action === "skip") {
36
+ this.skip();
37
+ }
38
+ }
39
+ });
40
+
41
+ const dependencies = sastAnalysis.dependencies;
42
+ const { idsLengthAvg, stringScore, warnings } = sastAnalysis.getResult(isMinified);
43
+ const isOneLineRequire = body.length <= 1 && dependencies.size <= 1;
44
+
45
+ return {
46
+ dependencies, warnings, idsLengthAvg, stringScore, isOneLineRequire
47
+ };
48
+ }
49
+
50
+ export async function runASTAnalysisOnFile(pathToFile, options = {}) {
51
+ try {
52
+ const { packageName = null, module = true } = options;
53
+ const str = await fs.readFile(pathToFile, "utf-8");
54
+
55
+ const isMin = pathToFile.includes(".min") || isMinified(str);
56
+ const data = runASTAnalysis(str, {
57
+ isMinified: isMin,
58
+ module: path.extname(pathToFile) === ".mjs" ? true : module
59
+ });
60
+ if (packageName !== null) {
61
+ data.dependencies.removeByName(packageName);
62
+ }
63
+
64
+ return {
65
+ ok: true,
66
+ dependencies: data.dependencies,
67
+ warnings: data.warnings,
68
+ isMinified: !data.isOneLineRequire && isMin
69
+ };
70
+ }
71
+ catch (error) {
72
+ return {
73
+ ok: false,
74
+ warnings: [
75
+ { kind: "parsing-error", value: error.message, location: [[0, 0], [0, 0]] }
76
+ ]
77
+ };
78
+ }
79
+ }
80
+
81
+ export const CONSTANTS = {
82
+ Warnings: Object.freeze({
83
+ parsingError: "ast-error",
84
+ unsafeImport: "unsafe-import",
85
+ unsafeRegex: "unsafe-regex",
86
+ unsafeStmt: "unsafe-stmt",
87
+ unsafeAssign: "unsafe-assign",
88
+ encodedLiteral: "encoded-literal",
89
+ shortIdentifiers: "short-identifiers",
90
+ suspiciousLiteral: "suspicious-literal",
91
+ obfuscatedCode: "obfuscated-code"
92
+ })
93
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nodesecure/js-x-ray",
3
- "version": "4.1.2",
3
+ "version": "4.2.0",
4
4
  "description": "JavaScript AST XRay analysis",
5
5
  "type": "module",
6
6
  "exports": "./index.js",
@@ -37,7 +37,7 @@
37
37
  },
38
38
  "homepage": "https://github.com/NodeSecure/js-x-ray#readme",
39
39
  "dependencies": {
40
- "@nodesecure/sec-literal": "^1.0.0",
40
+ "@nodesecure/sec-literal": "^1.0.1",
41
41
  "estree-walker": "^3.0.0",
42
42
  "is-minified-code": "^2.0.0",
43
43
  "meriyah": "^4.2.0",
@@ -48,10 +48,10 @@
48
48
  "@slimio/is": "^1.5.1",
49
49
  "@small-tech/esm-tape-runner": "^1.0.3",
50
50
  "@small-tech/tap-monkey": "^1.3.0",
51
- "@types/node": "^16.11.7",
51
+ "@types/node": "^16.11.10",
52
52
  "cross-env": "^7.0.3",
53
- "eslint": "^8.2.0",
53
+ "eslint": "^8.3.0",
54
54
  "pkg-ok": "^2.3.1",
55
- "tape": "^5.3.1"
55
+ "tape": "^5.3.2"
56
56
  }
57
57
  }
package/src/Analysis.js CHANGED
@@ -1,146 +1,152 @@
1
- // Import Third-party Dependencies
2
- import { Utils, Literal } from "@nodesecure/sec-literal";
3
-
4
- // Import Internal Dependencies
5
- import { rootLocation, toArrayLocation, generateWarning } from "./utils.js";
6
- import { warnings as _warnings, processMainModuleRequire } from "./constants.js";
7
- import ASTDeps from "./ASTDeps.js";
8
- import { isObfuscatedCode } from "./obfuscators/index.js";
9
- import { runOnProbes } from "./probes/index.js";
10
-
11
- // CONSTANTS
12
- const kDictionaryStrParts = [
13
- "abcdefghijklmnopqrstuvwxyz",
14
- "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
15
- "0123456789"
16
- ];
17
-
18
- const kWarningsNameStr = Object.freeze({
19
- [_warnings.parsingError]: "parsing-error",
20
- [_warnings.unsafeImport]: "unsafe-import",
21
- [_warnings.unsafeRegex]: "unsafe-regex",
22
- [_warnings.unsafeStmt]: "unsafe-stmt",
23
- [_warnings.unsafeAssign]: "unsafe-assign",
24
- [_warnings.encodedLiteral]: "encoded-literal",
25
- [_warnings.shortIdentifiers]: "short-identifiers",
26
- [_warnings.suspiciousLiteral]: "suspicious-literal",
27
- [_warnings.obfuscatedCode]: "obfuscated-code"
28
- });
29
-
30
- export default class Analysis {
31
- hasDictionaryString = false;
32
- hasPrefixedIdentifiers = false;
33
- varkinds = { var: 0, let: 0, const: 0 };
34
- idtypes = { assignExpr: 0, property: 0, variableDeclarator: 0, functionDeclaration: 0 };
35
- counter = {
36
- identifiers: 0,
37
- doubleUnaryArray: 0,
38
- computedMemberExpr: 0,
39
- memberExpr: 0,
40
- deepBinaryExpr: 0,
41
- encodedArrayValue: 0,
42
- morseLiteral: 0
43
- };
44
- identifiersName = [];
45
-
46
- constructor() {
47
- this.dependencies = new ASTDeps();
48
-
49
- this.identifiers = new Map();
50
- this.globalParts = new Map();
51
- this.handledEncodedLiteralValues = new Map();
52
-
53
- this.requireIdentifiers = new Set(["require", processMainModuleRequire]);
54
- this.warnings = [];
55
- this.literalScores = [];
56
- }
57
-
58
- addWarning(symbol, value, location = rootLocation()) {
59
- if (symbol === _warnings.encodedLiteral && this.handledEncodedLiteralValues.has(value)) {
60
- const index = this.handledEncodedLiteralValues.get(value);
61
- this.warnings[index].location.push(toArrayLocation(location));
62
-
63
- return;
64
- }
65
- const warningName = kWarningsNameStr[symbol];
66
- this.warnings.push(generateWarning(warningName, { value, location }));
67
- if (symbol === _warnings.encodedLiteral) {
68
- this.handledEncodedLiteralValues.set(value, this.warnings.length - 1);
69
- }
70
- }
71
-
72
- analyzeString(str) {
73
- const score = Utils.stringSuspicionScore(str);
74
- if (score !== 0) {
75
- this.literalScores.push(score);
76
- }
77
-
78
- if (!this.hasDictionaryString) {
79
- const isDictionaryStr = kDictionaryStrParts.every((word) => str.includes(word));
80
- if (isDictionaryStr) {
81
- this.hasDictionaryString = true;
82
- }
83
- }
84
-
85
- // Searching for morse string like "--.- --.--."
86
- if (Utils.stringCharDiversity(str, ["\n"]) >= 3 && Utils.isMorse(str)) {
87
- this.counter.morseLiteral++;
88
- }
89
- }
90
-
91
- analyzeLiteral(node, inArrayExpr = false) {
92
- if (typeof node.value !== "string" || Utils.isSvg(node)) {
93
- return;
94
- }
95
- this.analyzeString(node.value);
96
-
97
- const { hasHexadecimalSequence, hasUnicodeSequence, isBase64 } = Literal.defaultAnalysis(node);
98
- if ((hasHexadecimalSequence || hasUnicodeSequence) && isBase64) {
99
- if (inArrayExpr) {
100
- this.counter.encodedArrayValue++;
101
- }
102
- else {
103
- this.addWarning(_warnings.encodedLiteral, node.value, node.loc);
104
- }
105
- }
106
- }
107
-
108
- getResult(isMinified) {
109
- this.counter.identifiers = this.identifiersName.length;
110
- const [isObfuscated, kind] = isObfuscatedCode(this);
111
- if (isObfuscated) {
112
- this.addWarning(_warnings.obfuscatedCode, kind || "unknown");
113
- }
114
-
115
- const identifiersLengthArr = this.identifiersName
116
- .filter((value) => value.type !== "property" && typeof value.name === "string").map((value) => value.name.length);
117
-
118
- const [idsLengthAvg, stringScore] = [sum(identifiersLengthArr), sum(this.literalScores)];
119
- if (!isMinified && identifiersLengthArr.length > 5 && idsLengthAvg <= 1.5) {
120
- this.addWarning(_warnings.shortIdentifiers, idsLengthAvg);
121
- }
122
- if (stringScore >= 3) {
123
- this.addWarning(_warnings.suspiciousLiteral, stringScore);
124
- }
125
-
126
- return { idsLengthAvg, stringScore, warnings: this.warnings };
127
- }
128
-
129
- walk(node) {
130
- // Detect TryStatement and CatchClause to known which dependency is required in a Try {} clause
131
- if (node.type === "TryStatement" && typeof node.handler !== "undefined") {
132
- this.dependencies.isInTryStmt = true;
133
- }
134
- else if (node.type === "CatchClause") {
135
- this.dependencies.isInTryStmt = false;
136
- }
137
-
138
- return runOnProbes(node, this);
139
- }
140
- }
141
-
142
- function sum(arr = []) {
143
- return arr.length === 0 ? 0 : (arr.reduce((prev, curr) => prev + curr, 0) / arr.length);
144
- }
145
-
146
- Analysis.Warnings = _warnings;
1
+ // Import Third-party Dependencies
2
+ import { Utils, Literal } from "@nodesecure/sec-literal";
3
+
4
+ // Import Internal Dependencies
5
+ import { rootLocation, toArrayLocation, generateWarning } from "./utils.js";
6
+ import { warnings as _warnings, processMainModuleRequire } from "./constants.js";
7
+ import ASTDeps from "./ASTDeps.js";
8
+ import { isObfuscatedCode, hasTrojanSource } from "./obfuscators/index.js";
9
+ import { runOnProbes } from "./probes/index.js";
10
+
11
+ // CONSTANTS
12
+ const kDictionaryStrParts = [
13
+ "abcdefghijklmnopqrstuvwxyz",
14
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ",
15
+ "0123456789"
16
+ ];
17
+
18
+ const kWarningsNameStr = Object.freeze({
19
+ [_warnings.parsingError]: "parsing-error",
20
+ [_warnings.unsafeImport]: "unsafe-import",
21
+ [_warnings.unsafeRegex]: "unsafe-regex",
22
+ [_warnings.unsafeStmt]: "unsafe-stmt",
23
+ [_warnings.unsafeAssign]: "unsafe-assign",
24
+ [_warnings.encodedLiteral]: "encoded-literal",
25
+ [_warnings.shortIdentifiers]: "short-identifiers",
26
+ [_warnings.suspiciousLiteral]: "suspicious-literal",
27
+ [_warnings.obfuscatedCode]: "obfuscated-code"
28
+ });
29
+
30
+ export default class Analysis {
31
+ hasDictionaryString = false;
32
+ hasPrefixedIdentifiers = false;
33
+ varkinds = { var: 0, let: 0, const: 0 };
34
+ idtypes = { assignExpr: 0, property: 0, variableDeclarator: 0, functionDeclaration: 0 };
35
+ counter = {
36
+ identifiers: 0,
37
+ doubleUnaryArray: 0,
38
+ computedMemberExpr: 0,
39
+ memberExpr: 0,
40
+ deepBinaryExpr: 0,
41
+ encodedArrayValue: 0,
42
+ morseLiteral: 0
43
+ };
44
+ identifiersName = [];
45
+
46
+ constructor() {
47
+ this.dependencies = new ASTDeps();
48
+
49
+ this.identifiers = new Map();
50
+ this.globalParts = new Map();
51
+ this.handledEncodedLiteralValues = new Map();
52
+
53
+ this.requireIdentifiers = new Set(["require", processMainModuleRequire]);
54
+ this.warnings = [];
55
+ this.literalScores = [];
56
+ }
57
+
58
+ addWarning(symbol, value, location = rootLocation()) {
59
+ if (symbol === _warnings.encodedLiteral && this.handledEncodedLiteralValues.has(value)) {
60
+ const index = this.handledEncodedLiteralValues.get(value);
61
+ this.warnings[index].location.push(toArrayLocation(location));
62
+
63
+ return;
64
+ }
65
+ const warningName = kWarningsNameStr[symbol];
66
+ this.warnings.push(generateWarning(warningName, { value, location }));
67
+ if (symbol === _warnings.encodedLiteral) {
68
+ this.handledEncodedLiteralValues.set(value, this.warnings.length - 1);
69
+ }
70
+ }
71
+
72
+ analyzeSourceString(sourceString) {
73
+ if (hasTrojanSource(sourceString)) {
74
+ this.addWarning(_warnings.obfuscatedCode, "trojan-source");
75
+ }
76
+ }
77
+
78
+ analyzeString(str) {
79
+ const score = Utils.stringSuspicionScore(str);
80
+ if (score !== 0) {
81
+ this.literalScores.push(score);
82
+ }
83
+
84
+ if (!this.hasDictionaryString) {
85
+ const isDictionaryStr = kDictionaryStrParts.every((word) => str.includes(word));
86
+ if (isDictionaryStr) {
87
+ this.hasDictionaryString = true;
88
+ }
89
+ }
90
+
91
+ // Searching for morse string like "--.- --.--."
92
+ if (Utils.stringCharDiversity(str, ["\n"]) >= 3 && Utils.isMorse(str)) {
93
+ this.counter.morseLiteral++;
94
+ }
95
+ }
96
+
97
+ analyzeLiteral(node, inArrayExpr = false) {
98
+ if (typeof node.value !== "string" || Utils.isSvg(node)) {
99
+ return;
100
+ }
101
+ this.analyzeString(node.value);
102
+
103
+ const { hasHexadecimalSequence, hasUnicodeSequence, isBase64 } = Literal.defaultAnalysis(node);
104
+ if ((hasHexadecimalSequence || hasUnicodeSequence) && isBase64) {
105
+ if (inArrayExpr) {
106
+ this.counter.encodedArrayValue++;
107
+ }
108
+ else {
109
+ this.addWarning(_warnings.encodedLiteral, node.value, node.loc);
110
+ }
111
+ }
112
+ }
113
+
114
+ getResult(isMinified) {
115
+ this.counter.identifiers = this.identifiersName.length;
116
+ const [isObfuscated, kind] = isObfuscatedCode(this);
117
+ if (isObfuscated) {
118
+ this.addWarning(_warnings.obfuscatedCode, kind || "unknown");
119
+ }
120
+
121
+ const identifiersLengthArr = this.identifiersName
122
+ .filter((value) => value.type !== "property" && typeof value.name === "string").map((value) => value.name.length);
123
+
124
+ const [idsLengthAvg, stringScore] = [sum(identifiersLengthArr), sum(this.literalScores)];
125
+ if (!isMinified && identifiersLengthArr.length > 5 && idsLengthAvg <= 1.5) {
126
+ this.addWarning(_warnings.shortIdentifiers, idsLengthAvg);
127
+ }
128
+ if (stringScore >= 3) {
129
+ this.addWarning(_warnings.suspiciousLiteral, stringScore);
130
+ }
131
+
132
+ return { idsLengthAvg, stringScore, warnings: this.warnings };
133
+ }
134
+
135
+ walk(node) {
136
+ // Detect TryStatement and CatchClause to known which dependency is required in a Try {} clause
137
+ if (node.type === "TryStatement" && typeof node.handler !== "undefined") {
138
+ this.dependencies.isInTryStmt = true;
139
+ }
140
+ else if (node.type === "CatchClause") {
141
+ this.dependencies.isInTryStmt = false;
142
+ }
143
+
144
+ return runOnProbes(node, this);
145
+ }
146
+ }
147
+
148
+ function sum(arr = []) {
149
+ return arr.length === 0 ? 0 : (arr.reduce((prev, curr) => prev + curr, 0) / arr.length);
150
+ }
151
+
152
+ Analysis.Warnings = _warnings;
package/src/constants.js CHANGED
@@ -1,28 +1,47 @@
1
- /**
2
- * This is one of the way to get a valid require.
3
- *
4
- * @see https://nodejs.org/api/process.html#process_process_mainmodule
5
- */
6
- export const processMainModuleRequire = "process.mainModule.require";
7
-
8
- /**
9
- * JavaScript dangerous global identifiers that can be used by hackers
10
- */
11
- export const globalIdentifiers = new Set(["global", "globalThis", "root", "GLOBAL", "window"]);
12
-
13
- /**
14
- * Dangerous Global identifiers parts
15
- */
16
- export const globalParts = new Set([...globalIdentifiers, "process", "mainModule", "require"]);
17
-
18
- export const warnings = Object.freeze({
19
- parsingError: Symbol("ParsingError"),
20
- unsafeImport: Symbol("UnsafeImport"),
21
- unsafeRegex: Symbol("UnsafeRegex"),
22
- unsafeStmt: Symbol("UnsafeStmt"),
23
- unsafeAssign: Symbol("UnsafeAssign"),
24
- encodedLiteral: Symbol("EncodedLiteral"),
25
- shortIdentifiers: Symbol("ShortIdentifiers"),
26
- suspiciousLiteral: Symbol("SuspiciousLiteral"),
27
- obfuscatedCode: Symbol("ObfuscatedCode")
28
- });
1
+ /**
2
+ * This is one of the way to get a valid require.
3
+ *
4
+ * @see https://nodejs.org/api/process.html#process_process_mainmodule
5
+ */
6
+ export const processMainModuleRequire = "process.mainModule.require";
7
+
8
+ /**
9
+ * JavaScript dangerous global identifiers that can be used by hackers
10
+ */
11
+ export const globalIdentifiers = new Set(["global", "globalThis", "root", "GLOBAL", "window"]);
12
+
13
+ /**
14
+ * Dangerous Global identifiers parts
15
+ */
16
+ export const globalParts = new Set([...globalIdentifiers, "process", "mainModule", "require"]);
17
+
18
+ /**
19
+ * Dangerous Unicode control characters that can be used by hackers
20
+ * to perform trojan source.
21
+ */
22
+ export const unsafeUnicodeControlCharacters = [
23
+ "\u202A",
24
+ "\u202B",
25
+ "\u202D",
26
+ "\u202E",
27
+ "\u202C",
28
+ "\u2066",
29
+ "\u2067",
30
+ "\u2068",
31
+ "\u2069",
32
+ "\u200E",
33
+ "\u200F",
34
+ "\u061C"
35
+ ];
36
+
37
+ export const warnings = Object.freeze({
38
+ parsingError: Symbol("ParsingError"),
39
+ unsafeImport: Symbol("UnsafeImport"),
40
+ unsafeRegex: Symbol("UnsafeRegex"),
41
+ unsafeStmt: Symbol("UnsafeStmt"),
42
+ unsafeAssign: Symbol("UnsafeAssign"),
43
+ encodedLiteral: Symbol("EncodedLiteral"),
44
+ shortIdentifiers: Symbol("ShortIdentifiers"),
45
+ suspiciousLiteral: Symbol("SuspiciousLiteral"),
46
+ obfuscatedCode: Symbol("ObfuscatedCode")
47
+ });
@@ -1,65 +1,70 @@
1
- // Import Third-party Dependencies
2
- import { Patterns } from "@nodesecure/sec-literal";
3
-
4
- // Import Internal Dependencies
5
- import * as jjencode from "./jjencode.js";
6
- import * as jsfuck from "./jsfuck.js";
7
- import * as freejsobfuscator from "./freejsobfuscator.js";
8
- import * as obfuscatorio from "./obfuscator-io.js";
9
-
10
- // CONSTANTS
11
- const kMinimumIdsCount = 5;
12
-
13
- export function isObfuscatedCode(analysis) {
14
- let encoderName = null;
15
-
16
- if (jsfuck.verify(analysis)) {
17
- encoderName = "jsfuck";
18
- }
19
- else if (jjencode.verify(analysis)) {
20
- encoderName = "jjencode";
21
- }
22
- else if (analysis.counter.morseLiteral >= 36) {
23
- encoderName = "morse";
24
- }
25
- else {
26
- // TODO: also implement Dictionnary checkup
27
- const { prefix, oneTimeOccurence } = Patterns.commonHexadecimalPrefix(
28
- analysis.identifiersName.map((value) => value.name)
29
- );
30
- const uPrefixNames = new Set(Object.keys(prefix));
31
-
32
- if (analysis.counter.identifiers > kMinimumIdsCount && uPrefixNames.size > 0) {
33
- analysis.hasPrefixedIdentifiers = calcAvgPrefixedIdentifiers(analysis, prefix) > 80;
34
- }
35
- // console.log(prefix);
36
- // console.log(oneTimeOccurence);
37
- // console.log(analysis.hasPrefixedIdentifiers);
38
- // console.log(analysis.counter.identifiers);
39
- // console.log(analysis.counter.encodedArrayValue);
40
-
41
- if (uPrefixNames.size === 1 && freejsobfuscator.verify(analysis, prefix)) {
42
- encoderName = "freejsobfuscator";
43
- }
44
- else if (obfuscatorio.verify(analysis)) {
45
- encoderName = "obfuscator.io";
46
- }
47
- // else if ((analysis.counter.identifiers > (kMinimumIdsCount * 3) && analysis.hasPrefixedIdentifiers)
48
- // && (oneTimeOccurence <= 3 || analysis.counter.encodedArrayValue > 0)) {
49
- // encoderName = "unknown";
50
- // }
51
- }
52
-
53
- return [encoderName !== null, encoderName];
54
- }
55
-
56
- function calcAvgPrefixedIdentifiers(analysis, prefix) {
57
- const valuesArr = Object.values(prefix).slice().sort((left, right) => left - right);
58
- if (valuesArr.length === 0) {
59
- return 0;
60
- }
61
- const nbOfPrefixedIds = valuesArr.length === 1 ? valuesArr.pop() : (valuesArr.pop() + valuesArr.pop());
62
- const maxIds = analysis.counter.identifiers - analysis.idtypes.property;
63
-
64
- return ((nbOfPrefixedIds / maxIds) * 100);
65
- }
1
+ // Import Third-party Dependencies
2
+ import { Patterns } from "@nodesecure/sec-literal";
3
+
4
+ // Import Internal Dependencies
5
+ import * as jjencode from "./jjencode.js";
6
+ import * as jsfuck from "./jsfuck.js";
7
+ import * as freejsobfuscator from "./freejsobfuscator.js";
8
+ import * as obfuscatorio from "./obfuscator-io.js";
9
+ import * as trojan from "./trojan-source.js";
10
+
11
+ // CONSTANTS
12
+ const kMinimumIdsCount = 5;
13
+
14
+ export function isObfuscatedCode(analysis) {
15
+ let encoderName = null;
16
+
17
+ if (jsfuck.verify(analysis)) {
18
+ encoderName = "jsfuck";
19
+ }
20
+ else if (jjencode.verify(analysis)) {
21
+ encoderName = "jjencode";
22
+ }
23
+ else if (analysis.counter.morseLiteral >= 36) {
24
+ encoderName = "morse";
25
+ }
26
+ else {
27
+ // TODO: also implement Dictionnary checkup
28
+ const { prefix, oneTimeOccurence } = Patterns.commonHexadecimalPrefix(
29
+ analysis.identifiersName.map((value) => value.name)
30
+ );
31
+ const uPrefixNames = new Set(Object.keys(prefix));
32
+
33
+ if (analysis.counter.identifiers > kMinimumIdsCount && uPrefixNames.size > 0) {
34
+ analysis.hasPrefixedIdentifiers = calcAvgPrefixedIdentifiers(analysis, prefix) > 80;
35
+ }
36
+ // console.log(prefix);
37
+ // console.log(oneTimeOccurence);
38
+ // console.log(analysis.hasPrefixedIdentifiers);
39
+ // console.log(analysis.counter.identifiers);
40
+ // console.log(analysis.counter.encodedArrayValue);
41
+
42
+ if (uPrefixNames.size === 1 && freejsobfuscator.verify(analysis, prefix)) {
43
+ encoderName = "freejsobfuscator";
44
+ }
45
+ else if (obfuscatorio.verify(analysis)) {
46
+ encoderName = "obfuscator.io";
47
+ }
48
+ // else if ((analysis.counter.identifiers > (kMinimumIdsCount * 3) && analysis.hasPrefixedIdentifiers)
49
+ // && (oneTimeOccurence <= 3 || analysis.counter.encodedArrayValue > 0)) {
50
+ // encoderName = "unknown";
51
+ // }
52
+ }
53
+
54
+ return [encoderName !== null, encoderName];
55
+ }
56
+
57
+ export function hasTrojanSource(sourceString) {
58
+ return trojan.verify(sourceString);
59
+ }
60
+
61
+ function calcAvgPrefixedIdentifiers(analysis, prefix) {
62
+ const valuesArr = Object.values(prefix).slice().sort((left, right) => left - right);
63
+ if (valuesArr.length === 0) {
64
+ return 0;
65
+ }
66
+ const nbOfPrefixedIds = valuesArr.length === 1 ? valuesArr.pop() : (valuesArr.pop() + valuesArr.pop());
67
+ const maxIds = analysis.counter.identifiers - analysis.idtypes.property;
68
+
69
+ return ((nbOfPrefixedIds / maxIds) * 100);
70
+ }
@@ -0,0 +1,11 @@
1
+ import { unsafeUnicodeControlCharacters } from "../constants.js";
2
+
3
+ export function verify(sourceString) {
4
+ for (const unsafeCharacter of unsafeUnicodeControlCharacters) {
5
+ if (sourceString.includes(unsafeCharacter)) {
6
+ return true;
7
+ }
8
+ }
9
+
10
+ return false;
11
+ }