-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhera-auth-detector.js.backup
More file actions
1968 lines (1735 loc) · 62.1 KB
/
hera-auth-detector.js.backup
File metadata and controls
1968 lines (1735 loc) · 62.1 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
// Hera Comprehensive Authentication Protocol Security Analysis Framework
// Advanced detection and analysis of authentication vulnerabilities across all protocols
import { OAuth2VerificationEngine, HSTSVerificationEngine } from './oauth2-verification-engine.js';
class OAuth2Analyzer {
/**
* Calculate the entropy of a string
* Returns both per-character entropy and total information content
*/
calculateEntropy(str) {
if (!str) return { perChar: 0, total: 0 };
// Count character frequencies
const freq = {};
for (const char of str) {
freq[char] = (freq[char] || 0) + 1;
}
// Calculate Shannon entropy (bits per character)
let entropyPerChar = 0;
const len = str.length;
for (const char in freq) {
const p = freq[char] / len;
entropyPerChar -= p * Math.log2(p);
}
return {
perChar: entropyPerChar,
total: entropyPerChar * len
};
}
/**
* Analyze the quality of a state parameter
*/
analyzeStateQuality(state) {
const entropyData = this.calculateEntropy(state);
const analysis = {
exists: !!state,
length: state ? state.length : 0,
entropyPerChar: entropyData.perChar,
totalEntropy: entropyData.total,
appearsRandom: false,
risk: 'HIGH'
};
// Check entropy per character (should be >= 3 bits for decent randomness)
// AND total entropy (should be >= 64 bits minimum for security)
if (entropyData.perChar >= 3 && entropyData.total >= 128) {
analysis.appearsRandom = true;
analysis.risk = 'LOW';
} else if (entropyData.perChar >= 2 && entropyData.total >= 64) {
analysis.risk = 'MEDIUM';
}
return analysis;
}
/**
* Check if this appears to be a legitimate OAuth2/OIDC provider
*/
isKnownProvider(url) {
const knownProviders = [
'login.microsoftonline.com',
'accounts.google.com',
'github.com',
'facebook.com',
'auth0.com',
'okta.com',
'salesforce.com'
];
try {
const hostname = new URL(url).hostname;
return knownProviders.some(provider => hostname.includes(provider));
} catch {
return false;
}
}
}
class OAuth2FlowTracker {
constructor() {
// CRITICAL FIX P0: Persistent storage for service worker restarts
this._activeFlowsCache = new Map();
this.cleanupInterval = 10 * 60 * 1000;
this.initialized = false;
this.initPromise = this.initialize();
}
// Initialize by loading from storage.session
async initialize() {
if (this.initialized) return;
try {
// CRITICAL FIX P0: Use chrome.storage.local for completed OAuth flows (survives browser restart)
// Active flows need to persist for multi-day timing attack detection
const data = await chrome.storage.local.get(['oauthFlows']);
if (data.oauthFlows) {
for (const [flowId, flow] of Object.entries(data.oauthFlows)) {
this._activeFlowsCache.set(flowId, flow);
}
console.log(`Hera: Restored ${this._activeFlowsCache.size} OAuth flows from storage.local`);
}
this.initialized = true;
} catch (error) {
console.error('Hera: Failed to initialize OAuth2FlowTracker:', error);
this.initialized = true;
}
}
// Background sync to storage.local (CRITICAL FIX P0)
async _syncToStorage() {
try {
await this.initPromise;
const flowsObj = Object.fromEntries(this._activeFlowsCache.entries());
// CRITICAL FIX P0: Use chrome.storage.local (survives browser restart)
await chrome.storage.local.set({ oauthFlows: flowsObj });
} catch (error) {
console.error('Hera: Failed to sync OAuth flows:', error);
}
}
// Debounced sync
_debouncedSync() {
if (this._syncTimeout) clearTimeout(this._syncTimeout);
this._syncTimeout = setTimeout(() => {
this._syncToStorage().catch(err => console.error('OAuth flow sync failed:', err));
}, 100);
}
// Getter for activeFlows (backward compatibility)
get activeFlows() {
return this._activeFlowsCache;
}
/**
* Track an authorization request
*/
trackAuthRequest(request) {
try {
const url = new URL(request.url);
const state = url.searchParams.get('state');
const clientId = url.searchParams.get('client_id');
if (state && clientId) {
const flowId = `${clientId}_${state}`;
// Check if this flow already exists (potential replay attack)
if (this.activeFlows.has(flowId)) {
const existingFlow = this.activeFlows.get(flowId);
console.warn('Potential OAuth2 replay attack: state parameter reused', {
clientId,
state,
originalTimestamp: existingFlow.authRequest.timestamp,
newTimestamp: Date.now()
});
// Overwrite with warning - newer request takes precedence
}
this._activeFlowsCache.set(flowId, {
authRequest: {
url: request.url,
timestamp: Date.now(),
state: state,
hasPKCE: url.searchParams.has('code_challenge'),
hasNonce: url.searchParams.has('nonce'),
clientId: clientId
},
callback: null,
completed: false
});
// CRITICAL FIX: Persist to storage.session
this._debouncedSync();
// Schedule cleanup
setTimeout(() => {
this._activeFlowsCache.delete(flowId);
this._debouncedSync(); // Persist deletion
}, this.cleanupInterval);
return flowId;
}
} catch (error) {
console.warn('Error tracking OAuth2 auth request:', error);
}
return null;
}
/**
* Track a callback/redirect
*/
trackCallback(request) {
try {
const url = new URL(request.url);
const state = url.searchParams.get('state');
const code = url.searchParams.get('code');
const error = url.searchParams.get('error');
if (!state) {
return {
vulnerability: 'callbackWithoutState',
message: 'OAuth2 callback missing state parameter',
severity: 'HIGH'
};
}
// Find matching flow
for (const [flowId, flow] of this.activeFlows) {
if (flow.authRequest.state === state) {
// SECURITY: Check flow timing to prevent race attacks
const flowAge = Date.now() - flow.authRequest.timestamp;
if (flowAge < 2000) {
// SECURITY FIX P2: Increased from 500ms to 2s (industry standard for human-initiated flows)
// Callback arrived too quickly after request - likely race attack or automation
console.warn('OAuth callback timing suspicious (< 2s) - possible CSRF race attack or automation');
return {
vulnerability: 'suspiciousTimingAnomaly',
message: 'OAuth callback received too quickly after authorization request',
severity: 'HIGH',
details: `Flow age: ${flowAge}ms (expected > 2000ms for legitimate human interaction)`,
evidence: {
authRequestTime: flow.authRequest.timestamp,
callbackTime: Date.now(),
timeDifference: flowAge
}
};
}
if (flowAge > 600000) {
// Callback too slow (>10 min) - state likely expired
return {
vulnerability: 'expiredState',
message: 'OAuth state parameter expired (> 10 minutes)',
severity: 'MEDIUM',
details: `Flow age: ${Math.round(flowAge / 1000)}s`,
evidence: {
authRequestTime: flow.authRequest.timestamp,
callbackTime: Date.now(),
timeDifference: flowAge
}
};
}
flow.callback = {
url: request.url,
timestamp: Date.now(),
hasCode: !!code,
hasError: !!error,
stateMatches: true
};
flow.completed = true;
// CRITICAL FIX: Persist callback to storage.session
this._debouncedSync();
// Validate the complete flow
return this.validateFlow(flow);
}
}
// No matching flow found - potential attack
return {
vulnerability: 'orphanCallback',
message: 'OAuth2 callback without matching authorization request',
severity: 'HIGH'
};
} catch (error) {
console.warn('Error tracking OAuth2 callback:', error);
return null;
}
}
/**
* Validate a complete OAuth2 flow
*/
validateFlow(flow) {
const issues = [];
const analyzer = new OAuth2Analyzer();
// Check state parameter quality
const stateQuality = analyzer.analyzeStateQuality(flow.authRequest.state);
if (stateQuality.totalEntropy < 64 && !flow.authRequest.hasPKCE) {
issues.push({
type: 'weakStateInFlow',
message: `State entropy too low: ${stateQuality.totalEntropy.toFixed(0)} bits total (${stateQuality.entropyPerChar.toFixed(1)} bits/char)`,
severity: stateQuality.risk,
exploitation: 'Predictable state allows CSRF attacks'
});
}
// Check timing (callbacks should happen within reasonable time)
const flowDuration = flow.callback.timestamp - flow.authRequest.timestamp;
if (flowDuration > 5 * 60 * 1000) { // 5 minutes
issues.push({
type: 'suspiciousTiming',
message: 'Unusually long delay between auth request and callback',
severity: 'INFO',
exploitation: 'Possible session fixation or replay attack'
});
}
return issues;
}
/**
* Get statistics about tracked flows
*/
getFlowStats() {
const stats = {
activeFlows: this.activeFlows.size,
completedFlows: 0,
pendingFlows: 0
};
for (const flow of this.activeFlows.values()) {
if (flow.completed) {
stats.completedFlows++;
} else {
stats.pendingFlows++;
}
}
return stats;
}
}
class HeraAuthProtocolDetector {
constructor(evidenceCollector = null) {
this.detectedProtocols = [];
this.securityIssues = [];
this.issueDatabase = this.initializeIssueDatabase();
this.oauth2Analyzer = new OAuth2Analyzer();
this.flowTracker = new OAuth2FlowTracker();
// Evidence-based verification engines
this.evidenceCollector = evidenceCollector;
this.oauth2Verifier = evidenceCollector ? new OAuth2VerificationEngine(evidenceCollector) : null;
this.hstsVerifier = evidenceCollector ? new HSTSVerificationEngine(evidenceCollector) : null;
this.verificationResults = new Map();
}
initializeIssueDatabase() {
return {
OAuth2: {
implicitFlow: {
pattern: /response_type=token/,
issue: "Access token exposed in URL fragment",
severity: "CRITICAL",
detection: (req, detector) => {
const params = detector.parseParams(req.url);
return params?.response_type === 'token';
},
exploitation: "Tokens visible in browser history, referrer headers, server logs"
},
missingPKCE: {
pattern: /authorization_code.*(?!code_challenge)/,
issue: "Authorization code interception attack possible",
severity: "HIGH",
detection: (req, detector) => {
const params = detector.parseParams(req.url);
return params?.response_type === 'code' && !params?.code_challenge;
},
exploitation: "Attacker can intercept authorization code and exchange for token"
},
missingState: {
pattern: /authorize\?.*(?!state=)/,
issue: "CSRF attack possible",
severity: "HIGH",
detection: (req, detector) => {
const params = detector.parseParams(req.url);
return !params?.state;
},
exploitation: "Attacker can forge authorization requests"
},
weakState: {
pattern: /state=[a-z0-9]{1,8}$/,
issue: "Predictable state parameter",
severity: (req, detector) => {
const params = detector.parseParams(req.url);
const state = params?.state;
const analyzer = new OAuth2Analyzer();
const quality = analyzer.analyzeStateQuality(state);
if (quality.totalEntropy < 32 || quality.entropyPerChar < 1) return 'CRITICAL';
if (quality.totalEntropy < 64 || quality.entropyPerChar < 2) return 'HIGH';
if (quality.totalEntropy < 128 && !params?.code_challenge) return 'MEDIUM';
return 'INFO';
},
detection: (req, detector) => {
const params = detector.parseParams(req.url);
const state = params?.state;
if (!state) return false; // Different vuln (missingState)
// Check if this is actually an OAuth2 flow
if (!req.url.includes('authorize') && !req.url.includes('oauth')) {
return false;
}
const analyzer = new OAuth2Analyzer();
const quality = analyzer.analyzeStateQuality(state);
// Flag if entropy is too low AND no PKCE
return quality.totalEntropy < 64 && !params?.code_challenge;
},
exploitation: "Predictable state allows CSRF attacks"
},
openRedirect: {
pattern: /redirect_uri=(https?:)?\/\//,
issue: "Potential open redirect vulnerability",
severity: "HIGH",
detection: (req, detector) => {
const params = detector.parseParams(req.url);
const uri = params?.redirect_uri;
if (!uri) return false;
// Detects common open redirect patterns like redirect_uri=@evil.com or redirect_uri=//evil.com
try {
const url = new URL(uri);
return url.username || url.password;
} catch (e) {
return uri.startsWith('//') || uri.includes('@');
}
}
},
overlyBroadScopes: {
pattern: /scope=.*(\*|all|full|admin)/,
issue: "Requesting excessive permissions",
severity: "MEDIUM",
detection: (req, detector) => {
const params = detector.parseParams(req.url);
const scope = params?.scope;
const dangerous = ['*', 'all', 'full_access', 'admin', 'write:org'];
return dangerous.some(s => scope?.includes(s));
}
},
clientSecretInURL: {
pattern: /client_secret=[^&]+/,
issue: "Client secret exposed in URL",
severity: "CRITICAL",
detection: (req, detector) => {
const params = detector.parseParams(req.url);
return req.method === 'GET' && params?.client_secret;
}
},
longLivedTokens: {
pattern: /expires_in=(\d{7,})/,
issue: "Tokens valid for excessive duration",
severity: "MEDIUM",
detection: (res) => res.expires_in > 86400
}
},
OIDC: {
missingNonce: {
pattern: /id_token.*(?!nonce)/,
issue: "Replay attack possible",
severity: "HIGH",
detection: (req, detector) => {
const params = detector.parseParams(req.url);
return params?.response_type?.includes('id_token') && !params?.nonce;
}
},
unvalidatedIDToken: {
issue: "ID token signature not validated or weak algorithm",
severity: "CRITICAL",
detection: (idToken) => {
try {
const header = JSON.parse(atob(idToken.split('.')[0]));
return header.alg === 'none' || header.alg === 'HS256';
} catch { return false; }
}
},
missingAudienceCheck: {
issue: "Token meant for different client accepted",
severity: "HIGH",
detection: (idToken, expectedAud) => {
try {
const payload = JSON.parse(atob(idToken.split('.')[1]));
return payload.aud !== expectedAud;
} catch { return false; }
}
},
expiredToken: {
issue: "Expired tokens still accepted",
severity: "HIGH",
detection: (idToken) => {
try {
const payload = JSON.parse(atob(idToken.split('.')[1]));
return payload.exp < Date.now() / 1000;
} catch { return false; }
}
}
},
SAML: {
unsignedAssertion: {
pattern: /<saml:Assertion(?!.*<ds:Signature)/,
issue: "SAML assertion not signed - can be forged",
severity: "CRITICAL",
detection: (samlResponse) => !samlResponse.includes('<ds:Signature')
},
unencryptedAssertion: {
pattern: /<saml:Assertion(?!.*<xenc:EncryptedData)/,
issue: "Sensitive data transmitted in plaintext",
severity: "HIGH",
detection: (samlResponse) => !samlResponse.includes('EncryptedAssertion')
},
noAudienceRestriction: {
pattern: /<saml:Assertion(?!.*<saml:AudienceRestriction)/,
issue: "Assertion can be replayed to different service",
severity: "HIGH"
},
weakSignatureAlgorithm: {
pattern: /SignatureMethod.*Algorithm=".*sha1"/,
issue: "Using deprecated SHA1 for signatures",
severity: "MEDIUM"
},
signatureWrapping: {
issue: "XML signature wrapping attack possible",
severity: "CRITICAL",
detection: (samlResponse) => {
const signatureIndex = samlResponse.indexOf('<ds:Signature');
const assertionIndex = samlResponse.lastIndexOf('<saml:Assertion');
return signatureIndex > 0 && signatureIndex < assertionIndex;
}
},
missingExpiration: {
pattern: /<saml:Conditions(?!.*NotOnOrAfter)/,
issue: "Assertion never expires",
severity: "HIGH"
},
xxeVulnerability: {
pattern: /<!DOCTYPE.*SYSTEM/,
issue: "XML External Entity attack possible",
severity: "CRITICAL"
}
},
JWT: {
algorithmNone: {
pattern: /eyJ.*alg.*none/,
issue: "JWT signature verification bypassed",
severity: "CRITICAL",
detection: (jwt) => {
try {
const header = JSON.parse(atob(jwt.split('.')[0]));
return header.alg === 'none' || header.alg === 'None';
} catch { return false; }
}
},
algorithmConfusion: {
issue: "Algorithm confusion attack - using public key as HMAC secret",
severity: "CRITICAL",
detection: (jwt, expectedAlg) => {
try {
const header = JSON.parse(atob(jwt.split('.')[0]));
return expectedAlg === 'RS256' && header.alg === 'HS256';
} catch { return false; }
}
},
weakSecret: {
issue: "JWT signed with weak/guessable secret",
severity: "HIGH",
detection: (jwt) => {
const commonSecrets = ['secret', '123456', 'password', 'admin'];
return commonSecrets.some(secret => this.verifyHS256(jwt, secret));
}
},
noExpiration: {
issue: "JWT never expires",
severity: "HIGH",
detection: (jwt) => {
try {
const payload = JSON.parse(atob(jwt.split('.')[1]));
return !payload.exp;
} catch { return false; }
}
},
longExpiration: {
issue: "JWT valid for excessive duration",
severity: "MEDIUM",
detection: (jwt) => {
try {
const payload = JSON.parse(atob(jwt.split('.')[1]));
const exp = payload.exp;
const iat = payload.iat || (Date.now() / 1000);
return (exp - iat) > 86400 * 30;
} catch { return false; }
}
},
sensitiveData: {
issue: "Sensitive data exposed in JWT payload",
severity: "HIGH",
detection: (jwt) => {
try {
const payload = JSON.parse(atob(jwt.split('.')[1]));
const sensitive = ['password', 'ssn', 'creditcard', 'secret'];
return sensitive.some(s => JSON.stringify(payload).toLowerCase().includes(s));
} catch { return false; }
}
},
jwtInURL: {
pattern: /[?&]token=eyJ/,
issue: "JWT exposed in URL (logs, history, referrer)",
severity: "HIGH"
}
},
BasicAuth: {
basicOverHTTP: {
pattern: /^http:.*Authorization:\s*Basic/,
issue: "Credentials sent in plaintext",
severity: "CRITICAL"
},
noRateLimiting: {
issue: "Brute force attacks possible",
severity: "HIGH",
detection: (responses) => {
const failed401s = responses.filter(r => r.status === 401);
return failed401s.length > 10 && !responses.some(r => r.status === 429);
}
},
credentialsInURL: {
pattern: /https?:\/\/[^:]+:[^@]+@/,
issue: "Credentials exposed in URL",
severity: "HIGH"
}
},
APIKey: {
apiKeyInURL: {
pattern: /[?&](api_?key|apikey|key)=[^&]+/,
issue: "API key exposed in URL",
severity: "CRITICAL"
},
weakAPIKey: {
issue: "API key has weak entropy",
severity: "HIGH",
detection: (apiKey) => {
return apiKey.length < 32 ||
!/[A-Z]/.test(apiKey) ||
!/[!@#$%^&*]/.test(apiKey);
}
},
sensitivePrefix: {
pattern: /(sk_live|secret_|private_)/,
issue: "Secret API key exposed in client-side code",
severity: "CRITICAL",
detection: (apiKey, context) => {
return apiKey.startsWith('sk_live') && context === 'client_side';
}
}
},
Session: {
sessionFixation: {
issue: "Session ID not regenerated after authentication",
severity: "CRITICAL",
detection: (loginResponse, previousSessionId) => {
const newSessionId = this.extractSessionId(loginResponse);
return newSessionId === previousSessionId;
}
},
insecureCookieFlags: {
pattern: /Set-Cookie:.*(?!HttpOnly)/,
issue: "Session cookie missing security flags",
severity: "HIGH",
detection: (setCookie) => {
return !setCookie.includes('HttpOnly') ||
!setCookie.includes('Secure') ||
!setCookie.includes('SameSite');
}
},
predictableSessionId: {
issue: "Session IDs are predictable",
severity: "HIGH",
detection: (sessionIds) => {
return sessionIds.every((id, i) =>
parseInt(id) === parseInt(sessionIds[0]) + i
);
}
},
longSessionTimeout: {
pattern: /Max-Age=(\d{6,})/,
issue: "Session valid for excessive duration",
severity: "MEDIUM"
},
sessionInURL: {
pattern: /[?&](sid|sessionid|session)=/,
issue: "Session ID exposed in URL",
severity: "HIGH"
}
},
WebAuthn: {
weakChallenge: {
issue: "Challenge not cryptographically random",
severity: "HIGH",
detection: (challenge) => {
return challenge.length < 32 || this.isRepeatingPattern(challenge);
}
},
noUserVerification: {
pattern: /userVerification["']\s*:\s*["']discouraged/,
issue: "User verification not required",
severity: "HIGH",
detection: (options) => options.userVerification === 'discouraged'
},
challengeReuse: {
issue: "Same challenge used multiple times",
severity: "HIGH",
detection: (challenges) => new Set(challenges).size < challenges.length
}
},
MFA: {
weakOTP: {
pattern: /^\d{4}$/,
issue: "OTP too short or weak",
severity: "HIGH",
detection: (otp) => otp.length < 6 || !/\d/.test(otp)
},
otpInURL: {
pattern: /[?&](code|otp|token)=\d{4,6}/,
issue: "OTP exposed in URL",
severity: "CRITICAL"
},
longOTPValidity: {
issue: "OTP valid for too long",
severity: "HIGH",
detection: (otpLifetime) => otpLifetime > 600
},
smsOnly2FA: {
issue: "SMS vulnerable to SIM swapping",
severity: "CRITICAL",
detection: (mfaMethods) => {
return mfaMethods.length === 1 && mfaMethods[0] === 'sms';
}
},
mfaBypass: {
issue: "MFA can be bypassed",
severity: "HIGH",
detection: (response) => {
return response.includes('skip_mfa') || response.includes('trust_device_permanently');
}
}
},
Custom: {
homemadeCrypto: {
pattern: /md5|sha1|base64.*password/i,
issue: "Using weak/custom cryptography",
severity: "CRITICAL",
detection: (code) => {
return code.includes('md5(password)') ||
code.includes('base64(password)') ||
code.includes('custom_encrypt');
}
},
obscurity: {
pattern: /X-Secret-Header|magic_token/,
issue: "Relying on obscure headers/parameters",
severity: "HIGH",
detection: (headers) => {
const suspicious = ['X-Secret', 'X-Magic', 'X-Special-Auth'];
return suspicious.some(h => headers[h]);
}
},
sqlInAuth: {
pattern: /SELECT.*FROM.*users.*WHERE.*password/i,
issue: "Plaintext password comparison in SQL",
severity: "CRITICAL",
detection: (query) => {
return query.includes('password = ') && !query.includes('hash');
}
}
}
};
}
analyzeRequest(request) {
const issues = [];
// Detect protocol type
const protocol = this.detectProtocol(request);
// Track OAuth2 flows if applicable
if (protocol === 'OAuth2' && request.url.includes('authorize')) {
this.flowTracker.trackAuthRequest(request);
}
// Run protocol-specific checks
if (this.issueDatabase[protocol]) {
issues.push(...this.checkProtocolSecurity(protocol, request));
}
// Run universal checks
issues.push(...this.checkUniversalIssues(request));
// Enhance issues with confidence levels and evidence
const enhancedIssues = issues.map(issue => this.enhanceIssue(issue, request));
// Calculate risk score
const riskScore = this.calculateRiskScore(enhancedIssues);
return {
protocol,
issues: enhancedIssues,
riskScore,
recommendation: this.getRecommendation(riskScore),
timestamp: Date.now(),
flowStats: protocol === 'OAuth2' ? this.flowTracker.getFlowStats() : null
};
}
/**
* Enhance an issue with confidence levels and evidence
*/
enhanceIssue(issue, request) {
const enhanced = {
...issue,
confidence: this.calculateConfidence(issue, request),
evidence: this.gatherEvidence(issue, request),
recommendation: this.getIssueRecommendation(issue.type)
};
return enhanced;
}
/**
* Calculate confidence level for a finding
*/
calculateConfidence(issue, request) {
try {
const params = this.parseParams(request.url);
// High confidence if state is completely missing
if (issue.type === 'missingState' && !params.state) {
return 'HIGH';
}
// High confidence for known vulnerable patterns
if (issue.type === 'clientSecretInURL' || issue.type === 'implicitFlow') {
return 'HIGH';
}
// Lower confidence if compensating controls exist
if (issue.type === 'weakState' && (params.code_challenge || params.nonce)) {
return 'LOW';
}
// Check if this is a known provider (reduces false positive risk)
if (this.oauth2Analyzer.isKnownProvider(request.url)) {
if (issue.type === 'missingState' && (issue.severity === 'HIGH' || issue.severity === 'CRITICAL')) {
return 'MEDIUM'; // Lower confidence for known providers with missing state
}
}
return 'MEDIUM';
} catch (error) {
console.warn('Error calculating confidence:', error);
return 'LOW';
}
}
/**
* Gather evidence for a security issue
*/
gatherEvidence(issue, request) {
try {
const params = this.parseParams(request.url);
const evidence = {
hasState: !!params.state,
stateLength: params.state ? params.state.length : 0,
hasPKCE: !!params.code_challenge,
hasNonce: !!params.nonce,
isKnownProvider: this.oauth2Analyzer.isKnownProvider(request.url)
};
// Add state quality analysis for relevant issues
if (issue.type === 'weakState' || issue.type === 'missingState') {
if (params.state) {
const stateQuality = this.oauth2Analyzer.analyzeStateQuality(params.state);
evidence.stateEntropyPerChar = stateQuality.entropyPerChar;
evidence.stateTotalEntropy = stateQuality.totalEntropy;
evidence.stateAppearsRandom = stateQuality.appearsRandom;
}
}
return evidence;
} catch (error) {
console.warn('Error gathering evidence:', error);
return {};
}
}
/**
* Get recommendation for a specific issue type
*/
getIssueRecommendation(issueType) {
const recommendations = {
'missingState': 'Implement state parameter with cryptographically random values (minimum 128 bits entropy)',
'weakState': 'Increase state parameter entropy to at least 128 bits using cryptographically secure random generation',
'missingPKCE': 'Implement PKCE (Proof Key for Code Exchange) for public clients',
'implicitFlow': 'Switch to Authorization Code flow with PKCE instead of Implicit flow',
'clientSecretInURL': 'Move client secret to request body or use client authentication methods',
'openRedirect': 'Validate redirect_uri against a whitelist of allowed URLs',
'overlyBroadScopes': 'Request only the minimum required scopes for the application functionality',
'orphanCallback': 'Investigate potential CSRF attack attempt',
'callbackWithoutState': 'Ensure all OAuth2 callbacks include state parameter validation'
};
return recommendations[issueType] || 'Review OAuth2 implementation against security best practices';
}
detectProtocol(request) {
const url = request.url || '';
const headers = request.requestHeaders || request.headers || {};
const params = this.parseParams(url) || {};
const body = (request.requestBody && typeof request.requestBody === 'string') ? request.requestBody : '';
// OAuth 2.0
if (url.includes('/authorize') && params.response_type) {
return 'OAuth2';
}
// OIDC
if (params.scope?.includes('openid')) {
return 'OIDC';
}
// SAML
if (body && (body.includes('SAMLRequest') || body.includes('SAMLResponse'))) {
return 'SAML';
}
// JWT
const authHeader = this.getHeader(headers, 'Authorization');
if (authHeader?.startsWith('Bearer eyJ')) {
return 'JWT';
}
// Basic Auth
if (authHeader?.startsWith('Basic ')) {
return 'BasicAuth';
}
// API Key
if (this.getHeader(headers, 'X-API-Key') || params.api_key) {
return 'APIKey';
}
// Session
const cookie = this.getHeader(headers, 'Cookie');
if (cookie?.includes('SESSIONID') || cookie?.includes('JSESSIONID')) {
return 'Session';
}
// Kerberos
if (authHeader?.startsWith('Negotiate ')) {
return 'Kerberos';
}
// WebAuthn
if (url.includes('webauthn') || (body && body.includes('publicKey'))) {
return 'WebAuthn';
}
// MFA
if (url.includes('2fa') || url.includes('mfa') || (body && body.includes('code'))) {
return 'MFA';
}
// Certificate
if (this.getHeader(headers, 'X-Client-Cert')) {
return 'Certificate';
}
// ProtonMail API
if (this.getHeader(headers, 'x-pm-uid') ||
this.getHeader(headers, 'x-pm-appversion') ||
(cookie && cookie.includes('AUTH-')) ||
url.includes('/api/core/v4/') ||
url.includes('/api/auth/v4/') ||
url.includes('proton.me/api/')) {
return 'ProtonMail API';
}
return 'Custom';
}
checkProtocolSecurity(protocol, request) {
const issues = [];
const protocolIssues = this.issueDatabase[protocol];