cloud security

Detecting OAuth Token Theft

Detects and responds to OAuth token theft and replay attacks in cloud environments, focusing on Microsoft Entra ID (Azure AD) token protection, conditional access policies, and sign-in anomaly detection. Covers access token theft, refresh token replay, Primary Refresh Token (PRT) abuse, and pass-the-cookie attacks. Activates for requests involving OAuth token theft detection, token replay prevention, Azure AD conditional access token protection, or cloud identity attack investigation.

azure-adconditional-accessentra-ididentity-securityoauthprttoken-replaytoken-theft
Install this skill
npx skills add mukul975/Anthropic-Cybersecurity-Skills
Framework mappings

When to Use

  • Investigating alerts for impossible travel or anomalous token usage in Microsoft Entra ID
  • Responding to a suspected session hijacking or pass-the-cookie attack
  • Configuring proactive defenses against OAuth token theft in an Azure/M365 environment
  • Detecting OAuth device code phishing campaigns that bypass MFA
  • Analyzing sign-in logs for token replay indicators
  • Implementing Token Protection conditional access policies to bind tokens to devices

Do not use for on-premises Kerberos ticket attacks (pass-the-ticket, golden ticket); use Active Directory-specific investigation techniques for those scenarios.

Prerequisites

  • Microsoft Entra ID P2 license (required for Identity Protection risk detections and conditional access)
  • Global Administrator or Security Administrator role in the Entra admin center
  • Microsoft Defender for Cloud Apps (MDCA) license for session anomaly detection
  • Access to Entra ID Sign-in Logs and Audit Logs (requires Diagnostic Settings configured to Log Analytics or Sentinel)
  • Familiarity with OAuth 2.0 authorization flows (authorization code, device code, client credentials)
  • Microsoft Sentinel or equivalent SIEM ingesting Entra ID sign-in and audit logs

Workflow

Step 1: Understand the Token Theft Attack Surface

Identify which token types are at risk and how they are stolen:

Token Type            | Lifetime     | Theft Vector                    | Impact
----------------------|-------------|----------------------------------|------------------
Access Token          | 60-90 min   | Memory dump, proxy interception  | API access for token lifetime
Refresh Token         | Up to 90 days| Browser cookie theft, malware   | Persistent access, new access tokens
Primary Refresh Token | Session-based| Mimikatz, AADInternals, malware | Full SSO to all M365/Azure apps
Session Cookie        | Varies      | XSS, browser exploit, AitM proxy | Full session hijacking
Device Code Token     | 15 min auth | Phishing (device code flow abuse)| Attacker gets refresh token via social engineering

Common attack techniques:

  • AitM Phishing (Adversary-in-the-Middle): Attacker proxies the legitimate login page via tools like Evilginx2, capturing session cookies and tokens after the user completes MFA
  • Device Code Phishing: Attacker generates a device code, sends it to the victim via email/Teams, victim authenticates, attacker receives the token
  • PRT Extraction: Attacker with local admin on a device extracts the Primary Refresh Token using Mimikatz (sekurlsa::cloudap) or AADInternals
  • Browser Cookie Theft: Malware or infostealer exfiltrates browser cookies containing session tokens

Step 2: Configure Entra ID Sign-in Risk Detection

Enable Identity Protection to flag anomalous token usage:

Entra Admin Center > Protection > Identity Protection > Risk Detections
 
Key risk detections for token theft:
- Anomalous Token        : Token has unusual characteristics (claim anomalies)
- Token Issuer Anomaly   : Token issued by an unusual token issuer
- Unfamiliar Sign-in     : Sign-in from a location not seen before for the user
- Impossible Travel      : Sign-ins from geographically distant locations in impossible time
- Malicious IP Address   : Sign-in from a known malicious IP
- Suspicious Browser     : Sign-in from a suspicious or attacker-controlled browser

Configure risk-based conditional access:

Entra Admin Center > Protection > Conditional Access > New Policy
 
Policy Name: "Block High-Risk Sign-ins - Token Theft Protection"
Assignments:
  Users: All users (exclude break-glass accounts)
  Cloud Apps: All cloud apps
