Skip to content

Authentication Module - Enhanced with E2E & Security Compliance

Overview

The Authentication module provides comprehensive multi-factor authentication (MFA), multi-authentication strategy support, end-to-end encryption, and session management for the banking platform. It handles user authentication, JWT token generation, credential management, and security policies with full compliance to international banking and data protection standards.

API Prefix: /api/v1/auth

Key Features

1. Multi-Authentication Strategies

  • Local Authentication: Username/Email + Password with bcrypt hashing
  • SAML 2.0: Enterprise Single Sign-On (SSO) integration
  • LDAP: Directory services authentication (Active Directory, OpenLDAP)
  • OAuth2/Social: Google and Azure integration (extensible)

2. Multi-Factor Authentication (MFA)

  • TOTP (Time-based One-Time Password): Google Authenticator, Authy, Microsoft Authenticator
  • SMS/Email OTP: One-time passwords via SMS or email
  • Security Questions: Custom security question setup and verification
  • Two-Factor Verification: Email/SMS based verification
  • Biometric: Fingerprint/Face recognition (mobile)
  • Push Notifications: App-based approval

3. End-to-End (E2E) Encryption

3.1 E2E Encryption Architecture

Client ←──Encrypted──→ API Gateway ←──Encrypted──→ Backend
         RSA 2048              TLS 1.3            AES-256-GCM

3.2 Initial Handshake

1. Client Requests Public Key
   GET /api/v1/auth/public_key

   Response:
   {
     "public_key": "-----BEGIN PUBLIC KEY-----\n...\n-----END PUBLIC KEY-----",
     "algorithm": "RSA-2048",
     "key_id": "key_2024_06",
     "expires_at": "2025-06-01T00:00:00Z"
   }

2. Client Generates Symmetric Key
   - Generate random 256-bit AES key
   - Generate random 128-bit IV (Initialization Vector)
   - Generate random 16-byte authentication tag

3. Client Encrypts Symmetric Key with Public Key
   - Encrypt AES key using RSA-2048 OAEP padding
   - Encrypt IV using same public key
   - Send encrypted keys to server

3.3 Message Encryption/Decryption Flow

CLIENT SIDE - Encryption:
1. Take plaintext payload (JSON)
2. Serialize to bytes
3. Generate random IV (16 bytes)
4. Encrypt with AES-256-GCM using:
   - Key: Negotiated symmetric key
   - IV: Random per message
   - AAD: Request metadata (endpoint, method, timestamp)
5. Generate authentication tag
6. Prepend: IV + Auth Tag + Ciphertext
7. Base64 encode
8. Send in X-Encrypted-Payload header

SERVER SIDE - Decryption:
1. Extract X-Encrypted-Payload from header
2. Base64 decode
3. Extract IV (first 16 bytes)
4. Extract Auth Tag (next 16 bytes)
5. Extract Ciphertext (remaining bytes)
6. Decrypt with AES-256-GCM:
   - Verify authentication tag first (prevents tampering)
   - Decrypt using stored symmetric key
   - Validate AAD metadata
7. Deserialize to JSON
8. Process plaintext data

SERVER SIDE - Response Encryption:
1. Take response payload (JSON)
2. Serialize to bytes
3. Generate random IV
4. Encrypt with AES-256-GCM
5. Generate authentication tag
6. Prepend: IV + Auth Tag + Ciphertext
7. Base64 encode
8. Send in X-Encrypted-Payload header
9. Include authentication metadata

CLIENT SIDE - Response Decryption:
1. Extract X-Encrypted-Payload from header
2. Follow same decryption process

3.4 E2E Encryption Configuration

{
  "e2e_encryption": {
    "enabled": true,
    "algorithm": "AES-256-GCM",
    "key_derivation": "PBKDF2",
    "key_iterations": 100000,
    "rsa_key_size": 2048,
    "rsa_padding": "OAEP",
    "rsa_hash": "SHA-256",
    "iv_size_bytes": 16,
    "auth_tag_size_bytes": 16,
    "key_rotation_days": 90,
    "session_key_expiry_hours": 24,
    "forward_secrecy": true,
    "perfect_forward_secrecy": true
  }
}

