Listen to this Post

Introduction:
EvilTokens is a newly emerged Phishing-as-a-Service (PhaaS) platform that weaponizes stolen Microsoft 365 tokens and large language models to supercharge Business Email Compromise (BEC) attacks. First advertised on Telegram in mid-February 2026, this turnkey operation enables low‑skill threat actors to execute highly tailored, AI‑driven BEC campaigns in minutes instead of days, leveraging device‑code phishing and automated infrastructure deployment.
Learning Objectives:
- Understand the complete attack chain of EvilTokens, including device‑code phishing, token theft, and AI‑generated BEC emails.
- Detect and analyze stolen Microsoft 365 token usage using Azure AD sign‑in logs and Microsoft Graph API.
- Implement mitigation strategies such as Conditional Access policies, token protection, and Cloudflare Worker blocking.
You Should Know:
- How Device Code Phishing Steals Microsoft 365 Tokens
EvilTokens uses device‑code phishing – a technique that abuses the OAuth 2.0 device authorization flow. Attackers generate a device code and a verification URL (e.g., microsoft.com/devicelogin). The victim is tricked into entering the code on a legitimate Microsoft login page, where the attacker captures the resulting authentication token without ever handling the victim’s password.
Step‑by‑step guide explaining what this does and how to use it (defensive perspective):
Detection via Azure AD Sign‑in Logs
Use PowerShell to identify suspicious device‑code flows:
Install module
Install-Module -Name AzureADPreview -Force
Connect-AzureAD
Query sign‑ins with device‑code flow (client app "Microsoft Device Code Authentication")
Get-AzureADAuditSignInLogs -All $true | Where-Object {$_.ClientAppUsed -eq "Device Code Flow"} |
Select-Object UserPrincipalName, ClientAppUsed, DeviceDetail, Status, CreatedDateTime
Linux command to hunt for token artifacts in proxy logs
Extract bearer tokens from HTTP logs (common in AiTM)
grep -E "Bearer [A-Za-z0-9-_.]+" /var/log/nginx/access.log | awk '{print $7}' | sort -u
What this does: The PowerShell cmdlet filters sign‑ins specifically using device code authentication – a red flag if unexpected. The Linux command extracts potential OAuth tokens from web server logs, helping identify token exfiltration patterns. Use these to build detections for stolen token replay.
2. Analyzing EvilTokens’ AI‑Generated BEC Emails
EvilTokens integrates large language models to craft personalized, grammatically perfect BEC emails based on stolen context (e.g., email threads, signature blocks, financial data). This bypasses traditional spam filters that rely on spelling errors and generic templates.
Step‑by‑step guide to extract and analyze malicious emails (Linux/Windows)
On Linux, use `oletools` and `emlparser`:
Install oletools pip3 install oletools Extract all headers and body from .eml file olemap.py malicious_email.eml -i Look for AI‑generation indicators (rare but possible model‑specific patterns) grep -E "As an AI|generated by|language model" malicious_email.eml
On Windows with PowerShell (extract email headers and analyze authentication results):
Load .eml as a mail object
$eml = New-Object System.Net.Mail.MailMessage
$eml.Load("C:\samples\malicious.eml")
Check SPF/DKIM/DMARC headers
$eml.Headers | Select-String -Pattern "Authentication-Results|DKIM|SPF"
Use these commands to identify AI‑generated BEC emails that may lack traditional phishing fingerprints but contain model‑specific artifacts or authentication anomalies.
3. Hardening Against Token Replay and AiTM Attacks
To block EvilTokens from replaying stolen tokens, implement Conditional Access policies with token protection and Continuous Access Evaluation (CAE).
Step‑by‑step guide using Azure Portal and PowerShell
Azure Portal method:
- Navigate to Azure AD > Security > Conditional Access
- Create a new policy: “Block Token Replay”
- Assign all users and cloud apps (Office 365 Exchange Online, SharePoint)
- Under “Grant” > select “Require compliant device” and “Require hybrid Azure AD joined device”
- Under “Session” > enable “Sign‑in frequency” set to 1 hour and “Persistent browser session” to never
PowerShell equivalent:
Connect to MSGraph
Connect-MgGraph -Scopes Policy.ReadWrite.ConditionalAccess
Create token protection policy
$params = @{
displayName = "Block Token Replay - CAE"
state = "enabled"
conditions = @{
applications = @{ includeApplications = @("all") }
users = @{ includeUsers = @("all") }
}
grantControls = @{
operator = "OR"
builtInControls = @("compliantDevice", "domainJoinedDevice")
}
sessionControls = @{
signInFrequency = @{
value = 1
type = "hours"
isEnabled = $true
}
}
}
New-MgIdentityConditionalAccessPolicy -BodyParameter $params
What this does: Forces re‑authentication after one hour and requires device compliance, rendering stolen tokens useless once the short lifetime expires and device context fails.
- Monitoring for Stolen Token Usage with Microsoft Graph API
EvilTokens operators replay stolen tokens from different geographic locations and devices. Use Graph API to detect anomalous token usage patterns.
Step‑by‑step guide: Python script using MSAL
Install: pip install msal requests
import msal
import requests
from datetime import datetime, timedelta
Authenticate as a global admin
app = msal.ConfidentialClientApplication(
client_id="YOUR_CLIENT_ID",
client_credential="YOUR_SECRET",
authority="https://login.microsoftonline.com/YOUR_TENANT_ID"
)
token = app.acquire_token_for_client(scopes=["https://graph.microsoft.com/.default"])
Query sign‑in logs for anomalies
query = "https://graph.microsoft.com/v1.0/auditLogs/signIns?$filter=createdDateTime ge {}&$top=100".format(
(datetime.utcnow() - timedelta(days=1)).isoformat()
)
headers = {"Authorization": f"Bearer {token['access_token']}"}
response = requests.get(query, headers=headers)
for signin in response.json().get('value', []):
Detect token replay: same user, different city within 5 minutes
(Simplified – implement correlation logic)
if signin['riskDetail'] == 'none' and signin['location']['city'] not in signin['userAgent']:
print(f"Suspicious: {signin['userPrincipalName']} from {signin['location']['city']} at {signin['createdDateTime']}")
This script queries sign‑in logs and flags location mismatches – a strong indicator of token replay. Integrate with SIEM for real‑time alerting.
5. Defending Cloudflare Workers and Anti‑Bot Evasion
EvilTokens deploys phishing landing pages on Cloudflare Workers (free, ephemeral, HTTPS). Attackers also use anti‑bot services to block security scanners.
Step‑by‑step guide to block and mitigate
Block known EvilTokens Worker domains using Cloudflare WAF:
Using Cloudflare API – add firewall rule
curl -X POST "https://api.cloudflare.com/client/v4/zones/ZONE_ID/firewall/rules" \
-H "Authorization: Bearer YOUR_API_TOKEN" \
-H "Content-Type: application/json" \
--data '{
"action": "block",
"description": "Block EvilTokens Worker domains",
"expression": "(http.host contains \"evil-..workers.dev\") or (http.host contains \".evil-tokens.\")"
}'
Defeating anti‑bot evasion for researchers:
Use custom User‑Agent rotation and headless browser fingerprinting:
Use curl with randomized UA and proxy curl -A "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36" \ --proxy http://residential-proxy:8080 \ https://eviltokens-example.workers.dev/login
Alternatively, use Puppeteer to emulate human interaction:
// Save as scrape.js
const puppeteer = require('puppeteer-extra');
const StealthPlugin = require('puppeteer-extra-plugin-stealth');
puppeteer.use(StealthPlugin());
(async () => {
const browser = await puppeteer.launch({ headless: false });
const page = await browser.newPage();
await page.goto('https://suspicious-worker.dev');
await page.type('code', 'test123');
await page.click('button');
await page.screenshot({ path: 'phish_page.png' });
await browser.close();
})();
These commands help security teams proactively block malicious Workers domains and conduct undercover analysis without triggering anti‑bot protection.
6. Forensic Analysis of EvilTokens Compromise
After a suspected token theft, collect and correlate Microsoft 365 audit logs to determine the scope.
Step‑by‑step guide using PowerShell and Unified Audit Log
Search Unified Audit Log for token theft activity
Search-UnifiedAuditLog -StartDate (Get-Date).AddDays(-7) -EndDate (Get-Date) `
-Operations "UserLoggedIn", "MailboxLogin", "AddAppRoleAssignment" `
-ResultSize 5000 | Export-Csv -Path "EvilTokens_forensics.csv"
Extract suspicious OAuth app grants (often used for persistence)
Get-AzureADPSOutOfBandProvisioningEvent -All $true | Where-Object {$<em>.AppDisplayName -like "token" -or $</em>.AppDisplayName -like "phish"}
Linux command to check for token leakage on compromised endpoints:
Search for OAuth token files in user profiles find /home -type f -name "oauth" -o -name "token" 2>/dev/null | xargs grep -l "access_token"
These commands reconstruct the attack timeline: initial token theft (device‑code login), mailbox access (MailboxLogin), and any malicious app consent grants. Use output to revoke all sessions (Revoke-AzureADUserAllRefreshToken).
7. Mitigating BEC with AI Defenses
While EvilTokens uses AI to attack, defenders can deploy Microsoft Defender for Office 365 with AI‑based detection.
Step‑by‑step configuration
Enable Safe Links and Safe Attachments:
Connect-ExchangeOnline Set-AtpPolicyForO365 -EnableSafeLinks $true -EnableSafeAttachments $true Set-SafeLinksPolicy -Identity "Default" -BlockURL $true -EnableOrganizationBranding $true
Create anti‑phishing policy to block impersonation:
New-AntiPhishPolicy -Name "Block BEC Impersonation" ` -EnableSpoofIntelligence $true ` -EnableMailboxIntelligence $true ` -EnableMailboxIntelligenceProtection $true ` -EnableTargetedUserProtection $true ` -TargetedUserProtectionAction "Quarantine"
User training commands (Linux/Windows automated reminder):
Linux: send training email via sendmail echo -e "Subject: [ACTION REQUIRED] BEC & Token Phishing Training\n\nNever enter device codes from unsolicited messages. Report suspicious login prompts." | sendmail -v [email protected]
These configurations block AI‑generated emails that impersonate executives or vendors. Combined with user awareness, they break the BEC chain even when tokens are stolen.
What Undercode Say:
- EvilTokens lowers the barrier to BEC attacks by packaging token theft and AI content generation into a subscription service – expect a surge in high‑quality, automated email compromises.
- Traditional MFA is insufficient; device‑code phishing bypasses password and push notifications. Organizations must enforce Conditional Access with token protection and device compliance.
- Defenders must shift to monitoring OAuth token replay anomalies (location, device, time) rather than just credential theft indicators.
- Cloudflare Workers and similar ephemeral platforms are the new attack infrastructure – block by pattern and use behavioral analysis to detect phishing pages.
- AI‑generated BEC emails defeat legacy spam filters; deploy AI‑defense tools (Microsoft Defender, Abnormal Security) that analyze context and relationship graphs.
- The Telegram‑driven PhaaS model means attack kits evolve weekly – threat intelligence sharing on token abuse patterns is critical.
Prediction:
EvilTokens is the first of many AI‑powered token‑theft‑as‑a‑service platforms. Within 12 months, we will see similar offerings targeting Google Workspace, Slack, and AWS, using generative AI to automate social engineering at scale. Defenders will respond by adopting zero‑trust identity architectures, continuous access evaluation, and real‑time token binding to hardware. The cat‑and‑mouse game will shift from stealing passwords to stealing and revoking session tokens – making identity threat detection and response (ITDR) a mandatory security layer.
▶️ Related Video (72% Match):
🎯Let’s Practice For Free:
IT/Security Reporter URL:
Reported By: Mayura Kathiresh – Hackers Feeds
Extra Hub: Undercode MoN
Basic Verification: Pass ✅


