Why Detection Matters
Before you can deobfuscate code, you need to understand what techniques were used to protect it. Different obfuscation patterns require different deobfuscation approaches, and applying the wrong technique can make code worse, corrupt its functionality, or waste significant time. Accurate detection is the critical first step in any deobfuscation workflow.
Detection also serves other important purposes. Security teams use pattern detection to flag suspicious scripts in their web applications. Malware analysts use it to quickly triage samples. And automated tools like Astify rely on detection to select the optimal processing strategy for each file.
The Three Pillars of Detection
Effective obfuscation detection combines three complementary approaches:
- Signature-based detection: Looking for known patterns specific to particular obfuscation tools
- Heuristic analysis: Measuring statistical properties that distinguish obfuscated from normal code
- AST pattern matching: Analyzing the code's structural patterns at the syntax tree level
Each approach has strengths and weaknesses. Signature detection is fast and precise but misses unknown obfuscators. Heuristic analysis catches novel techniques but produces more false positives. AST matching provides deep structural insight but requires more processing time. The best detection systems combine all three.
Signature-Based Detection
Signature-based detection looks for specific patterns known to be produced by particular obfuscation tools. This is the fastest and most reliable method when the obfuscator is known.
Obfuscator.io Signatures
The most popular open-source obfuscator produces highly recognizable patterns:
1// Signature 1: String array with rotation IIFE
2var _0x1234 = ['string1', 'string2', ...];
3(function(_0xArr, _0xNum) {
4 var _0xShift = function(_0xCount) {
5 while (--_0xCount) {
6 _0xArr['push'](_0xArr['shift']());
7 }
8 };
9 _0xShift(++_0xNum);
10}(_0x1234, 0x1b3));
11
12// Signature 2: Decoder function with offset
13var _0xdec = function(_0xIdx, _0xKey) {
14 _0xIdx = _0xIdx - 0x1f4;
15 var _0xStr = _0x1234[_0xIdx];
16 return _0xStr;
17};Key identifiers for obfuscator.io:
- Variable names matching
_0x[a-f0-9]{4,6} - String array at the top of the file with a rotation IIFE
- Decoder function with hexadecimal offset subtraction
- The
'push'and'shift'array method pattern in the rotation function
JScrambler Signatures
JScrambler produces different recognizable patterns:
- Code lock functions that verify the execution environment
- Self-defending functions with specific regex patterns
- Unique encoding patterns for string protection
- Anti-tampering integrity checks
Webpack Bundle Signatures
Webpack-bundled code has a distinctive wrapper structure:
1// Webpack bootstrap pattern
2(function(modules) {
3 var installedModules = {};
4 function __webpack_require__(moduleId) {
5 if (installedModules[moduleId]) {
6 return installedModules[moduleId].exports;
7 }
8 var module = installedModules[moduleId] = {
9 i: moduleId, l: false, exports: {}
10 };
11 modules[moduleId].call(
12 module.exports, module, module.exports, __webpack_require__
13 );
14 module.l = true;
15 return module.exports;
16 }
17 // ... bootstrap continues
18})([ /* module array */ ]);Building a Signature Detector
1function detectObfuscator(code) {
2 const signatures = [];
3
4 // Obfuscator.io detection
5 if (/_0x[a-f0-9]{4,6}/.test(code) &&
6 /\['push'\].*\['shift'\]/.test(code)) {
7 signatures.push({
8 tool: 'obfuscator.io',
9 confidence: 0.95
10 });
11 }
12
13 // Webpack detection
14 if (/__webpack_require__/.test(code) ||
15 /webpackJsonp/.test(code)) {
16 signatures.push({
17 tool: 'webpack',
18 confidence: 0.9
19 });
20 }
21
22 // JScrambler detection
23 if (/\$jscomp/.test(code) ||
24 code.includes('jscramblerSecretKey')) {
25 signatures.push({
26 tool: 'jscrambler',
27 confidence: 0.85
28 });
29 }
30
31 return signatures;
32}Heuristic Analysis
Heuristic analysis uses statistical measurements to determine if code has been obfuscated, even when the specific tool is unknown. These metrics look at properties that reliably distinguish obfuscated from normal code.
Entropy Measurement
Information entropy measures the randomness of data. Obfuscated code typically has higher entropy than normal code because of encoded strings, hex identifiers, and encrypted content:
1function calculateEntropy(text) {
2 const freq = {};
3 for (const char of text) {
4 freq[char] = (freq[char] || 0) + 1;
5 }
6
7 const len = text.length;
8 let entropy = 0;
9
10 for (const count of Object.values(freq)) {
11 const p = count / len;
12 entropy -= p * Math.log2(p);
13 }
14
15 return entropy;
16}
17
18// Normal JavaScript: entropy ~4.5-5.5
19// Obfuscated code: entropy ~5.5-7.0
20// Heavily encoded: entropy ~7.0+An entropy threshold of around 5.5 provides a good initial signal, though it should be combined with other indicators to avoid false positives from legitimate code with many string constants.
Identifier Analysis
The naming patterns of identifiers provide strong signals:
1function analyzeIdentifiers(identifiers) {
2 const metrics = {
3 total: identifiers.length,
4 hexPattern: 0, // _0x... pattern
5 singleChar: 0, // a, b, c
6 averageLength: 0,
7 uniqueRatio: 0
8 };
9
10 let totalLength = 0;
11 const unique = new Set();
12
13 for (const id of identifiers) {
14 totalLength += id.length;
15 unique.add(id);
16
17 if (/_0x[a-f0-9]+/i.test(id)) metrics.hexPattern++;
18 if (id.length === 1) metrics.singleChar++;
19 }
20
21 metrics.averageLength = totalLength / identifiers.length;
22 metrics.uniqueRatio = unique.size / identifiers.length;
23
24 // High hex pattern ratio = strong obfuscation signal
25 // Low average length = possible minification
26 // Low unique ratio = possible obfuscation (reused patterns)
27
28 return metrics;
29}String Analysis
Examining string literals reveals encoding patterns:
1function analyzeStrings(strings) {
2 let base64Count = 0;
3 let hexEscapeCount = 0;
4 let unicodeEscapeCount = 0;
5 let suspiciouslyLong = 0;
6
7 for (const str of strings) {
8 // Base64 pattern
9 if (/^[A-Za-z0-9+/]+=*$/.test(str) && str.length > 8) {
10 base64Count++;
11 }
12 // Hex escape sequences
13 if (/\x[0-9a-f]{2}/i.test(str)) {
14 hexEscapeCount++;
15 }
16 // Unicode escapes
17 if (/\u[0-9a-f]{4}/i.test(str)) {
18 unicodeEscapeCount++;
19 }
20 // Unusually long strings (possible encoded payloads)
21 if (str.length > 200) {
22 suspiciouslyLong++;
23 }
24 }
25
26 return {
27 base64Count,
28 hexEscapeCount,
29 unicodeEscapeCount,
30 suspiciouslyLong,
31 totalStrings: strings.length
32 };
33}Complexity Scoring
Combining multiple heuristics into a single score provides the most reliable detection. Here is a comprehensive scoring approach:
1function calculateObfuscationScore(code) {
2 let score = 0;
3
4 // Entropy check (0-20 points)
5 const entropy = calculateEntropy(code);
6 if (entropy > 6.5) score += 20;
7 else if (entropy > 5.5) score += 10;
8 else if (entropy > 5.0) score += 5;
9
10 // Hex identifier ratio (0-25 points)
11 const hexMatches = code.match(/_0x[a-f0-9]{2,}/gi) || [];
12 const allIdentifiers = code.match(/[a-zA-Z_$][a-zA-Z0-9_$]*/g) || [];
13 const hexRatio = hexMatches.length / (allIdentifiers.length || 1);
14 if (hexRatio > 0.3) score += 25;
15 else if (hexRatio > 0.1) score += 15;
16
17 // String array pattern (0-20 points)
18 if (/var\s+_0x\w+\s*=\s*\[/.test(code)) score += 20;
19
20 // Control flow flattening (0-15 points)
21 if (/while\s*\(\s*!!\s*\[\]\s*\)|while\s*\(\s*true\s*\)/.test(code)) {
22 if (/switch\s*\(/.test(code)) score += 15;
23 }
24
25 // Bracket notation overuse (0-10 points)
26 const bracketAccess = (code.match(/\[['"][a-zA-Z]+['"]\]/g) || []).length;
27 const dotAccess = (code.match(/\.[a-zA-Z_]\w*/g) || []).length;
28 if (bracketAccess > dotAccess * 2) score += 10;
29
30 // Debug protection patterns (0-10 points)
31 if (/setInterval.*debugger|debugger.*setInterval/.test(code)) {
32 score += 10;
33 }
34
35 return {
36 score,
37 isObfuscated: score >= 30,
38 level: score >= 60 ? 'heavy' : score >= 30 ? 'moderate' : 'light'
39 };
40}AST Pattern Matching
For the deepest and most reliable analysis, AST pattern matching examines the code's structural properties. This catches obfuscation patterns that text-based analysis might miss.
Detecting Control Flow Flattening
1const parser = require('@babel/parser');
2const traverse = require('@babel/traverse').default;
3
4function detectCFF(code) {
5 const ast = parser.parse(code, { sourceType: 'unambiguous' });
6 const detections = [];
7
8 traverse(ast, {
9 WhileStatement(path) {
10 // Look for while(true) or while(!![])
11 const test = path.node.test;
12 const isInfinite =
13 (test.type === 'BooleanLiteral' && test.value === true) ||
14 (test.type === 'UnaryExpression' && test.operator === '!');
15
16 if (!isInfinite) return;
17
18 // Check for switch statement inside
19 const body = path.node.body;
20 if (body.type !== 'BlockStatement') return;
21
22 for (const stmt of body.body) {
23 if (stmt.type === 'SwitchStatement') {
24 detections.push({
25 type: 'control-flow-flattening',
26 line: path.node.loc?.start.line,
27 cases: stmt.cases.length
28 });
29 }
30 }
31 }
32 });
33
34 return detections;
35}Detecting String Array Pattern
1function detectStringArray(code) {
2 const ast = parser.parse(code, { sourceType: 'unambiguous' });
3 const detections = [];
4
5 traverse(ast, {
6 VariableDeclarator(path) {
7 // Look for large string arrays
8 if (path.node.init?.type === 'ArrayExpression') {
9 const elements = path.node.init.elements;
10 if (elements.length > 5) {
11 const stringCount = elements.filter(
12 e => e?.type === 'StringLiteral'
13 ).length;
14
15 if (stringCount / elements.length > 0.8) {
16 detections.push({
17 type: 'string-array',
18 name: path.node.id.name,
19 count: elements.length,
20 line: path.node.loc?.start.line
21 });
22 }
23 }
24 }
25 }
26 });
27
28 return detections;
29}Detecting Dead Code
1function detectDeadCode(code) {
2 const ast = parser.parse(code, { sourceType: 'unambiguous' });
3 const detections = [];
4
5 traverse(ast, {
6 IfStatement(path) {
7 const test = path.get('test');
8 const { confident, value } = test.evaluate();
9
10 if (confident) {
11 detections.push({
12 type: 'dead-code',
13 subtype: value ? 'always-true' : 'always-false',
14 line: path.node.loc?.start.line
15 });
16 }
17 },
18
19 // Code after return statements
20 ReturnStatement(path) {
21 const nextSiblings = path.getAllNextSiblings();
22 if (nextSiblings.length > 0) {
23 detections.push({
24 type: 'dead-code',
25 subtype: 'unreachable',
26 line: nextSiblings[0].node.loc?.start.line
27 });
28 }
29 }
30 });
31
32 return detections;
33}Detecting Debug Protection
1function detectDebugProtection(code) {
2 const ast = parser.parse(code, { sourceType: 'unambiguous' });
3 const detections = [];
4
5 traverse(ast, {
6 // Look for 'debugger' statements
7 DebuggerStatement(path) {
8 // Check if inside a loop or interval callback
9 let current = path.parentPath;
10 while (current) {
11 if (current.isWhileStatement() ||
12 current.isForStatement() ||
13 current.isDoWhileStatement()) {
14 detections.push({
15 type: 'debug-protection',
16 subtype: 'debugger-loop',
17 line: path.node.loc?.start.line
18 });
19 break;
20 }
21 current = current.parentPath;
22 }
23 },
24
25 // Detect console overwriting
26 AssignmentExpression(path) {
27 const left = path.node.left;
28 if (left.type === 'MemberExpression' &&
29 left.object.name === 'console') {
30 detections.push({
31 type: 'debug-protection',
32 subtype: 'console-override',
33 method: left.property.name || left.property.value,
34 line: path.node.loc?.start.line
35 });
36 }
37 }
38 });
39
40 return detections;
41}Building a Complete Detection System
A production-ready detection system combines all three approaches into a unified analysis pipeline. Here is how Astify's detection works at a high level:
Step 1: Quick Scan
Run fast signature checks and heuristic measurements to determine if the code is likely obfuscated and identify probable tools:
1function quickScan(code) {
2 return {
3 signatures: detectObfuscator(code),
4 score: calculateObfuscationScore(code),
5 entropy: calculateEntropy(code)
6 };
7}Step 2: Deep Analysis
If the quick scan indicates obfuscation, perform full AST analysis to identify specific patterns:
1function deepAnalysis(code) {
2 return {
3 controlFlowFlattening: detectCFF(code),
4 stringEncryption: detectStringArray(code),
5 deadCode: detectDeadCode(code),
6 debugProtection: detectDebugProtection(code),
7 // ... additional detectors
8 };
9}Step 3: Strategy Selection
Based on detected patterns, select the optimal deobfuscation strategy and transformation order.
The 14+ Patterns Astify Detects
Astify's analyzer detects and categorizes the following obfuscation patterns:
- Hex Identifiers: Variable names matching
_0xpatterns - String Encryption: String arrays with decoder functions
- Control Flow Flattening: State-machine dispatchers with switch/while
- Dead Code: Unreachable code blocks and always-true/false conditions
- Opaque Predicates: Conditions with deterministic but obscured outcomes
- Debug Protection: Anti-debugging measures and console overrides
- Self-Defending: Code that detects tampering or beautification
- Domain Lock: Execution restricted to specific domains
- Dynamic Code Execution: Runtime code generation and execution
- Unicode Escapes: Character encoding obfuscation
- Property Access Transformation: Dot to bracket notation conversion
- Number Encoding: Hex or expression-based number obfuscation
- Wrapper Functions: Unnecessary function call indirection
- Comma Expressions: Statement merging via sequence operators
Each detector produces a confidence score and detailed metadata about the detected pattern, enabling Astify's AI engine to generate precisely targeted transformation scripts.
Practical Tips for Manual Detection
When analyzing obfuscated code manually, keep these tips in mind:
- Start from the top: Most obfuscators place their setup code (string arrays, decoder functions) at the beginning of the file
- Look for the entry point: Find where the actual application logic begins, usually after the obfuscation scaffolding
- Check file size vs. functionality: Obfuscated code is significantly larger than its readable equivalent. A simple utility function should not be 10,000 lines
- Count unique patterns: If every variable follows the same naming convention (like
_0x), it is almost certainly obfuscated - Use browser DevTools: The Sources panel with pretty-printing can help you see the overall structure before detailed analysis
- Compare with known samples: Keep a reference library of obfuscated samples from different tools for quick comparison
Automated Detection with Astify
Astify's analyzer performs comprehensive pattern detection automatically. Upload any JavaScript file and within seconds you will receive a detailed breakdown of every obfuscation technique detected, the likely obfuscation tool used, a complexity score, and the recommended processing strategy. This detection powers our intelligent deobfuscation pipeline, ensuring each file receives exactly the right treatment for optimal results.