-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
483 lines (429 loc) · 19.8 KB
/
Copy pathcontent.js
File metadata and controls
483 lines (429 loc) · 19.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
// NULLBREACH — Content Script
// Runs on every page at document_idle
// Passive analysis only — reads DOM, scripts, network requests already made by the page
(function () {
'use strict';
if (window.__NULLBREACH_INJECTED__) return;
window.__NULLBREACH_INJECTED__ = true;
const startTime = Date.now();
const findings = {
url: location.href,
cookies: [],
xssSurfaces: [],
openRedirects: [],
cveFindings: [],
secretFindings: [],
infoDisclosures: [],
endpoints: [],
corsData: [],
mixedContent: [],
techStack: [],
scanDuration: 0,
};
// ── MODULE: TECH STACK DETECTION ────────────────────────────────────────
function detectTechStack() {
const stack = [];
const html = document.documentElement.outerHTML;
const scripts = Array.from(document.querySelectorAll('script[src]')).map(s => s.src);
const metas = Array.from(document.querySelectorAll('meta')).reduce((acc, m) => {
if (m.name) acc[m.name.toLowerCase()] = m.content;
return acc;
}, {});
// Framework / library detection
const checks = [
{ name: 'React', test: () => !!(window.React || window.__REACT_DEVTOOLS_GLOBAL_HOOK__ || document.querySelector('[data-reactroot],[data-reactid]')) },
{ name: 'Vue.js', test: () => !!(window.Vue || document.querySelector('[data-v-]')) },
{ name: 'Angular', test: () => !!(window.angular || document.querySelector('[ng-version],[ng-app]')) },
{ name: 'Next.js', test: () => !!(window.__NEXT_DATA__ || document.querySelector('#__NEXT_DATA__')) },
{ name: 'Nuxt.js', test: () => !!(window.__NUXT__ || document.querySelector('#__nuxt')) },
{ name: 'jQuery', test: () => !!(window.jQuery || window.$?.fn?.jquery) },
{ name: 'WordPress', test: () => !!(document.querySelector('link[href*="/wp-content/"]') || document.querySelector('script[src*="/wp-includes/"]')) },
{ name: 'Drupal', test: () => !!(window.Drupal || document.querySelector('script[src*="drupal"]')) },
{ name: 'Shopify', test: () => !!(window.Shopify || metas['shopify-checkout-api-token']) },
{ name: 'Laravel', test: () => !!(metas['csrf-token'] && document.querySelector('meta[name="csrf-token"]')) },
{ name: 'Django', test: () => !!(document.querySelector('[name="csrfmiddlewaretoken"]')) },
{ name: 'ASP.NET', test: () => !!(document.querySelector('[name="__RequestVerificationToken"]') || document.querySelector('[id*="__VIEWSTATE"]')) },
{ name: 'Ruby on Rails', test: () => !!(document.querySelector('meta[name="csrf-token"][content]') && html.includes('rails')) },
{ name: 'Bootstrap', test: () => !!(document.querySelector('link[href*="bootstrap"]') || scripts.some(s => s.includes('bootstrap'))) },
{ name: 'Tailwind CSS', test: () => Array.from(document.querySelectorAll('[class]')).some(el => /\b(flex|grid|text-\w+|bg-\w+|p-\d|m-\d)\b/.test(el.className)) },
{ name: 'GraphQL', test: () => !!(window.__APOLLO_CLIENT__ || document.querySelector('script[src*="graphql"]') || html.includes('__typename')) },
{ name: 'Firebase', test: () => !!(window.firebase || scripts.some(s => s.includes('firebase'))) },
{ name: 'Stripe', test: () => !!(window.Stripe || scripts.some(s => s.includes('stripe'))) },
{ name: 'Google Analytics', test: () => !!(window.ga || window.gtag || window.dataLayer) },
{ name: 'Cloudflare', test: () => !!(document.querySelector('script[src*="cloudflare"]') || document.querySelector('div#challenge-form')) },
];
for (const check of checks) {
try { if (check.test()) stack.push(check.name); } catch (_) {}
}
// jQuery version detection
if (window.jQuery) {
const version = window.jQuery.fn.jquery;
if (version) stack.push(`jQuery ${version}`);
}
return stack;
}
// ── MODULE: LIBRARY VERSION SCANNER ─────────────────────────────────────
async function scanLibraries() {
const libs = [];
// Inline version detection from window globals
const candidates = [
{ name: 'jQuery', version: () => window.jQuery?.fn?.jquery || window.$?.fn?.jquery },
{ name: 'angular', version: () => window.angular?.version?.full },
{ name: 'bootstrap', version: () => window.bootstrap?.Tooltip?.VERSION || window.$.fn?.tooltip?.Constructor?.VERSION },
{ name: 'lodash', version: () => window._?.VERSION },
{ name: 'moment', version: () => window.moment?.version },
{ name: 'underscore', version: () => window._?.VERSION && !window._.chain ? window._.VERSION : null },
{ name: 'handlebars', version: () => window.Handlebars?.VERSION },
{ name: 'axios', version: () => window.axios?.VERSION },
{ name: 'marked', version: () => window.marked?.defaults ? window.marked?.setOptions?.toString().match(/[\d.]+/)?.[0] : null },
];
for (const c of candidates) {
try {
const v = c.version();
if (v) libs.push({ name: c.name, version: v });
} catch (_) {}
}
// Script src version detection
const scriptTags = Array.from(document.querySelectorAll('script[src]'));
for (const s of scriptTags) {
const src = s.src;
const match = src.match(/(?:jquery|bootstrap|angular|lodash|moment|underscore|handlebars|axios|highlight\.?js|marked)[.@/-]([\d]+\.[\d]+\.?[\d]*)/i);
if (match) {
const libName = match[0].split(/[.@/-]/)[0].toLowerCase().replace('highlight', 'highlight.js');
const already = libs.find(l => l.name.toLowerCase() === libName);
if (!already) libs.push({ name: libName, version: match[1] });
}
}
// CVE check each found library
for (const lib of libs) {
const result = await sendMessage({ type: 'CHECK_CVE', library: lib.name, version: lib.version });
if (result?.findings?.length) {
findings.cveFindings.push(...result.findings.map(f => ({
...f,
detail: f.detail,
path: location.href,
})));
}
}
}
// ── MODULE: XSS SURFACE SCANNER ─────────────────────────────────────────
function scanXSSSurfaces() {
const surfaces = [];
// URL parameter reflection detection
const urlParams = new URLSearchParams(location.search);
for (const [key, value] of urlParams.entries()) {
if (value.length > 2) {
// Check if value appears in DOM (reflection)
const bodyText = document.body?.innerHTML || '';
if (bodyText.includes(value) && !value.match(/^[0-9a-f-]{36}$/i)) {
const isEscaped = bodyText.includes(escapeHTML(value));
surfaces.push({
type: 'URL Parameter Reflection',
severity: isEscaped ? 'medium' : 'high',
description: `URL parameter "${key}" is reflected in the page ${isEscaped ? '(appears HTML-encoded)' : '— NO HTML encoding detected, potential XSS'}`,
detail: `Param: ${key}=${value.substring(0, 40)}`,
location: location.href,
});
}
}
}
// Dangerous innerHTML / document.write usage (from inline scripts)
const inlineScripts = Array.from(document.querySelectorAll('script:not([src])')).map(s => s.textContent);
for (const script of inlineScripts) {
if (/innerHTML\s*=\s*(?!`|'[^']*'|"[^"]*")/.test(script)) {
surfaces.push({
type: 'Dangerous innerHTML Assignment',
severity: 'medium',
description: 'Inline script assigns to innerHTML from a non-literal source — potential DOM XSS vector',
detail: 'Pattern: innerHTML = <non-literal>',
location: location.href,
});
break;
}
if (/document\.write\s*\(/.test(script)) {
surfaces.push({
type: 'document.write Usage',
severity: 'low',
description: 'document.write() usage detected — can introduce XSS if input is unsanitized',
detail: 'Pattern: document.write()',
location: location.href,
});
break;
}
}
// Forms without CSRF tokens
const forms = Array.from(document.querySelectorAll('form[method]'));
for (const form of forms) {
const method = form.method?.toUpperCase();
if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
const hasCSRF = form.querySelector(
'[name*="csrf"],[name*="token"],[name*="_token"],[name="authenticity_token"],[name="__RequestVerificationToken"]'
);
if (!hasCSRF) {
surfaces.push({
type: 'Form Missing CSRF Token',
severity: 'medium',
description: `POST form "${form.action || 'current URL'}" has no visible CSRF token field`,
detail: `Action: ${form.action || location.href}`,
location: form.action || location.href,
});
}
}
}
// Input fields without autocomplete=off on sensitive fields
const sensitiveInputs = document.querySelectorAll(
'input[type="password"], input[name*="ssn"], input[name*="card"], input[name*="cvv"]'
);
for (const input of sensitiveInputs) {
if (input.autocomplete !== 'off' && input.autocomplete !== 'new-password') {
surfaces.push({
type: 'Sensitive Input Autocomplete Enabled',
severity: 'low',
description: `Sensitive input field "${input.name || input.id || input.type}" may be cached by browser via autocomplete`,
detail: `Field: ${input.name || input.id || '(unnamed)'}`,
location: location.href,
});
break;
}
}
return surfaces;
}
// ── MODULE: OPEN REDIRECT SCANNER ───────────────────────────────────────
function scanOpenRedirects() {
const redirectParams = ['redirect', 'redirect_uri', 'redirect_url', 'return', 'returnto', 'return_to', 'next', 'url', 'to', 'goto', 'destination', 'dest', 'forward', 'target', 'redir', 'r', 'u'];
const found = [];
const urlParams = new URLSearchParams(location.search);
for (const param of redirectParams) {
if (urlParams.has(param)) {
const value = urlParams.get(param);
if (value && (value.startsWith('http') || value.startsWith('//') || value.startsWith('%2F%2F'))) {
found.push({ param, url: location.href });
} else if (value) {
found.push({ param, url: location.href, note: 'relative redirect — verify destination' });
}
}
}
// Hash-based redirects
if (location.hash) {
const hash = decodeURIComponent(location.hash.slice(1));
if (hash.startsWith('http') || hash.startsWith('//')) {
found.push({ param: '#fragment', url: location.href });
}
}
return found;
}
// ── MODULE: MIXED CONTENT SCANNER ───────────────────────────────────────
function scanMixedContent() {
if (!location.protocol.includes('https')) return [];
const insecure = [];
const selectors = [
['img', 'src'], ['script', 'src'], ['link', 'href'],
['iframe', 'src'], ['audio', 'src'], ['video', 'src'],
['source', 'src'], ['object', 'data'], ['embed', 'src'],
];
for (const [tag, attr] of selectors) {
document.querySelectorAll(`${tag}[${attr}]`).forEach(el => {
const val = el.getAttribute(attr);
if (val && val.startsWith('http://')) insecure.push(`${tag}[${attr}]: ${val.substring(0, 80)}`);
});
}
return insecure;
}
// ── MODULE: ENDPOINT MAPPER ──────────────────────────────────────────────
function mapEndpoints() {
const endpoints = new Set();
// Links
document.querySelectorAll('a[href]').forEach(a => {
try {
const url = new URL(a.href, location.href);
if (url.hostname === location.hostname) endpoints.add(url.pathname + url.search);
} catch (_) {}
});
// Forms
document.querySelectorAll('form[action]').forEach(f => {
try {
const url = new URL(f.action, location.href);
if (url.hostname === location.hostname) endpoints.add(url.pathname);
} catch (_) {}
});
// API calls from inline scripts
const scriptContent = Array.from(document.querySelectorAll('script:not([src])')).map(s => s.textContent).join('\n');
const apiPatterns = [
/fetch\(['"`](\/[^'"`\s]+)/g,
/axios\.\w+\(['"`](\/[^'"`\s]+)/g,
/\$\.(?:get|post|ajax)\s*\(\s*['"`](\/[^'"`\s]+)/g,
/XMLHttpRequest[\s\S]{0,100}open\s*\(\s*['"`]\w+['"`]\s*,\s*['"`](\/[^'"`\s]+)/g,
/['"`](\/api\/[^'"`\s]+)/g,
/['"`](\/v\d+\/[^'"`\s]+)/g,
/['"`](\/graphql[^'"`\s]*)/g,
];
for (const pattern of apiPatterns) {
let m;
const regex = new RegExp(pattern.source, 'g');
while ((m = regex.exec(scriptContent)) !== null) {
endpoints.add(m[1].split('?')[0]);
}
}
return [...endpoints].slice(0, 100);
}
// ── MODULE: INFO DISCLOSURE SCANNER ─────────────────────────────────────
function scanInfoDisclosures() {
const disclosures = [];
// HTML comments containing sensitive info
const walker = document.createTreeWalker(document.documentElement, NodeFilter.SHOW_COMMENT, null);
const interestingComments = [];
let node;
while ((node = walker.nextNode())) {
const text = node.textContent.trim();
if (text.length > 5 && (
/todo|fixme|hack|bug|password|secret|key|token|credential|internal|staging|debug|remove|temp|todo/i.test(text) ||
/http[s]?:\/\//i.test(text) ||
/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/.test(text)
)) {
interestingComments.push(text.substring(0, 120));
}
}
if (interestingComments.length > 0) {
disclosures.push({
type: 'SENSITIVE_COMMENT',
title: `Sensitive HTML Comments (${interestingComments.length})`,
severity: 'low',
description: 'HTML comments contain potentially sensitive information visible in page source',
detail: interestingComments.slice(0, 5).join('\n---\n'),
cwe: 'CWE-615',
cvss: 3.7,
path: location.href,
});
}
// Version/path disclosure in meta tags
document.querySelectorAll('meta[name="generator"]').forEach(m => {
disclosures.push({
type: 'INFO_DISCLOSURE',
title: 'Generator Tag Discloses CMS/Version',
severity: 'low',
description: `<meta name="generator"> reveals platform: "${m.content}"`,
detail: `Generator: ${m.content}`,
cwe: 'CWE-200',
cvss: 3.1,
path: location.href,
});
});
// Stack traces / error messages in DOM
const bodyText = document.body?.textContent || '';
const errorPatterns = [
{ pattern: /(?:stack trace|at \w+\.\w+ \(|Exception in thread)/i, name: 'Stack Trace in Page' },
{ pattern: /(?:mysql_error|pg_error|ORA-\d{5}|SQL syntax|sqlite_error)/i, name: 'Database Error Message' },
{ pattern: /(?:Warning: .+ on line \d|Notice: .+ on line \d|Fatal error:)/i, name: 'PHP Error Message' },
{ pattern: /(?:Internal Server Error|Unhandled Promise Rejection|TypeError:|ReferenceError:)/i, name: 'Application Error Exposed' },
];
for (const ep of errorPatterns) {
if (ep.pattern.test(bodyText)) {
disclosures.push({
type: 'ERROR_DISCLOSURE',
title: ep.name,
severity: 'medium',
description: `Page appears to expose ${ep.name.toLowerCase()} — reveals internal implementation details`,
detail: 'Pattern matched in visible page content',
cwe: 'CWE-209',
cvss: 5.3,
path: location.href,
});
}
}
return disclosures;
}
// ── MODULE: COOKIE READER ────────────────────────────────────────────────
async function readCookies() {
// Read document.cookie for JS-accessible cookies
const jsCookies = [];
if (document.cookie) {
document.cookie.split(';').forEach(pair => {
const [name] = pair.trim().split('=');
if (name) {
jsCookies.push({
name: name.trim(),
httpOnly: false, // If we can read it, it's not HttpOnly
secure: location.protocol === 'https:' ? undefined : false,
sameSite: undefined, // Cannot read from JS
});
}
});
}
// Get full cookies via background (chrome.cookies API)
try {
const response = await sendMessage({ type: 'GET_COOKIES_FOR_URL', url: location.href });
return response?.cookies || jsCookies;
} catch {
return jsCookies;
}
}
// ── MODULE: INLINE SCRIPT SECRET SCANNER ────────────────────────────────
async function scanInlineSecrets() {
const inlineScripts = Array.from(document.querySelectorAll('script:not([src])')).map(s => s.textContent);
const allFindings = [];
for (let i = 0; i < inlineScripts.length; i++) {
const code = inlineScripts[i];
if (code.length < 10) continue;
const result = await sendMessage({
type: 'ANALYSE_SECRETS',
code,
source: `inline-script-${i + 1} @ ${location.href}`,
});
if (result?.findings?.length) allFindings.push(...result.findings);
}
return allFindings;
}
// ── UTILITIES ─────────────────────────────────────────────────────────────
function escapeHTML(str) {
return str.replace(/[&<>"']/g, c => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));
}
function sendMessage(msg) {
return new Promise((resolve) => {
try {
chrome.runtime.sendMessage(msg, (response) => {
if (chrome.runtime.lastError) resolve(null);
else resolve(response);
});
} catch {
resolve(null);
}
});
}
// ── MAIN SCAN ORCHESTRATOR ────────────────────────────────────────────────
async function runScan() {
try {
// Run all modules
findings.techStack = detectTechStack();
findings.xssSurfaces = scanXSSSurfaces();
findings.openRedirects = scanOpenRedirects();
findings.mixedContent = scanMixedContent();
findings.endpoints = mapEndpoints();
findings.infoDisclosures = scanInfoDisclosures();
findings.cookies = await readCookies();
findings.secretFindings = await scanInlineSecrets();
await scanLibraries(); // populates findings.cveFindings
findings.scanDuration = Date.now() - startTime;
// Send everything to background for processing
const result = await sendMessage({
type: 'SCAN_COMPLETE',
data: findings,
});
// Signal popup if it's open
if (result?.success) {
sendMessage({ type: 'SCAN_RESULT_READY', tabId: null });
}
} catch (err) {
console.error('[NULLBREACH] Scan error:', err);
}
}
// Run after DOM is fully loaded
if (document.readyState === 'complete') {
setTimeout(runScan, 800);
} else {
window.addEventListener('load', () => setTimeout(runScan, 800));
}
// Listen for re-scan requests from popup
chrome.runtime.onMessage.addListener((msg) => {
if (msg.type === 'RESCAN') runScan();
});
})();