
Analyzing Command And Control Communication
- 408 installs
- 27.3k repo stars
- Updated August 2, 2026
- mukul975/anthropic-cybersecurity-skills
Analyzing Command and Control Communication is an agent skill that structures how your coding agent reasons about malicious command-and-control traffic and channels.
About
Analyzing Command and Control Communication is a security-focused agent skill from the Anthropic cybersecurity skills collection, intended for solo builders and small teams who need structured help reasoning about how malware talks to external infrastructure. Use it when you are reviewing logs, designing detections, or documenting suspicious beaconing during ship-phase security work—not for casual feature coding. The catalog entry currently surfaces license metadata more than procedural SKILL.md text, so you should treat it as a specialized procedural companion your agent loads alongside concrete log samples and your own runbooks. It matters because misclassified C2 noise wastes nights and misses real breaches; a named skill nudges the agent toward consistent MITRE-aligned questions instead of generic “check the network” advice. Confirm scope and steps in the upstream repo before relying on it in production incident response.
- Frames investigation of attacker C2 channels (beacons, DNS, HTTP/S) for agent-assisted triage
- Fits security skill packs aimed at blue-team and defensive coding workflows
- Pairs with broader Anthropic cybersecurity skills for layered incident response
- Apache-2.0 licensed package suitable for auditing before enabling network-heavy agent steps
Analyzing Command And Control Communication by the numbers
- 408 all-time installs (skills.sh)
- +23 installs in the week ending Aug 4, 2026 (Skillselion tracking)
- Ranked #549 of 2,203 Security skills by installs in the Skillselion catalog
- Security screen: MEDIUM risk (skills.sh audit)
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/mukul975/anthropic-cybersecurity-skills --skill analyzing-command-and-control-communicationAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 408 |
|---|---|
| repo stars | ★ 27.3k |
| Security audit | 2 / 3 scanners passed |
| Last updated | August 2, 2026 |
| Repository | mukul975/anthropic-cybersecurity-skills ↗ |
What it does
Guide your agent through structured analysis of command-and-control (C2) traffic and infrastructure when you are hardening or investigating compromised systems.
Who is it for?
Best when you're doing your own security reviews and want agent-guided C2 analysis checklists during launch prep or post-incident triage.
Skip if: Skip if you have no logs or network context to analyze, or teams that need certified IR vendors instead of agent-assisted reasoning—verify full SKILL.md and tooling in the source repo first.
When should I use this skill?
When investigating suspicious network behavior, designing C2 detections, or documenting attacker communication patterns during security review.
What you get
You get a consistent analysis frame for C2 indicators and communication patterns you can fold into detection notes, tickets, or hardening tasks.
- C2 analysis notes
- Detection or hardening follow-up tasks
Files
Analyzing Command-and-Control Communication
When to Use
- Reverse engineering a malware sample has revealed network communication that needs protocol analysis
- Building network-level detection signatures for a specific C2 framework (Cobalt Strike, Metasploit, Sliver)
- Mapping C2 infrastructure including primary servers, fallback domains, and dead drops
- Analyzing encrypted or encoded C2 traffic to understand the command set and data format
- Attributing malware to a threat actor based on C2 infrastructure patterns and tooling
Do not use for general network anomaly detection; this is specifically for understanding known or suspected C2 protocols from malware analysis.
Prerequisites
- PCAP capture of malware network traffic (from sandbox, network tap, or full packet capture)
- Wireshark/tshark for packet-level analysis
- Reverse engineering tools (Ghidra, dnSpy) for understanding C2 code in the malware binary
- Python 3.8+ with
scapy,dpkt, andrequestsfor protocol analysis and replay - Threat intelligence databases for C2 infrastructure correlation (VirusTotal, Shodan, Censys)
- JA3/JA3S fingerprint databases for TLS-based C2 identification
Workflow
Step 1: Identify the C2 Channel
Determine the protocol and transport used for C2 communication:
C2 Communication Channels:
━━━━━━━━━━━━━━━━━━━━━━━━━
HTTP/HTTPS: Most common; uses standard web traffic to blend in
Indicators: Regular POST/GET requests, specific URI patterns, custom headers
DNS: Tunneling data through DNS queries and responses
Indicators: High-volume TXT queries, long subdomain names, high entropy
Custom TCP/UDP: Proprietary binary protocol on non-standard port
Indicators: Non-HTTP traffic on high ports, unknown protocol
ICMP: Data encoded in ICMP echo/reply payloads
Indicators: ICMP packets with large or non-standard payloads
WebSocket: Persistent bidirectional connection for real-time C2
Indicators: WebSocket upgrade followed by binary frames
Cloud Services: Using legitimate APIs (Telegram, Discord, Slack, GitHub)
Indicators: API calls to cloud services from unexpected processes
Email: SMTP/IMAP for C2 commands and data exfiltration
Indicators: Automated email operations from non-email processesStep 2: Analyze Beacon Pattern
Characterize the periodic communication pattern:
from scapy.all import rdpcap, IP, TCP
from collections import defaultdict
import statistics
import json
packets = rdpcap("c2_traffic.pcap")
# Group TCP SYN packets by destination
connections = defaultdict(list)
for pkt in packets:
if IP in pkt and TCP in pkt and (pkt[TCP].flags & 0x02):
key = f"{pkt[IP].dst}:{pkt[TCP].dport}"
connections[key].append(float(pkt.time))
# Analyze each destination for beaconing
for dst, times in sorted(connections.items()):
if len(times) < 3:
continue
intervals = [times[i+1] - times[i] for i in range(len(times)-1)]
avg_interval = statistics.mean(intervals)
stdev = statistics.stdev(intervals) if len(intervals) > 1 else 0
jitter_pct = (stdev / avg_interval * 100) if avg_interval > 0 else 0
duration = times[-1] - times[0]
beacon_data = {
"destination": dst,
"connections": len(times),
"duration_seconds": round(duration, 1),
"avg_interval_seconds": round(avg_interval, 1),
"stdev_seconds": round(stdev, 1),
"jitter_percent": round(jitter_pct, 1),
"is_beacon": 5 < avg_interval < 7200 and jitter_pct < 25,
}
if beacon_data["is_beacon"]:
print(f"[!] BEACON DETECTED: {dst}")
print(f" Interval: {avg_interval:.0f}s +/- {stdev:.0f}s ({jitter_pct:.0f}% jitter)")
print(f" Sessions: {len(times)} over {duration:.0f}s")Step 3: Decode C2 Protocol Structure
Reverse engineer the message format from captured traffic:
# HTTP-based C2 protocol analysis
import dpkt
import base64
with open("c2_traffic.pcap", "rb") as f:
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
if not isinstance(eth.data, dpkt.ip.IP):
continue
ip = eth.data
if not isinstance(ip.data, dpkt.tcp.TCP):
continue
tcp = ip.data
if tcp.dport == 80 or tcp.dport == 443:
if len(tcp.data) > 0:
try:
http = dpkt.http.Request(tcp.data)
print(f"\n--- C2 REQUEST ---")
print(f"Method: {http.method}")
print(f"URI: {http.uri}")
print(f"Headers: {dict(http.headers)}")
if http.body:
print(f"Body ({len(http.body)} bytes):")
# Try Base64 decode
try:
decoded = base64.b64decode(http.body)
print(f" Decoded: {decoded[:200]}")
except:
print(f" Raw: {http.body[:200]}")
except:
passStep 4: Identify C2 Framework
Match observed patterns to known C2 frameworks:
Known C2 Framework Signatures:
━━━━━━━━━━━━━━━━━━━━━━━━━━━━
Cobalt Strike:
- Default URIs: /pixel, /submit.php, /___utm.gif, /ca, /dpixel
- Malleable C2 profiles customize all traffic characteristics
- JA3: varies by profile, catalog at ja3er.com
- Watermark in beacon config (unique per license)
- Config extraction: use CobaltStrikeParser or 1768.py
Metasploit/Meterpreter:
- Default staging URI patterns: random 4-char checksum
- Reverse HTTP(S) handler patterns
- Meterpreter TLV (Type-Length-Value) protocol structure
Sliver:
- mTLS, HTTP, DNS, WireGuard transport options
- Protobuf-encoded messages
- Unique implant ID in communication
Covenant:
- .NET-based C2 framework
- HTTP with customizable profiles
- Task-based command execution
PoshC2:
- PowerShell/C# based
- HTTP with encrypted payloads
- Cookie-based session management# Extract Cobalt Strike beacon configuration from PCAP or sample
python3 << 'PYEOF'
# Using CobaltStrikeParser (pip install cobalt-strike-parser)
from cobalt_strike_parser import BeaconConfig
try:
config = BeaconConfig.from_file("suspect.exe")
print("Cobalt Strike Beacon Configuration:")
for key, value in config.items():
print(f" {key}: {value}")
except Exception as e:
print(f"Not a Cobalt Strike beacon or parse error: {e}")
PYEOFStep 5: Map C2 Infrastructure
Document the full C2 infrastructure and failover mechanisms:
# Infrastructure mapping
import requests
import json
c2_indicators = {
"primary_c2": "185.220.101.42",
"domains": ["update.malicious.com", "backup.evil.net"],
"ports": [443, 8443],
"failover_dns": ["ns1.malicious-dns.com"],
}
# Enrich with Shodan
def shodan_lookup(ip, api_key):
resp = requests.get(f"https://api.shodan.io/shodan/host/{ip}?key={api_key}")
if resp.status_code == 200:
data = resp.json()
return {
"ip": ip,
"ports": data.get("ports", []),
"os": data.get("os"),
"org": data.get("org"),
"asn": data.get("asn"),
"country": data.get("country_code"),
"hostnames": data.get("hostnames", []),
"last_update": data.get("last_update"),
}
return None
# Enrich with passive DNS
def pdns_lookup(domain):
# Using VirusTotal passive DNS
resp = requests.get(
f"https://www.virustotal.com/api/v3/domains/{domain}/resolutions",
headers={"x-apikey": VT_API_KEY}
)
if resp.status_code == 200:
data = resp.json()
resolutions = []
for r in data.get("data", []):
resolutions.append({
"ip": r["attributes"]["ip_address"],
"date": r["attributes"]["date"],
})
return resolutions
return []Step 6: Create Network Detection Signatures
Build detection rules based on analyzed C2 characteristics:
# Suricata rules for the analyzed C2
cat << 'EOF' > c2_detection.rules
# HTTP beacon pattern
alert http $HOME_NET any -> $EXTERNAL_NET any (
msg:"MALWARE MalwareX C2 HTTP Beacon";
flow:established,to_server;
http.method; content:"POST";
http.uri; content:"/gate.php"; startswith;
http.header; content:"User-Agent: Mozilla/5.0 (compatible; MSIE 10.0)";
threshold:type threshold, track by_src, count 5, seconds 600;
sid:9000010; rev:1;
)
# JA3 fingerprint match
alert tls $HOME_NET any -> $EXTERNAL_NET any (
msg:"MALWARE MalwareX TLS JA3 Fingerprint";
ja3.hash; content:"a0e9f5d64349fb13191bc781f81f42e1";
sid:9000011; rev:1;
)
# DNS beacon detection (high-entropy subdomain)
alert dns $HOME_NET any -> any any (
msg:"MALWARE Suspected DNS C2 Tunneling";
dns.query; pcre:"/^[a-z0-9]{20,}\./";
threshold:type threshold, track by_src, count 10, seconds 60;
sid:9000012; rev:1;
)
# Certificate-based detection
alert tls $HOME_NET any -> $EXTERNAL_NET any (
msg:"MALWARE MalwareX Self-Signed C2 Certificate";
tls.cert_subject; content:"CN=update.malicious.com";
sid:9000013; rev:1;
)
EOFKey Concepts
| Term | Definition |
|---|---|
| Beaconing | Periodic check-in communication from malware to C2 server at regular intervals, often with jitter to avoid pattern detection |
| Jitter | Randomization applied to beacon interval (e.g., 60s +/- 15%) to make the timing pattern less predictable and harder to detect |
| Malleable C2 | Cobalt Strike feature allowing operators to customize all aspects of C2 traffic (URIs, headers, encoding) to mimic legitimate services |
| Dead Drop | Intermediate location (paste site, cloud storage, social media) where C2 commands are posted for the malware to retrieve |
| Domain Fronting | Using a trusted CDN domain in the TLS SNI while routing to a different backend, making C2 traffic appear to go to a legitimate service |
| Fast Flux | Rapidly changing DNS records for C2 domains to distribute across many IPs and resist takedown efforts |
| C2 Framework | Software toolkit providing C2 server, implant generator, and operator interface (Cobalt Strike, Metasploit, Sliver, Covenant) |
Tools & Systems
- Wireshark: Packet analyzer for detailed C2 protocol analysis at the packet level
- RITA (Real Intelligence Threat Analytics): Open-source tool analyzing Zeek logs for beacon detection and DNS tunneling
- CobaltStrikeParser: Tool extracting Cobalt Strike beacon configuration from samples and memory dumps
- JA3/JA3S: TLS fingerprinting method for identifying C2 frameworks by their TLS implementation characteristics
- Shodan/Censys: Internet scanning platforms for mapping C2 infrastructure and identifying related servers
Common Scenarios
Scenario: Reverse Engineering a Custom C2 Protocol
Context: A malware sample communicates with its C2 server using an unknown binary protocol over TCP port 8443. The protocol needs to be decoded to understand the command set and build detection signatures.
Approach: 1. Filter PCAP for TCP port 8443 conversations and extract the TCP streams 2. Analyze the first few exchanges to identify the handshake/authentication mechanism 3. Map the message structure (length prefix, type field, payload encoding) 4. Cross-reference with Ghidra disassembly of the send/receive functions in the malware 5. Identify the command dispatcher and document each command code's function 6. Build a protocol decoder in Python for ongoing traffic analysis 7. Create Suricata rules matching the protocol handshake or static header bytes
Pitfalls:
- Assuming the protocol is static; some C2 frameworks negotiate encryption during the handshake
- Not capturing enough traffic to see all command types (some commands are rare)
- Missing fallback C2 channels (DNS, ICMP) that activate when the primary channel fails
- Confusing encrypted payload data with the protocol framing structure
Output Format
C2 COMMUNICATION ANALYSIS REPORT
===================================
Sample: malware.exe (SHA-256: e3b0c44...)
C2 Framework: Cobalt Strike 4.9
BEACON CONFIGURATION
C2 Server: hxxps://185.220.101[.]42/updates
Beacon Type: HTTPS (reverse)
Sleep: 60 seconds
Jitter: 15%
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)
URI (GET): /dpixel
URI (POST): /submit.php
Watermark: 1234567890
PROTOCOL ANALYSIS
Transport: HTTPS (TLS 1.2)
JA3 Hash: a0e9f5d64349fb13191bc781f81f42e1
Certificate: CN=Microsoft Update (self-signed)
Encoding: Base64 with XOR key 0x69
Command Format: [4B length][4B command_id][payload]
COMMAND SET
0x01 - Sleep Change beacon interval
0x02 - Shell Execute cmd.exe command
0x03 - Download Transfer file from C2
0x04 - Upload Exfiltrate file to C2
0x05 - Inject Process injection
0x06 - Keylog Start keylogger
0x07 - Screenshot Capture screen
INFRASTRUCTURE
Primary: 185.220.101[.]42 (AS12345, Hosting Co, NL)
Failover: 91.215.85[.]17 (AS67890, VPS Provider, RU)
DNS: update.malicious[.]com -> 185.220.101[.]42
Registrar: NameCheap
Registration: 2025-09-01
DETECTION SIGNATURES
SID 9000010: HTTP beacon pattern
SID 9000011: JA3 TLS fingerprint
SID 9000013: C2 certificate match
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to the Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by the Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding any notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. Please do not remove or change
the license header comment from a contributed file except when
necessary.
Copyright 2026 mukul975
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
API Reference: C2 Communication Analysis Tools
Scapy - Packet Analysis Library (Python)
Reading PCAPs
from scapy.all import rdpcap, IP, TCP, UDP, DNS, DNSQR
packets = rdpcap("capture.pcap")Filtering Packets
# TCP SYN packets (connection initiation)
syn_pkts = [p for p in packets if TCP in p and (p[TCP].flags & 0x02)]
# DNS queries
dns_pkts = [p for p in packets if DNS in p and p[DNS].qr == 0]
# Access fields
pkt[IP].src # Source IP
pkt[IP].dst # Destination IP
pkt[TCP].sport # Source port
pkt[TCP].dport # Destination port
pkt[TCP].flags # TCP flags (0x02 = SYN)
float(pkt.time) # Packet timestampdpkt - Packet Parsing Library (Python)
Reading PCAPs
import dpkt
with open("capture.pcap", "rb") as f:
pcap = dpkt.pcap.Reader(f)
for timestamp, buf in pcap:
eth = dpkt.ethernet.Ethernet(buf)
ip = eth.data
tcp = ip.dataHTTP Request Parsing
http = dpkt.http.Request(tcp.data)
http.method # GET, POST
http.uri # /path
http.headers # dict of headers
http.body # POST bodytshark - CLI Wireshark
Beacon Analysis
tshark -r capture.pcap -T fields -e ip.dst -e tcp.dstport -e frame.time_epoch \
-Y "tcp.flags.syn==1" > syn_times.csvHTTP Extraction
tshark -r capture.pcap -Y "http.request" -T fields \
-e http.request.method -e http.host -e http.request.uri -e http.user_agentDNS Extraction
tshark -r capture.pcap -Y "dns.qr==0" -T fields \
-e dns.qry.name -e dns.qry.type -e ip.srcJA3 TLS Fingerprinting
tshark -r capture.pcap -Y "tls.handshake.type==1" -T fields \
-e ip.src -e tls.handshake.ja3CobaltStrikeParser - Beacon Config Extraction
Usage
from cobalt_strike_parser import BeaconConfig
config = BeaconConfig.from_file("beacon.bin")
for key, value in config.items():
print(f"{key}: {value}")Key Config Fields
| Field | Description |
|---|---|
BeaconType | HTTP, HTTPS, DNS, SMB |
C2Server | Primary C2 URL |
SleepTime | Beacon interval (ms) |
Jitter | Jitter percentage |
UserAgent | HTTP User-Agent string |
Watermark | License watermark ID |
Suricata - Network IDS Rules
Rule Syntax
alert <proto> <src> <port> -> <dst> <port> (msg:""; <options>; sid:N; rev:N;)Key Keywords
| Keyword | Purpose |
|---|---|
http.method | Match HTTP method |
http.uri | Match request URI |
http.header | Match header content |
ja3.hash | Match JA3 TLS fingerprint |
dns.query | Match DNS query name |
tls.cert_subject | Match TLS certificate CN |
threshold | Rate-based detection |
#!/usr/bin/env python3
"""C2 communication analysis agent for beacon detection and protocol decoding."""
import statistics
import base64
import os
import sys
from collections import defaultdict
try:
from scapy.all import rdpcap, IP, TCP, DNS, DNSQR
HAS_SCAPY = True
except ImportError:
HAS_SCAPY = False
try:
import dpkt
HAS_DPKT = True
except ImportError:
HAS_DPKT = False
def detect_beacons(pcap_path, min_connections=5, max_jitter_pct=25.0):
"""Analyze PCAP for periodic beacon patterns using TCP SYN timing."""
if not HAS_SCAPY:
print("[ERROR] scapy not installed: pip install scapy")
return []
packets = rdpcap(pcap_path)
connections = defaultdict(list)
for pkt in packets:
if IP in pkt and TCP in pkt and (pkt[TCP].flags & 0x02):
key = f"{pkt[IP].dst}:{pkt[TCP].dport}"
connections[key].append(float(pkt.time))
beacons = []
for dst, times in sorted(connections.items()):
if len(times) < min_connections:
continue
intervals = [times[i + 1] - times[i] for i in range(len(times) - 1)]
avg_interval = statistics.mean(intervals)
stdev = statistics.stdev(intervals) if len(intervals) > 1 else 0
jitter_pct = (stdev / avg_interval * 100) if avg_interval > 0 else 0
is_beacon = 5 < avg_interval < 7200 and jitter_pct < max_jitter_pct
record = {
"destination": dst,
"connections": len(times),
"duration_seconds": round(times[-1] - times[0], 1),
"avg_interval_seconds": round(avg_interval, 1),
"stdev_seconds": round(stdev, 1),
"jitter_percent": round(jitter_pct, 1),
"is_beacon": is_beacon,
}
if is_beacon:
beacons.append(record)
return beacons
def extract_http_requests(pcap_path):
"""Extract HTTP requests from a PCAP file using dpkt."""
if not HAS_DPKT:
print("[ERROR] dpkt not installed: pip install dpkt")
return []
requests = []
with open(pcap_path, "rb") as f:
pcap = dpkt.pcap.Reader(f)
for ts, buf in pcap:
try:
eth = dpkt.ethernet.Ethernet(buf)
if not isinstance(eth.data, dpkt.ip.IP):
continue
ip = eth.data
if not isinstance(ip.data, dpkt.tcp.TCP):
continue
tcp = ip.data
if len(tcp.data) == 0:
continue
try:
http = dpkt.http.Request(tcp.data)
decoded_body = None
if http.body:
try:
decoded_body = base64.b64decode(http.body).decode("utf-8", errors="replace")
except Exception:
decoded_body = http.body[:200]
requests.append({
"timestamp": ts,
"src_ip": ".".join(str(b) for b in ip.src),
"dst_ip": ".".join(str(b) for b in ip.dst),
"dst_port": tcp.dport,
"method": http.method,
"uri": http.uri,
"host": http.headers.get("host", ""),
"user_agent": http.headers.get("user-agent", ""),
"body_size": len(http.body) if http.body else 0,
"decoded_body_preview": decoded_body,
})
except (dpkt.dpkt.NeedData, dpkt.dpkt.UnpackError):
pass
except Exception:
continue
return requests
def extract_dns_queries(pcap_path):
"""Extract DNS queries from a PCAP for C2 domain identification."""
if not HAS_SCAPY:
return []
packets = rdpcap(pcap_path)
queries = []
for pkt in packets:
if DNS in pkt and pkt[DNS].qr == 0 and DNSQR in pkt:
qname = pkt[DNSQR].qname.decode("utf-8", errors="replace").rstrip(".")
queries.append({
"src_ip": pkt[IP].src if IP in pkt else "?",
"query": qname,
"type": pkt[DNSQR].qtype,
})
return queries
def identify_c2_framework(http_requests):
"""Match HTTP request patterns against known C2 framework signatures."""
cs_uris = ["/pixel", "/submit.php", "/__utm.gif", "/ca", "/dpixel",
"/push", "/visit.js", "/tab_icon"]
framework_hits = []
for req in http_requests:
uri = req.get("uri", "")
ua = req.get("user_agent", "")
for cs_uri in cs_uris:
if cs_uri in uri:
framework_hits.append({
"framework": "Cobalt Strike",
"indicator": f"URI pattern: {cs_uri}",
"request": req,
})
break
if "MeterSSL" in ua or len(uri) == 5 and uri.startswith("/"):
framework_hits.append({
"framework": "Metasploit/Meterpreter",
"indicator": f"URI/UA pattern: {uri} / {ua[:50]}",
"request": req,
})
return framework_hits
def generate_suricata_rules(beacons, http_requests):
"""Generate Suricata IDS rules from observed C2 patterns."""
rules = []
sid = 9000100
for beacon in beacons:
dst_ip, dst_port = beacon["destination"].rsplit(":", 1)
rules.append(
f'alert tcp $HOME_NET any -> {dst_ip} {dst_port} ('
f'msg:"MALWARE Detected C2 Beacon to {dst_ip}:{dst_port}"; '
f'flow:established,to_server; '
f'threshold:type threshold, track by_src, count 5, seconds 600; '
f'sid:{sid}; rev:1;)'
)
sid += 1
for req in http_requests[:5]:
if req.get("uri"):
uri = req["uri"]
rules.append(
f'alert http $HOME_NET any -> $EXTERNAL_NET any ('
f'msg:"MALWARE Suspected C2 HTTP Request {uri}"; '
f'flow:established,to_server; '
f'http.method; content:"{req["method"]}"; '
f'http.uri; content:"{uri}"; '
f'sid:{sid}; rev:1;)'
)
sid += 1
return rules
if __name__ == "__main__":
print("=" * 60)
print("C2 Communication Analysis Agent")
print("Beacon detection, protocol decoding, signature generation")
print("=" * 60)
pcap_file = sys.argv[1] if len(sys.argv) > 1 else None
if pcap_file and os.path.exists(pcap_file):
print(f"\n[*] Analyzing PCAP: {pcap_file}")
print("\n--- Beacon Detection ---")
beacons = detect_beacons(pcap_file)
for b in beacons:
print(f"[!] BEACON: {b['destination']} "
f"interval={b['avg_interval_seconds']}s "
f"jitter={b['jitter_percent']}% "
f"sessions={b['connections']}")
print("\n--- HTTP Requests ---")
http_reqs = extract_http_requests(pcap_file)
for r in http_reqs[:10]:
print(f" {r['method']} {r['host']}{r['uri']}")
print("\n--- DNS Queries ---")
dns_qs = extract_dns_queries(pcap_file)
for q in dns_qs[:10]:
print(f" {q['src_ip']} -> {q['query']}")
print("\n--- C2 Framework Identification ---")
hits = identify_c2_framework(http_reqs)
for h in hits:
print(f"[!] {h['framework']}: {h['indicator']}")
print("\n--- Suricata Rules ---")
rules = generate_suricata_rules(beacons, http_reqs)
for r in rules:
print(r)
else:
print("\n[DEMO] Usage: python agent.py <capture.pcap>")
print("[*] Provide a PCAP file to analyze for C2 communication patterns.")
Related skills
How it compares
Use as a focused security procedure skill, not a generic debugging or DevOps deploy playbook.
FAQ
Who is analyzing-command-and-control-communication for?
Developers handling their own security reviews, side-project APIs, or small prod fleets who want an agent skill oriented to C2 and beacon analysis rather than feature development.
When should I use analyzing-command-and-control-communication?
Use it in Ship (security) when reviewing suspicious traffic before launch, after a breach scare, or in Operate when correlating monitoring alerts with possible C2—always with real telemetry you can share with the agent.
Is analyzing-command-and-control-communication safe to install?
Review the Security Audits panel on this Prism page and the upstream Apache-2.0 package; do not grant broad network or shell access until you have read the full skill source and scoped agent permissions.