mirror of
https://github.com/mukul975/Anthropic-Cybersecurity-Skills.git
synced 2026-07-17 21:19:40 +03:00
Initial commit - 611 cybersecurity skills across all subdomains
This commit is contained in:
@@ -0,0 +1,111 @@
|
||||
---
|
||||
name: None
|
||||
description: Configure secure OAuth 2.0 authorization flows including Authorization Code with PKCE, Client Credentials, and Device Authorization Grant. This skill covers flow selection, PKCE implementation, token
|
||||
domain: cybersecurity
|
||||
subdomain: identity-access-management
|
||||
tags: [iam, identity, access-control, authentication, authorization, oauth2, oidc, pkce]
|
||||
version: "1.0"
|
||||
author: mahipal
|
||||
license: MIT
|
||||
---
|
||||
# Configuring OAuth 2.0 Authorization Flow
|
||||
|
||||
## Overview
|
||||
Configure secure OAuth 2.0 authorization flows including Authorization Code with PKCE, Client Credentials, and Device Authorization Grant. This skill covers flow selection, PKCE implementation, token lifecycle management, scope design, and alignment with OAuth 2.1 security requirements.
|
||||
|
||||
## Objectives
|
||||
- Implement Authorization Code flow with PKCE for public and confidential clients
|
||||
- Configure Client Credentials flow for machine-to-machine communication
|
||||
- Design least-privilege scope hierarchies
|
||||
- Implement secure token storage, refresh, and revocation
|
||||
- Apply OAuth 2.1 best practices and RFC 9700 security recommendations
|
||||
- Validate token integrity and prevent common OAuth attacks
|
||||
|
||||
## Key Concepts
|
||||
|
||||
### OAuth 2.0 Grant Types
|
||||
1. **Authorization Code + PKCE**: Recommended for all client types (web, mobile, SPA). PKCE is mandatory in OAuth 2.1.
|
||||
2. **Client Credentials**: Machine-to-machine authentication without user context.
|
||||
3. **Device Authorization Grant (RFC 8628)**: For input-constrained devices (smart TVs, CLI tools).
|
||||
4. **Refresh Token**: Long-lived token to obtain new access tokens without re-authentication.
|
||||
|
||||
### PKCE (Proof Key for Code Exchange)
|
||||
PKCE (RFC 7636) prevents authorization code interception attacks:
|
||||
1. Client generates random `code_verifier` (43-128 characters, unreserved URI chars)
|
||||
2. Client computes `code_challenge = BASE64URL(SHA256(code_verifier))`
|
||||
3. Authorization request includes `code_challenge` and `code_challenge_method=S256`
|
||||
4. Token request includes original `code_verifier`
|
||||
5. Server validates `SHA256(code_verifier)` matches stored `code_challenge`
|
||||
|
||||
### Token Types
|
||||
- **Access Token**: Short-lived (5-60 min), bearer or DPoP-bound
|
||||
- **Refresh Token**: Long-lived, single-use with rotation
|
||||
- **ID Token (OIDC)**: JWT containing user identity claims
|
||||
|
||||
## Implementation Steps
|
||||
|
||||
### Step 1: Authorization Code Flow with PKCE
|
||||
1. Generate cryptographically random code_verifier (min 43 chars)
|
||||
2. Compute code_challenge using S256 method
|
||||
3. Redirect user to authorization endpoint with parameters:
|
||||
- response_type=code
|
||||
- client_id, redirect_uri, scope, state
|
||||
- code_challenge, code_challenge_method=S256
|
||||
4. User authenticates and consents
|
||||
5. Authorization server redirects with authorization code
|
||||
6. Exchange code + code_verifier for tokens at token endpoint
|
||||
7. Validate state parameter matches original value
|
||||
|
||||
### Step 2: Scope Design
|
||||
- Define granular scopes: `read:users`, `write:orders`, `admin:settings`
|
||||
- Follow least-privilege: request minimum scopes needed
|
||||
- Implement scope validation on resource server
|
||||
- Document scope hierarchy and consent requirements
|
||||
|
||||
### Step 3: Token Security
|
||||
- Store tokens securely (httpOnly cookies for web, keychain for mobile)
|
||||
- Implement token refresh with rotation (one-time-use refresh tokens)
|
||||
- Set appropriate expiration: access tokens 5-15 min, refresh tokens 8-24 hrs
|
||||
- Enable DPoP (Demonstration of Proof-of-Possession) for sender-constrained tokens
|
||||
- Implement token revocation endpoint
|
||||
|
||||
### Step 4: Client Credentials Flow
|
||||
1. Register service client with client_id and client_secret
|
||||
2. Request token: POST /oauth/token with grant_type=client_credentials
|
||||
3. Include scope for required permissions
|
||||
4. Store client_secret securely (vault, env vars, not code)
|
||||
5. Implement certificate-based client authentication for higher assurance
|
||||
|
||||
### Step 5: Security Hardening
|
||||
- Enforce PKCE for all authorization code flows
|
||||
- Use exact redirect URI matching (no wildcards)
|
||||
- Implement CSRF protection with state parameter
|
||||
- Enable refresh token rotation and revocation on reuse detection
|
||||
- Apply RFC 9700 security best practices
|
||||
- Block implicit grant and ROPC (removed in OAuth 2.1)
|
||||
|
||||
## Security Controls
|
||||
| Control | NIST 800-53 | Description |
|
||||
|---------|-------------|-------------|
|
||||
| Access Control | AC-3 | Token-based access enforcement |
|
||||
| Authentication | IA-5 | Client credential management |
|
||||
| Session Management | SC-23 | Token lifecycle management |
|
||||
| Audit | AU-3 | Log all token issuance and revocation |
|
||||
| Cryptographic Protection | SC-13 | PKCE and token signing |
|
||||
|
||||
## Common Pitfalls
|
||||
- Using implicit grant (removed in OAuth 2.1) instead of authorization code + PKCE
|
||||
- Storing tokens in localStorage (XSS vulnerable) instead of httpOnly cookies
|
||||
- Not validating state parameter enabling CSRF attacks
|
||||
- Using wildcard redirect URIs allowing open redirect exploitation
|
||||
- Not implementing refresh token rotation allowing token theft persistence
|
||||
|
||||
## Verification
|
||||
- [ ] Authorization Code + PKCE flow completes successfully
|
||||
- [ ] PKCE code_challenge validated at token endpoint
|
||||
- [ ] State parameter prevents CSRF
|
||||
- [ ] Access tokens expire within configured lifetime
|
||||
- [ ] Refresh token rotation issues new refresh token each use
|
||||
- [ ] Token revocation invalidates both access and refresh tokens
|
||||
- [ ] Client Credentials flow works for service-to-service calls
|
||||
- [ ] Scopes correctly enforced at resource server
|
||||
@@ -0,0 +1,72 @@
|
||||
# OAuth 2.0 Authorization Flow Configuration Template
|
||||
|
||||
## Application Registration
|
||||
| Field | Value |
|
||||
|-------|-------|
|
||||
| Application Name | |
|
||||
| Client ID | |
|
||||
| Client Type | [ ] Public [ ] Confidential |
|
||||
| Grant Types | [ ] Authorization Code [ ] Client Credentials [ ] Refresh Token [ ] Device Code |
|
||||
| PKCE Required | [ ] Yes (mandatory for OAuth 2.1) |
|
||||
|
||||
## Redirect URI Configuration
|
||||
| Environment | URI | Status |
|
||||
|-------------|-----|--------|
|
||||
| Development | http://localhost:3000/callback | [ ] Registered |
|
||||
| Staging | https://staging.example.com/callback | [ ] Registered |
|
||||
| Production | https://app.example.com/callback | [ ] Registered |
|
||||
|
||||
**Rules:**
|
||||
- Exact match only - no wildcards
|
||||
- HTTPS required for non-localhost URIs
|
||||
- Each URI must be explicitly registered
|
||||
|
||||
## Scope Design
|
||||
| Scope | Description | Sensitivity |
|
||||
|-------|-------------|-------------|
|
||||
| openid | OpenID Connect identity | Low |
|
||||
| profile | User profile information | Low |
|
||||
| email | User email address | Low |
|
||||
| read:users | Read user records | Medium |
|
||||
| write:users | Modify user records | High |
|
||||
| admin:settings | Modify system settings | Critical |
|
||||
|
||||
## Token Configuration
|
||||
| Parameter | Value | Justification |
|
||||
|-----------|-------|---------------|
|
||||
| Access Token Lifetime | 15 minutes | Minimize window of exposure |
|
||||
| Refresh Token Lifetime | 8 hours | Align with business hours |
|
||||
| Refresh Token Rotation | Enabled | Detect token theft via reuse |
|
||||
| Refresh Token Absolute Expiry | 24 hours | Force re-authentication daily |
|
||||
| ID Token Lifetime | 5 minutes | Only used for initial authentication |
|
||||
| Token Format | JWT (signed) | Enable stateless validation |
|
||||
| Signing Algorithm | RS256 | Asymmetric verification |
|
||||
|
||||
## Security Checklist
|
||||
- [ ] PKCE enforced for all authorization code flows
|
||||
- [ ] Implicit grant disabled
|
||||
- [ ] ROPC (password) grant disabled
|
||||
- [ ] State parameter validated
|
||||
- [ ] Exact redirect URI matching enforced
|
||||
- [ ] Refresh token rotation enabled
|
||||
- [ ] Token revocation endpoint active
|
||||
- [ ] DPoP enabled for high-security APIs
|
||||
- [ ] Consent screen configured for sensitive scopes
|
||||
- [ ] Token introspection secured with authentication
|
||||
|
||||
## Client Authentication Methods
|
||||
| Method | Use Case | Security Level |
|
||||
|--------|----------|---------------|
|
||||
| none | Public clients (SPA, mobile) | Requires PKCE |
|
||||
| client_secret_basic | Server-side web apps | Medium |
|
||||
| client_secret_post | Server-side web apps | Medium |
|
||||
| private_key_jwt | High-security services | High |
|
||||
| tls_client_auth | mTLS-capable services | High |
|
||||
|
||||
## Monitoring & Alerting
|
||||
- [ ] Token issuance rate monitoring
|
||||
- [ ] Failed authentication attempts tracking
|
||||
- [ ] Refresh token reuse detection alerts
|
||||
- [ ] Scope escalation attempt alerts
|
||||
- [ ] Unusual client_id activity monitoring
|
||||
- [ ] Geographic anomaly detection for token usage
|
||||
@@ -0,0 +1,52 @@
|
||||
# Standards and References - OAuth 2.0 Authorization Flow
|
||||
|
||||
## Core OAuth Standards
|
||||
- **RFC 6749**: The OAuth 2.0 Authorization Framework
|
||||
- https://datatracker.ietf.org/doc/html/rfc6749
|
||||
- **RFC 6750**: The OAuth 2.0 Authorization Framework: Bearer Token Usage
|
||||
- https://datatracker.ietf.org/doc/html/rfc6750
|
||||
- **RFC 7636**: Proof Key for Code Exchange (PKCE)
|
||||
- https://datatracker.ietf.org/doc/html/rfc7636
|
||||
- **RFC 9700**: OAuth 2.0 Security Best Current Practice
|
||||
- https://datatracker.ietf.org/doc/html/rfc9700
|
||||
- **OAuth 2.1 Draft**: Consolidation of OAuth 2.0 with PKCE mandatory
|
||||
- https://oauth.net/2.1/
|
||||
|
||||
## Token Standards
|
||||
- **RFC 7519**: JSON Web Token (JWT)
|
||||
- https://datatracker.ietf.org/doc/html/rfc7519
|
||||
- **RFC 7515**: JSON Web Signature (JWS)
|
||||
- https://datatracker.ietf.org/doc/html/rfc7515
|
||||
- **RFC 9449**: OAuth 2.0 Demonstrating Proof of Possession (DPoP)
|
||||
- https://datatracker.ietf.org/doc/html/rfc9449
|
||||
- **RFC 7009**: OAuth 2.0 Token Revocation
|
||||
- https://datatracker.ietf.org/doc/html/rfc7009
|
||||
|
||||
## OpenID Connect
|
||||
- **OpenID Connect Core 1.0**: Authentication layer on OAuth 2.0
|
||||
- https://openid.net/specs/openid-connect-core-1_0.html
|
||||
- **OpenID Connect Discovery**: Provider metadata discovery
|
||||
- https://openid.net/specs/openid-connect-discovery-1_0.html
|
||||
|
||||
## Additional Grant Types
|
||||
- **RFC 8628**: OAuth 2.0 Device Authorization Grant
|
||||
- https://datatracker.ietf.org/doc/html/rfc8628
|
||||
|
||||
## NIST Standards
|
||||
- **NIST SP 800-63B**: Digital Identity Guidelines - Authentication
|
||||
- **NIST SP 800-53 Rev 5**:
|
||||
- AC-3: Access Enforcement
|
||||
- IA-5: Authenticator Management
|
||||
- SC-13: Cryptographic Protection
|
||||
- SC-23: Session Authenticity
|
||||
- AU-3: Content of Audit Records
|
||||
|
||||
## Implementation Guides
|
||||
- **Auth0 PKCE Guide**: https://auth0.com/docs/get-started/authentication-and-authorization-flow/authorization-code-flow-with-pkce
|
||||
- **Microsoft OIDC Flow**: https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth2-auth-code-flow
|
||||
- **Okta OAuth Express**: https://developer.okta.com/blog/2025/07/28/express-oauth-pkce
|
||||
- **PKCE Explained**: https://oauth.net/2/pkce/
|
||||
|
||||
## Security References
|
||||
- **OWASP OAuth 2.0 Security**: Common vulnerabilities and mitigations
|
||||
- **OAuth Security Workshop**: Annual research on OAuth attack vectors
|
||||
@@ -0,0 +1,123 @@
|
||||
# OAuth 2.0 Authorization Flow Workflows
|
||||
|
||||
## Workflow 1: Authorization Code Flow with PKCE
|
||||
|
||||
```
|
||||
Client Auth Server Resource Server
|
||||
| | |
|
||||
|-- Generate code_verifier --| |
|
||||
|-- Compute code_challenge --| |
|
||||
| | |
|
||||
|--- AuthZ Request --------->| |
|
||||
| (code_challenge, state) | |
|
||||
| |-- User Authenticates -->|
|
||||
| |<- User Consents --------|
|
||||
|<-- AuthZ Code + state -----| |
|
||||
| | |
|
||||
|--- Token Request --------->| |
|
||||
| (code + code_verifier) | |
|
||||
|<-- Access + Refresh Token--| |
|
||||
| | |
|
||||
|--- API Request (Bearer) ---|------------------------>|
|
||||
|<-- API Response ---------- |<------------------------|
|
||||
```
|
||||
|
||||
### Step-by-Step:
|
||||
1. Client generates `code_verifier`: random 43-128 char string (A-Z, a-z, 0-9, -._~)
|
||||
2. Client computes `code_challenge = BASE64URL(SHA256(code_verifier))`
|
||||
3. Client redirects to: `GET /authorize?response_type=code&client_id=xxx&redirect_uri=xxx&scope=xxx&state=RANDOM&code_challenge=xxx&code_challenge_method=S256`
|
||||
4. User authenticates and consents at authorization server
|
||||
5. Server redirects to: `redirect_uri?code=AUTH_CODE&state=RANDOM`
|
||||
6. Client validates state matches original
|
||||
7. Client exchanges code: `POST /token` with `grant_type=authorization_code&code=AUTH_CODE&code_verifier=xxx&redirect_uri=xxx`
|
||||
8. Server validates SHA256(code_verifier) matches stored code_challenge
|
||||
9. Server returns access_token, refresh_token, id_token (if OIDC)
|
||||
|
||||
## Workflow 2: Client Credentials Flow (Machine-to-Machine)
|
||||
|
||||
```
|
||||
Service A Auth Server Service B (API)
|
||||
| | |
|
||||
|--- Token Request --------->| |
|
||||
| (client_id, secret, scope)| |
|
||||
|<-- Access Token -----------| |
|
||||
| | |
|
||||
|--- API Request (Bearer) ---|------------------------>|
|
||||
|<-- API Response ---------- |<------------------------|
|
||||
```
|
||||
|
||||
### Step-by-Step:
|
||||
1. Service registers with auth server (client_id + client_secret)
|
||||
2. Service requests token: `POST /token` with `grant_type=client_credentials&scope=api:read`
|
||||
3. Auth server validates client credentials
|
||||
4. Auth server returns access_token (no refresh token, no user context)
|
||||
5. Service calls API with `Authorization: Bearer ACCESS_TOKEN`
|
||||
|
||||
## Workflow 3: Token Refresh with Rotation
|
||||
|
||||
```
|
||||
Client Auth Server
|
||||
| |
|
||||
|--- Refresh Request ------->|
|
||||
| (refresh_token_v1) |
|
||||
|<-- New Access Token -------|
|
||||
|<-- New Refresh Token (v2) -|
|
||||
| (v1 invalidated) |
|
||||
| |
|
||||
|--- Refresh Request ------->|
|
||||
| (refresh_token_v2) |
|
||||
|<-- New Access Token -------|
|
||||
|<-- New Refresh Token (v3) -|
|
||||
| |
|
||||
|--- THEFT: Reuse v1 ------->|
|
||||
| (DETECTED: v1 reused) |
|
||||
|<-- REVOKE ALL TOKENS ------|
|
||||
```
|
||||
|
||||
### Rotation Detection:
|
||||
- Each refresh token is single-use
|
||||
- On reuse of an old refresh token, server detects theft
|
||||
- All tokens in the grant chain are revoked
|
||||
- User must re-authenticate
|
||||
|
||||
## Workflow 4: Device Authorization Grant
|
||||
|
||||
```
|
||||
Device Auth Server User (Browser)
|
||||
| | |
|
||||
|--- Device AuthZ Request -->| |
|
||||
|<-- device_code, | |
|
||||
| user_code, | |
|
||||
| verification_uri -------| |
|
||||
| | |
|
||||
|-- Display user_code ------>| |
|
||||
| to user on screen | |
|
||||
| |<-- User visits URI -----|
|
||||
| |<-- Enters user_code ----|
|
||||
| |<-- Authenticates -------|
|
||||
| |<-- Consents ------------|
|
||||
| | |
|
||||
|--- Poll Token Endpoint --->| |
|
||||
| (device_code) | |
|
||||
|<-- Access Token -----------| |
|
||||
```
|
||||
|
||||
## Workflow 5: Token Revocation
|
||||
|
||||
### Steps:
|
||||
1. Client sends revocation request: `POST /revoke` with `token=xxx&token_type_hint=refresh_token`
|
||||
2. Auth server invalidates the token
|
||||
3. If refresh token revoked, all associated access tokens also invalidated
|
||||
4. Server returns 200 OK regardless of whether token was valid (prevents token fishing)
|
||||
|
||||
## Workflow 6: Security Incident - Token Compromise Response
|
||||
|
||||
### Steps:
|
||||
1. Detect suspicious token usage (unusual IP, impossible travel)
|
||||
2. Immediately revoke the compromised token via revocation endpoint
|
||||
3. If refresh token compromised, revoke entire token family
|
||||
4. Force re-authentication for affected user
|
||||
5. Audit all API calls made with compromised token
|
||||
6. Check for scope escalation attempts
|
||||
7. Review authorization logs for the compromised session
|
||||
8. Notify affected user and security team
|
||||
@@ -0,0 +1,465 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
OAuth 2.0 Authorization Flow Security Auditor
|
||||
|
||||
Validates OAuth 2.0 configurations, tests PKCE implementation,
|
||||
checks token security, and audits scope assignments for compliance
|
||||
with OAuth 2.1 and RFC 9700 best practices.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import base64
|
||||
import secrets
|
||||
import json
|
||||
import time
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
import ssl
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
from dataclasses import dataclass, field
|
||||
|
||||
|
||||
@dataclass
|
||||
class OAuthConfig:
|
||||
"""OAuth 2.0 configuration to audit."""
|
||||
authorization_endpoint: str
|
||||
token_endpoint: str
|
||||
revocation_endpoint: str = ""
|
||||
userinfo_endpoint: str = ""
|
||||
jwks_uri: str = ""
|
||||
issuer: str = ""
|
||||
client_id: str = ""
|
||||
redirect_uris: List[str] = field(default_factory=list)
|
||||
scopes_supported: List[str] = field(default_factory=list)
|
||||
grant_types_supported: List[str] = field(default_factory=list)
|
||||
response_types_supported: List[str] = field(default_factory=list)
|
||||
pkce_required: bool = True
|
||||
token_endpoint_auth_methods: List[str] = field(default_factory=list)
|
||||
|
||||
|
||||
@dataclass
|
||||
class AuditFinding:
|
||||
"""Individual audit finding."""
|
||||
category: str
|
||||
severity: str # critical, high, medium, low, info
|
||||
title: str
|
||||
description: str
|
||||
recommendation: str = ""
|
||||
reference: str = ""
|
||||
|
||||
|
||||
class PKCEHelper:
|
||||
"""PKCE code verifier and challenge generation."""
|
||||
|
||||
@staticmethod
|
||||
def generate_code_verifier(length: int = 128) -> str:
|
||||
"""Generate a cryptographically random code verifier (43-128 chars)."""
|
||||
if length < 43 or length > 128:
|
||||
raise ValueError("Code verifier length must be between 43 and 128")
|
||||
unreserved = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~"
|
||||
return ''.join(secrets.choice(unreserved) for _ in range(length))
|
||||
|
||||
@staticmethod
|
||||
def generate_code_challenge(code_verifier: str) -> str:
|
||||
"""Compute S256 code challenge from code verifier."""
|
||||
digest = hashlib.sha256(code_verifier.encode('ascii')).digest()
|
||||
return base64.urlsafe_b64encode(digest).rstrip(b'=').decode('ascii')
|
||||
|
||||
@staticmethod
|
||||
def verify_pkce(code_verifier: str, code_challenge: str) -> bool:
|
||||
"""Verify PKCE code_verifier matches code_challenge."""
|
||||
computed = PKCEHelper.generate_code_challenge(code_verifier)
|
||||
return secrets.compare_digest(computed, code_challenge)
|
||||
|
||||
@staticmethod
|
||||
def generate_state() -> str:
|
||||
"""Generate a cryptographically random state parameter."""
|
||||
return secrets.token_urlsafe(32)
|
||||
|
||||
|
||||
class OAuth2Auditor:
|
||||
"""Audits OAuth 2.0 configurations against security best practices."""
|
||||
|
||||
DEPRECATED_GRANTS = ["implicit", "password"]
|
||||
SECURE_AUTH_METHODS = [
|
||||
"private_key_jwt",
|
||||
"tls_client_auth",
|
||||
"self_signed_tls_client_auth"
|
||||
]
|
||||
|
||||
def __init__(self, config: OAuthConfig):
|
||||
self.config = config
|
||||
self.findings: List[AuditFinding] = []
|
||||
|
||||
def audit_all(self) -> List[AuditFinding]:
|
||||
"""Run all OAuth 2.0 security audits."""
|
||||
self.findings = []
|
||||
self._audit_grant_types()
|
||||
self._audit_pkce_requirement()
|
||||
self._audit_redirect_uris()
|
||||
self._audit_scopes()
|
||||
self._audit_endpoints_https()
|
||||
self._audit_token_endpoint_auth()
|
||||
self._audit_response_types()
|
||||
self._audit_revocation_endpoint()
|
||||
self._audit_jwks_endpoint()
|
||||
self._audit_discovery_endpoint()
|
||||
return self.findings
|
||||
|
||||
def _audit_grant_types(self):
|
||||
"""Check for deprecated or insecure grant types."""
|
||||
for grant in self.config.grant_types_supported:
|
||||
if grant in self.DEPRECATED_GRANTS:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Grant Types",
|
||||
severity="critical",
|
||||
title=f"Deprecated grant type: {grant}",
|
||||
description=f"The '{grant}' grant type is removed in OAuth 2.1 and is insecure.",
|
||||
recommendation=f"Remove '{grant}' grant type. Use authorization_code with PKCE instead.",
|
||||
reference="RFC 9700 Section 2.1"
|
||||
))
|
||||
|
||||
if "authorization_code" not in self.config.grant_types_supported:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Grant Types",
|
||||
severity="high",
|
||||
title="Authorization Code grant not supported",
|
||||
description="The most secure interactive grant type is not enabled.",
|
||||
recommendation="Enable authorization_code grant type with PKCE.",
|
||||
reference="OAuth 2.1 Draft"
|
||||
))
|
||||
|
||||
if "refresh_token" not in self.config.grant_types_supported:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Grant Types",
|
||||
severity="medium",
|
||||
title="Refresh token grant not supported",
|
||||
description="Without refresh tokens, users must re-authenticate more frequently or access tokens must have longer lifetimes.",
|
||||
recommendation="Enable refresh_token grant with token rotation.",
|
||||
reference="RFC 6749 Section 6"
|
||||
))
|
||||
|
||||
if not any(g in self.DEPRECATED_GRANTS for g in self.config.grant_types_supported):
|
||||
self.findings.append(AuditFinding(
|
||||
category="Grant Types",
|
||||
severity="info",
|
||||
title="No deprecated grant types detected",
|
||||
description="All configured grant types are aligned with OAuth 2.1 requirements."
|
||||
))
|
||||
|
||||
def _audit_pkce_requirement(self):
|
||||
"""Check if PKCE is required for authorization code flow."""
|
||||
if "authorization_code" in self.config.grant_types_supported:
|
||||
if self.config.pkce_required:
|
||||
self.findings.append(AuditFinding(
|
||||
category="PKCE",
|
||||
severity="info",
|
||||
title="PKCE is required for authorization code flow",
|
||||
description="PKCE enforcement is correctly enabled, preventing code interception attacks."
|
||||
))
|
||||
else:
|
||||
self.findings.append(AuditFinding(
|
||||
category="PKCE",
|
||||
severity="critical",
|
||||
title="PKCE is not required",
|
||||
description="Authorization code flow without PKCE is vulnerable to code interception attacks.",
|
||||
recommendation="Enforce PKCE (code_challenge_method=S256) for all authorization code requests.",
|
||||
reference="RFC 7636, OAuth 2.1 Draft"
|
||||
))
|
||||
|
||||
def _audit_redirect_uris(self):
|
||||
"""Check redirect URI security."""
|
||||
for uri in self.config.redirect_uris:
|
||||
if '*' in uri:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Redirect URIs",
|
||||
severity="critical",
|
||||
title=f"Wildcard redirect URI: {uri}",
|
||||
description="Wildcard redirect URIs enable open redirect attacks and token theft.",
|
||||
recommendation="Use exact redirect URI matching. Register each URI explicitly.",
|
||||
reference="RFC 9700 Section 4.1"
|
||||
))
|
||||
elif uri.startswith("http://") and "localhost" not in uri and "127.0.0.1" not in uri:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Redirect URIs",
|
||||
severity="high",
|
||||
title=f"Non-HTTPS redirect URI: {uri}",
|
||||
description="HTTP redirect URIs expose authorization codes in transit.",
|
||||
recommendation="Use HTTPS for all production redirect URIs.",
|
||||
reference="RFC 6749 Section 3.1.2.1"
|
||||
))
|
||||
elif uri.startswith("http://localhost") or uri.startswith("http://127.0.0.1"):
|
||||
self.findings.append(AuditFinding(
|
||||
category="Redirect URIs",
|
||||
severity="low",
|
||||
title=f"Localhost redirect URI: {uri}",
|
||||
description="Localhost redirect URI detected. Acceptable for native apps per RFC 8252.",
|
||||
reference="RFC 8252 Section 7.3"
|
||||
))
|
||||
|
||||
if not self.config.redirect_uris:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Redirect URIs",
|
||||
severity="medium",
|
||||
title="No redirect URIs configured for audit",
|
||||
description="Could not audit redirect URIs - none provided in configuration."
|
||||
))
|
||||
|
||||
def _audit_scopes(self):
|
||||
"""Audit scope configuration for least privilege."""
|
||||
overly_broad = ["*", "all", "admin", "root", "superuser"]
|
||||
for scope in self.config.scopes_supported:
|
||||
if scope.lower() in overly_broad:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Scopes",
|
||||
severity="high",
|
||||
title=f"Overly broad scope: {scope}",
|
||||
description="This scope grants excessive permissions violating least privilege.",
|
||||
recommendation="Replace with granular scopes (e.g., read:users, write:orders).",
|
||||
reference="NIST SP 800-53 AC-6"
|
||||
))
|
||||
|
||||
if self.config.scopes_supported:
|
||||
granular_pattern = any(':' in s or '.' in s for s in self.config.scopes_supported)
|
||||
if not granular_pattern:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Scopes",
|
||||
severity="medium",
|
||||
title="Scopes may lack granularity",
|
||||
description="Scopes do not follow resource:action pattern (e.g., read:users).",
|
||||
recommendation="Design scopes using resource:action notation for fine-grained access control."
|
||||
))
|
||||
|
||||
def _audit_endpoints_https(self):
|
||||
"""Verify all OAuth endpoints use HTTPS."""
|
||||
endpoints = {
|
||||
"Authorization": self.config.authorization_endpoint,
|
||||
"Token": self.config.token_endpoint,
|
||||
"Revocation": self.config.revocation_endpoint,
|
||||
"UserInfo": self.config.userinfo_endpoint,
|
||||
"JWKS": self.config.jwks_uri,
|
||||
}
|
||||
for name, url in endpoints.items():
|
||||
if not url:
|
||||
continue
|
||||
if not url.startswith("https://"):
|
||||
self.findings.append(AuditFinding(
|
||||
category="Transport Security",
|
||||
severity="critical",
|
||||
title=f"{name} endpoint not using HTTPS",
|
||||
description=f"{name} endpoint ({url}) is not secured with TLS.",
|
||||
recommendation=f"Configure {name} endpoint to use HTTPS.",
|
||||
reference="RFC 6749 Section 3.1"
|
||||
))
|
||||
|
||||
def _audit_token_endpoint_auth(self):
|
||||
"""Check token endpoint authentication methods."""
|
||||
if not self.config.token_endpoint_auth_methods:
|
||||
return
|
||||
|
||||
if "client_secret_post" in self.config.token_endpoint_auth_methods and \
|
||||
"client_secret_basic" in self.config.token_endpoint_auth_methods:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Client Authentication",
|
||||
severity="medium",
|
||||
title="Basic/POST client authentication supported",
|
||||
description="client_secret_basic and client_secret_post transmit secrets in requests.",
|
||||
recommendation="Prefer private_key_jwt or tls_client_auth for higher assurance.",
|
||||
reference="RFC 9700"
|
||||
))
|
||||
|
||||
has_secure = any(m in self.SECURE_AUTH_METHODS for m in self.config.token_endpoint_auth_methods)
|
||||
if has_secure:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Client Authentication",
|
||||
severity="info",
|
||||
title="Strong client authentication methods available",
|
||||
description="Server supports certificate-based or JWT-based client authentication."
|
||||
))
|
||||
|
||||
if "none" in self.config.token_endpoint_auth_methods:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Client Authentication",
|
||||
severity="high",
|
||||
title="Unauthenticated token endpoint access allowed",
|
||||
description="Token endpoint accepts requests without client authentication.",
|
||||
recommendation="Require PKCE for public clients and client authentication for confidential clients."
|
||||
))
|
||||
|
||||
def _audit_response_types(self):
|
||||
"""Check for insecure response types."""
|
||||
insecure_types = ["token", "id_token"]
|
||||
for rt in self.config.response_types_supported:
|
||||
if rt in insecure_types:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Response Types",
|
||||
severity="high",
|
||||
title=f"Implicit response type enabled: {rt}",
|
||||
description=f"Response type '{rt}' exposes tokens in browser URL/history.",
|
||||
recommendation="Use 'code' response type with PKCE instead.",
|
||||
reference="OAuth 2.1 Draft, RFC 9700"
|
||||
))
|
||||
|
||||
def _audit_revocation_endpoint(self):
|
||||
"""Check if token revocation endpoint is configured."""
|
||||
if not self.config.revocation_endpoint:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Token Revocation",
|
||||
severity="high",
|
||||
title="No token revocation endpoint configured",
|
||||
description="Without revocation, compromised tokens cannot be invalidated before expiry.",
|
||||
recommendation="Implement RFC 7009 token revocation endpoint.",
|
||||
reference="RFC 7009"
|
||||
))
|
||||
|
||||
def _audit_jwks_endpoint(self):
|
||||
"""Check JWKS endpoint availability for token verification."""
|
||||
if not self.config.jwks_uri:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Token Verification",
|
||||
severity="medium",
|
||||
title="No JWKS URI configured",
|
||||
description="Resource servers need JWKS endpoint to verify JWT signatures.",
|
||||
recommendation="Publish JWKS endpoint for token signature verification."
|
||||
))
|
||||
|
||||
def _audit_discovery_endpoint(self):
|
||||
"""Check OpenID Connect Discovery metadata."""
|
||||
if not self.config.issuer:
|
||||
return
|
||||
|
||||
discovery_url = f"{self.config.issuer.rstrip('/')}/.well-known/openid-configuration"
|
||||
try:
|
||||
req = urllib.request.Request(
|
||||
discovery_url,
|
||||
headers={'User-Agent': 'OAuth2-Auditor/1.0'}
|
||||
)
|
||||
ctx = ssl.create_default_context()
|
||||
response = urllib.request.urlopen(req, context=ctx, timeout=10)
|
||||
|
||||
if response.status == 200:
|
||||
metadata = json.loads(response.read().decode('utf-8'))
|
||||
self.findings.append(AuditFinding(
|
||||
category="Discovery",
|
||||
severity="info",
|
||||
title="OpenID Connect Discovery endpoint accessible",
|
||||
description=f"Discovery metadata available at {discovery_url}"
|
||||
))
|
||||
|
||||
# Check for PKCE support in discovery
|
||||
if "code_challenge_methods_supported" in metadata:
|
||||
methods = metadata["code_challenge_methods_supported"]
|
||||
if "S256" in methods:
|
||||
self.findings.append(AuditFinding(
|
||||
category="PKCE",
|
||||
severity="info",
|
||||
title="S256 PKCE method supported",
|
||||
description="Server advertises S256 code challenge method support."
|
||||
))
|
||||
if "plain" in methods:
|
||||
self.findings.append(AuditFinding(
|
||||
category="PKCE",
|
||||
severity="high",
|
||||
title="Plain PKCE method supported",
|
||||
description="'plain' code challenge method does not provide security.",
|
||||
recommendation="Require S256 only. Disable plain method.",
|
||||
reference="RFC 7636 Section 4.2"
|
||||
))
|
||||
except Exception as e:
|
||||
self.findings.append(AuditFinding(
|
||||
category="Discovery",
|
||||
severity="low",
|
||||
title="Cannot reach discovery endpoint",
|
||||
description=f"Error accessing {discovery_url}: {str(e)}"
|
||||
))
|
||||
|
||||
def generate_report(self) -> str:
|
||||
"""Generate audit report."""
|
||||
if not self.findings:
|
||||
self.audit_all()
|
||||
|
||||
severity_order = {"critical": 0, "high": 1, "medium": 2, "low": 3, "info": 4}
|
||||
sorted_findings = sorted(self.findings, key=lambda f: severity_order.get(f.severity, 5))
|
||||
|
||||
lines = [
|
||||
"=" * 70,
|
||||
"OAUTH 2.0 SECURITY AUDIT REPORT",
|
||||
"=" * 70,
|
||||
f"Issuer: {self.config.issuer or 'N/A'}",
|
||||
f"Authorization Endpoint: {self.config.authorization_endpoint}",
|
||||
f"Token Endpoint: {self.config.token_endpoint}",
|
||||
f"Grant Types: {', '.join(self.config.grant_types_supported)}",
|
||||
f"PKCE Required: {self.config.pkce_required}",
|
||||
"-" * 70,
|
||||
""
|
||||
]
|
||||
|
||||
by_severity = {}
|
||||
for f in sorted_findings:
|
||||
by_severity.setdefault(f.severity, []).append(f)
|
||||
|
||||
total = len(self.findings)
|
||||
critical = len(by_severity.get("critical", []))
|
||||
high = len(by_severity.get("high", []))
|
||||
|
||||
lines.append(f"TOTAL FINDINGS: {total}")
|
||||
lines.append(f" Critical: {critical} | High: {high} | Medium: {len(by_severity.get('medium', []))} | Low: {len(by_severity.get('low', []))} | Info: {len(by_severity.get('info', []))}")
|
||||
lines.append("")
|
||||
|
||||
for f in sorted_findings:
|
||||
icon = {"critical": "[!!!]", "high": "[!!]", "medium": "[!]", "low": "[~]", "info": "[i]"}.get(f.severity, "[?]")
|
||||
lines.append(f"{icon} [{f.severity.upper()}] {f.title}")
|
||||
lines.append(f" Category: {f.category}")
|
||||
lines.append(f" {f.description}")
|
||||
if f.recommendation:
|
||||
lines.append(f" Recommendation: {f.recommendation}")
|
||||
if f.reference:
|
||||
lines.append(f" Reference: {f.reference}")
|
||||
lines.append("")
|
||||
|
||||
overall = "FAIL" if critical > 0 else "NEEDS IMPROVEMENT" if high > 0 else "PASS"
|
||||
lines.append("=" * 70)
|
||||
lines.append(f"OVERALL: {overall}")
|
||||
lines.append("=" * 70)
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def main():
|
||||
"""Run OAuth 2.0 security audit with example configuration."""
|
||||
config = OAuthConfig(
|
||||
authorization_endpoint="https://auth.example.com/authorize",
|
||||
token_endpoint="https://auth.example.com/oauth/token",
|
||||
revocation_endpoint="https://auth.example.com/oauth/revoke",
|
||||
userinfo_endpoint="https://auth.example.com/userinfo",
|
||||
jwks_uri="https://auth.example.com/.well-known/jwks.json",
|
||||
issuer="https://auth.example.com",
|
||||
client_id="my-app-client",
|
||||
redirect_uris=[
|
||||
"https://app.example.com/callback",
|
||||
"http://localhost:3000/callback"
|
||||
],
|
||||
scopes_supported=["openid", "profile", "email", "read:users", "write:users"],
|
||||
grant_types_supported=["authorization_code", "refresh_token", "client_credentials"],
|
||||
response_types_supported=["code"],
|
||||
pkce_required=True,
|
||||
token_endpoint_auth_methods=["client_secret_basic", "private_key_jwt"]
|
||||
)
|
||||
|
||||
auditor = OAuth2Auditor(config)
|
||||
report = auditor.generate_report()
|
||||
print(report)
|
||||
|
||||
# Demo PKCE generation
|
||||
print("\n--- PKCE Demo ---")
|
||||
verifier = PKCEHelper.generate_code_verifier(128)
|
||||
challenge = PKCEHelper.generate_code_challenge(verifier)
|
||||
state = PKCEHelper.generate_state()
|
||||
print(f"Code Verifier: {verifier[:40]}...")
|
||||
print(f"Code Challenge (S256): {challenge}")
|
||||
print(f"State: {state}")
|
||||
print(f"Verification: {PKCEHelper.verify_pkce(verifier, challenge)}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user