The recursive internet scanner for hackers. 🧡
Python asmattack-surface-managementautomationbugbountyclieasmhackingneo4josintosint-frameworkpentestingpythonreconrecursionscannersubdomain-enumerationsubdomain-scannersubdomainsthreat-intelligencethreatintel
Add js_unpacker module for detecting and unpacking obfuscated JS (#3335)
Paul Mueller47e3e90507df
diff --git a/bbot/core/event/base.py b/bbot/core/event/base.pyindex 1bbf23462..0880180b6 100644--- a/bbot/core/event/base.py+++ b/bbot/core/event/base.py@@ -962,6 +962,10 @@ class BaseEvent:archive_url = self.archive_urlif archive_url:j["archive_url"] = archive_url+ # also kept out of `data`, though unlike archive_url this one does feed the event's identity+ reemit_source = getattr(self, "reemit_source", None)+ if reemit_source:+ j["reemit_source"] = reemit_source# scope distancej["scope_distance"] = self.scope_distance# scan@@ -1749,8 +1753,31 @@ class HTTP_RESPONSE(URL_UNVERIFIED):return ""return body_bytes.decode("utf-8", errors="replace")+ @property+ def reemit_source(self):+ """Name of the module that re-emitted this response with a transformed body.++ Kept off ``data`` so the marker isn't part of the event's public body. ``json()``+ surfaces it top-level and ``event_from_json()`` restores it.+ """+ return getattr(self, "_reemit_source", None)++ @reemit_source.setter+ def reemit_source(self, value):+ self._reemit_source = value+ # the marker feeds _data_id, so any already-cached identity is stale+ self._id = None+ self._data_hash = None+ self._hash = None+def _data_id(self):- return self.data["method"] + "|" + self.data["url"]+ base = self.data["method"] + "|" + self.data["url"]+ # a module re-emitting the same (method, url) with a transformed body sets+ # reemit_source, so the two events don't collide on event.id and get deduped away+ reemit_source = self.reemit_source+ if reemit_source:+ return base + "|" + str(reemit_source)+ return basedef sanitize_data(self, data):url = data.get("url", "")@@ -2468,6 +2495,15 @@ def event_from_json(j):except AttributeError:pass+ # must be restored, not recomputed: it feeds _data_id, so dropping it here+ # would give the rebuilt event a different id than the one that was serialized+ reemit_source = j.get("reemit_source", "")+ if reemit_source:+ try:+ event.reemit_source = reemit_source+ except AttributeError:+ pass+# accept both isoformat and unix timestamptry:event.timestamp = datetime.datetime.fromtimestamp(j["timestamp"], ZoneInfo("UTC"))diff --git a/bbot/modules/js_unpacker.py b/bbot/modules/js_unpacker.pynew file mode 100644index 000000000..7233ee3a8--- /dev/null+++ b/bbot/modules/js_unpacker.py@@ -0,0 +1,417 @@+import json+import regex as re+from hashlib import md5, sha256+from urllib.parse import urljoin++import mmh3+import yara++from bbot.modules.base import BaseModule+++class BaseUnpacker:+ name = "base"+ yara_rule = ""++ def __init__(self, module):+ self.module = module+ self.helpers = module.helpers++ async def unpack(self, event, match):+ raise NotImplementedError++ async def emit_unlocked(self, event, body):+ """Re-emit an HTTP_RESPONSE with unpacked body so excavate can extract from it."""+ data = dict(event.data)+ data["body"] = body+ # recompute body hashes so downstream content-dedup doesn't collapse this+ # against the original response+ body_bytes = body.encode("utf-8", errors="replace") if isinstance(body, str) else body+ old_hash = data.get("hash") or {}+ data["hash"] = {+ **old_hash,+ "body_md5": md5(body_bytes).hexdigest(),+ "body_mmh3": mmh3.hash(body_bytes),+ "body_sha256": sha256(body_bytes).hexdigest(),+ }+ unpacked = self.module.make_event(+ data,+ "HTTP_RESPONSE",+ parent=event.parent,+ tags=["js-unpacked"],+ context=f"{{module}} unpacked {self.name} JavaScript from {{event.type}}",+ )+ if unpacked is None:+ return+ # distinct id from the original response so per-module dedup doesn't drop this+ unpacked.reemit_source = "js_unpacker"+ await self.module.emit_event(unpacked)+++class SourceMapUnpacker(BaseUnpacker):+ name = "source-map"+ yara_rule = """+rule source_map+{+ strings:+ $a = "sourceMappingURL="+ condition:+ any of them+}+"""+ _url_regex = re.compile(r"[/*][#@]\s*sourceMappingURL=(\S+)")++ async def unpack(self, event, match):+ body = event.body+ m = await self.helpers.re.search(self._url_regex, body)+ if not m:+ return+ map_ref = m.group(1)++ # data: URI+ if map_ref.startswith("data:"):+ parts = map_ref.split(",", 1)+ if len(parts) == 2:+ import base64++ try:+ map_json = base64.b64decode(parts[1]).decode("utf-8", errors="replace")+ except Exception:+ return+ else:+ return+ else:+ base_url = event.data.get("url", "")+ map_url = urljoin(base_url, map_ref)+ # maps often live on third-party CDNs, so don't require scope, but honor the blacklist+ if self.module.scan.blacklisted(map_url):+ self.module.debug(f"Skipping blacklisted source map {map_url}")+ return+ r = await self.helpers.request(map_url)+ if not r or r.status_code != 200:+ return+ map_json = r.text++ parsed = await self.helpers.run_in_executor_cpu(self._parse_source_map, map_json)+ if parsed is None:+ return+ num_sources, num_files, combined = parsed++ url = event.data.get("url", "unknown")+ source_url = map_url if not map_ref.startswith("data:") else url+ await self.module.emit_event(+ {+ "host": str(event.host),+ "url": source_url,+ "name": "Exposed source map",+ "description": f"Source map with {num_files} source files exposed ({num_sources} total entries)",+ "severity": "LOW",+ "confidence": "CONFIRMED",+ },+ "FINDING",+ parent=event,+ context="{module} discovered an exposed source map at {event.data[url]}",+ )+ await self.emit_unlocked(event, combined)++ @staticmethod+ def _parse_source_map(map_json):+ """Parse the map and join its embedded sources. CPU-bound; runs off the event loop."""+ try:+ source_map = json.loads(map_json)+ except (json.JSONDecodeError, ValueError):+ return None+ non_empty = [c for c in source_map.get("sourcesContent", []) if c and c.strip()]+ if not non_empty:+ return None+ return len(source_map.get("sources", [])), len(non_empty), "\n".join(non_empty)+++class DeanEdwardsUnpacker(BaseUnpacker):+ name = "dean-edwards"+ yara_rule = """+rule dean_edwards_packer+{+ strings:+ $a = "eval(function(p,a,c,k,e,"+ condition:+ any of them+}+"""+ _extract_regex = re.compile(+ r"eval\s*\(\s*function\s*\(\s*p\s*,\s*a\s*,\s*c\s*,\s*k\s*,\s*e\s*,\s*\w\s*\)"+ r".*?\}\s*\(\s*'(.*?)'\s*,\s*(\d+)\s*,\s*(\d+)\s*,\s*'(.*?)'\s*\.split\s*\(\s*'\|'\s*\)",+ re.DOTALL,+ )++ async def unpack(self, event, match):+ result = await self.helpers.run_in_executor_cpu(self._decode, event.body)+ if result:+ await self.emit_unlocked(event, result)++ @classmethod+ def _decode(cls, body):+ """Reverse the packer's base-N keyword substitution. CPU-bound; runs off the event loop."""+ m = cls._extract_regex.search(body)+ if not m:+ return ""++ payload, radix, count, keywords_str = m.group(1), int(m.group(2)), int(m.group(3)), m.group(4)+ keywords = keywords_str.split("|")++ def base_n(value, base):+ chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"+ if value < base:+ return chars[value]+ return base_n(value // base, base) + chars[value % base]++ lookup = {}+ # count comes from the page, so never iterate past the keywords we actually have+ for i in range(min(count, len(keywords))):+ key = base_n(i, radix)+ if keywords[i]:+ lookup[key] = keywords[i]++ def replacer(m):+ word = m.group(0)+ return lookup.get(word, word)++ result = re.sub(r"\b\w+\b", replacer, payload)+ result = result.encode("utf-8").decode("unicode_escape", errors="replace")+ return result if result.strip() else ""+++class ObfuscatorIOUnpacker(BaseUnpacker):+ name = "obfuscator-io"+ yara_rule = """+rule obfuscator_io+{+ strings:+ $a = /var _0x[a-f0-9]{4,6}\\s*=\\s*\\[/+ condition:+ any of them+}+"""+ _array_regex = re.compile(r"var\s+(_0x[a-f0-9]+)\s*=\s*\[(.*?)\];", re.DOTALL)++ async def unpack(self, event, match):+ result = await self.helpers.run_in_executor_cpu(self._deobfuscate, event.body)+ if result:+ await self.emit_unlocked(event, result)++ @classmethod+ def _deobfuscate(cls, body):+ """Inline the string-array lookups back into the source. CPU-bound; runs off the event loop."""+ arr_match = cls._array_regex.search(body)+ if not arr_match:+ return ""++ arr_name = arr_match.group(1)+ string_array = re.findall(r"'([^']*)'", arr_match.group(2))++ # find and apply rotation+ rot_pattern = (+ r"\(function\s*\(\s*\w+\s*,\s*\w+\s*\)\s*\{.*?push.*?shift.*?\}\s*\(\s*"+ + re.escape(arr_name)+ + r"\s*,\s*(0x[a-f0-9]+|\d+)\s*\)"+ )+ rot_match = re.search(rot_pattern, body, re.DOTALL)+ if rot_match:+ amount_str = rot_match.group(1)+ amount = int(amount_str, 16) if amount_str.startswith("0x") else int(amount_str)+ # rotation is cyclic, so reduce the page-supplied amount before applying it+ if string_array:+ amount %= len(string_array)+ string_array = string_array[amount:] + string_array[:amount]++ # find accessor function name+ accessor_pattern = (+ r"var\s+(_0x[a-f0-9]+)\s*=\s*function\s*\(\s*\w+\s*,\s*\w+\s*\)\s*\{"+ r"[^}]*" + re.escape(arr_name) + r"\s*\["+ )+ accessor_match = re.search(accessor_pattern, body)+ if not accessor_match:+ return ""++ accessor_name = accessor_match.group(1)++ def replace_accessor(m):+ idx_str = m.group(1)+ idx = int(idx_str, 16) if idx_str.startswith("0x") else int(idx_str)+ if 0 <= idx < len(string_array):+ return f"'{string_array[idx]}'"+ return m.group(0)++ result = re.sub(+ re.escape(accessor_name) + r"\(\s*'(0x[a-f0-9]+|\d+)'\s*\)",+ replace_accessor,+ body,+ )+ return result if result != body else ""+++class NextJSUnpacker(BaseUnpacker):+ name = "nextjs"+ yara_rule = """+rule nextjs_manifest+{+ strings:+ $a = "self.__BUILD_MANIFEST"+ $b = "__NEXT_DATA__"+ condition:+ any of them+}+"""+ _nextdata_regex = re.compile(r'<script\s+id="__NEXT_DATA__"[^>]*>(.*?)</script>', re.DOTALL)+ _route_regex = re.compile(r'"(/[^"]*)"')+ _chunk_regex = re.compile(r'"(static/chunks/[^"]*)"')++ async def unpack(self, event, match):+ body = event.body+ base_url = event.data.get("url", "")++ # __NEXT_DATA__ in HTML: extract buildId, emit _buildManifest.js URL+ nd_match = await self.helpers.re.search(self._nextdata_regex, body)+ if nd_match:+ try:+ next_data = json.loads(nd_match.group(1))+ except (json.JSONDecodeError, ValueError):+ return+ build_id = next_data.get("buildId")+ if build_id:+ manifest_path = f"/_next/static/{build_id}/_buildManifest.js"+ manifest_url = urljoin(base_url, manifest_path)+ await self.module.emit_event(+ manifest_url,+ "URL_UNVERIFIED",+ parent=event,+ tags=["js-unpacked"],+ context="{module} extracted Next.js buildId and discovered {event.type}: {event.data}",+ )+ return++ # _buildManifest.js: extract routes and chunk paths+ if "self.__BUILD_MANIFEST" not in body:+ return++ routes = set(await self.helpers.re.findall(self._route_regex, body))+ chunks = set(await self.helpers.re.findall(self._chunk_regex, body))++ for route in routes:+ if route.startswith("/_") or route == "/":+ continue+ route_url = urljoin(base_url, route)+ await self.module.emit_event(+ route_url,+ "URL_UNVERIFIED",+ parent=event,+ tags=["js-unpacked"],+ context="{module} extracted Next.js route {event.type}: {event.data}",+ )++ for chunk in chunks:+ chunk_url = urljoin(base_url, f"/_next/{chunk}")+ await self.module.emit_event(+ chunk_url,+ "URL_UNVERIFIED",+ parent=event,+ tags=["js-unpacked"],+ context="{module} extracted Next.js chunk {event.type}: {event.data}",+ )+++class WebpackUnpacker(BaseUnpacker):+ name = "webpack"+ yara_rule = """+rule webpack_bundle+{+ strings:+ $a = "webpackJsonp"+ $b = "webpackChunk"+ $c = "__webpack_require__"+ condition:+ any of them+}+"""+ _string_regex = re.compile(r"""(?:"([^"\\]{2,}(?:\\.[^"\\]*)*)"|'([^'\\]{2,}(?:\\.[^'\\]*)*)')""")+ _noise = frozenset({"use strict", "object", "function", "undefined", "string", "number", "boolean"})++ async def unpack(self, event, match):+ combined = await self.helpers.run_in_executor_cpu(self._extract_strings, event.body)+ if combined:+ await self.emit_unlocked(event, combined)++ @classmethod+ def _extract_strings(cls, body):+ """Flatten the bundle's string literals. CPU-bound; runs off the event loop."""+ strings = []+ for m in cls._string_regex.finditer(body):+ s = m.group(1) or m.group(2)+ if s and s not in cls._noise and not s.startswith("__"):+ strings.append(s)+ return "\n".join(strings)+++class js_unpacker(BaseModule):+ watched_events = ["HTTP_RESPONSE"]+ produced_events = ["HTTP_RESPONSE", "URL_UNVERIFIED", "FINDING"]+ flags = ["active", "safe", "web"]+ meta = {+ "description": "Detect and unpack JavaScript obfuscation/packing frameworks",+ "created_date": "2026-06-05",+ "author": "@liquidsec",+ }+ _module_threads = 4++ unpacker_classes = [+ SourceMapUnpacker,+ DeanEdwardsUnpacker,+ ObfuscatorIOUnpacker,+ NextJSUnpacker,+ WebpackUnpacker,+ ]++ async def setup(self):+ self.unpackers_by_rule = {}+ self.detections = []+ combined_rules = []+ for cls in self.unpacker_classes:+ unpacker = cls(self)+ rule_name = self._extract_rule_name(unpacker.yara_rule)+ self.unpackers_by_rule[rule_name] = unpacker+ combined_rules.append(unpacker.yara_rule)+ self.yara_rules = yara.compile(source="\n".join(combined_rules))+ return True++ @staticmethod+ def _extract_rule_name(yara_source):+ for line in yara_source.splitlines():+ line = line.strip()+ if line.startswith("rule "):+ return line.split()[1].rstrip("{").strip()+ raise ValueError(f"No rule name found in YARA source: {yara_source[:80]}")++ async def filter_event(self, event):+ if not event.body:+ return False, "no response body"+ content_type = event.data.get("content_type", "")+ if not any(t in content_type for t in ("javascript", "text/", "json", "xml")):+ return False, f"non-text content type: {content_type}"+ return True++ async def handle_event(self, event):+ body = event.body+ url = event.data.get("url", "unknown")+ matches = await self.helpers.run_in_executor_cpu(self.yara_rules.match, data=body)+ if not matches:+ return+ for match in matches:+ unpacker = self.unpackers_by_rule.get(match.rule)+ if unpacker is None:+ continue+ self.verbose(f"Detected {unpacker.name} in {url}")+ self.detections.append((unpacker.name, url))+ try:+ await unpacker.unpack(event, match)+ except Exception as e:+ self.warning(f"{unpacker.name} unpacker error on {url}: {e}")diff --git a/bbot/presets/web/js-audit.yml b/bbot/presets/web/js-audit.ymlindex a408f4078..325f0597b 100644--- a/bbot/presets/web/js-audit.yml+++ b/bbot/presets/web/js-audit.yml@@ -8,6 +8,7 @@ modules:- retirejs- robots- wayback+ - js_unpackerconfig:modules:diff --git a/bbot/test/test_step_1/test_events.py b/bbot/test/test_step_1/test_events.pyindex c91ce0015..dbc219756 100644--- a/bbot/test/test_step_1/test_events.py+++ b/bbot/test/test_step_1/test_events.py@@ -699,6 +699,21 @@ async def test_events(events, helpers):assert reconstituted_event.type == "HTTP_RESPONSE"assert reconstituted_event.parent_id == scan.root_event.id+ # a re-emitted response is distinguished by a marker on the event rather than in its data,+ # and has to keep that distinct id across a json round trip+ assert "reemit_source" not in http_response.json()+ unpacked_response = scan.make_event(blasthttp_response, "HTTP_RESPONSE", parent=scan.root_event)+ assert unpacked_response.id == http_response.id+ unpacked_response.reemit_source = "js_unpacker"+ assert unpacked_response.id != http_response.id+ assert "_reemit_source" not in unpacked_response.data+ unpacked_json = unpacked_response.json()+ assert unpacked_json["reemit_source"] == "js_unpacker"+ assert "_reemit_source" not in unpacked_json["data_json"]+ reconstituted_unpacked = event_from_json(unpacked_json)+ assert reconstituted_unpacked.reemit_source == "js_unpacker"+ assert reconstituted_unpacked.id == unpacked_response.id+event_1 = scan.make_event("127.0.0.1", parent=scan.root_event)event_2 = scan.make_event("127.0.0.2", parent=event_1)event_3 = scan.make_event("127.0.0.3", parent=event_2)diff --git a/bbot/test/test_step_2/module_tests/test_module_js_unpacker.py b/bbot/test/test_step_2/module_tests/test_module_js_unpacker.pynew file mode 100644index 000000000..75617026d--- /dev/null+++ b/bbot/test/test_step_2/module_tests/test_module_js_unpacker.py@@ -0,0 +1,279 @@+import json++from .base import ModuleTestBase+from bbot.modules.js_unpacker import DeanEdwardsUnpacker, ObfuscatorIOUnpacker+from bbot.test.worker import HTTPSERVER_PORT, HTTPSERVER_URL+++def _use_worker_port(js):+ """Point a fixture's baked-in URLs at this xdist worker's mock server.++ Dean Edwards carries its host as a packer keyword, so only the port is substituted there.+ """+ return js.replace("http://127.0.0.1:8888", HTTPSERVER_URL).replace(":8888", f":{HTTPSERVER_PORT}")+++# -- Realistic packed/obfuscated JS fixtures --++SOURCE_MAP_JS = r"""!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.MyLib=t():e.MyLib=t()}(self,(function(){return(()=>{"use strict";var e={d:(t,n)=>{for(var r in n)e.o(n,r)&&!e.o(t,r)&&Object.defineProperty(t,r,{enumerable:!0,get:n[r]})},o:(e,t)=>Object.prototype.hasOwnProperty.call(e,t)};var t={};e.d(t,{default:()=>n});const n={init:function(e){this.config=Object.assign({debug:!1,endpoint:"/api/v2/collect"},e)},track:function(e,t){this.queue.push({event:e,properties:t||{},timestamp:Date.now()})}};return t})()}));+//# sourceMappingURL=my-lib.min.js.map"""++SOURCE_MAP_JSON = json.dumps(+ {+ "version": 3,+ "file": "my-lib.min.js",+ "sources": ["src/index.js", "src/tracker.js"],+ "sourcesContent": [+ 'import { Tracker } from "./tracker";\nconst tracker = new Tracker({\n endpoint: "http://127.0.0.1:8888/analytics/collect",\n batchSize: 10,\n});\ntracker.init();\n',+ 'export class Tracker {\n constructor(config) {\n this.endpoint = config.endpoint || "http://127.0.0.1:8888/fallback/collect";\n }\n flush() {\n navigator.sendBeacon(this.endpoint, JSON.stringify({ events: this.queue }));\n }\n}\n',+ ],+ "mappings": "AAAA",+ }+)+SOURCE_MAP_JSON = _use_worker_port(SOURCE_MAP_JSON)++# Dean Edwards packed JS. The payload "u://s:PORT/p/o.j" decodes via keyword+# substitution to "http://127.0.0.1:PORT/hidden/tracker.js":+# u(pos30)=http, s(pos28)=127.0.0.1, p(pos25)=hidden, o(pos24)=tracker, j(pos19)=js+# The ":PORT/" and "." separators stay literal (not word chars), so the port is substituted in.+DEAN_EDWARDS_JS = _use_worker_port(+ r"""eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--){d[e(c)]=k[c]||e(c)}k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--){if(k[c]){p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c])}}return p}('v 9=["\\x6F\\x6E\\x6C\\x6F\\x61\\x64"];b[9[0]]=f(){v 3=h[9[1]]("r");3[9[2]]="";v 7=h[9[5]](9[4]);7[9[3]]="u://s:8888/p/o.j";h[9[6]][9[7]](7)};',32,32,'|||el|||||||_0x1a2b|||||function||document||js|analytics|cdn|static|loader|tracker|hidden|com|main|127.0.0.1|cdn2|http|var'.split('|'),0,{}))"""+)++# obfuscator.io sample with a hidden API URL in the string array+OBFUSCATOR_IO_JS = _use_worker_port(+ r"""var _0x4e2f=['querySelector','addEventListener','click','getAttribute','data-target','getElementById','style','display','none','block','http://127.0.0.1:8888/tracker/events','POST','Content-Type','application/json','fetch','method','DOMContentLoaded','complete','readyState'];(function(_0x2a8c13,_0x4e2f6d){var _0x3b1c04=function(_0x5d6e2a){while(--_0x5d6e2a){_0x2a8c13['push'](_0x2a8c13['shift']());}};_0x3b1c04(++_0x4e2f6d);}(_0x4e2f,0x7b));var _0x3b1c=function(_0x2a8c13,_0x4e2f6d){_0x2a8c13=_0x2a8c13-0x0;var _0x3b1c04=_0x4e2f[_0x2a8c13];return _0x3b1c04;};(function(){document[_0x3b1c('0x0')]('.nav-toggle')[_0x3b1c('0x1')](_0x3b1c('0x2'),function(){var _0x2ce9=this[_0x3b1c('0x3')](_0x3b1c('0x4'));document[_0x3b1c('0x5')](_0x2ce9)[_0x3b1c('0x6')][_0x3b1c('0x7')]=_0x3b1c('0x9');_0x3b1c('0xe')(_0x3b1c('0xa'),{_0x3b1c('0xf'):_0x3b1c('0xb')});});})();"""+)++NEXTJS_MANIFEST_JS = """self.__BUILD_MANIFEST=function(s,c,a,e,d,b,f,g){return{__rewrites:{afterFiles:[],beforeFiles:[],fallback:[]},"/":["static/chunks/pages/index-8a3b2c1d.js"],"/about":[s,"static/chunks/pages/about-f4e7d6a2.js"],"/blog":[s,c,"static/chunks/pages/blog-1b9e3c5a.js"],"/blog/[slug]":[s,c,a,"static/chunks/pages/blog/[slug]-7d2f4e8b.js"],"/contact":[s,"static/chunks/pages/contact-3a6c9d1e.js"],"/dashboard":[s,c,e,"static/chunks/pages/dashboard-5e8b2f7d.js"],"/dashboard/settings":[s,c,e,d,"static/chunks/pages/dashboard/settings-9c4a1e6f.js"],"/api/health":[],"/_error":["static/chunks/pages/_error-2b5d8f3a.js"],sortedPages:["/","/about","/api/health","/blog","/blog/[slug]","/contact","/dashboard","/dashboard/settings","/_error"]}}("static/chunks/438-a2c7e4d1b3f89056.js","static/chunks/291-d5f8a1c3e7b24690.js","static/chunks/834-b7e2d4f6a8c31095.js","static/chunks/612-c9a3e5d7f1b48062.js","static/chunks/157-e1d3f5a7c9b20648.js"),self.__BUILD_MANIFEST_CB&&self.__BUILD_MANIFEST_CB();"""++NEXTJS_HTML = """<!DOCTYPE html><html><head><meta charSet="utf-8"/><title>Blog</title></head><body><div id="__next"><main><h1>Blog</h1></main></div><script id="__NEXT_DATA__" type="application/json">{"props":{"pageProps":{"posts":[{"id":"a1b2c3","title":"Getting Started","slug":"getting-started"}],"totalPages":5,"currentPage":1},"__N_SSP":true},"page":"/blog","query":{},"buildId":"xK7rT2mN9pQ4wE6y","isFallback":false,"gssp":true,"scriptLoader":[]}</script></body></html>"""++WEBPACK_JS = _use_worker_port(+ """(window.webpackJsonp=window.webpackJsonp||[]).push([[3],{147:function(e,t,n){"use strict";n.r(t);var r=n(0),o=n(1),i=n(12);var u=function(){function e(t){this.baseUrl=t.baseUrl||"http://127.0.0.1:8888/api/v1",this.headers={"Content-Type":"application/json",Accept:"application/json"},t.apiKey&&(this.headers["X-API-Key"]=t.apiKey)}var t;return t=e,(n=[{key:"request",value:function(e,t,n){var r=this;return fetch(this.baseUrl+t,Object.assign({},{method:e,headers:this.headers}))}}])&&l(t.prototype,n),e}();t.default=u},12:function(e,t,n){"use strict";n.d(t,"a",(function(){return r}));var r=function(e){return"string"==typeof e&&e.length>0}}}]);"""+)++# Plain JS with no packing+CLEAN_JS = """(function(){"use strict";var app={init:function(){document.addEventListener("DOMContentLoaded",function(){console.log("ready")})},render:function(el,data){el.innerHTML=data.map(function(item){return"<div>"+item.name+"</div>"}).join("")}};app.init()})();"""+++class TestJsUnpacker(ModuleTestBase):+ module_name = "js_unpacker"+ targets = [HTTPSERVER_URL]+ modules_overrides = ["http", "excavate", "js_unpacker"]+ config_overrides = {"web": {"spider_distance": 2, "spider_depth": 4, "spider_links_per_page": 25}}++ async def setup_after_prep(self, module_test):+ index_html = """<html><head>+ <script src="/js/packed.js"></script>+ <script src="/js/bundle.js"></script>+ <script src="/js/obfuscated.js"></script>+ <script src="/js/lib.min.js"></script>+ <script src="/_next/static/xK7rT2mN9pQ4wE6y/_buildManifest.js"></script>+ <script src="/js/clean.js"></script>+ <a href="/blog">Blog</a>+ </head><body>ok</body></html>"""+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/"},+ respond_args={"response_data": index_html},+ )+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/js/packed.js"},+ respond_args={"response_data": DEAN_EDWARDS_JS, "content_type": "application/javascript"},+ )+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/js/bundle.js"},+ respond_args={"response_data": WEBPACK_JS, "content_type": "application/javascript"},+ )+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/js/obfuscated.js"},+ respond_args={"response_data": OBFUSCATOR_IO_JS, "content_type": "application/javascript"},+ )+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/js/lib.min.js"},+ respond_args={"response_data": SOURCE_MAP_JS, "content_type": "application/javascript"},+ )+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/js/my-lib.min.js.map"},+ respond_args={"response_data": SOURCE_MAP_JSON, "content_type": "application/json"},+ )+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/_next/static/xK7rT2mN9pQ4wE6y/_buildManifest.js"},+ respond_args={"response_data": NEXTJS_MANIFEST_JS, "content_type": "application/javascript"},+ )+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/js/clean.js"},+ respond_args={"response_data": CLEAN_JS, "content_type": "application/javascript"},+ )+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/blog"},+ respond_args={"response_data": NEXTJS_HTML, "content_type": "text/html"},+ )++ def check(self, module_test, events):+ detections = module_test.module.detections+ detected_names = {name for name, url in detections}+ detected_urls = {url for name, url in detections}++ # -- Detection assertions --+ assert "dean-edwards" in detected_names, "Dean Edwards packer not detected"+ assert "webpack" in detected_names, "Webpack bundle not detected"+ assert "obfuscator-io" in detected_names, "obfuscator.io not detected"+ assert "source-map" in detected_names, "Source map not detected"+ assert "nextjs" in detected_names, "Next.js manifest not detected"+ assert not any("clean.js" in u for u in detected_urls), "Clean JS should not trigger detection"++ # Next.js should detect both _buildManifest.js and __NEXT_DATA__ in HTML+ nextjs_urls = {url for name, url in detections if name == "nextjs"}+ assert any("blog" in u for u in nextjs_urls), "Next.js __NEXT_DATA__ not detected in /blog HTML"+ assert any("_buildManifest.js" in u for u in nextjs_urls), "Next.js _buildManifest not detected"++ # -- End-to-end extraction assertions --+ # All hidden URLs point at the worker's mock server, so they stay in-scope+ url_events = {e.data.get("url", e.data) for e in events if e.type == "URL_UNVERIFIED"}++ # Source map: excavate should find URLs from the original source+ assert any("/analytics/collect" in str(u) for u in url_events), (+ "Source map: excavate didn't find /analytics/collect"+ )+ assert any("/fallback/collect" in str(u) for u in url_events), (+ "Source map: excavate didn't find /fallback/collect"+ )++ # Dean Edwards: the hidden URL should survive into the unpacked body.+ # Asserted on the body rather than on excavate's output because .js URLs are emitted+ # internal, and only reach output modules if they get promoted for graph-importance.+ # excavate's consumption of dean-edwards output is covered by TestJsUnpackerBadsecretsChain.+ dean_edwards_bodies = [+ e.body+ for e in events+ if e.type == "HTTP_RESPONSE" and "js-unpacked" in e.tags and e.data["url"].endswith("/js/packed.js")+ ]+ assert any("/hidden/tracker.js" in b for b in dean_edwards_bodies), (+ f"Dean Edwards: /hidden/tracker.js missing from unpacked body: {dean_edwards_bodies}"+ )++ # obfuscator.io: excavate should find the API endpoint after deobfuscation+ assert any("/tracker/events" in str(u) for u in url_events), (+ "obfuscator.io: excavate didn't find /tracker/events"+ )++ # Webpack: excavate should find the API base URL+ assert any("/api/v1" in str(u) for u in url_events), "Webpack: excavate didn't find /api/v1"++ # the re-emit marker rides on the event, not inside the response data+ unpacked = [e for e in events if e.type == "HTTP_RESPONSE" and "js-unpacked" in e.tags]+ assert unpacked, "no unpacked HTTP_RESPONSE events were emitted"+ assert all(e.reemit_source == "js_unpacker" for e in unpacked), (+ f"unpacked responses missing reemit_source: {[e.reemit_source for e in unpacked]}"+ )+ assert not any("_reemit_source" in e.data for e in unpacked), "reemit marker leaked back into the event's data"++ # Next.js: should emit route URLs+ assert any("/about" in str(u) for u in url_events), "Next.js: didn't emit /about route"+ assert any("/contact" in str(u) for u in url_events), "Next.js: didn't emit /contact route"+ assert any("/dashboard" in str(u) for u in url_events), "Next.js: didn't emit /dashboard route"+++# JWT signed with "keyboard cat" (in badsecrets wordlist), packed with Dean Edwards+PACKED_JWT_JS = r"""eval(function(p,a,c,k,e,d){e=function(c){return(c<a?'':e(parseInt(c/a)))+((c=c%a)>35?String.fromCharCode(c+29):c.toString(36))};if(!''.replace(/^/,String)){while(c--)d[e(c)]=k[c]||e(c);k=[function(e){return d[e]}];e=function(){return'\\w+'};c=1};while(c--)if(k[c])p=p.replace(new RegExp('\\b'+e(c)+'\\b','g'),k[c]);return p}('0 1 = 1 || {};\n1.2 = "/3/4";\n1.5 = "6.7.8";\n1.9 = a() {\n 0 b = c.d("b");\n b.e = "f";\n g.h("9 i");\n};\nc.j("k", 1.9);',22,21,'var|Config|apiBase|api|v2|platformToken|eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9|eyJzdWIiOiJzdmMtdGVzdCIsImlhdCI6MTcxODAwMDAwMCwiZXhwIjoxNzQ5NTM2MDAwLCJyb2xlIjoiYWRtaW4ifQ|G3x7IT4oTz4LNpphnOEcFEuztBOE_zBSs1owpqDluFU|init|function|status|document|getElementById|textContent|connected|console|log|complete|addEventListener|DOMContentLoaded'.split('|'),0,{}))"""++VULN_JWT = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJzdmMtdGVzdCIsImlhdCI6MTcxODAwMDAwMCwiZXhwIjoxNzQ5NTM2MDAwLCJyb2xlIjoiYWRtaW4ifQ.G3x7IT4oTz4LNpphnOEcFEuztBOE_zBSs1owpqDluFU"+++class TestJsUnpackerBadsecretsChain(ModuleTestBase):+ """js_unpacker -> excavate -> badsecrets: a packed JWT with a weak secret should produce a HIGH finding."""++ module_name = "js_unpacker"+ targets = [HTTPSERVER_URL]+ modules_overrides = ["http", "excavate", "js_unpacker", "badsecrets"]++ async def setup_after_prep(self, module_test):+ page_html = f"<html><head><script>{PACKED_JWT_JS}</script></head><body>ok</body></html>"+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/"},+ respond_args={"response_data": page_html},+ )++ def check(self, module_test, events):+ badsecrets_finding = any(+ e.type == "FINDING" and "keyboard cat" in e.data["description"] and VULN_JWT in e.data["description"]+ for e in events+ )+ assert badsecrets_finding, "badsecrets should find 'keyboard cat' in unpacked JWT"++ excavate_jwt = any(+ e.type == "FINDING"+ and "JWT" in e.data["description"]+ and "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9" in e.data["description"]+ for e in events+ )+ assert excavate_jwt, "excavate should extract JWT from unpacked response"+++def _cdn_map(marker):+ return json.dumps({"version": 3, "sources": ["src/app.js"], "sourcesContent": [f"const marker = '{marker}';"]})+++class TestJsUnpackerSourceMapBlacklist(ModuleTestBase):+ """Off-scope source maps are fetched, but blacklisted ones never are."""++ module_name = "js_unpacker"+ targets = [HTTPSERVER_URL]+ blacklist = ["blocked-cdn.test"]+ modules_overrides = ["http", "excavate", "js_unpacker"]+ config_overrides = {"web": {"spider_distance": 1, "spider_depth": 2}}+ allowed_map = "https://allowed-cdn.test/app.min.js.map"+ blocked_map = "https://blocked-cdn.test/app.min.js.map"++ async def setup_after_prep(self, module_test):+ index_html = (+ '<html><head><script src="/js/allowed.js"></script><script src="/js/blocked.js"></script></head></html>'+ )+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": "/"},+ respond_args={"response_data": index_html},+ )+ for name, map_url in (("allowed", self.allowed_map), ("blocked", self.blocked_map)):+ module_test.set_expect_requests(+ expect_args={"method": "GET", "uri": f"/js/{name}.js"},+ respond_args={+ "response_data": f"var a=1;\n//# sourceMappingURL={map_url}",+ "content_type": "application/javascript",+ },+ )+ module_test.blasthttp_mock.add_response(url=map_url, text=_cdn_map(f"{name}-map-marker"))++ def check(self, module_test, events):+ finding_urls = {e.data["url"] for e in events if e.type == "FINDING"}+ assert self.allowed_map in finding_urls, "off-scope (non-blacklisted) source map should still be fetched"+ assert self.blocked_map not in finding_urls, "blacklisted source map should never be fetched"+ unpacked_bodies = [e.body for e in events if e.type == "HTTP_RESPONSE" and "js-unpacked" in e.tags]+ assert any("allowed-map-marker" in b for b in unpacked_bodies)+ assert not any("blocked-map-marker" in b for b in unpacked_bodies)+++def test_dean_edwards_ignores_inflated_keyword_count():+ """A page-supplied keyword count far beyond the keyword list must not change or stall decoding."""+ inflated = DEAN_EDWARDS_JS.replace("',32,32,'", "',32,99999999999999,'")+ assert inflated != DEAN_EDWARDS_JS+ expected = DeanEdwardsUnpacker._decode(DEAN_EDWARDS_JS)+ assert "/hidden/tracker.js" in expected+ assert DeanEdwardsUnpacker._decode(inflated) == expected+++def test_obfuscator_io_reduces_rotation_amount():+ """A huge page-supplied rotation amount is applied modulo the array length."""+ amount = 3 * 10**15 + 1++ def body(rotation):+ return (+ "var _0xabcd=['aaa','bbb','ccc'];"+ "(function(_0x1,_0x2){var f=function(n){while(--n){_0x1['push'](_0x1['shift']());}};f(++_0x2);}"+ f"(_0xabcd,{hex(rotation)}));"+ "var _0xacc=function(_0x1,_0x2){_0x1=_0x1-0x0;var r=_0xabcd[_0x1];return r;};"+ "x(_0xacc('0x0'));"+ )++ assert "x('bbb')" in ObfuscatorIOUnpacker._deobfuscate(body(amount))+ assert "x('aaa')" in ObfuscatorIOUnpacker._deobfuscate(body(3 * 10**15))