3.5 Key Management

Key Hierarchy:
├── Master Key (HSM stored, never transmitted)
├── Session Master Key (per user session)
│   ├── Encryption Key (for payload encryption)
│   ├── Authentication Key (for HMAC)
│   └── Derivation Key (for sub-keys)
└── Per-Message Keys (ephemeral)
    ├── Message IV (random per message)
    └── Derived from Session Master Key

3.6 Perfect Forward Secrecy (PFS)

Implementation:
- Each session generates unique Diffie-Hellman parameters
- Ephemeral session keys never stored
- Previous session keys cannot decrypt current messages
- Even if server compromise, historical messages remain safe

Key Exchange:
1. Initial TLS 1.3 with ECDHE (Elliptic Curve Diffie-Hellman Ephemeral)
2. Session-specific symmetric key derivation
3. Message-specific IV and authentication tag
4. Keys destroyed after session ends

Session Management

  • User session tracking with last activity timestamp
  • Multi-session support per user (configurable limit)
  • Session history audit trail with detailed logging
  • Automatic session cleanup middleware
  • Inactivity-based session termination
  • Concurrent session detection and prevention (optional)
  • Secure session token storage (HttpOnly, Secure, SameSite cookies)

Token Management

JWT Token Structure

Header:
{
  "alg": "HS256",
  "typ": "JWT",
  "kid": "key_2024_06"
}

Payload (Access Token):
{
  "sub": "<encrypted_username>",
  "user_id": "<user_uuid>",
  "roles": ["admin", "loan_officer"],
  "permissions": ["loan.approve", "transaction.view"],
  "iat": 1719000000,
  "exp": 1719003600,
  "nbf": 1719000000,
  "jti": "<unique_token_id>",
  "iss": "bank.example.com",
  "aud": ["api", "web"],
  "session_id": "<session_uuid>",
  "device_fingerprint": "<fingerprint>",
  "ip_address": "<hashed_ip>"
}

Signature:
HMACSHA256(
  base64UrlEncode(header) + "." +
  base64UrlEncode(payload),
  secret
)

Token Types

  • Access Tokens: JWT with 60-minute default expiry
  • Refresh Tokens: Long-lived JWT (7 days) for token refresh
  • Reset Tokens: For password reset flows (10-minute expiry)
  • 2FA Tokens: For second factor verification (5-minute expiry)
  • Token Denylist: Redis-backed blacklist for immediate token revocation

Token Rotation

Refresh Token Rotation:
1. Client receives access_token + refresh_token
2. Access token expires after 60 minutes
3. Client sends refresh_token to /auth/refresh
4. Server validates refresh_token
5. Server generates new access_token + new refresh_token
6. Old refresh_token is invalidated (single-use)
7. Client stores new tokens
8. Prevents token reuse and limits exposure window

Security Compliance

1. GDPR Compliance

Data Protection

✓ Data Minimization: Collect only necessary data
✓ Purpose Limitation: Use data only for stated purpose
✓ Storage Limitation: Delete data after retention period
✓ Integrity & Confidentiality: Encrypt all sensitive data
✓ Accountability: Maintain complete audit trail

User Rights Implementation

Right to Access:
- User can request all personal data
- Export in machine-readable format (JSON/CSV)
- Endpoint: GET /api/v1/auth/gdpr/export

Right to Deletion:
- User can request account deletion
- "Right to be Forgotten" implementation
- Endpoint: POST /api/v1/auth/gdpr/delete
- Keeps minimal data for legal obligations

Right to Rectification:
- User can correct personal data
- Audit trail of all corrections
- Endpoint: PUT /api/v1/auth/profile/update

Right to Data Portability:
- Export personal data in standard format
- Endpoint: GET /api/v1/auth/gdpr/portability

Consent Management:
- Track consent for each data use
- Allow withdrawal of consent
- Endpoint: GET/POST /api/v1/auth/consent

Data Breach Notification

Timeline:
- Detect breach
- Notify affected users within 72 hours (or without undue delay)
- Notify regulatory authority
- Document incident details
- Implement remediation measures