Conditions:
  Sign-in Risk: High
Grant:
  Block access
 
Policy Name: "Require MFA for Medium-Risk Sign-ins"
Assignments:
  Users: All users
  Cloud Apps: All cloud apps
Conditions:
  Sign-in Risk: Medium
Grant:
  Require multifactor authentication
  Require password change

Step 3: Enable Token Protection (Preview)

Configure Token Protection to bind sign-in session tokens to the device:

Entra Admin Center > Protection > Conditional Access > New Policy
 
Policy Name: "Enforce Token Protection for Desktop Sessions"
Assignments:
  Users: All users (start with a pilot group)
  Cloud Apps: Office 365 Exchange Online, Office 365 SharePoint Online
  Conditions:
    Device Platforms: Windows
Session:
  Require token protection for sign-in sessions (Preview): Enabled
Grant:
  Require device to be marked as compliant
  OR Require Hybrid Azure AD joined device

Token Protection ensures that access tokens are cryptographically bound to the device's Trusted Platform Module (TPM). If an attacker steals a token and replays it from a different device, the token is rejected because the proof-of-possession key does not match.

Step 4: Detect Token Replay in Sign-in Logs

Query Entra sign-in logs for indicators of token theft:

// KQL query for Microsoft Sentinel or Log Analytics
// Detect sign-ins where the token was issued in one location and used in another
SigninLogs
| where TimeGenerated > ago(7d)
| where RiskDetail contains "token" or RiskEventTypes_V2 has "anomalousToken"
| project TimeGenerated, UserPrincipalName, IPAddress, Location,
          RiskDetail, RiskLevelDuringSignIn, AppDisplayName,
          DeviceDetail, ClientAppUsed, TokenIssuerType
| sort by TimeGenerated desc
 
// Detect impossible travel with token reuse
SigninLogs
| where TimeGenerated > ago(7d)
| where ResultType == 0  // Successful sign-ins only
| summarize Locations=make_set(Location), IPs=make_set(IPAddress),
            Count=count() by UserPrincipalName, bin(TimeGenerated, 1h)
| where array_length(Locations) > 1
| sort by TimeGenerated desc
 
// Detect device code flow abuse (often used in phishing)
SigninLogs
| where TimeGenerated > ago(7d)
| where AuthenticationProtocol == "deviceCode"
| project TimeGenerated, UserPrincipalName, IPAddress, Location,
          AppDisplayName, DeviceDetail, ResultType
| sort by TimeGenerated desc
 
// Detect token replay: same token used from multiple IPs
AADNonInteractiveUserSignInLogs
| where TimeGenerated > ago(7d)
| where ResultType == 0
| summarize IPs=make_set(IPAddress), IPCount=dcount(IPAddress)
            by UserPrincipalName, CorrelationId
| where IPCount > 1
| sort by IPCount desc

Step 5: Investigate and Respond to Token Theft

When a token theft event is detected, follow this response procedure:

# Step 5a: Revoke all refresh tokens for the compromised user
# Microsoft Graph PowerShell
Connect-MgGraph -Scopes "User.ReadWrite.All"
Revoke-MgUserSignInSession -UserId "user@contoso.com"
 
# Step 5b: Force password reset
Update-MgUser -UserId "user@contoso.com" -PasswordProfile @{
    ForceChangePasswordNextSignIn = $true
}
 
# Step 5c: Review and revoke OAuth app consent grants
# Check for malicious app consent (common post-compromise persistence)
Get-MgUserOauth2PermissionGrant -UserId "user@contoso.com" |
    Select-Object ClientId, ConsentType, Scope
 
# Remove suspicious OAuth grants
Remove-MgOauth2PermissionGrant -OAuth2PermissionGrantId "<grant-id>"
 
# Step 5d: Review enterprise app registrations for rogue apps
Get-MgServicePrincipal -Filter "displayName eq 'Suspicious App'" |
    Select-Object AppId, DisplayName, SignInAudience
 
