Threat Hunting for OilRig (APT34): A Deep Dive for Threat Hunters

APT34, also known as OilRig, is a well-organized and persistent Iranian cyber espionage group that has been actively targeting organizations within the oil, gas, energy, and telecommunications industries, primarily across the Middle East. This group, believed to be state-sponsored, uses a wide array of custom malware, advanced exploitation techniques, and evasive tactics to infiltrate, persist, and exfiltrate sensitive data. Their operations are highly targeted and tailored to specific organizations, making it essential for threat hunters to adopt a proactive, detailed, and technical approach when hunting for OilRig’s presence.

In this blog post, we will explore how to hunt for OilRig, step by step, in a very technical manner. The following guide is meant for seasoned threat hunters who want to improve their skills and approach for detecting this highly sophisticated adversary. I will walk you through the threat hunting process for OilRig, from the initial hypothesis to detection, investigation, and response. This guide covers both high-level strategies and granular technical details on how to set up detections, analyze IOCs, and identify key TTPs associated with OilRig.

Step 1: Understand the Threat Landscape – Tactics, Techniques, and Procedures (TTPs)

The first step to hunting any adversary, including APT34, is to understand their tactics, techniques, and procedures (TTPs). OilRig’s activities can be mapped to the MITRE ATT&CK framework, a living document that helps security professionals identify the TTPs used by threat actors. APT34 has a well-documented history of exploiting specific vulnerabilities, deploying custom malware, and using various evasion techniques.

Key Tactics and Techniques of OilRig (APT34):

    • • Initial Access:
      • – Phishing (T1071): OilRig often uses spear-phishing emails with malicious attachments to gain initial access. They also employ social engineering and fake websites to trick employees into downloading malicious files.
      • – Exploitation of Public-Facing Applications (T1190): Exploiting unpatched vulnerabilities in web servers, such as CVE-2017-5638 (Apache Struts) or other common RCE vulnerabilities.
      • – Valid Accounts (T1078): OilRig uses compromised credentials for RDP and SMB lateral movement.
    • • Execution:
      • – PowerShell (T1086): PowerShell is heavily leveraged by OilRig for command-and-control (C2) communication, persistence, and malware deployment. The group often uses obfuscated PowerShell scripts.
      • – Command and Scripting Interpreter (T1059): Other scripting languages, including Python and Perl, may be used to execute payloads.
      • – Scheduled Tasks (T1053): OilRig often creates scheduled tasks to maintain persistence on infected systems.
    • • Persistence:
      • – Web Shell (T1505): One of OilRig’s primary persistence mechanisms is web shells deployed on vulnerable web servers. This allows them to maintain access even after other malware is removed.
      • – Registry Run Keys (T1060): OilRig modifies registry keys to ensure their malware persists across system reboots.
    • • Privilege Escalation:
      • – Credential Dumping (T1003): Tools like Mimikatz are used to extract credentials from memory.
      • – Exploitation for Privilege Escalation (T1068): OilRig has been known to exploit kernel vulnerabilities to elevate privileges.
    • • Defense Evasion:
      • – Obfuscated Files or Information (T1027): OilRig often uses obfuscation techniques, such as packing their malware or using encoded PowerShell scripts.
      • – Fileless Malware (T1056): The group uses PowerShell and other in-memory techniques to evade traditional file-based detection.
    • • Command and Control (C2):
      • – Encrypted C2 (T1071.001): Communication is usually encrypted over HTTPS to avoid detection. Random subdomains may be generated to connect to the C2 server.
      • – Application Layer Protocol (T1071): They often communicate over standard ports (443/80) using HTTP/S for C2 traffic.
    • • Exfiltration:
      • – Exfiltration Over C2 Channel (T1041): Exfiltration often happens over the same encrypted channels used for C2.
      • – Exfiltration Over Alternative Protocol (T1048): Occasionally, DNS tunneling or other covert channels are used for data exfiltration.

With this framework, we now have a roadmap of potential indicators to look for during a hunt for OilRig activity. As a threat hunter, the next logical step is setting up monitoring and detection mechanisms tailored to these TTPs.

Step 2: Set Up Detection Mechanisms for Key OilRig Indicators

