-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathjavascript-identification-authentication-failures.mdc
More file actions
493 lines (418 loc) · 20.4 KB
/
javascript-identification-authentication-failures.mdc
File metadata and controls
493 lines (418 loc) · 20.4 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
---
description: Detect and prevent identification and authentication failures in JavaScript applications as defined in OWASP Top 10:2021-A07
globs: **/*.js, **/*.jsx, **/*.ts, **/*.tsx, !**/node_modules/**, !**/dist/**, !**/build/**, !**/coverage/**
---
# JavaScript Identification and Authentication Failures (OWASP A07:2021)
<rule>
name: javascript_identification_authentication_failures
description: Detect and prevent identification and authentication failures in JavaScript applications as defined in OWASP Top 10:2021-A07
actions:
- type: enforce
conditions:
# Pattern 1: Weak Password Validation
- pattern: "(?:password|passwd|pwd)\\s*\\.\\s*(?:length\\s*[<>]=?\\s*(?:[0-9]|10)\\b|match\\(\\s*['\"][^'\"]*['\"]\\s*\\))"
message: "Weak password validation detected. Implement strong password policies requiring minimum length, complexity, and avoiding common passwords."
# Pattern 2: Missing MFA Implementation
- pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"
negative_pattern: "(?:mfa|2fa|two-factor|multi-factor|otp|totp)"
message: "Authentication implementation without multi-factor authentication (MFA). Consider implementing MFA for enhanced security."
# Pattern 3: Hardcoded Credentials
- pattern: "(?:const|let|var)\\s+(?:password|passwd|pwd|secret|key|token|apiKey)\\s*=\\s*['\"][^'\"]+['\"]"
message: "Hardcoded credentials detected. Store sensitive authentication data in secure configuration or environment variables."
# Pattern 4: Insecure Session Management
- pattern: "(?:localStorage|sessionStorage)\\.setItem\\(['\"](?:token|jwt|session|auth|user)['\"]"
message: "Storing authentication tokens in localStorage or sessionStorage. Consider using HttpOnly cookies for sensitive authentication data."
# Pattern 5: Missing CSRF Protection
- pattern: "(?:post|put|delete|patch)\\([^)]*?\\)"
negative_pattern: "(?:csrf|xsrf|token)"
location: "(?:src|components|pages|api)"
message: "Potential missing CSRF protection in API requests. Implement CSRF tokens for state-changing operations."
# Pattern 6: Insecure JWT Handling
- pattern: "jwt\\.sign\\([^)]*?{[^}]*?}\\s*,\\s*[^,)]+\\s*(?:\\)|,\\s*{\\s*(?:expiresIn|algorithm)\\s*:\\s*[^}]*?}\\s*\\))"
negative_pattern: "(?:expiresIn|exp).*(?:algorithm|alg)"
message: "Insecure JWT configuration. Ensure JWTs have proper expiration and use secure algorithms (RS256 preferred over HS256)."
# Pattern 7: Insecure Password Storage
- pattern: "(?:bcrypt|argon2|pbkdf2|scrypt)\\.[^(]*\\([^)]*?(?:rounds|iterations|cost|factor)\\s*[:<=>]\\s*(?:[0-9]|1[0-2])\\b"
message: "Weak password hashing parameters. Use sufficient work factors for password hashing algorithms."
# Pattern 8: Missing Account Lockout
- pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"
negative_pattern: "(?:lock|attempt|count|limit|throttle|rate)"
message: "Authentication implementation without account lockout or rate limiting. Implement account lockout after failed attempts."
# Pattern 9: Insecure Password Recovery
- pattern: "(?:reset|forgot|recover)(?:Password|Pwd)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"
negative_pattern: "(?:expire|timeout|token|verify)"
message: "Potentially insecure password recovery mechanism. Implement secure, time-limited recovery tokens."
# Pattern 10: Missing Brute Force Protection
- pattern: "(?:login|signin|authenticate|auth)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"
negative_pattern: "(?:captcha|recaptcha|hcaptcha|rate\\s*limit)"
message: "Authentication without CAPTCHA or rate limiting. Implement protection against brute force attacks."
# Pattern 11: Insecure Remember Me Functionality
- pattern: "(?:rememberMe|keepLoggedIn|staySignedIn)"
negative_pattern: "(?:secure|httpOnly|sameSite)"
message: "Potentially insecure 'Remember Me' functionality. Implement with secure, HttpOnly cookies and proper expiration."
# Pattern 12: Insecure Logout Implementation
- pattern: "(?:logout|signout)\\s*\\([^)]*\\)\\s*\\{[^}]*?\\}"
negative_pattern: "(?:invalidate|revoke|clear|remove).*(?:token|session|cookie)"
message: "Potentially incomplete logout implementation. Ensure proper invalidation of sessions and tokens on logout."
# Pattern 13: Missing Session Timeout
- pattern: "(?:session|cookie|jwt)\\s*\\.\\s*(?:create|set|sign)"
negative_pattern: "(?:expire|timeout|maxAge)"
message: "Missing session timeout configuration. Implement proper session expiration for security."
# Pattern 14: Insecure OAuth Implementation
- pattern: "(?:oauth|openid|oidc).*(?:callback|redirect)"
negative_pattern: "(?:state|nonce|pkce)"
message: "Potentially insecure OAuth implementation. Use state parameters, PKCE for authorization code flow, and validate redirect URIs."
# Pattern 15: Missing Credential Validation
- pattern: "(?:email|username|user)\\s*=\\s*(?:req\\.body|req\\.query|req\\.params|formData\\.get)\\(['\"][^'\"]+['\"]\\)"
negative_pattern: "(?:validate|sanitize|check|trim)"
message: "Missing input validation for user credentials. Implement proper validation and sanitization."
- type: suggest
message: |
**JavaScript Identification and Authentication Failures Best Practices:**
1. **Strong Password Policies:**
- Implement minimum length (at least 12 characters)
- Require complexity (uppercase, lowercase, numbers, special characters)
- Check against common password lists
- Example:
```javascript
// Using a library like zxcvbn for password strength estimation
import zxcvbn from 'zxcvbn';
function validatePassword(password) {
if (password.length < 12) {
return { valid: false, message: 'Password must be at least 12 characters' };
}
const strength = zxcvbn(password);
if (strength.score < 3) {
return {
valid: false,
message: 'Password is too weak. ' + strength.feedback.warning
};
}
return { valid: true };
}
```
2. **Multi-Factor Authentication (MFA):**
- Implement TOTP (Time-based One-Time Password)
- Support hardware security keys (WebAuthn/FIDO2)
- Example:
```javascript
// Using speakeasy for TOTP implementation
import speakeasy from 'speakeasy';
// Generate a secret for a user
const secret = speakeasy.generateSecret({ length: 20 });
// Verify a token
function verifyToken(token, secret) {
return speakeasy.totp.verify({
secret: secret.base32,
encoding: 'base32',
token: token,
window: 1 // Allow 1 period before and after for clock drift
});
}
```
3. **Secure Session Management:**
- Use HttpOnly, Secure, and SameSite cookies
- Implement proper session expiration
- Example:
```javascript
// Express.js example
app.use(session({
secret: process.env.SESSION_SECRET,
name: '__Host-session', // Prefix with __Host- for added security
cookie: {
httpOnly: true,
secure: true, // Requires HTTPS
sameSite: 'strict',
maxAge: 3600000, // 1 hour
path: '/'
},
resave: false,
saveUninitialized: false
}));
```
4. **CSRF Protection:**
- Implement CSRF tokens for all state-changing operations
- Example:
```javascript
// Using csurf middleware with Express
import csrf from 'csurf';
// Setup CSRF protection
const csrfProtection = csrf({ cookie: true });
// Apply to routes
app.post('/api/user/profile', csrfProtection, (req, res) => {
// Handle the request
});
// In your frontend (React example)
function ProfileForm() {
// Get CSRF token from cookie or meta tag
const csrfToken = document.querySelector('meta[name="csrf-token"]').content;
return (
<form method="POST" action="/api/user/profile">
<input type="hidden" name="_csrf" value={csrfToken} />
{/* Form fields */}
<button type="submit">Update Profile</button>
</form>
);
}
```
5. **Secure JWT Implementation:**
- Use strong algorithms (RS256 preferred over HS256)
- Include proper expiration (exp), issued at (iat), and audience (aud) claims
- Example:
```javascript
import jwt from 'jsonwebtoken';
import fs from 'fs';
// Using asymmetric keys (preferred for production)
const privateKey = fs.readFileSync('private.key');
function generateToken(userId) {
return jwt.sign(
{
sub: userId,
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + (60 * 60), // 1 hour
aud: 'your-app-name'
},
privateKey,
{ algorithm: 'RS256' }
);
}
```
6. **Secure Password Storage:**
- Use bcrypt, Argon2, or PBKDF2 with sufficient work factor
- Example:
```javascript
import bcrypt from 'bcrypt';
async function hashPassword(password) {
// Cost factor of 12+ for production
const saltRounds = 12;
return await bcrypt.hash(password, saltRounds);
}
async function verifyPassword(password, hash) {
return await bcrypt.compare(password, hash);
}
```
7. **Account Lockout and Rate Limiting:**
- Implement progressive delays or account lockout after failed attempts
- Example:
```javascript
import rateLimit from 'express-rate-limit';
// Apply rate limiting to login endpoint
const loginLimiter = rateLimit({
windowMs: 15 * 60 * 1000, // 15 minutes
max: 5, // 5 attempts per window
message: 'Too many login attempts, please try again after 15 minutes',
standardHeaders: true,
legacyHeaders: false,
});
app.post('/api/login', loginLimiter, (req, res) => {
// Handle login
});
```
8. **Secure Password Recovery:**
- Use time-limited, single-use tokens
- Send to verified email addresses only
- Example:
```javascript
import crypto from 'crypto';
function generatePasswordResetToken() {
return {
token: crypto.randomBytes(32).toString('hex'),
expires: new Date(Date.now() + 3600000) // 1 hour
};
}
// Store token in database with user ID and expiration
// Send token via email (never include in URL directly)
// Verify token is valid and not expired when used
```
9. **Brute Force Protection:**
- Implement CAPTCHA or reCAPTCHA
- Example:
```javascript
// Using Google reCAPTCHA v3
async function verifyRecaptcha(token) {
const response = await fetch('https://www.google.com/recaptcha/api/siteverify', {
method: 'POST',
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: `secret=${process.env.RECAPTCHA_SECRET_KEY}&response=${token}`
});
const data = await response.json();
return data.success && data.score >= 0.5; // Adjust threshold as needed
}
app.post('/api/login', async (req, res) => {
const { recaptchaToken } = req.body;
if (!(await verifyRecaptcha(recaptchaToken))) {
return res.status(400).json({ error: 'CAPTCHA verification failed' });
}
// Continue with login process
});
```
10. **Secure Logout Implementation:**
- Invalidate sessions on both client and server
- Example:
```javascript
app.post('/api/logout', (req, res) => {
// Clear server-side session
req.session.destroy((err) => {
if (err) {
return res.status(500).json({ error: 'Failed to logout' });
}
// Clear client-side cookie
res.clearCookie('__Host-session', {
httpOnly: true,
secure: true,
sameSite: 'strict',
path: '/'
});
res.status(200).json({ message: 'Logged out successfully' });
});
});
```
11. **Secure OAuth Implementation:**
- Use state parameter to prevent CSRF
- Implement PKCE for authorization code flow
- Validate redirect URIs against whitelist
- Example:
```javascript
// Generate state and code verifier for PKCE
function generateOAuthState() {
return crypto.randomBytes(32).toString('hex');
}
function generateCodeVerifier() {
return crypto.randomBytes(43).toString('base64url');
}
function generateCodeChallenge(verifier) {
const hash = crypto.createHash('sha256').update(verifier).digest('base64url');
return hash;
}
// Store state and code verifier in session
// Use code challenge in authorization request
// Verify state and use code verifier in token request
```
12. **Input Validation:**
- Validate and sanitize all user inputs
- Example:
```javascript
import validator from 'validator';
function validateCredentials(email, password) {
const errors = {};
if (!validator.isEmail(email)) {
errors.email = 'Invalid email format';
}
if (!password || password.length < 12) {
errors.password = 'Password must be at least 12 characters';
}
return {
isValid: Object.keys(errors).length === 0,
errors
};
}
```
13. **Secure Headers:**
- Implement security headers for authentication-related pages
- Example:
```javascript
// Using helmet with Express
import helmet from 'helmet';
app.use(helmet({
contentSecurityPolicy: {
directives: {
defaultSrc: ["'self'"],
scriptSrc: ["'self'", 'https://www.google.com/recaptcha/', 'https://www.gstatic.com/recaptcha/'],
frameSrc: ["'self'", 'https://www.google.com/recaptcha/'],
styleSrc: ["'self'", "'unsafe-inline'"],
connectSrc: ["'self'"]
}
},
referrerPolicy: { policy: 'same-origin' }
}));
```
14. **Credential Stuffing Protection:**
- Implement device fingerprinting and anomaly detection
- Example:
```javascript
// Simple device fingerprinting
function getDeviceFingerprint(req) {
return {
ip: req.ip,
userAgent: req.headers['user-agent'],
acceptLanguage: req.headers['accept-language']
};
}
// Check if login is from a new device
async function isNewDevice(userId, fingerprint) {
// Compare with stored fingerprints for this user
// Alert or require additional verification for new devices
}
```
15. **Secure Password Change:**
- Require current password verification
- Example:
```javascript
async function changePassword(userId, currentPassword, newPassword) {
// Retrieve user from database
const user = await getUserById(userId);
// Verify current password
const isValid = await bcrypt.compare(currentPassword, user.passwordHash);
if (!isValid) {
return { success: false, message: 'Current password is incorrect' };
}
// Validate new password strength
const validation = validatePassword(newPassword);
if (!validation.valid) {
return { success: false, message: validation.message };
}
// Hash and store new password
const newHash = await bcrypt.hash(newPassword, 12);
await updateUserPassword(userId, newHash);
// Invalidate existing sessions (optional but recommended)
await invalidateUserSessions(userId);
return { success: true };
}
```
- type: validate
conditions:
# Check 1: Strong Password Validation
- pattern: "(?:password|pwd).*(?:length\\s*>=\\s*(?:1[2-9]|[2-9][0-9]))"
message: "Implementing strong password length requirements (12+ characters)."
# Check 2: Secure Password Storage
- pattern: "(?:bcrypt|argon2|pbkdf2|scrypt)\\.[^(]*\\([^)]*?(?:rounds|iterations|cost|factor)\\s*[:<=>]\\s*(?:1[2-9]|[2-9][0-9])"
message: "Using secure password hashing with appropriate work factor."
# Check 3: CSRF Protection
- pattern: "(?:csrf|xsrf).*(?:token|middleware|protection)"
message: "Implementing CSRF protection for state-changing operations."
# Check 4: Secure Cookie Configuration
- pattern: "(?:cookie|session).*(?:httpOnly|secure|sameSite)"
message: "Using secure cookie configuration for sessions."
# Check 5: Rate Limiting
- pattern: "(?:rate|limit|throttle).*(?:login|signin|auth)"
message: "Implementing rate limiting for authentication endpoints."
metadata:
priority: high
version: 1.0
tags:
- security
- javascript
- nodejs
- browser
- authentication
- owasp
- language:javascript
- framework:express
- framework:react
- framework:vue
- framework:angular
- category:security
- subcategory:authentication
- standard:owasp-top10
- risk:a07-identification-authentication-failures
references:
- "https://owasp.org/Top10/A07_2021-Identification_and_Authentication_Failures/"
- "https://cheatsheetseries.owasp.org/cheatsheets/Authentication_Cheat_Sheet.html"
- "https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html"
- "https://cheatsheetseries.owasp.org/cheatsheets/Credential_Stuffing_Prevention_Cheat_Sheet.html"
- "https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html"
- "https://cheatsheetseries.owasp.org/cheatsheets/JSON_Web_Token_for_Java_Cheat_Sheet.html"
- "https://auth0.com/blog/a-look-at-the-latest-draft-for-jwt-bcp/"
- "https://github.com/OWASP/CheatSheetSeries/blob/master/cheatsheets/Multifactor_Authentication_Cheat_Sheet.md"
- "https://www.nist.gov/itl/applied-cybersecurity/tig/back-basics-multi-factor-authentication"
</rule>