# Step 5e: Check for mail forwarding rules (common post-compromise action)
Get-MgUserMailFolderRule -UserId "user@contoso.com" -MailFolderId "Inbox" |
    Where-Object { $_.Actions.ForwardTo -ne $null -or $_.Actions.RedirectTo -ne $null }

Step 6: Implement Continuous Access Evaluation (CAE)

Enable CAE to revoke tokens in near-real-time when conditions change:

Entra Admin Center > Protection > Conditional Access > Continuous Access Evaluation
 
Settings:
  Strictly enforce location policies: Enabled
 
CAE ensures that when you revoke a user's session or change their
risk level, the enforcement happens within minutes rather than waiting
for the access token to naturally expire (60-90 minutes).
 
Critical events that trigger immediate token revocation with CAE:
- User account disabled or deleted
- Password changed or reset
- MFA enabled for the user
- Admin explicitly revokes refresh tokens
- Azure AD Identity Protection detects elevated user risk
- Network location change violates conditional access policy

Step 7: Configure Defender for Cloud Apps Session Policies

Set up real-time session monitoring to detect and block suspicious token usage:

Microsoft Defender for Cloud Apps > Policies > Session Policies
 
Policy: "Block download from unmanaged device with stolen token"
  Session Control Type: Monitor and block activities
  Activity Source: App = Office 365, SharePoint Online
  Activity Filter: Device tag does not equal "Compliant"
  Activity Type: Download
  Action: Block
 
Policy: "Alert on mass file download (exfiltration via stolen token)"
  Session Control Type: Monitor only
  Activity Source: App = Office 365
  Activity Filter: Repeated activity > 10 downloads in 5 minutes
  Action: Alert administrators

Key Concepts

Term Definition
Primary Refresh Token (PRT) A long-lived token issued to a registered device that provides SSO to all Azure AD-integrated applications, cryptographically bound to the device's TPM
Token Protection Entra ID conditional access feature that binds sign-in session tokens to the device, preventing replay from other devices
Continuous Access Evaluation (CAE) Protocol that enables near-real-time enforcement of security policies by allowing resource providers to subscribe to Entra ID critical events
AitM (Adversary-in-the-Middle) Phishing technique where an attacker proxies the legitimate authentication flow to capture session cookies after the victim completes MFA
Device Code Flow OAuth 2.0 authorization grant for input-constrained devices; abused by attackers who send device codes to victims via phishing
Proof of Possession (PoP) Cryptographic mechanism where a token includes a claim tied to a device key, ensuring the token can only be used by the device that obtained it
Refresh Token Long-lived OAuth token (up to 90 days) used to obtain new access tokens without re-authentication; primary target for persistent access

Verification

  • Identity Protection risk detections are enabled and generating alerts for anomalous token activity
  • Conditional access policies block high-risk sign-ins and require MFA for medium-risk
  • Token Protection policy is applied to pilot group and confirmed working (test from unregistered device fails)
  • KQL queries in Sentinel return results when tested against synthetic token anomaly events
  • Continuous Access Evaluation is enabled and verified (revoke session, confirm access blocked within minutes)
  • Defender for Cloud Apps session policies are active and monitoring download activity
  • Device code flow is restricted via conditional access (block or require compliant device)
  • Incident response runbook includes token revocation, password reset, and OAuth consent review steps
  • Mail forwarding rules and OAuth app grants are audited for compromised accounts
Source materials

References and resources

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

References 1

api-reference.md1.6 KB

API Reference: Detecting OAuth Token Theft

Microsoft Graph Sign-In Logs

# Query sign-in logs
curl -H "Authorization: Bearer $MS_TOKEN" \
  "https://graph.microsoft.com/v1.0/auditLogs/signIns?\$filter=createdDateTime ge 2025-01-01&\$top=100"

Sign-In Event Fields

Field Description
userPrincipalName User email/UPN
ipAddress Source IP address
location.city Geo city
location.geoCoordinates Lat/lon
deviceDetail.deviceId Device identifier
resourceDisplayName Target resource
status.errorCode 0 = success
riskState none, confirmedCompromised, remediated

Okta System Log API

