DEV Community

sen
sen

Posted on

Keycloak tm 2

Threat Model: Keycloak Authentication Provider in Kubernetes

System Architecture Overview

Components:

  • Keycloak instance running in Kubernetes container
  • REST API Gateway (external-facing)
  • Internal network communication only
  • JWT token-based authentication for downstream applications

STRIDE Threat Analysis

1. SPOOFING (Identity Theft)

Threat S.1: Credential Stuffing Attacks

MITRE Technique: T1110.004 - Brute Force: Credential Stuffing

  • Description: Attackers use leaked credentials from other breaches to authenticate against Keycloak
  • Impact: Unauthorized access to user accounts
  • Mitigations:
    • Implement account lockout policies after failed attempts
    • Enable CAPTCHA for login forms
    • Implement rate limiting at API Gateway
    • Use breach password detection (HaveIBeenPwned integration)
    • Enforce MFA for all users
  • Challenges: Balancing security with user experience; legitimate users may be locked out

Threat S.2: JWT Token Forgery

MITRE Technique: T1606.001 - Forge Web Credentials: Web Cookies

  • Description: Attacker attempts to forge JWT tokens with weak signing algorithms or stolen keys
  • Impact: Complete authentication bypass
  • Mitigations:
    • Use strong asymmetric algorithms (RS256, ES256) instead of HS256
    • Implement short token expiration times (5-15 minutes for access tokens)
    • Rotate signing keys regularly
    • Store private keys in Kubernetes secrets with encryption at rest
    • Implement token introspection for sensitive operations
  • Challenges: Key rotation requires coordination across services; short expiration increases refresh token usage

Threat S.3: Session Hijacking via Token Theft

MITRE Technique: T1539 - Steal Web Session Cookie

  • Description: Attacker steals JWT tokens from client-side storage or network traffic
  • Impact: Account takeover
  • Mitigations:
    • Enforce HTTPS/TLS for all communications
    • Use HttpOnly and Secure flags for refresh tokens
    • Implement token binding to client certificates or device fingerprints
    • Use short-lived access tokens with refresh token rotation
    • Implement anomaly detection (IP changes, user-agent changes)
  • Challenges: Token binding may break legitimate multi-device scenarios

Threat S.4: Compromised Service Account Credentials

MITRE Technique: T1078.004 - Valid Accounts: Cloud Accounts

  • Description: Service-to-service authentication credentials leaked or compromised
  • Impact: Lateral movement within cluster
  • Mitigations:
    • Use Kubernetes service accounts with RBAC
    • Implement OAuth2 client credentials flow with certificate-based authentication
    • Rotate service account credentials regularly
    • Use pod security policies to limit service account usage
    • Implement network policies restricting pod-to-pod communication
  • Challenges: Service credential rotation can cause service disruptions

2. TAMPERING (Data Modification)

Threat T.1: JWT Claims Manipulation

MITRE Technique: T1565.002 - Data Manipulation: Transmitted Data Manipulation

  • Description: Attacker modifies JWT claims (roles, permissions, user ID) after issuance
  • Impact: Privilege escalation, unauthorized access
  • Mitigations:
    • Use digital signatures (RS256/ES256) to ensure token integrity
    • Validate token signature on every request in downstream services
    • Implement claim validation (issuer, audience, expiration)
    • Use JWE (JSON Web Encryption) for sensitive claims
  • Challenges: Performance overhead of signature verification on every request

Threat T.2: Configuration Tampering in Kubernetes

MITRE Technique: T1612 - Build Image on Host

  • Description: Malicious modification of Keycloak ConfigMaps, Secrets, or container images
  • Impact: Authentication bypass, backdoor creation
  • Mitigations:
    • Implement RBAC limiting access to Keycloak namespace
    • Use admission controllers (OPA/Gatekeeper) to validate configurations
    • Enable audit logging for all configuration changes
    • Use signed container images and image scanning
    • Implement GitOps for configuration management with approval workflows
  • Challenges: Overly restrictive RBAC may hinder legitimate operations

Threat T.3: Database Tampering

MITRE Technique: T1565.001 - Data Manipulation: Stored Data Manipulation

  • Description: Direct manipulation of Keycloak's backend database (user credentials, roles, client secrets)
  • Impact: Complete authentication system compromise
  • Mitigations:
    • Encrypt database at rest
    • Use network policies to restrict database access to Keycloak pods only
    • Implement database access logging and monitoring
    • Use strong database authentication (certificate-based)
    • Regular database backups with integrity verification
    • Hash passwords with strong algorithms (bcrypt/PBKDF2)
  • Challenges: Performance impact of encryption; backup security management

Threat T.4: Man-in-the-Middle Attacks