Effective threat hunting starts with ensuring the proper detection mechanisms are in place. Given OilRig’s varied tactics, creating a comprehensive monitoring strategy is crucial.

A. Endpoint Detection and Response (EDR) and SIEM

Start by configuring your EDR (such as CrowdStrike, SentinelOne, or CarbonBlack) to capture detailed endpoint telemetry. Here’s what to focus on:

    1. • Process Execution Monitoring: Track the execution of suspicious processes. OilRig often leverages legitimate system tools like PowerShell, WMI, and net.exe for lateral movement and exploitation.
      • – PowerShell Execution: Monitor for abnormal PowerShell scripts. Use Sysmon or PowerShell logging to capture all execution details
      • – Suspicious Command Line Arguments: Watch for encoded or obfuscated PowerShell commands and flags like -e (for encoded commands).
      • Malicious File Creation: Monitor for the creation of unusual files, particularly in directories that are not commonly used for executable files, such as %Temp%, %AppData%, or %SystemRoot%\Temp. OilRig often hides malware in these locations.
        • – File Hashing: Implement file integrity monitoring and hash comparison. Known OilRig malware, such as Helminth or RDAT, can be identified by its file hash (MD5/SHA1/SHA256).

B. Network Traffic Analysis

Monitoring network traffic is crucial for identifying C2 communication and exfiltration attempts. OilRig relies heavily on encrypted HTTP/S traffic for both C2 and data exfiltration. Here’s how to detect it:

    1. • DNS Logs: OilRig frequently uses domain generation algorithms (DGAs), which involve generating random subdomains for their C2 servers. This type of traffic can often be detected in DNS query logs.
      • – Anomaly Detection in DNS Queries: Use KQL (Kusto Query Language) for querying DNS logs in tools like Microsoft Sentinel or Azure Monitor. Look for unusually frequent DNS queries or random subdomains
      • – Network Flow Monitoring: Look for unusual outbound traffic on port 443 or 80, particularly to known OilRig IP addresses or domains. Use flow monitoring tools like Zeek (formerly Bro) to track suspicious patterns:
      • – SSL/TLS Inspection: Since OilRig often uses HTTPS for C2 communication, implement SSL/TLS inspection on your network firewall or proxy server to decrypt and analyze the traffic.

C. Log Management and SIEM Correlation

Integrate your endpoint, network, and authentication logs into a Security Information and Event Management (SIEM) system. This enables you to correlate events across different data sources and identify suspicious patterns. For example, you can correlate Windows Event Logs with PowerShell execution logs to detect credential dumping or lateral movement.

Use correlation rules to detect:

    • – Multiple failed login attempts followed by successful logins using valid credentials (T1078).
    • – Unusual network connections followed by the execution of obfuscated PowerShell scripts (T1086).

D. Use of Threat Intelligence

Incorporate threat intelligence feeds that provide IOCs (Indicators of Compromise) related to OilRig. These may include:

    • – IP addresses associated with C2 servers.
    • – Malware hashes for known OilRig payloads.
    • – Domain names and URLs used in the attack infrastructure.

By integrating open-source threat intelligence (e.g., MISP or OTX) or commercial feeds, you can automatically enrich your detections with updated IOCs.

Step 3: Investigate Suspicious Activity

After you’ve set up the appropriate monitoring and detection mechanisms, the next step is to perform the actual threat hunting. When investigating suspicious activity related to OilRig, you need to think critically about the adversary’s objectives and the tools they use to achieve them.

A. Analyze Malicious PowerShell Activity

OilRig frequently uses PowerShell scripts to establish persistence, escalate privileges, and communicate with C2 servers. When you detect suspicious PowerShell activity, perform the following analysis:

    1. 1- Extract the PowerShell script from the logs.
    2. 2- Deobfuscate the script to see what actions it performs. Tools like PowerShell Empire, Cobalt Strike, or Mimikatz may be used to dump credentials or create web shells.
    3. 3- Check for the presence of C2 communication or payload execution within the script.

B. Examine Web Shells