Notification Template:
{
  "breach_id": "BREACH_2024_001",
  "description": "Unauthorized access to user data",
  "data_affected": ["names", "phone_numbers"],
  "discovery_date": "2024-06-20",
  "notification_date": "2024-06-23",
  "users_affected": 1500,
  "remediation": "..."
}

2. PCI DSS (Payment Card Industry Data Security Standard) Compliance

Version 3.2.1 & 4.0 Compliance

Requirement 1: Network Architecture
✓ Firewall configuration and rules
✓ Deny direct public access to cardholder data
✓ Network segmentation (DMZ, internal zones)

Requirement 2: Default Security Settings
✓ Change all default passwords
✓ Remove unnecessary accounts
✓ Disable unnecessary services
✓ Document and justify all open ports

Requirement 3: Cardholder Data Protection
✓ Render card numbers unreadable
✓ Tokens instead of card numbers
✓ Encryption of cardholder data in transit and at rest

Requirement 4: Encryption in Transit
✓ TLS 1.2 minimum (1.3 recommended)
✓ Strong cipher suites only
✓ Certificate pinning for sensitive channels
✓ HSTS (HTTP Strict Transport Security) enabled

Requirement 5: Malware Protection
✓ Antivirus on all systems
✓ Real-time monitoring
✓ Regular updates and patches

Requirement 6: Code Security
✓ Secure development lifecycle
✓ Code review before deployment
✓ Security testing (static & dynamic)
✓ Vulnerability scanning

Requirement 7: Access Control
✓ Role-based access control
✓ Principle of least privilege
✓ Multi-factor authentication
✓ Unique user IDs (no shared accounts)

Requirement 8: User Identification & Authentication
✓ Strong passwords (12+ chars, complexity)
✓ Multi-factor authentication
✓ Session timeout (15 minutes)
✓ Password history (no reuse last 4)

Requirement 9: Physical Security
✓ Restricted physical access
✓ Video surveillance
✓ Access logs and visitor logs

Requirement 10: Logging & Monitoring
✓ All access to cardholder data logged
✓ Audit logs for all system components
✓ Real-time monitoring and alerting
✓ Logs retained for 1+ year

Requirement 11: Testing & Remediation
✓ Regular vulnerability scans (quarterly minimum)
✓ Penetration testing (annual minimum)
✓ Patching (critical within 1 month)

Requirement 12: Policy & Procedure
✓ Information security policy
✓ Acceptable use policy
✓ Risk assessment procedures
✓ Incident response plan

3. OWASP Top 10 Mitigation

1. Injection Prevention
   ✓ Parameterized queries (SQLAlchemy ORM)
   ✓ Input validation and sanitization
   ✓ Prepared statements

2. Broken Authentication
   ✓ Multi-factor authentication (TOTP, SMS, Email)
   ✓ Session management (tokens, expiry)
   ✓ Password policies (complexity, expiry)
   ✓ Rate limiting on login attempts

3. Sensitive Data Exposure
   ✓ E2E encryption (AES-256-GCM)
   ✓ HTTPS/TLS 1.3
   ✓ Data masking in logs/responses
   ✓ Encryption at rest (database)

4. XML External Entity (XXE)
   ✓ Disable XML external entity parsing
   ✓ Input validation for XML
   ✓ Restrict SAML payload size

5. Broken Access Control
   ✓ Role-based access control (RBAC)
   ✓ Permission enforcement middleware
   ✓ Audit logging of all access

6. Security Misconfiguration
   ✓ Default passwords changed
   ✓ Unnecessary services disabled
   ✓ Security headers configured
   ✓ Regular security scanning

7. Cross-Site Scripting (XSS)
   ✓ Input validation and output encoding
   ✓ Content Security Policy (CSP) headers
   ✓ HttpOnly cookies

8. Insecure Deserialization
   ✓ Type checking on deserialized data
   ✓ Version control for serialized objects
   ✓ Input validation

9. Using Components with Known Vulnerabilities
   ✓ Dependency scanning (pip-audit)
   ✓ Regular updates and patching
   ✓ Vulnerability monitoring