MITRE Technique: T1557 - Adversary-in-the-Middle

  • Description: Interception and modification of traffic between API Gateway and Keycloak
  • Impact: Credential theft, session hijacking
  • Mitigations:
    • Use mutual TLS (mTLS) between API Gateway and Keycloak
    • Implement service mesh (Istio/Linkerd) with automatic mTLS
    • Use certificate pinning where possible
    • Monitor for certificate anomalies
  • Challenges: Certificate management complexity; service mesh overhead

3. REPUDIATION (Denying Actions)

Threat R.1: Insufficient Audit Logging

MITRE Technique: T1070 - Indicator Removal

  • Description: Lack of comprehensive logging allows attackers to hide their activities
  • Impact: Inability to detect, investigate, or prove security incidents
  • Mitigations:
    • Enable Keycloak event logging for all authentication events
    • Log to centralized logging system (ELK, Splunk, CloudWatch)
    • Implement tamper-proof logging (write-once storage)
    • Log: login attempts, token issuance, permission changes, admin actions
    • Implement log retention policies (compliance requirements)
    • Use structured logging (JSON format)
  • Challenges: Log volume management; storage costs; GDPR compliance for user data in logs

Threat R.2: Token Replay Attacks

MITRE Technique: T1550.001 - Use Alternate Authentication Material: Application Access Token

  • Description: Captured valid tokens are replayed by attackers
  • Impact: Unauthorized access using legitimate tokens
  • Mitigations:
    • Implement token jti (JWT ID) claim with one-time use validation
    • Use short token lifetimes
    • Implement token revocation lists (though challenging at scale)
    • Bind tokens to specific clients/IPs where appropriate
    • Monitor for anomalous token usage patterns
  • Challenges: Stateless JWT benefits lost with revocation checking; performance impact

4. INFORMATION DISCLOSURE (Exposing Information)

Threat I.1: Exposed Secrets in Container Environment

MITRE Technique: T1552.007 - Unsecured Credentials: Container API

  • Description: Keycloak secrets, database credentials, or signing keys exposed via environment variables or config files
  • Impact: Complete authentication system compromise
  • Mitigations:
    • Use Kubernetes secrets with encryption at rest enabled
    • Implement external secrets management (HashiCorp Vault, AWS Secrets Manager)
    • Use CSI drivers for secret injection
    • Never embed secrets in container images
    • Implement secret scanning in CI/CD pipelines
    • Use workload identity where possible
  • Challenges: Secrets management complexity; application changes for external secret providers

Threat I.2: Information Leakage via Error Messages

MITRE Technique: T1213 - Data from Information Repositories

  • Description: Detailed error messages reveal system architecture, usernames, or configuration details
  • Impact: Intelligence gathering for targeted attacks
  • Mitigations:
    • Configure generic error messages for authentication failures
    • Disable stack traces in production
    • Implement proper exception handling
    • Log detailed errors server-side only
    • Use separate logging for debug vs. production
  • Challenges: Balancing security with troubleshooting needs

Threat I.3: JWT Token Information Disclosure

MITRE Technique: T1552.001 - Unsecured Credentials: Credentials In Files

  • Description: JWT tokens contain sensitive information in claims (PII, internal IDs)
  • Impact: Privacy violations, information leakage
  • Mitigations:
    • Minimize claims in JWT tokens (only essential data)
    • Use opaque reference tokens for sensitive operations
    • Implement JWE for encrypting token contents
    • Avoid storing sensitive PII in tokens
    • Use token introspection endpoint for detailed information
  • Challenges: Balance between token size and information needs; encryption overhead

Threat I.4: Keycloak Admin Console Exposure

MITRE Technique: T1190 - Exploit Public-Facing Application

  • Description: Admin console accessible from unintended networks or with weak authentication
  • Impact: Complete system compromise, user data breach
  • Mitigations:
    • Restrict admin console to specific IPs/networks via NetworkPolicy
    • Require MFA for all admin accounts
    • Use separate admin realm with stricter security
    • Implement time-based access restrictions
    • Regular admin access reviews
    • Use just-in-time admin access
  • Challenges: Emergency access scenarios; admin user experience

Threat I.5: Container Image Vulnerabilities

MITRE Technique: T1525 - Implant Internal Image

  • Description: Vulnerabilities in base images or Keycloak dependencies expose sensitive data
  • Impact: Container compromise, data exfiltration
  • Mitigations:
    • Regular vulnerability scanning (Trivy, Clair, Snyk)
    • Use minimal base images (distroless)
    • Implement automated patching workflows
    • Use admission controllers to block vulnerable images
    • Monitor CVE feeds for Keycloak-specific vulnerabilities
  • Challenges: False positives in scanning; breaking changes in updates

5. DENIAL OF SERVICE (Resource Exhaustion)

