identity access management

Configuring OAuth 2.0 Authorization Flow

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.

access-controlauthenticationauthorizationiamidentityoauth2oidcpkce
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

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.

When to Use

  • When deploying or configuring configuring oauth2 authorization flow capabilities in your environment
  • When establishing security controls aligned to compliance requirements
  • When building or improving security architecture for this domain
  • When conducting security assessments that require this implementation

Prerequisites

  • Familiarity with identity access management concepts and tools
  • Access to a test or lab environment for safe execution
  • Python 3.8+ with required dependencies installed
  • Appropriate authorization for any testing activities

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

Workflow

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
Source materials

References and resources

Everything below is rendered for inspection. Script files are read-only and never run.

References 3

api-reference.md1.5 KB

OAuth 2.0 Authorization Flow — API Reference

Libraries

Library Install Purpose
requests pip install requests HTTP client for OAuth endpoints
authlib pip install authlib Full OAuth 2.0 / OIDC client library
PyJWT pip install PyJWT[crypto] JWT token validation and inspection

OIDC Discovery Endpoint

GET {issuer}/.well-known/openid-configuration

Returns: authorization_endpoint, token_endpoint, jwks_uri, supported grant types, scopes.

OAuth 2.0 Grant Types

Grant Type Use Case Security
authorization_code Server-side apps Recommended with PKCE
client_credentials Machine-to-machine Service accounts only
implicit (DEPRECATED) SPAs Avoid — tokens in URL fragment
password (DEPRECATED) Legacy Avoid — credentials exposed to client
urn:ietf:params:oauth:grant-type:device_code IoT/CLI Approved for limited-input devices

Security Best Practices

Practice RFC
PKCE (Proof Key for Code Exchange) RFC 7636
Token Binding RFC 8471
DPoP (Demonstrating Proof of Possession) RFC 9449
Sender-Constrained Tokens OAuth 2.0 Security BCP

External References

standards.md2.2 KB

Standards and References - OAuth 2.0 Authorization Flow

Core OAuth Standards

Token Standards

OpenID Connect

Additional Grant Types

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

Security References

  • OWASP OAuth 2.0 Security: Common vulnerabilities and mitigations
  • OAuth Security Workshop: Annual research on OAuth attack vectors
workflows.md5.3 KB

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

Scripts 2

agent.py5.4 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""OAuth 2.0 authorization flow security audit agent."""

import json
import sys
import argparse
from datetime import datetime

try:
    import requests
except ImportError:
    print("Install: pip install requests")
    sys.exit(1)


def discover_oauth_endpoints(issuer_url):
    """Discover OAuth 2.0 / OIDC endpoints from well-known configuration."""
    discovery_url = f"{issuer_url.rstrip('/')}/.well-known/openid-configuration"
    try:
        resp = requests.get(discovery_url, timeout=10)
        resp.raise_for_status()
        config = resp.json()
        return {
            "issuer": config.get("issuer", ""),
            "authorization_endpoint": config.get("authorization_endpoint", ""),
            "token_endpoint": config.get("token_endpoint", ""),
            "userinfo_endpoint": config.get("userinfo_endpoint", ""),
            "jwks_uri": config.get("jwks_uri", ""),
            "supported_grant_types": config.get("grant_types_supported", []),
            "supported_scopes": config.get("scopes_supported", []),
            "supported_response_types": config.get("response_types_supported", []),
            "token_endpoint_auth_methods": config.get("token_endpoint_auth_methods_supported", []),
        }
    except Exception as e:
        return {"error": str(e)}


def audit_oauth_security(config):
    """Audit OAuth configuration for security issues."""
    findings = []
    if "implicit" in config.get("supported_grant_types", []):
        findings.append({
            "issue": "Implicit grant type supported",
            "severity": "HIGH",
            "recommendation": "Disable implicit flow; use authorization code + PKCE",
        })
    if "password" in config.get("supported_grant_types", []):
        findings.append({
            "issue": "Resource owner password grant supported",
            "severity": "MEDIUM",
            "recommendation": "Disable ROPC grant; use authorization code flow",
        })
    auth_methods = config.get("token_endpoint_auth_methods", [])
    if "none" in auth_methods:
        findings.append({
            "issue": "Token endpoint allows unauthenticated clients",
            "severity": "MEDIUM",
            "recommendation": "Require client_secret_basic or private_key_jwt",
        })
    if "code" in config.get("supported_response_types", []):
        if "code id_token" not in config.get("supported_response_types", []):
            findings.append({
                "issue": "Authorization code flow available",
                "severity": "INFO",
                "note": "Ensure PKCE is enforced for public clients",
            })
    return findings


def test_token_endpoint(token_url, client_id, client_secret, grant_type="client_credentials"):
    """Test token endpoint with client credentials."""
    try:
        resp = requests.post(token_url, data={
            "grant_type": grant_type,
            "client_id": client_id,
            "client_secret": client_secret,
        }, timeout=10)
        if resp.status_code == 200:
            token_data = resp.json()
            return {
                "status": "success",
                "token_type": token_data.get("token_type", ""),
                "expires_in": token_data.get("expires_in", 0),
                "scope": token_data.get("scope", ""),
            }
        return {"status": "failed", "code": resp.status_code, "body": resp.text[:200]}
    except Exception as e:
        return {"status": "error", "message": str(e)}


def run_audit(issuer_url, client_id=None, client_secret=None):
    """Execute OAuth 2.0 security audit."""
    print(f"\n{'='*60}")
    print(f"  OAUTH 2.0 AUTHORIZATION FLOW AUDIT")
    print(f"  Issuer: {issuer_url}")
    print(f"  Generated: {datetime.utcnow().isoformat()} UTC")
    print(f"{'='*60}\n")

    config = discover_oauth_endpoints(issuer_url)
    if "error" in config:
        print(f"  Error: {config['error']}")
        return config

    print(f"--- DISCOVERED ENDPOINTS ---")
    print(f"  Authorization: {config.get('authorization_endpoint', 'N/A')}")
    print(f"  Token: {config.get('token_endpoint', 'N/A')}")
    print(f"  JWKS: {config.get('jwks_uri', 'N/A')}")
    print(f"  Grant types: {config.get('supported_grant_types', [])}")

    findings = audit_oauth_security(config)
    print(f"\n--- SECURITY FINDINGS ({len(findings)}) ---")
    for f in findings:
        print(f"  [{f['severity']}] {f['issue']}")

    token_test = {}
    if client_id and client_secret and config.get("token_endpoint"):
        token_test = test_token_endpoint(config["token_endpoint"], client_id, client_secret)
        print(f"\n--- TOKEN ENDPOINT TEST ---")
        print(f"  Status: {token_test.get('status', 'N/A')}")

    return {"config": config, "findings": findings, "token_test": token_test}


def main():
    parser = argparse.ArgumentParser(description="OAuth 2.0 Audit Agent")
    parser.add_argument("--issuer", required=True, help="OAuth issuer URL")
    parser.add_argument("--client-id", help="Client ID for token test")
    parser.add_argument("--client-secret", help="Client secret for token test")
    parser.add_argument("--output", help="Save report to JSON file")
    args = parser.parse_args()

    report = run_audit(args.issuer, args.client_id, args.client_secret)
    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2, default=str)
        print(f"\n[+] Report saved to {args.output}")


if __name__ == "__main__":
    main()
process.py19.9 KB
Display-only source. This catalog never executes bundled scripts.
#!/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()

Assets 1

template.mdtext/markdown · 2.8 KB
Keep exploring