10. Insufficient Logging & Monitoring
    ✓ Comprehensive audit logging
    ✓ Real-time alerting
    ✓ Log retention and analysis
    ✓ Incident response procedures

4. ISO 27001 (Information Security Management)

Asset Management (A.8)
✓ Inventory of all sensitive assets
✓ Classification and handling rules
✓ Responsibility assignment

Access Control (A.9)
✓ User access provisioning
✓ Privileged access management
✓ Access review procedures
✓ Password management policies

Cryptography (A.10)
✓ Encryption key management
✓ Strong encryption algorithms
✓ Key rotation schedule
✓ Secure key storage (HSM)

Physical & Environmental Security (A.11)
✓ Secure data centers
✓ Access controls
✓ Monitoring and recording

Operations Security (A.12)
✓ Change management procedures
✓ Backup and recovery plans
✓ Event logging and monitoring
✓ System maintenance

Communications Security (A.13)
✓ Network segmentation
✓ TLS/SSL encryption
✓ Firewall rules
✓ Email encryption

System Acquisition, Development & Maintenance (A.14)
✓ Secure SDLC (Software Development Lifecycle)
✓ Security testing
✓ Code review
✓ Change control

Supplier Relationships (A.15)
✓ Vendor security assessment
✓ Contract security clauses
✓ Incident notification requirements

Information Security Incident Management (A.16)
✓ Incident detection and response
✓ Breach notification procedures
✓ Post-incident review
✓ Continuous improvement

Business Continuity (A.17)
✓ Disaster recovery plan
✓ Backup and restore procedures
✓ Recovery time objectives (RTO)
✓ Recovery point objectives (RPO)

Compliance (A.18)
✓ Regulatory compliance verification
✓ Information security audit
✓ Compliance reporting

5. Banking Regulatory Compliance

Basel III (Operational Risk)

✓ Risk management framework
✓ Stress testing procedures
✓ Scenario analysis
✓ Operational risk monitoring
✓ Incident reporting

Central Bank Requirements (Bank of Zambia)

✓ Cybersecurity Framework adherence
✓ IT governance and risk management
✓ Business continuity and disaster recovery
✓ Third-party risk management
✓ Security incident notification (24 hours)

FinCEN (Financial Crime Enforcement Network)

✓ Know Your Customer (KYC)
✓ Anti-Money Laundering (AML) procedures
✓ Suspicious Activity Reporting (SAR)
✓ Currency Transaction Reporting (CTR)
✓ Customer Due Diligence (CDD)
✓ Enhanced Due Diligence (EDD) for high-risk

6. Data Residency & Privacy Laws

POPIA (Protection of Personal Information Act - South Africa)
✓ Lawful processing of personal information
✓ Purpose specification
✓ Further processing limitation
✓ Information quality and accuracy
✓ Security safeguards
✓ Data subject rights (access, correction, deletion)
✓ Openness and transparency
✓ Accountability principle

GDPR Articles Implemented:
✓ Article 5: Principles (lawfulness, fairness, transparency)
✓ Article 9: Special category data handling
✓ Article 12-22: Data subject rights
✓ Article 25: Data protection by design
✓ Article 28: Processor agreements
✓ Article 32: Security of processing
✓ Article 33-34: Breach notification

Authentication Security Implementation

Password Security

Hashing Algorithm: Bcrypt

Configuration:
- Algorithm: bcrypt (Blowfish cipher)
- Cost Factor: 12 (configurable, default)
- Salt: Generated per password
- Output: 60 character hash

Process:
1. Generate random salt (22 characters)
2. Hash password with cost factor 12
3. Store hash (never store plaintext)
4. On verification: hash input + compare hashes
5. Time constant comparison (prevent timing attacks)

Additional Layer - Fernet Encryption:
- Hash stored in database
- Password also encrypted with Fernet for at-rest protection
- Two layers of protection against database compromise

Password Policy Enforcement