Threat D.1: Authentication Request Flooding

MITRE Technique: T1499.002 - Endpoint Denial of Service: Service Exhaustion Flood

  • Description: Mass authentication requests overwhelm Keycloak
  • Impact: Legitimate users cannot authenticate
  • Mitigations:
    • Implement rate limiting at API Gateway (per IP, per user)
    • Configure Kubernetes resource limits (CPU, memory)
    • Implement horizontal pod autoscaling (HPA)
    • Use connection pooling for database
    • Implement request queuing with circuit breakers
    • Deploy Web Application Firewall (WAF)
  • Challenges: Distinguishing legitimate high traffic from attacks; autoscaling costs

Threat D.2: Token Generation Exhaustion

MITRE Technique: T1499.004 - Endpoint Denial of Service: Application or System Exploitation

  • Description: Attackers repeatedly request token refresh, exhausting resources
  • Impact: Service degradation or failure
  • Mitigations:
    • Rate limit token refresh endpoints
    • Implement token refresh quotas per user/session
    • Use sliding window rate limiting
    • Monitor token generation metrics
    • Implement graceful degradation
  • Challenges: Legitimate apps with multiple services may hit limits

Threat D.3: Database Connection Pool Exhaustion

MITRE Technique: T1499.002 - Endpoint Denial of Service: Service Exhaustion Flood

  • Description: Excessive authentication requests exhaust database connections
  • Impact: Complete authentication service failure
  • Mitigations:
    • Configure appropriate connection pool sizes
    • Implement connection timeouts
    • Use read replicas for token validation
    • Cache frequently accessed data (realm configuration, client data)
    • Implement database query optimization
  • Challenges: Cache invalidation complexity; consistency issues

Threat D.4: Resource Exhaustion via Slow Loris

MITRE Technique: T1499.001 - Endpoint Denial of Service: OS Exhaustion Flood

  • Description: Slow, prolonged connections exhaust container resources
  • Impact: Service unavailability
  • Mitigations:
    • Configure connection timeouts at API Gateway and Keycloak
    • Implement request size limits
    • Use reverse proxy with timeout controls
    • Monitor connection metrics
    • Configure pod disruption budgets
  • Challenges: Slow legitimate clients may be affected

6. ELEVATION OF PRIVILEGE (Gaining Unauthorized Access)

Threat E.1: Container Escape

MITRE Technique: T1611 - Escape to Host

  • Description: Attacker exploits container runtime vulnerability to access Kubernetes node
  • Impact: Complete cluster compromise
  • Mitigations:
    • Run containers as non-root users
    • Implement Pod Security Standards (restricted profile)
    • Use seccomp and AppArmor/SELinux profiles
    • Disable privileged containers
    • Keep container runtime updated
    • Use RuntimeClass with sandboxed runtimes (gVisor, Kata)
  • Challenges: Application compatibility with security restrictions

Threat E.2: Privilege Escalation via Keycloak Vulnerabilities