OilRig’s use of web shells is a critical point for investigation. Web shells often appear as anomalous HTTP requests or unexpected scripts placed in web-accessible directories (e.g., /admin/, /uploads/). To hunt for them:

    1. 1- Web Server Log Analysis: Look for unusual HTTP methods (e.g., POST, PUT) or base64-encoded payloads.
    2. 2- File Integrity: Check for unauthorized file changes in web server directories, especially scripts like .php, .asp, or .jsp.

C. Track Lateral Movement

Use your network monitoring tools to identify lateral movement techniques like RDP, SMB, and WMI, which are commonly used by OilRig. Look for:

    • – RDP connections from unusual sources.
    • – Uncommon SMB shares accessed by internal systems.
    • – WMI execution from remote machines or from untrusted IP addresses.

Step 4: Responding to OilRig’s Activities

Once you’ve detected OilRig’s activities, it’s critical to respond swiftly to mitigate damage. Here’s how you can proceed with a technical, incident response approach:

    1. 1- Containment:
      • – Isolate infected hosts immediately.
      • – Revoke compromised credentials and force a password reset for all accounts, especially administrative ones.
      • – Block any identified C2 infrastructure at the network level.
    2. 2- Eradication:
      • – Remove any malicious files, scripts, or tools that were installed during the intrusion (e.g., PowerShell scripts, web shells, malware).
      • – Apply patches for exploited vulnerabilities, ensuring that all systems are up-to-date.
    3. 3- Recovery:
      • – Rebuild compromised systems from known, trusted backups.
      • – Monitor the network closely for any signs of reinfection or re-exploitation.
    4. 4- Post-Incident:
      • – After containment and eradication, perform a thorough post-mortem to assess the full scope of the attack.
      • – Update detection mechanisms and improve threat-hunting playbooks based on lessons learned.

To support a technical, real-world threat-hunting effort against APT34 (OilRig) using Microsoft Sentinel and Splunk, we’ll develop and adapt queries specifically tailored to these tools. Both platforms are powerful for security event monitoring, detection, and analysis. Below, we will cover hunting queries designed for use in Sentinel and Splunk, based on the identified TTPs for APT34. These queries are meant to help you detect malicious behaviors associated with OilRig.


1. PowerShell Suspicious Execution (T1086)

A. Microsoft Sentinel (KQL Query)

OilRig frequently uses PowerShell for malicious activity, such as executing obfuscated scripts and performing C2 communications. To detect such activity in Sentinel:

// PowerShell suspicious execution detection in Sentinel
SecurityEvent
| where EventID == 4688  // Process creation event
| where CommandLine has "powershell" or CommandLine has "iex" or CommandLine has "-enc"
| project TimeGenerated, Computer, Account, CommandLine, ParentProcessName, NewProcessName, ProcessId, ParentProcessId
| extend EncodedCommand = extract("[-]enc\\s([A-Za-z0-9+/=]+)", 1, CommandLine)
| extend Obfuscated = iff(isnull(EncodedCommand), "No", "Yes")
| where Obfuscated == "Yes"
| order by TimeGenerated desc

Explanation:

    • • This query looks for PowerShell executions (EventID 4688) and checks if there are obfuscated or encoded commands (-enc flag or base64 encoding).
    • • It also extracts the base64-encoded string from the command line to help identify obfuscation.

B. Splunk (SPL Query)

To detect PowerShell execution anomalies in Splunk, use the following SPL query:

index=wineventlog EventCode=4688
| where like(CommandLine, "%powershell%" OR like(CommandLine, "%iex%") OR like(CommandLine, "%-enc%"))
| eval EncodedCommand = if(like(CommandLine, "%-enc%"), "Yes", "No")
| table _time, host, User, CommandLine, Process_Name, Parent_Process_Name, EncodedCommand
| sort _time desc

Explanation:

    • • The query searches for EventCode 4688 (new process creation) in Windows Event logs for PowerShell commands that include common flags or obfuscation (e.g., iex and -enc).
    • • The EncodedCommand field checks if the command contains obfuscated or encoded payloads, and results are sorted by time.

2. Web Shell Detection (T1505)

Web shells are one of the primary persistence mechanisms for OilRig. In this case, we’ll look for HTTP requests that could indicate web shell usage.

