Skip to content
Merged

Docs #19

Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
80 changes: 58 additions & 22 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,45 +2,72 @@
[![Node.js CI](https://github.com/PerimeterX/obfuscation-detector/actions/workflows/node.js.yml/badge.svg?branch=main)](https://github.com/PerimeterX/obfuscation-detector/actions/workflows/node.js.yml)
[![Downloads](https://img.shields.io/npm/dm/obfuscation-detector.svg?maxAge=43200)](https://www.npmjs.com/package/obfuscation-detector)

Detect different types of JS obfuscation by their AST structure.
## Overview
Obfuscation Detector is a tool for identifying different types of JavaScript obfuscation by analyzing the code's Abstract Syntax Tree (AST). It is designed for security researchers, reverse engineers, and developers who need to quickly determine if and how a JavaScript file has been obfuscated.

**Use Cases:**
- Automated analysis of suspicious or third-party JavaScript
- Security auditing and malware research
- Integration into CI/CD pipelines to flag obfuscated code
- Educational purposes for understanding obfuscation techniques

## How it Works
Obfuscation Detector parses JavaScript code into an AST using [flAST](https://www.npmjs.com/package/flast) and applies a series of modular detectors. Each detector looks for specific patterns or structures that are characteristic of known obfuscation techniques. The tool can return all matching types or just the most likely (best) match.

## Installation
`npm install obfuscation-detector`
```shell
npm install obfuscation-detector
```

## Usage
### Module
### As a Module
```javascript
import fs from 'node:fs';
import detectObfuscation from 'obfuscation-detector';

const code = fs.readFileSync('obfuscated.js', 'utf-8');
const most_likely_obfuscation_type = detectObfuscation(code);
// const all_matching_obfuscation_types = detectObfuscation(code, false);
console.log(`Obfuscation type is probably ${most_likely_obfuscation_type}`);
const bestMatch = detectObfuscation(code); // returns [bestMatch] or []
const allMatches = detectObfuscation(code, false); // returns all matches as an array
console.log(`Obfuscation type(s): ${allMatches.join(', ')}`);
```

### CLI
```bash
obfuscation-detector /path/to/obfuscated.js [stopAfterFirst]
```shell
obfuscation-detector /path/to/obfuscated.js [--bestMatch|-b]
cat /path/to/obfuscated.js | obfuscation-detector [--bestMatch|-b]
obfuscation-detector --help
```

Getting all matching obfuscation types for a file:
```bash
$ obfuscation-detector /path/to/obfuscated.js
[+] function_to_array_replacements, augmented_proxied_array_function_replacements
```
#### CLI Options
- `--bestMatch`, `-b`: Return only the first (most likely) detected obfuscation type.
- `--help`, `-h`: Show usage instructions.
- Unknown flags will result in an error and print the usage.

Getting just the first match:
```bash
$ obfuscation-detector /path/to/obfuscated.js stop
[+] function_to_array_replacements
```
#### Examples
- **All matches:**
```shell
$ obfuscation-detector /path/to/obfuscated.js
[+] function_to_array_replacements, augmented_proxied_array_function_replacements
```
- **Best match only:**
```shell
$ obfuscation-detector /path/to/obfuscated.js --bestMatch
[+] function_to_array_replacements
```
- **From stdin:**
```shell
$ cat obfuscated.js | obfuscation-detector -b
[+] function_to_array_replacements
```


The `stopAfterFirst` arguments doesn't have to be any specific string, it just needs not to be empty.
## API Reference
### `detectObfuscation(code: string, stopAfterFirst: boolean = true): string[]`
- **code**: JavaScript source code as a string.
- **stopAfterFirst**: If `true`, returns after the first positive detection (default). If `false`, returns all detected types.
- **Returns**: An array of detected obfuscation type names. Returns an empty array if no known type is detected.

## Supported Obfuscation Types
You can find descriptions of the different types in the code itself, and more info [here](src/detectors/README.md).
Descriptions and technical details for each type are available in [src/detectors/README.md](src/detectors/README.md):
- [Array Replacements](src/detectors/arrayReplacements.js)
- [Augmented Array Replacements](src/detectors/augmentedArrayReplacements.js)
- [Array Function Replacements](src/detectors/arrayFunctionReplacements.js)
Expand All @@ -49,5 +76,14 @@ You can find descriptions of the different types in the code itself, and more in
- [Obfuscator.io](src/detectors/obfuscator-io.js)
- [Caesar Plus](src/detectors/caesarp.js)

## Troubleshooting
- **No obfuscation detected:** The code may not be obfuscated, or it uses an unknown technique. Consider contributing a new detector!
- **Error: File not found:** Check the file path and try again.
- **Unknown flag:** Run with only `--help` to see what options are available.
- **Performance issues:** For very large files, detection may take longer. Consider running with only the detectors you need (advanced usage).

## Contribution
To contribute to this project see our [contribution guide](CONTRIBUTING.md)
To contribute to this project, see our [contribution guide](CONTRIBUTING.md).

---
For technical details on each obfuscation type and how to add new detectors, see [src/detectors/README.md](src/detectors/README.md).
62 changes: 49 additions & 13 deletions bin/obfuscation-detector.js
Original file line number Diff line number Diff line change
@@ -1,19 +1,55 @@
#!/usr/bin/env node
import fs from 'node:fs';
import {fileURLToPath} from 'node:url';
import {detectObfuscation} from './../src/index.js';

if (process.argv[1] === fileURLToPath(import.meta.url)) {
try {
const args = process.argv.slice(2);
if (args.length) {
let content = fs.readFileSync(args[0], 'utf-8');
const stopAfterFirst = !!args[1];
const obfuscationType = detectObfuscation(content, stopAfterFirst);
if (obfuscationType.length) console.log('[+] ' + obfuscationType.join(', '));
else console.log('[-] No obfuscation detected / unknown obfuscation');
} else console.log('Usage: obfuscation-detector /path/to/obfuscated.js [stopAfterFirst]');
} catch (e) {
console.error(`[X] Critical Error: ${e.message}`);
function printUsage() {
console.log('Usage: obfuscation-detector /path/to/obfuscated.js [--bestMatch|-b]');
console.log(' obfuscation-detector < file.js [--bestMatch|-b]');
console.log(' obfuscation-detector --help|-h');
}

const args = process.argv.slice(2);
const allowedFlags = new Set(['--help', '-h', '--bestMatch', '-b']);

// Check for unknown flags
const unknownFlags = args.filter(arg => arg.startsWith('-') && !allowedFlags.has(arg));
if (unknownFlags.length) {
console.error(`[-] Unknown flag(s): ${unknownFlags.join(', ')}`);
printUsage();
process.exit(1);
}

if (args.includes('--help') || args.includes('-h')) {
printUsage();
process.exit(0);
}

try {
let content = '';
// Default: show all matches unless --bestMatch or -b is present
let stopAfterFirst = args.includes('--bestMatch') || args.includes('-b');

// Remove flags from file argument
const fileArg = args.find(arg => !arg.startsWith('-'));

if (fileArg) {
if (!fs.existsSync(fileArg)) {
console.error(`[-] File not found: ${fileArg}`);
printUsage();
process.exit(1);
}
content = fs.readFileSync(fileArg, 'utf-8');
} else if (!process.stdin.isTTY) {
content = fs.readFileSync(0, 'utf-8');
} else {
printUsage();
process.exit(1);
}

const obfuscationType = detectObfuscation(content, stopAfterFirst);
if (obfuscationType.length) console.log('[+] ' + obfuscationType.join(', '));
else console.log('[-] No obfuscation detected / unknown obfuscation');
} catch (e) {
console.error(`[X] Critical Error: ${e.message}`);
process.exit(1);
}
2 changes: 1 addition & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,6 @@ export default [{
}],

semi: ["error", "always"],
"no-empty": ["off"],
"no-empty": ["error", { "allowEmptyCatch": true }],
},
}];
Loading