# Query events
curl -H "Authorization: SSWS $OKTA_TOKEN" \
  "https://your-org.okta.com/api/v1/logs?filter=eventType eq \"user.session.start\"&since=2025-01-01"

Detection Logic

Detection Method
Impossible travel Haversine distance / time > 900 km/h
Token replay Same user, 3+ IPs within 5 min window
New device Device ID not in known device inventory
Suspicious scopes 2+ sensitive OAuth scopes requested

Sensitive OAuth Scopes (Microsoft)

Scope Risk
Mail.ReadWrite Email access
Mail.Send Send-as capability
Files.ReadWrite.All Full file access
Directory.ReadWrite.All AD modification
Application.ReadWrite.All App registration

MITRE ATT&CK Mapping

Technique Description
T1528 Steal Application Access Token
T1550.001 Application Access Token reuse
T1078.004 Cloud Accounts

Scripts 1

agent.py7.0 KB
Display-only source. This catalog never executes bundled scripts.
#!/usr/bin/env python3
"""OAuth token theft detection agent.

Analyzes sign-in logs for impossible travel, new device sign-ins,
token replay from unusual IPs, and anomalous scope requests.
"""

import argparse
import json
import math
import datetime
import collections

try:
    import requests
    HAS_REQUESTS = True
except ImportError:
    HAS_REQUESTS = False


EARTH_RADIUS_KM = 6371


def haversine(lat1, lon1, lat2, lon2):
    """Calculate great-circle distance between two points in km."""
    lat1, lon1, lat2, lon2 = map(math.radians, [lat1, lon1, lat2, lon2])
    dlat = lat2 - lat1
    dlon = lon2 - lon1
    a = math.sin(dlat / 2) ** 2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon / 2) ** 2
    return 2 * EARTH_RADIUS_KM * math.asin(math.sqrt(a))


def detect_impossible_travel(sign_ins, max_speed_kmh=900):
    """Detect impossible travel based on geo and time between logins."""
    alerts = []
    by_user = collections.defaultdict(list)
    for event in sign_ins:
        by_user[event.get("user", "")].append(event)

    for user, events in by_user.items():
        sorted_events = sorted(events, key=lambda e: e.get("timestamp", ""))
        for i in range(1, len(sorted_events)):
            prev, curr = sorted_events[i - 1], sorted_events[i]
            if not all(k in prev for k in ("lat", "lon")) or not all(k in curr for k in ("lat", "lon")):
                continue
            dist = haversine(prev["lat"], prev["lon"], curr["lat"], curr["lon"])
            try:
                t1 = datetime.datetime.fromisoformat(prev["timestamp"].replace("Z", "+00:00"))
                t2 = datetime.datetime.fromisoformat(curr["timestamp"].replace("Z", "+00:00"))
                hours = max((t2 - t1).total_seconds() / 3600, 0.001)
            except (ValueError, KeyError):
                continue
            speed = dist / hours
            if speed > max_speed_kmh and dist > 100:
                alerts.append({
                    "type": "impossible_travel",
                    "user": user,
                    "from_ip": prev.get("ip", ""),
                    "to_ip": curr.get("ip", ""),
                    "distance_km": round(dist, 1),
                    "time_hours": round(hours, 2),
                    "speed_kmh": round(speed, 1),
                    "severity": "HIGH",
                })
    return alerts


def detect_token_replay(sign_ins):
    """Detect token replay from multiple IPs in short timeframe."""
    alerts = []
    by_user = collections.defaultdict(list)
    for event in sign_ins:
        by_user[event.get("user", "")].append(event)

    for user, events in by_user.items():
        sorted_events = sorted(events, key=lambda e: e.get("timestamp", ""))
        window = []
        for event in sorted_events:
            try:
                ts = datetime.datetime.fromisoformat(event["timestamp"].replace("Z", "+00:00"))
            except (ValueError, KeyError):
                continue
            window = [e for e in window
                      if (ts - datetime.datetime.fromisoformat(
                          e["timestamp"].replace("Z", "+00:00"))).total_seconds() < 300]
            window.append(event)
            unique_ips = set(e.get("ip") for e in window if e.get("ip"))
            if len(unique_ips) >= 3:
                alerts.append({
                    "type": "token_replay",
                    "user": user,
                    "ips": list(unique_ips),
                    "window_seconds": 300,
                    "severity": "CRITICAL",
                })
    return alerts