A. Microsoft Sentinel (KQL Query)

// Web shell activity detection in Sentinel
AzureDiagnostics
| where ResourceType == "APPLICATIONGATEWAY" and HttpMethod == "POST" 
| where Url has_any ("php", "jsp", "asp", "exe", "cgi") // Check for web shell file extensions
| where (ClientIP != "127.0.0.1" and ClientIP != "0.0.0.0")
| project TimeGenerated, ClientIP, HttpMethod, Url, RequestUri, ResponseCode, BytesSent, UserAgent, RequestBody
| order by TimeGenerated desc

Explanation:

    • • This query checks for HTTP POST requests (common in web shell activity) that contain suspicious file extensions like .php, .jsp, .asp, etc.
    • • Filters out local traffic (from 127.0.0.1) to focus on external web shell activity.
    • • Projected fields like ClientIP, Url, ResponseCode, and UserAgent help identify the malicious actor’s behavior.

B. Splunk (SPL Query)

index=web_logs sourcetype=access_combined
| regex uri_path="(\.php|\.jsp|\.asp|\.exe|\.cgi)"
| stats count by src_ip, uri_path, user_agent, _time
| where count > 5 // Threshold for suspicious activity
| sort -_time

Explanation:

    • • This query looks at web server logs for uri_path that contains typical web shell file extensions.
    • • The count > 5 threshold flags possible web shell usage, as multiple requests for these extensions within a short period could indicate an attack.

3. Credential Dumping (T1003)

APT34 uses credential dumping techniques like Mimikatz to steal passwords. This can be detected through EventID 4672 (special privileges assigned to new logon) or abnormal processes.

A. Microsoft Sentinel (KQL Query)

// Detect credential dumping attempts in Sentinel
SecurityEvent
| where EventID == 4672  // Special privileges assigned to new logon
| where AccountType == "User" and LogonType == "10"  // RDP logon (for lateral movement)
| project TimeGenerated, Computer, Account, LogonType, EventID, ProcessId, ProcessName, TargetUserName, LogonProcessName
| extend IsCredentialDump = iff(ProcessName in ("mimikatz.exe", "procdump.exe", "rundll32.exe"), "Yes", "No")
| where IsCredentialDump == "Yes"
| order by TimeGenerated desc

Explanation:

    • • This query identifies potential credential dumping attempts by looking for EventID 4672, which indicates special privileges.
    • • It then filters for known credential dumping tools like mimikatz.exe, procdump.exe, or rundll32.exe.

B. Splunk (SPL Query)

index=wineventlog EventCode=4672
| where Account_Type="User" AND Logon_Type="10"  // RDP sessions
| lookup credential_dumping_tools ProcessName OUTPUTNEW ProcessName AS MaliciousProcess
| where isnotnull(MaliciousProcess)
| table _time, src_ip, Account_Name, ProcessName, MaliciousProcess, Target_Username
| sort _time desc

Explanation:

    • • This Splunk query uses the lookup command to correlate known credential dumping tools (like Mimikatz) with EventCode 4672.
    • • It highlights suspicious RDP logins associated with these tools.

4. DNS Tunneling or C2 Communication (T1071)

OilRig uses encrypted DNS requests for command-and-control (C2) communication. Monitoring for unusual DNS traffic patterns or abnormal subdomains can help identify C2 communication.

A. Microsoft Sentinel (KQL Query)

// Detect DNS tunneling or C2 via DNS requests in Sentinel
DnsEvents
| where QueryName endswith ".com" // Look for domains used in C2 traffic
| extend DGA_Indicator = iff(QueryName matches regex @"^[a-z0-9]{8,}.com$", "Potential DGA", "Normal")
| where DGA_Indicator == "Potential DGA"
| summarize Count = count() by DGA_Indicator, QueryName, Computer, TimeGenerated
| where Count > 5 // Threshold for suspicious activity
| order by Count desc

Explanation:

    • • This query identifies DNS requests with domain names matching a Domain Generation Algorithm (DGA) pattern (e.g., random alphanumeric strings).
    • • Flags the requests where the Count exceeds a threshold of 5 within a short time, which could be indicative of C2 traffic.

