e35ac6a41c
Security Enhancements: - Fix SQL injection vulnerabilities by replacing whereRaw queries with parameterized queries - Add LIKE pattern escaping to prevent SQL injection in search functionality - Implement account lockout protection (5 failed attempts = 30 min lockout) - Add comprehensive login attempt tracking and audit trail - Enhance JWT tokens with issuer validation, IP tracking, and password change detection - Add logout endpoint and session management - Prevent user enumeration with generic error messages Database Changes: - Add login_attempts table for authentication tracking - Add security columns to admin_users (password_changed_at, last_login_ip, two_factor_enabled) New Security Features: - Brute force protection with configurable lockout duration - Automatic cleanup of old login attempts - Enhanced authentication middleware with stricter validation - Monitoring scripts for security health checks All fixes are backward compatible and production-ready with rollback plans included. 🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
221 lines
5.5 KiB
Markdown
221 lines
5.5 KiB
Markdown
# Authentication Security Enhancement Migration Guide
|
|
|
|
## Overview
|
|
This guide provides a safe migration path to enhance authentication security without disrupting the production system.
|
|
|
|
## Security Enhancements Implemented
|
|
|
|
### 1. Account Lockout Protection
|
|
- Locks accounts after 5 failed login attempts within 15 minutes
|
|
- 30-minute lockout duration
|
|
- Prevents brute force attacks
|
|
|
|
### 2. Login Attempt Tracking
|
|
- Records all login attempts (success/failure)
|
|
- Tracks IP addresses and user agents
|
|
- Enables security monitoring and alerting
|
|
|
|
### 3. Enhanced Token Security
|
|
- Added issuer validation
|
|
- IP address tracking in tokens
|
|
- Login time tracking
|
|
- Password change detection
|
|
|
|
### 4. Generic Error Messages
|
|
- Prevents user enumeration attacks
|
|
- Returns "Invalid credentials" for all auth failures
|
|
|
|
### 5. Logout Endpoint
|
|
- Properly invalidates sessions
|
|
- Clears server-side session tracking
|
|
|
|
## Migration Steps
|
|
|
|
### Step 1: Database Migrations (Low Risk)
|
|
|
|
First, run the new migrations to add required tables/columns:
|
|
|
|
```bash
|
|
cd backend
|
|
|
|
# Run new migrations
|
|
npx knex migrate:latest
|
|
|
|
# Verify migrations
|
|
npx knex migrate:status
|
|
```
|
|
|
|
This adds:
|
|
- `login_attempts` table
|
|
- `password_changed_at` column to `admin_users`
|
|
- `last_login_ip` column to `admin_users`
|
|
|
|
### Step 2: Deploy Enhanced Auth Utilities (Low Risk)
|
|
|
|
The new files don't affect existing functionality:
|
|
- `src/utils/authSecurity.js` - New security utilities
|
|
- `src/middleware/auth-enhanced.js` - Enhanced auth middleware
|
|
- `src/routes/auth-enhanced.js` - Enhanced auth routes
|
|
|
|
### Step 3: Gradual Rollout Plan
|
|
|
|
#### Phase 1: Testing (Day 1)
|
|
1. Deploy code but keep using existing auth routes
|
|
2. Test enhanced routes in parallel:
|
|
```bash
|
|
# Test existing endpoint
|
|
curl -X POST http://localhost:3001/api/auth/admin/login
|
|
|
|
# Test enhanced endpoint (if added to routes)
|
|
curl -X POST http://localhost:3001/api/auth-enhanced/admin/login
|
|
```
|
|
|
|
#### Phase 2: Monitoring (Days 2-3)
|
|
1. Add the auth security initialization to server.js:
|
|
```javascript
|
|
// In server.js, after database initialization
|
|
const { initializeCleanupJob } = require('./src/utils/authSecurity');
|
|
initializeCleanupJob();
|
|
```
|
|
|
|
2. Monitor logs for any issues
|
|
3. Check login_attempts table is populating
|
|
|
|
#### Phase 3: Switch Routes (Day 4)
|
|
1. Update route imports in server.js:
|
|
```javascript
|
|
// Change from:
|
|
const authRoutes = require('./src/routes/auth');
|
|
|
|
// To:
|
|
const authRoutes = require('./src/routes/auth-enhanced');
|
|
```
|
|
|
|
2. Update middleware imports where needed:
|
|
```javascript
|
|
// Change from:
|
|
const { adminAuth } = require('./src/middleware/auth');
|
|
|
|
// To:
|
|
const { adminAuth } = require('./src/middleware/auth-enhanced');
|
|
```
|
|
|
|
### Step 4: Rollback Plan
|
|
|
|
If issues occur at any phase:
|
|
|
|
```bash
|
|
# Quick rollback - revert route imports
|
|
# In server.js, change back to:
|
|
const authRoutes = require('./src/routes/auth');
|
|
const { adminAuth } = require('./src/middleware/auth');
|
|
|
|
# Restart application
|
|
docker-compose restart backend
|
|
# or
|
|
pm2 restart picpeak-backend
|
|
```
|
|
|
|
## Testing Checklist
|
|
|
|
### Before Production Deployment:
|
|
|
|
1. **Test Normal Login Flow**:
|
|
```bash
|
|
# Should work normally
|
|
curl -X POST http://localhost:3001/api/auth/admin/login \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"username":"admin","password":"correct-password"}'
|
|
```
|
|
|
|
2. **Test Account Lockout**:
|
|
```bash
|
|
# Make 5 failed attempts
|
|
for i in {1..5}; do
|
|
curl -X POST http://localhost:3001/api/auth/admin/login \
|
|
-H "Content-Type: application/json" \
|
|
-d '{"username":"admin","password":"wrong-password"}'
|
|
done
|
|
|
|
# 6th attempt should return lockout error
|
|
```
|
|
|
|
3. **Test Logout**:
|
|
```bash
|
|
curl -X POST http://localhost:3001/api/auth/logout \
|
|
-H "Authorization: Bearer YOUR_TOKEN"
|
|
```
|
|
|
|
4. **Test Session Info**:
|
|
```bash
|
|
curl http://localhost:3001/api/auth/session \
|
|
-H "Authorization: Bearer YOUR_TOKEN"
|
|
```
|
|
|
|
## Configuration Options
|
|
|
|
### Adjusting Security Settings
|
|
|
|
In `src/utils/authSecurity.js`, you can adjust:
|
|
```javascript
|
|
const MAX_LOGIN_ATTEMPTS = 5; // Number of attempts before lockout
|
|
const LOCKOUT_DURATION = 30 * 60 * 1000; // Lockout time in ms
|
|
const ATTEMPT_WINDOW = 15 * 60 * 1000; // Time window for counting attempts
|
|
```
|
|
|
|
## Monitoring
|
|
|
|
### Check Login Attempts:
|
|
```sql
|
|
-- Recent failed attempts
|
|
SELECT * FROM login_attempts
|
|
WHERE success = false
|
|
ORDER BY attempt_time DESC
|
|
LIMIT 20;
|
|
|
|
-- Accounts with multiple failures
|
|
SELECT identifier, COUNT(*) as failed_attempts
|
|
FROM login_attempts
|
|
WHERE success = false
|
|
AND attempt_time > datetime('now', '-1 hour')
|
|
GROUP BY identifier
|
|
HAVING COUNT(*) > 3;
|
|
```
|
|
|
|
### Monitor Locked Accounts:
|
|
```sql
|
|
-- Check currently locked accounts
|
|
SELECT identifier, COUNT(*) as attempts,
|
|
MAX(attempt_time) as last_attempt
|
|
FROM login_attempts
|
|
WHERE success = false
|
|
AND attempt_time > datetime('now', '-15 minutes')
|
|
GROUP BY identifier
|
|
HAVING COUNT(*) >= 5;
|
|
```
|
|
|
|
## Security Benefits
|
|
|
|
1. **Prevents Brute Force**: Account lockout after failed attempts
|
|
2. **Audit Trail**: Complete login history for security analysis
|
|
3. **Session Security**: Tokens invalidated on password change
|
|
4. **IP Monitoring**: Detect suspicious login patterns
|
|
5. **User Privacy**: Generic errors prevent user enumeration
|
|
|
|
## Notes
|
|
|
|
- Old tokens remain valid until expiration
|
|
- No immediate user impact
|
|
- Gradual rollout minimizes risk
|
|
- Full rollback possible at any stage
|
|
|
|
## Support
|
|
|
|
Monitor logs after deployment:
|
|
```bash
|
|
# Docker
|
|
docker-compose logs -f backend | grep -E "(auth|login|security)"
|
|
|
|
# PM2
|
|
pm2 logs picpeak-backend | grep -E "(auth|login|security)"
|
|
``` |