MITRE Technique: T1068 - Exploitation for Privilege Escalation

  • Description: Exploiting Keycloak bugs to gain admin privileges
  • Impact: Complete authentication system control
  • Mitigations:
    • Keep Keycloak updated to latest stable version
    • Subscribe to security advisories
    • Implement defense-in-depth (even admin can't access certain resources)
    • Regular security assessments and penetration testing
    • Implement role-based access control with principle of least privilege
  • Challenges: Update testing overhead; potential breaking changes

Threat E.3: Kubernetes RBAC Misconfiguration

MITRE Technique: T1078.004 - Valid Accounts: Cloud Accounts

  • Description: Overly permissive RBAC allows unauthorized access to Keycloak resources
  • Impact: Configuration tampering, credential theft
  • Mitigations:
    • Implement least privilege RBAC policies
    • Regular RBAC audits
    • Use namespace isolation
    • Implement admission controllers for policy enforcement
    • Monitor for privilege escalation attempts
  • Challenges: RBAC complexity; operational overhead

Threat E.4: Client Secret Compromise Leading to Privilege Escalation

MITRE Technique: T1552.001 - Unsecured Credentials: Credentials In Files

  • Description: Compromised OAuth2 client credentials used to gain elevated access
  • Impact: Access to resources beyond intended scope
  • Mitigations:
    • Use public clients with PKCE for SPAs and mobile apps
    • Rotate client secrets regularly
    • Implement client authentication with mutual TLS
    • Use dynamic client registration carefully
    • Audit client configurations regularly
    • Implement scope validation and least privilege
  • Challenges: Managing secret rotation across multiple services

Threat E.5: Admin REST API Exploitation

MITRE Technique: T1212 - Exploitation for Credential Access

  • Description: Unauthorized access to Keycloak Admin REST API
  • Impact: Complete realm manipulation, user data access
  • Mitigations:
    • Restrict Admin API access via network policies
    • Require separate authentication for Admin API
    • Implement API rate limiting
    • Use IP allowlisting for admin operations
    • Enable comprehensive audit logging for admin actions
  • Challenges: Legitimate automation may require admin API access

Additional Kubernetes-Specific Threats

Threat K.1: Sidecar Container Injection

MITRE Technique: T1525 - Implant Internal Image

  • Description: Malicious sidecar containers injected to intercept Keycloak traffic
  • Impact: Credential theft, traffic manipulation
  • Mitigations:
    • Use admission webhooks to validate pod specifications
    • Implement Pod Security Admission
    • Monitor for unexpected container additions
    • Use service mesh with mTLS
  • Challenges: Legitimate sidecars (logging, monitoring) need allowlisting

Threat K.2: Supply Chain Attacks

MITRE Technique: T1195.002 - Supply Chain Compromise: Compromise Software Supply Chain

  • Description: Compromised Keycloak container images or dependencies
  • Impact: Backdoors, malware in authentication system
  • Mitigations:
    • Use official Keycloak images only
    • Implement image signing and verification
    • Use private container registry with scanning
    • Implement Software Bill of Materials (SBOM)
    • Regular dependency audits
  • Challenges: False positives; trusted source verification

JWT-Specific Threats in Downstream Applications

Threat J.1: Algorithm Confusion Attacks

MITRE Technique: T1556 - Modify Authentication Process

  • Description: Attacker changes JWT algorithm from RS256 to HS256, using public key as HMAC secret
  • Impact: Token forgery, authentication bypass
  • Mitigations:
    • Explicitly specify and validate expected algorithm
    • Never accept "none" algorithm
    • Use JWT libraries with algorithm validation
    • Implement JWK (JSON Web Key) sets with proper validation
  • Challenges: Requires proper library configuration in all consuming services

Threat J.2: Token Substitution Attacks

MITRE Technique: T1134 - Access Token Manipulation

  • Description: Valid token from one context used in another unauthorized context
  • Impact: Unauthorized access to resources
  • Mitigations:
    • Validate audience (aud) claim strictly
    • Implement resource-specific tokens
    • Use scope validation
    • Validate token issuer (iss) claim
  • Challenges: Complex multi-tenant or multi-service architectures

Cross-Cutting Security Measures

Network Security

  • Implement NetworkPolicies: Restrict egress/ingress to only necessary services
  • Use Service Mesh: Automatic mTLS, traffic control, observability
  • Segment Networks: Separate Keycloak, database, and application networks

Monitoring & Detection

  • SIEM Integration: Feed all logs to security information and event management
  • Anomaly Detection: ML-based detection of unusual authentication patterns
  • Metrics Monitoring: Track failed authentications, token generation rates, latency
  • Alert on: Multiple failed logins, unusual token patterns, configuration changes

Compliance & Governance

  • Regular Security Audits: Penetration testing, code reviews
  • Compliance Frameworks: GDPR, SOC2, ISO 27001 considerations
  • Incident Response Plan: Documented procedures for breach scenarios
  • Regular Updates: Patch management schedule

Key Challenges Summary

  1. Performance vs. Security Trade-offs: Token validation, encryption, and logging impact performance
  2. Operational Complexity: Secret rotation, certificate management, and configuration across multiple services
  3. User Experience: Security measures (MFA, rate limiting) may frustrate legitimate users
  4. Stateless vs. Stateful Dilemma: JWT benefits of statelessness conflict with revocation needs
  5. Multi-Service Coordination: Consistent security implementation across consuming applications
  6. Cloud-Native Complexity: Kubernetes adds layers of potential vulnerabilities
  7. Compliance Requirements: GDPR, data retention policies complicate logging and monitoring
  8. Emergency Access: Balancing security restrictions with operational needs during incidents

Priority Recommendations

Critical (Implement Immediately):

  1. Enable mTLS between all components
  2. Implement strong RBAC in Kubernetes
  3. Use external secrets management
  4. Enable comprehensive audit logging
  5. Implement JWT signature validation with RS256

High Priority:

  1. Deploy service mesh for automatic security
  2. Implement MFA for all accounts
  3. Set up rate limiting and DDoS protection
  4. Regular vulnerability scanning and patching
  5. Network segmentation with NetworkPolicies

Medium Priority:
1.Implement token binding/device fingerprinting

  1. Deploy SIEM with anomaly detection
  2. Regular penetration testing
  3. Implement JWE for sensitive claims
  4. Automated secret rotation

This threat model should be reviewed quarterly and updated as the architecture evolves or new threats emerge.

Top comments (0)