B. Splunk (SPL Query)

index=dns_logs
| regex query="^[a-z0-9]{8,}\.com$"  // Matches DGA-like domains
| stats count by query, src_ip, _time
| where count > 5 // Threshold for suspicious activity
| sort - _time

Explanation:

    • • Similar to the Sentinel query, this Splunk query looks for DNS queries with random alphanumeric domain names, indicative of DNS tunneling or C2 communication.
    • • Flags suspicious activity based on the number of queries within a set timeframe.

5. Lateral Movement via SMB or RDP (T1075)

OilRig commonly uses SMB and RDP for lateral movement within networks. Monitoring for RDP logins or SMB connections outside of normal usage patterns is critical.

A. Microsoft Sentinel (KQL Query)

// Detect lateral movement using RDP or SMB in Sentinel
SecurityEvent
| where EventID == 4624 // Logon event
| where LogonType in (10, 7) // RDP (10) or Network (3)
| where Account != "SYSTEM" and Account != "LOCAL SERVICE"
| project TimeGenerated, Computer, Account, LogonType, LogonProcessName, SourceNetworkAddress, TargetUserName
| extend Suspicious = iff(SourceNetworkAddress != "InternalSubnet", "Yes", "No")
| where Suspicious == "Yes"
| order by TimeGenerated desc

Explanation:

    • • This query monitors for RDP and SMB logons (LogonType 10 and 7) from non-local accounts.
    • • It flags suspicious logins originating from external or unusual IP addresses.

B. Splunk (SPL Query)

index=wineventlog EventCode=4624
| where Logon_Type="10" OR Log

on_Type="3"
| where src_ip NOT IN ["192.168.0.0/16", "10.0.0.0/8"]  // Specify your internal network ranges
| table _time, src_ip, User, Logon_Type, host
| sort -_time

Explanation:

    • • This Splunk query detects RDP (10) and Network (7) logins from external IP addresses, highlighting potential lateral movement or unauthorized access.

Using Microsoft Sentinel and Splunk for threat hunting requires a robust understanding of attack techniques like those used by APT34 (OilRig). By creating tailored queries to detect suspicious PowerShell usage, web shell activity, credential dumping, DNS tunneling, and lateral movement, you can proactively identify malicious activity. Combining these queries with threat intelligence and ongoing monitoring will help strengthen your defenses against advanced adversaries.

Conclusion: Ongoing Monitoring and Continuous Improvement

Hunting for OilRig, like any advanced persistent threat (APT), requires continuous monitoring, up-to-date detection techniques, and a deep understanding of adversary behavior. By combining threat intelligence, advanced detection tools, and a structured hunting methodology, you can significantly improve your chances of detecting and mitigating OilRig’s activities before they can cause significant harm.

Threat hunters must constantly refine their tools and strategies, ensuring they stay ahead of adversaries who are always evolving. By staying focused on the TTPs, leveraging automation, and continually improving detection capabilities, you can protect your organization against these highly sophisticated and persistent threat actors.


📢 If you’re looking to specialize in cybersecurity and master both offensive and defensive tactics, check out the training programs at Cyber Dojo:

    • – SOC Analyst Bootcamp – Kickstart your career as a SOC Analyst and become an expert in security analysis.
    • – DFIR Bootcamp – Learn the art of digital forensics and incident response and prepare to handle attacks with professionalism.
    • – Pentest Bootcamp – Master penetration testing techniques and analyze vulnerabilities in real-world environments.

• Explore all our courses here: Cyber Dojo Courses
• Check out our bundles for more value: Cyber Dojo Bundles

Leave A Reply

Your email address will not be published. Required fields are marked *

This site uses User Verification plugin to reduce spam. See how your comment data is processed.

You May Also Like

Main project by Mayfly: https://github.com/Orange-Cyberdefense/GOAD This was fully tested only on a Windows 10 machine with 64GB of RAM. This may...
DCShadow is an advanced feature of the Mimikatz tool, specifically found in the lsadump module. This powerful attack simulates the...
What are LolBins? “LolBins” or Living of the Land Binaries, is a term used to describe the exploitation of legitimate operating...