def detect_new_device(sign_ins, known_devices=None):
    """Detect sign-ins from previously unseen devices."""
    known = set(known_devices or [])
    alerts = []
    for event in sign_ins:
        device_id = event.get("device_id", event.get("user_agent", ""))
        if device_id and device_id not in known:
            alerts.append({
                "type": "new_device",
                "user": event.get("user", ""),
                "device": device_id,
                "ip": event.get("ip", ""),
                "timestamp": event.get("timestamp", ""),
                "severity": "MEDIUM",
            })
            known.add(device_id)
    return alerts


def detect_suspicious_scopes(sign_ins):
    """Detect OAuth requests with overly broad or sensitive scopes."""
    sensitive_scopes = {
        "Mail.ReadWrite", "Mail.Send", "Files.ReadWrite.All",
        "Directory.ReadWrite.All", "User.ReadWrite.All",
        "Application.ReadWrite.All", "RoleManagement.ReadWrite.Directory",
    }
    alerts = []
    for event in sign_ins:
        scopes = set(event.get("scopes", []))
        dangerous = scopes & sensitive_scopes
        if len(dangerous) >= 2:
            alerts.append({
                "type": "suspicious_scopes",
                "user": event.get("user", ""),
                "scopes": list(dangerous),
                "app": event.get("app_name", ""),
                "severity": "HIGH",
            })
    return alerts


def main():
    parser = argparse.ArgumentParser(description="OAuth token theft detection agent")
    parser.add_argument("--log-file", help="JSON file with sign-in events")
    parser.add_argument("--max-speed", type=int, default=900, help="Max travel speed km/h (default: 900)")
    parser.add_argument("--output", "-o", help="Output JSON report path")
    args = parser.parse_args()

    print("[*] OAuth Token Theft Detection Agent")
    report = {"timestamp": datetime.datetime.utcnow().isoformat() + "Z", "alerts": []}

    if args.log_file:
        with open(args.log_file) as f:
            sign_ins = json.load(f)
    else:
        sign_ins = [
            {"user": "alice@corp.com", "ip": "203.0.113.10", "lat": 40.7128, "lon": -74.0060,
             "timestamp": "2025-06-15T10:00:00Z", "device_id": "device-A"},
            {"user": "alice@corp.com", "ip": "198.51.100.50", "lat": 51.5074, "lon": -0.1278,
             "timestamp": "2025-06-15T10:30:00Z", "device_id": "device-B"},
            {"user": "bob@corp.com", "ip": "10.0.0.1", "lat": 37.7749, "lon": -122.4194,
             "timestamp": "2025-06-15T09:00:00Z", "device_id": "device-C",
             "scopes": ["Mail.ReadWrite", "Mail.Send", "Files.ReadWrite.All"]},
        ]
        print("[DEMO] Using sample sign-in events")

    report["alerts"].extend(detect_impossible_travel(sign_ins, args.max_speed))
    report["alerts"].extend(detect_token_replay(sign_ins))
    report["alerts"].extend(detect_new_device(sign_ins))
    report["alerts"].extend(detect_suspicious_scopes(sign_ins))

    by_type = collections.Counter(a["type"] for a in report["alerts"])
    print(f"[*] Total alerts: {len(report['alerts'])}")
    for alert_type, count in by_type.items():
        print(f"    {alert_type}: {count}")
    for a in report["alerts"]:
        print(f"  [{a['severity']}] {a['type']}: {a.get('user', '')} - {a.get('distance_km', a.get('ips', a.get('device', '')))}")

    if args.output:
        with open(args.output, "w") as f:
            json.dump(report, f, indent=2)
    print(json.dumps({"total_alerts": len(report["alerts"]), "by_type": dict(by_type)}, indent=2))


if __name__ == "__main__":
    main()
Keep exploring