forked from CyberDrain/Check
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontent.js
More file actions
5403 lines (4868 loc) · 186 KB
/
content.js
File metadata and controls
5403 lines (4868 loc) · 186 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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Check - Final Rule-Driven Content Script
* 100% rule-driven architecture - NO hardcoded detections
*
* Logic Flow (CORRECTED):
* 1. Load rules and check trusted origins FIRST - immediate exit if trusted
* 2. Check if page is MS logon page (using rule file requirements)
* 3. If MS logon page on non-trusted domain, apply blocking rules
*/
// Prevent multiple script execution
if (window.checkExtensionLoaded) {
console.warn(
"[M365-Protection] Content script already loaded, skipping re-execution"
);
} else {
window.checkExtensionLoaded = true;
// Global state
let protectionActive = false;
let detectionRules = null;
let trustedLoginPatterns = [];
let microsoftDomainPatterns = [];
let domObserver = null;
let lastScanTime = 0;
let scanCount = 0;
let lastDetectionResult = null; // Store last detection analysis
let lastScannedPageSource = null; // Store the page source from the last scan
let lastPageSourceScanTime = 0; // When the page source was captured
let developerConsoleLoggingEnabled = false; // Cache for developer console logging setting
let showingBanner = false; // Flag to prevent DOM monitoring loops when showing banners
const MAX_SCANS = 5; // Prevent infinite scanning - reduced for performance
const SCAN_COOLDOWN = 1200; // 1200ms between scans - increased for performance
const THREAT_TRIGGERED_COOLDOWN = 500; // Shorter cooldown for threat-triggered re-scans
const WARNING_THRESHOLD = 3; // Block if 4+ warning threats found (escalation threshold)
let initialBody; // Reference to the initial body element
let lastPageSourceHash = null; // Hash of page source to detect real changes
let threatTriggeredRescanCount = 0; // Track threat-triggered re-scans
const MAX_THREAT_TRIGGERED_RESCANS = 2; // Max follow-up scans when threats detected
let scheduledRescanTimeout = null; // Track scheduled re-scan timeout
const regexCache = new Map();
let cachedPageSource = null;
let cachedPageSourceTime = 0;
const PAGE_SOURCE_CACHE_TTL = 1000;
const domQueryCache = new WeakMap();
let cachedStylesheetAnalysis = null;
// Console log capturing
let capturedLogs = [];
const MAX_LOGS = 100; // Limit the number of stored logs
// Override console methods to capture logs
function setupConsoleCapture() {
const originalConsole = {
log: console.log,
info: console.info,
warn: console.warn,
error: console.error,
debug: console.debug,
};
function createLogCapture(level, originalMethod) {
return function (...args) {
// Store the log entry
const logEntry = {
level: level,
message: args
.map((arg) =>
typeof arg === "object"
? JSON.stringify(arg, null, 2)
: String(arg)
)
.join(" "),
timestamp: Date.now(),
url: window.location.href,
};
capturedLogs.push(logEntry);
// Keep only the most recent logs
if (capturedLogs.length > MAX_LOGS) {
capturedLogs = capturedLogs.slice(-MAX_LOGS);
}
// Call the original method
originalMethod.apply(console, args);
};
}
// Override console methods
console.log = createLogCapture("log", originalConsole.log);
console.info = createLogCapture("info", originalConsole.info);
console.warn = createLogCapture("warn", originalConsole.warn);
console.error = createLogCapture("error", originalConsole.error);
console.debug = createLogCapture("debug", originalConsole.debug);
// Also capture window.onerror events
window.addEventListener("error", (event) => {
const logEntry = {
level: "error",
message: `${event.message} at ${event.filename}:${event.lineno}:${event.colno}`,
timestamp: Date.now(),
url: window.location.href,
};
capturedLogs.push(logEntry);
if (capturedLogs.length > MAX_LOGS) {
capturedLogs = capturedLogs.slice(-MAX_LOGS);
}
});
// Capture unhandled promise rejections
window.addEventListener("unhandledrejection", (event) => {
const logEntry = {
level: "error",
message: `Unhandled Promise Rejection: ${event.reason}`,
timestamp: Date.now(),
url: window.location.href,
};
capturedLogs.push(logEntry);
if (capturedLogs.length > MAX_LOGS) {
capturedLogs = capturedLogs.slice(-MAX_LOGS);
}
});
}
function isInIframe() {
try {
return window.self !== window.top;
} catch (e) {
// If we can't access window.top due to cross-origin, we're likely in an iframe
return true;
}
}
function getCachedRegex(pattern, flags = "") {
const key = `${pattern}|||${flags}`;
if (!regexCache.has(key)) {
try {
regexCache.set(key, new RegExp(pattern, flags));
} catch (error) {
logger.warn(`Invalid regex pattern: ${pattern}`, error);
return null;
}
}
return regexCache.get(key);
}
function getPageSource() {
const now = Date.now();
if (
!cachedPageSource ||
now - cachedPageSourceTime > PAGE_SOURCE_CACHE_TTL
) {
cachedPageSource = document.documentElement.outerHTML;
cachedPageSourceTime = now;
}
return cachedPageSource;
}
function clearPerformanceCaches() {
cachedPageSource = null;
cachedPageSourceTime = 0;
domQueryCache.delete(document);
cachedStylesheetAnalysis = null;
}
/**
* Compute simple hash of page source to detect changes
* Uses string length and character sampling for performance
*/
function computePageSourceHash(pageSource) {
if (!pageSource) return null;
// Simple hash: length + sample characters at key positions
const len = pageSource.length;
const samples = [];
const positions = [
Math.floor(len * 0.1),
Math.floor(len * 0.3),
Math.floor(len * 0.5),
Math.floor(len * 0.7),
Math.floor(len * 0.9)
];
for (const pos of positions) {
if (pos < len) {
samples.push(pageSource.charCodeAt(pos));
}
}
return `${len}:${samples.join(',')}`;
}
/**
* Check if page source has changed significantly
*/
function hasPageSourceChanged() {
const currentSource = getPageSource();
const currentHash = computePageSourceHash(currentSource);
if (!lastPageSourceHash) {
lastPageSourceHash = currentHash;
return false; // First check, no previous hash to compare
}
const changed = currentHash !== lastPageSourceHash;
if (changed) {
logger.debug(`Page source changed: ${lastPageSourceHash} -> ${currentHash}`);
lastPageSourceHash = currentHash;
}
return changed;
}
/**
* Schedule threat-triggered re-scans with progressive delays
* Automatically re-scans when threats detected to catch late-loading content
*/
function scheduleThreatTriggeredRescan(threatCount) {
// Clear any existing scheduled re-scan
if (scheduledRescanTimeout) {
clearTimeout(scheduledRescanTimeout);
scheduledRescanTimeout = null;
}
// Don't schedule if we've reached the limit
if (threatTriggeredRescanCount >= MAX_THREAT_TRIGGERED_RESCANS) {
logger.debug(`Max threat-triggered re-scans (${MAX_THREAT_TRIGGERED_RESCANS}) reached`);
return;
}
// Progressive delays: 800ms for first re-scan, 2000ms for second
const delays = [800, 2000];
const delay = delays[threatTriggeredRescanCount] || 2000;
logger.log(
`⏱️ Scheduling threat-triggered re-scan #${threatTriggeredRescanCount + 1} in ${delay}ms (${threatCount} threat(s) detected)`
);
threatTriggeredRescanCount++;
scheduledRescanTimeout = setTimeout(() => {
logger.log(`🔄 Running threat-triggered re-scan #${threatTriggeredRescanCount}`);
runProtection(true);
scheduledRescanTimeout = null;
}, delay);
}
function analyzeStylesheets() {
if (cachedStylesheetAnalysis) return cachedStylesheetAnalysis;
const analysis = { hasMicrosoftCSS: false, cssContent: "", sheets: [] };
try {
const styleSheets = Array.from(document.styleSheets);
for (const sheet of styleSheets) {
const sheetInfo = { href: sheet.href || "inline" };
if (sheet.href?.match(/msauth|msft|microsoft/i)) {
analysis.hasMicrosoftCSS = true;
}
try {
if (sheet.cssRules) {
analysis.cssContent +=
Array.from(sheet.cssRules)
.map((r) => r.cssText)
.join(" ") + " ";
sheetInfo.accessible = true;
}
} catch (e) {
sheetInfo.accessible = false;
}
analysis.sheets.push(sheetInfo);
}
} catch (e) {}
cachedStylesheetAnalysis = analysis;
return analysis;
}
/**
* Check if a URL matches any pattern in the given pattern array
* @param {string} url - The URL to check
* @param {string[]} patterns - Array of regex patterns
* @returns {boolean} - True if URL matches any pattern
*/
function matchesAnyPattern(url, patterns) {
if (!patterns || patterns.length === 0) return false;
for (const pattern of patterns) {
const regex = getCachedRegex(pattern);
if (regex && regex.test(url)) {
logger.debug(`URL "${url}" matches pattern: ${pattern}`);
return true;
}
}
return false;
}
/**
* Check if current URL is from a trusted Microsoft login domain
* @param {string} url - The URL to check
* @returns {boolean} - True if trusted login domain
*/
function isTrustedLoginDomain(url) {
try {
const urlObj = new URL(url);
const origin = urlObj.origin;
return matchesAnyPattern(origin, trustedLoginPatterns);
} catch (error) {
logger.warn("Invalid URL for trusted login domain check:", url);
return false;
}
}
/**
* Check if current URL is from a Microsoft domain (but not necessarily login)
* @param {string} url - The URL to check
* @returns {boolean} - True if Microsoft domain
*/
function isMicrosoftDomain(url) {
try {
const urlObj = new URL(url);
const origin = urlObj.origin;
return matchesAnyPattern(origin, microsoftDomainPatterns);
} catch (error) {
logger.warn("Invalid URL for Microsoft domain check:", url);
return false;
}
}
// Conditional logger that respects developer console logging setting
const logger = {
log: (...args) => {
if (developerConsoleLoggingEnabled) {
console.log("[M365-Protection]", ...args);
}
},
warn: (...args) => {
// Always show warnings regardless of developer setting
console.warn("[M365-Protection]", ...args);
},
error: (...args) => {
// Always show errors regardless of developer setting
console.error("[M365-Protection]", ...args);
},
debug: (...args) => {
if (developerConsoleLoggingEnabled) {
console.debug("[M365-Protection]", ...args);
}
},
};
/**
* Load developer mode setting from configuration (enables console logging and debug features)
*/
async function loadDeveloperConsoleLoggingSetting() {
try {
const config = await new Promise((resolve) => {
chrome.storage.local.get(["config"], (result) => {
resolve(result.config || {});
});
});
developerConsoleLoggingEnabled =
config.enableDeveloperConsoleLogging === true; // "Developer Mode" in UI
// Only setup console capture if developer mode is enabled
if (developerConsoleLoggingEnabled) {
setupConsoleCapture();
logger.log("Console capture enabled (developer mode active)");
}
} catch (error) {
// If there's an error loading settings, default to false
developerConsoleLoggingEnabled = false;
console.error(
"[M365-Protection] Error loading developer console logging setting:",
error
);
}
}
/**
* Re-initialize the DOM observer. This is critical for pages that use
* document.write() to replace the entire DOM after initial load.
*/
function reinitializeObserver() {
logger.warn("DOM appears to have been replaced. Re-initializing observer.");
if (domObserver) {
domObserver.disconnect();
domObserver = null;
}
clearPerformanceCaches();
setupDomObserver();
}
/**
* Load detection rules from the rule file - EVERYTHING comes from here
* Now uses the detection rules manager for caching and remote loading
*/
async function loadDetectionRules() {
try {
// Try to get rules from background script first (which handles caching)
try {
const response = await chrome.runtime.sendMessage({
type: "get_detection_rules",
});
if (response && response.success && response.rules) {
logger.log("Loaded detection rules from background script cache");
// Set up trusted login patterns and Microsoft domain patterns from cached rules
const rules = response.rules;
if (
rules.trusted_login_patterns &&
Array.isArray(rules.trusted_login_patterns)
) {
trustedLoginPatterns = rules.trusted_login_patterns;
logger.debug(
`Set up ${trustedLoginPatterns.length} trusted login patterns from cache`
);
}
if (
rules.microsoft_domain_patterns &&
Array.isArray(rules.microsoft_domain_patterns)
) {
microsoftDomainPatterns = rules.microsoft_domain_patterns;
logger.debug(
`Set up ${microsoftDomainPatterns.length} Microsoft domain patterns from cache`
);
}
return rules;
}
} catch (error) {
logger.warn(
"Failed to get rules from background script:",
error.message
);
}
// Fallback to direct loading (with no-cache to ensure fresh data)
const response = await fetch(
chrome.runtime.getURL("rules/detection-rules.json"),
{
cache: "no-cache",
}
);
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const rules = await response.json();
// Set up trusted login patterns and Microsoft domain patterns from rules ONLY
if (
rules.trusted_login_patterns &&
Array.isArray(rules.trusted_login_patterns)
) {
trustedLoginPatterns = rules.trusted_login_patterns.slice();
logger.debug(
`Set up ${trustedLoginPatterns.length} trusted login patterns from direct load`
);
} else {
logger.error(
"No trusted_login_patterns found in rules or not an array:",
rules.trusted_login_patterns
);
}
if (
rules.microsoft_domain_patterns &&
Array.isArray(rules.microsoft_domain_patterns)
) {
microsoftDomainPatterns = rules.microsoft_domain_patterns.slice();
logger.debug(
`Set up ${microsoftDomainPatterns.length} Microsoft domain patterns from direct load`
);
}
logger.log(
`Loaded detection rules: ${
trustedLoginPatterns.length
} trusted login patterns, ${rules.rules?.length || 0} detection rules`
);
return rules;
} catch (error) {
logger.error("CRITICAL: Failed to load detection rules:", error.message);
throw error; // Don't continue without rules
}
}
/**
* Manual test function for debugging detection patterns
* Call this from browser console: testDetectionPatterns()
*/
function testDetectionPatterns() {
console.log("🔍 MANUAL DETECTION TESTING");
const pageSource = getPageSource();
// Test each pattern individually
const patterns = [
{ name: "idPartnerPL", pattern: "idPartnerPL", type: "source_content" },
{ name: "loginfmt", pattern: "loginfmt", type: "source_content" },
{
name: "aadcdn_msauth",
pattern: "aadcdn\\.msauth\\.net",
type: "source_content",
},
{ name: "urlMsaSignUp", pattern: "urlMsaSignUp", type: "source_content" },
{ name: "i0116_element", pattern: "#i0116", type: "source_content" },
{
name: "ms_background_cdn",
pattern: "logincdn\\.msauth\\.net",
type: "source_content",
},
{
name: "segoe_ui_font",
pattern: "Segoe\\s+UI(?:\\s+(?:Webfont|Symbol|Historic|Emoji))?",
type: "source_content",
},
];
const cssPatterns = [
"width:\\s*27\\.5rem",
"height:\\s*21\\.125rem",
"max-width:\\s*440px",
"background-color:\\s*#0067b8",
"display:\\s*grid.*place-items:\\s*center",
];
patterns.forEach((p) => {
const regex = new RegExp(p.pattern, "i");
const found = regex.test(pageSource);
console.log(`${found ? "✅" : "❌"} ${p.name}: ${p.pattern}`);
if (found) {
const match = pageSource.match(regex);
console.log(` Match: "${match[0]}"`);
}
});
console.log("🎨 CSS PATTERNS:");
cssPatterns.forEach((pattern, idx) => {
const regex = new RegExp(pattern, "i");
const found = regex.test(pageSource);
console.log(`${found ? "✅" : "❌"} CSS[${idx}]: ${pattern}`);
if (found) {
const match = pageSource.match(regex);
console.log(` Match: "${match[0]}"`);
}
});
// Check external stylesheets
console.log("📎 EXTERNAL STYLESHEETS:");
const styleSheets = Array.from(document.styleSheets);
styleSheets.forEach((sheet, idx) => {
try {
const href = sheet.href || "inline";
console.log(` [${idx}] ${href}`);
// Check if stylesheet URL contains Microsoft patterns
if (href !== "inline") {
const msPatterns = [
"microsoft",
"msauth",
"msft",
"office365",
"o365",
];
const hasMsPattern = msPatterns.some((pattern) =>
href.toLowerCase().includes(pattern)
);
console.log(
` ${hasMsPattern ? "✅" : "❌"} Microsoft-themed URL`
);
}
// Try to check CSS rules (may be blocked by CORS)
if (sheet.cssRules) {
const cssText = Array.from(sheet.cssRules)
.map((rule) => rule.cssText)
.join(" ");
const hasSegoeUI = /segoe\s+ui/i.test(cssText);
const hasMsBlue = /#0067b8/i.test(cssText);
const has440px = /440px|27\.5rem/i.test(cssText);
console.log(` ${hasSegoeUI ? "✅" : "❌"} Segoe UI font`);
console.log(
` ${hasMsBlue ? "✅" : "❌"} Microsoft blue (#0067b8)`
);
console.log(` ${has440px ? "✅" : "❌"} 440px/27.5rem width`);
}
} catch (e) {
console.log(` ⚠️ Cannot access stylesheet (CORS): ${e.message}`);
}
});
return {
pageLength: pageSource.length,
url: window.location.href,
stylesheets: styleSheets.length,
};
}
// Make it globally available for testing
window.testDetectionPatterns = testDetectionPatterns;
/**
* Debug function to test phishing indicators - call from console
*/
async function testPhishingIndicators() {
console.log("🔍 TESTING PHISHING INDICATORS");
if (!detectionRules) {
console.error("❌ Detection rules not loaded!");
return;
}
if (!detectionRules.phishing_indicators) {
console.error("❌ No phishing indicators in detection rules!");
return;
}
console.log(
`📋 Found ${detectionRules.phishing_indicators.length} phishing indicators to test`
);
const pageSource = document.documentElement.outerHTML;
const pageText = document.body?.textContent || "";
const currentUrl = window.location.href;
console.log(`📄 Page source length: ${pageSource.length} chars`);
console.log(`📝 Page text length: ${pageText.length} chars`);
console.log(`🌐 Current URL: ${currentUrl}`);
let foundThreats = 0;
detectionRules.phishing_indicators.forEach((indicator, idx) => {
try {
console.log(
`\n🔍 Testing indicator ${idx + 1}/${
detectionRules.phishing_indicators.length
}: ${indicator.id}`
);
console.log(` Pattern: ${indicator.pattern}`);
console.log(` Flags: ${indicator.flags || "i"}`);
console.log(
` Severity: ${indicator.severity} | Action: ${indicator.action}`
);
const pattern = new RegExp(indicator.pattern, indicator.flags || "i");
// Test against page source
let matches = false;
let matchLocation = "";
if (pattern.test(pageSource)) {
matches = true;
matchLocation = "page source";
const match = pageSource.match(pattern);
console.log(` ✅ MATCH in ${matchLocation}: "${match[0]}"`);
}
// Test against visible text
else if (pattern.test(pageText)) {
matches = true;
matchLocation = "page text";
const match = pageText.match(pattern);
console.log(` ✅ MATCH in ${matchLocation}: "${match[0]}"`);
}
// Test against URL
else if (pattern.test(currentUrl)) {
matches = true;
matchLocation = "URL";
const match = currentUrl.match(pattern);
console.log(` ✅ MATCH in ${matchLocation}: "${match[0]}"`);
}
// Special handling for additional_checks
if (!matches && indicator.additional_checks) {
console.log(
` 🔍 Testing ${indicator.additional_checks.length} additional checks...`
);
for (const check of indicator.additional_checks) {
if (pageSource.includes(check) || pageText.includes(check)) {
matches = true;
matchLocation = "additional checks";
console.log(` ✅ MATCH in ${matchLocation}: "${check}"`);
break;
}
}
}
if (matches) {
foundThreats++;
console.log(` 🚨 THREAT DETECTED: ${indicator.description}`);
} else {
console.log(` ❌ No match found`);
}
} catch (error) {
console.error(` ⚠️ Error testing indicator ${indicator.id}:`, error);
}
});
console.log(
`\n📊 SUMMARY: ${foundThreats} threats found out of ${detectionRules.phishing_indicators.length} indicators tested`
);
// Also test the actual function
console.log("\n🔧 Testing processPhishingIndicators() function...");
try {
const result = await processPhishingIndicators();
console.log("Function result:", result);
} catch (error) {
console.error("Error running processPhishingIndicators:", error);
}
return {
totalIndicators: detectionRules.phishing_indicators.length,
threatsFound: foundThreats,
functionResult: result,
};
}
/**
* Debug function to show current detection rules status
*/
async function debugDetectionRules() {
console.log("🔍 DETECTION RULES DEBUG");
console.log("Detection rules loaded:", !!detectionRules);
if (detectionRules) {
console.log("Available sections:");
Object.keys(detectionRules).forEach((key) => {
const section = detectionRules[key];
if (Array.isArray(section)) {
console.log(` - ${key}: ${section.length} items`);
} else if (typeof section === "object") {
console.log(
` - ${key}: object with ${Object.keys(section).length} keys`
);
} else {
console.log(` - ${key}: ${typeof section} = ${section}`);
}
});
if (detectionRules.phishing_indicators) {
console.log("\nPhishing indicators:");
detectionRules.phishing_indicators.forEach((indicator, idx) => {
console.log(
` ${idx + 1}. ${indicator.id} (${indicator.severity}/${
indicator.action
})`
);
});
}
}
return detectionRules;
}
// Make debug functions globally available
window.testPhishingIndicators = testPhishingIndicators;
window.debugDetectionRules = debugDetectionRules;
/**
* Manual trigger function for testing
*/
window.manualPhishingCheck = async function () {
console.log("🚨 MANUAL PHISHING CHECK TRIGGERED");
const result = await processPhishingIndicators();
console.log("Manual check result:", result);
if (result.threats.length > 0) {
console.log("🚨 THREATS FOUND:");
result.threats.forEach((threat) => {
console.log(
` - ${threat.id}: ${threat.description} (${threat.severity})`
);
});
} else {
console.log("✅ No threats detected");
}
return result;
};
/**
* Function to re-run the entire protection analysis
*/
window.rerunProtection = function () {
console.log("🔄 RE-RUNNING PROTECTION ANALYSIS");
runProtection(true);
};
/**
* Store debug data before redirect to blocked page
*/
async function storeDebugDataBeforeRedirect(originalUrl, analysisData) {
try {
const debugData = {
detectionDetails: {
m365Detection: lastDetectionResult?.m365Detection || null,
phishingIndicators: {
threats: analysisData?.threats || [],
score: analysisData?.score || 0,
totalChecked: analysisData?.totalChecked || 0,
},
observerStatus: {
isActive: domObserver !== null,
scanCount: scanCount,
lastScanTime: lastScanTime,
},
pageSource: {
content:
lastScannedPageSource || document.documentElement.outerHTML,
length: (
lastScannedPageSource || document.documentElement.outerHTML
).length,
scanTime: lastPageSourceScanTime || Date.now(),
},
},
consoleLogs: capturedLogs.slice(), // Copy the captured logs
pageSource: lastScannedPageSource || document.documentElement.outerHTML,
timestamp: Date.now(),
};
console.log(
`Storing debug data with ${debugData.consoleLogs.length} console logs`
);
// Store in chrome storage with URL-based key
const storageKey = `debug_data_${btoa(originalUrl).substring(0, 50)}`;
await new Promise((resolve, reject) => {
chrome.storage.local.set({ [storageKey]: debugData }, () => {
if (chrome.runtime.lastError) {
reject(chrome.runtime.lastError);
} else {
console.log("Debug data stored before redirect:", storageKey);
resolve();
}
});
});
} catch (error) {
console.error("Failed to store debug data before redirect:", error);
}
}
/**
* Function to check if detection rules are loaded and show their status
*/
window.checkRulesStatus = function () {
console.log("📋 DETECTION RULES STATUS CHECK");
console.log(`Rules loaded: ${!!detectionRules}`);
if (!detectionRules) {
console.error("❌ Detection rules not loaded!");
console.log("Attempting to reload rules...");
loadDetectionRules()
.then(() => {
console.log("✅ Rules reload attempt completed");
console.log(`Rules now loaded: ${!!detectionRules}`);
if (detectionRules?.phishing_indicators) {
console.log(
`Phishing indicators available: ${detectionRules.phishing_indicators.length}`
);
}
})
.catch((error) => {
console.error("❌ Failed to reload rules:", error);
});
return false;
}
console.log("✅ Detection rules are loaded");
if (detectionRules.phishing_indicators) {
console.log(
`✅ Phishing indicators: ${detectionRules.phishing_indicators.length} available`
);
console.log("Sample indicators:");
detectionRules.phishing_indicators
.slice(0, 5)
.forEach((indicator, idx) => {
console.log(
` ${idx + 1}. ${indicator.id}: ${indicator.description}`
);
});
} else {
console.error("❌ No phishing_indicators section found!");
}
return true;
};
/**
* Manual test function for phishing indicators
* Call this from browser console: testPhishingIndicators()
*/
// Make it globally available for testing
window.testPhishingIndicators = testDetectionPatterns;
/**
* Global function to analyze current page - call from browser console: analyzeCurrentPage()
*/
window.analyzeCurrentPage = async function () {
console.log("🔍 MANUAL PAGE ANALYSIS");
console.log("=".repeat(50));
// Check detection rules loading
console.log("Detection Rules Status:", {
loaded: !!detectionRules,
phishingIndicators: detectionRules?.phishing_indicators?.length || 0,
m365Requirements: !!detectionRules?.m365_detection_requirements,
blockingRules: detectionRules?.blocking_rules?.length || 0,
});
// Check current URL
console.log("Current URL:", window.location.href);
console.log("Current Domain:", window.location.hostname);
// Check if trusted
const isTrusted = isTrustedOrigin(window.location.href);
console.log("Is Trusted Domain:", isTrusted);
// Check M365 detection
const isMSLogon = isMicrosoftLogonPage();
console.log("Detected as M365 Login:", isMSLogon);
// Run phishing indicators
const phishingResult = await processPhishingIndicators();
console.log("Phishing Analysis:", {
threatsFound: phishingResult.threats.length,
totalScore: phishingResult.score,
threats: phishingResult.threats.map((t) => ({
id: t.id,
severity: t.severity,
category: t.category,
description: t.description,
confidence: t.confidence,
})),
});
// Run blocking rules
const blockingResult = runBlockingRules();
console.log("Blocking Rules Result:", {
shouldBlock: blockingResult.shouldBlock,
reason: blockingResult.reason,
});
// Run detection rules
const detectionResult = runDetectionRules();
console.log("Detection Rules Result:", {
score: detectionResult.score,
threshold: detectionResult.threshold,
triggeredRules: detectionResult.triggeredRules,
});
// Check for forms
const forms = document.querySelectorAll("form");
console.log(
"Forms Found:",
Array.from(forms).map((form) => ({
action: form.action || "none",
method: form.method || "get",
hasPasswordField: !!form.querySelector('input[type="password"]'),
hasEmailField: !!form.querySelector(
'input[type="email"], input[name*="email"], input[id*="email"]'
),
}))
);
// Check for suspicious patterns in page source
const pageSource = getPageSource();
const suspiciousPatterns = [
{
name: "Microsoft mentions",
count: (pageSource.match(/microsoft/gi) || []).length,
},
{
name: "Office mentions",
count: (pageSource.match(/office/gi) || []).length,
},
{ name: "365 mentions", count: (pageSource.match(/365/gi) || []).length },
{
name: "Login mentions",
count: (pageSource.match(/login/gi) || []).length,
},
{
name: "Password fields",
count: document.querySelectorAll('input[type="password"]').length,
},
{
name: "Email fields",
count: document.querySelectorAll('input[type="email"]').length,
},
];
console.log("Content Analysis:", suspiciousPatterns);
console.log("=".repeat(50));
console.log("✅ Analysis complete. Check the results above.");
return {