Minimum Requirements:
- Length: 12 characters minimum
- Uppercase: At least 1 uppercase letter
- Lowercase: At least 1 lowercase letter
- Numbers: At least 1 digit
- Symbols: At least 1 special character (!@#$%^&*)
- No common patterns: Avoid keyboard patterns
- No dictionary words: Check against dictionary
- No username/email: Cannot contain user identifier

Password Expiry:
- Admin: 60 days
- Regular User: 90 days
- Service Account: No expiry (if service account)

Password History:
- Keep history of last 8 passwords
- Prevent reuse of previous passwords
- Prevent using same password for 12 months

Reset Requirements:
- Force password change on first login
- Force change on admin reset
- Notify via email before expiry (7 days warning)

Token Security

JWT Implementation

Signature Algorithm: HMAC with SHA-256 (HS256)
Secret Key Management:
- Store secret in AWS Secrets Manager
- Rotate secret every 90 days
- Maintain last 2 versions for validation
- Never commit to version control

Token Verification:
1. Verify signature (HMAC-SHA256)
2. Check expiration (exp claim)
3. Check not-before (nbf claim)
4. Check issuer (iss claim)
5. Check audience (aud claim)
6. Verify JTI in token denylist (Redis)
7. Validate device fingerprint
8. Validate IP address (optional)

Token Revocation (Denylist):
- Immediate revocation via Redis key
- TTL set to token expiry time
- Pattern: "token_denylist:{jti}"
- Check on every request

Secure Token Storage (Client-Side)

Access Token:
- Store in memory only (for SPAs)
- Never store in localStorage (XSS vulnerable)
- HttpOnly cookie if using cookies

Refresh Token:
- HttpOnly cookie (prevents JavaScript access)
- Secure flag (HTTPS only)
- SameSite=Strict (CSRF protection)
- Domain restriction

Token Transmission:
- HTTP Authorization header: "Bearer {token}"
- HTTPS/TLS 1.3 required
- Never transmit in URL parameters

Session Security

Session Storage

Session Data Structure:
{
  "session_id": "<uuid>",
  "user_id": "<user_uuid>",
  "created_at": "2024-06-20T10:00:00Z",
  "last_activity": "2024-06-20T10:15:00Z",
  "expires_at": "2024-06-20T11:00:00Z",
  "device_fingerprint": "<fingerprint>",
  "ip_address": "<hashed_ip>",
  "user_agent": "<device_info>",
  "is_active": true,
  "mfa_completed": true,
  "channel": "web"
}

Session Validation on Each Request:
1. Extract session_id from token
2. Lookup session in database
3. Verify not expired
4. Verify device fingerprint matches
5. Update last_activity timestamp
6. Check concurrent session limit
7. Allow request or reject

Concurrency Control

Single Session Mode:
- Only one active session per user
- New login invalidates previous session
- Suitable for banking apps

Multi-Session Mode (Default):
- Up to N concurrent sessions (default: 3)
- Different devices/channels
- Each session independent
- Can view/manage all sessions

Multi-Factor Authentication (MFA)

TOTP Implementation

Algorithm: HMAC-Based One-Time Password (RFC 6238)
- Time window: 30 seconds
- Digits: 6
- Hash algorithm: SHA-1 (standard) or SHA-256 (recommended)
- Accepted windows: Current + 1 before + 1 after (90 second window)

Setup Process:
1. Server generates secret (Base32 encoded)
2. Generate QR code: otpauth://totp/{label}?secret={secret}
3. User scans QR with authenticator app
4. User enters 6-digit code to verify
5. Server generates backup codes (10 codes)
6. TOTP enabled

Verification:
1. User submits 6-digit code
2. Server computes current TOTP (using secret)
3. Compare submitted vs expected (within 90 second window)
4. Verify code hasn't been used before (prevents replay)
5. If match: Grant 2FA completion

SMS/Email OTP

Process:
1. User requests 2FA (after password validation)
2. System generates random 6-digit code
3. Send via SMS/Email
4. User enters code within 5 minutes
5. System verifies code
6. Code cannot be reused
7. Retry limit: 3 attempts

Security Features:
- Time-limited (5 minutes)
- Single use only
- Rate limited (max 3 attempts)
- Delivery tracking
- Audit trail of all OTPs (masked)

Security Questions

Implementation:
1. Admin defines predefined questions (30+ pool)
2. User selects 3-5 questions during setup
3. User answers questions (hashed and stored)
4. During verification: ask 2-3 random questions
5. User must answer correctly

Security:
- Answers are hashed (bcrypt), not stored plaintext
- Case-insensitive comparison
- Whitespace trimming
- Retry limit: 3 attempts
- Lockout after failures
- Audit trail maintained

API Security Headers

Standard Security Headers

HTTP/1.1 200 OK
Strict-Transport-Security: max-age=31536000; includeSubDomains; preload
X-Content-Type-Options: nosniff
X-Frame-Options: DENY
X-XSS-Protection: 1; mode=block
Content-Security-Policy: default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline'
Referrer-Policy: strict-origin-when-cross-origin
Permissions-Policy: geolocation=(), microphone=(), camera=()
Content-Type: application/json; charset=utf-8
Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate
Pragma: no-cache
Expires: 0

Custom Security Headers

X-Request-ID: <unique-request-id>
X-Correlation-ID: <correlation-id>
X-Content-SHA256: <hash-of-response-body>
X-API-Version: 1.0
X-Response-Time: <milliseconds>

Audit Logging & Monitoring

Audit Log Entry

{
  "audit_id": "AUD_2024_001234",
  "timestamp": "2024-06-20T10:15:00Z",
  "event_type": "USER_LOGIN",
  "user_id": "user_123",
  "username": "john.doe",
  "status": "SUCCESS",
  "ip_address": "192.168.1.100",
  "device_fingerprint": "abcd1234",
  "user_agent": "Mozilla/5.0...",
  "channel": "web",
  "mfa_method": "totp",
  "location": {
    "country": "Zambia",
    "city": "Lusaka",
    "latitude": -12.8845,
    "longitude": 28.3203
  },
  "security_events": [
    {
      "event": "FAILED_LOGIN_ATTEMPT",
      "count": 1,
      "timestamp": "2024-06-20T10:14:00Z"
    }
  ],
  "risk_score": 0.2,
  "suspicious_indicators": []
}

Real-Time Alerts

Alert Triggers:
- Failed login attempts > 5 in 15 minutes
- New device login from new location
- Login from impossible travel (different countries < 1 hour)
- Unusual access patterns
- Multiple failed MFA attempts
- Geographic anomalies
- Time-based anomalies (login outside business hours)

Alert Response:
- Send email to user
- Send SMS alert
- Require additional verification
- Temporary account lock
- Notify security team

Compliance Checklist

✅ Encryption in Transit (TLS 1.3)
✅ Encryption at Rest (AES-256-GCM)
✅ End-to-End Encryption (RSA-2048 + AES-256)
✅ Perfect Forward Secrecy
✅ Multi-Factor Authentication
✅ Strong Password Hashing (bcrypt)
✅ Session Management & Timeout
✅ Rate Limiting on Auth Endpoints
✅ GDPR Compliance (User Rights)
✅ PCI DSS Compliance
✅ OWASP Top 10 Mitigation
✅ ISO 27001 Controls
✅ Audit Logging & Monitoring
✅ Incident Response Plan
✅ Regular Security Testing
✅ Data Breach Notification (72-hour)
✅ Security Headers Implementation
✅ CORS Configuration
✅ CSRF Protection
✅ XSS Prevention

Security Testing & Validation

Penetration Testing Scope

- SQL Injection testing
- Cross-Site Scripting (XSS)
- Cross-Site Request Forgery (CSRF)
- Authentication bypass attempts
- Session fixation/hijacking
- Brute force testing
- MFA bypass attempts
- API endpoint fuzzing
- Token manipulation
- Certificate validation

Automated Security Scanning

- Static Application Security Testing (SAST)
- Dynamic Application Security Testing (DAST)
- Dependency vulnerability scanning
- Container image scanning
- Infrastructure as Code (IaC) scanning
- Regular vulnerability assessments

Regular Audits

- Annual security audit by third-party
- Quarterly internal security review
- Monthly vulnerability assessment
- Weekly log review and analysis
- Daily automated threat detection