Master network protocol reverse engineering including packet

by wshobson · MIT license · ★ 39,857 on GitHub · updated Sep 21

Protocol reverse engineering cover

Master network protocol reverse engineering including packet analysis, protocol dissection, and custom protocol documentation. Use when analyzing network traffic, understanding proprietary protocols, or debugging network communication.

---
name: protocol-reverse-engineering
description: Master network protocol reverse engineering including packet analysis, protocol dissection, and custom protocol documentation. Use when analyzing network traffic, understanding proprietary protocols, or debugging network communication.
---

# Protocol Reverse Engineering

Comprehensive techniques for capturing, analyzing, and documenting network protocols for security research, interoperability, and debugging.

## Traffic Capture

### Wireshark Capture

```bash
# Capture on specific interface
wireshark -i eth0 -k

# Capture with filter

Overview

Comprehensive techniques for capturing, analyzing, and documenting network protocols for security research, interoperability, and debugging.

Manual install (npx, ZIP)
Claude Codenpx skills add wshobson/agents --skill protocol-reverse-engineering -g -a claude-code
Claude Code (manual)mkdir -p ~/.claude/skills && curl -sL https://codeload.github.com/wshobson/agents/tar.gz/4236bb91f839 \ | tar -xz -C ~/.claude/skills --strip-components=4 agents-4236bb91f839/plugins/reverse-engineering/skills/protocol-reverse-engineering
Windows (PowerShell)New-Item -ItemType Directory -Force "$HOME\.claude\skills" | Out-Null; Invoke-WebRequest "https://m.agentalley.io/zip/99ccf0f191f0653132f7/protocol-reverse-engineering.zip" -OutFile "$env:TEMP\protocol-reverse-engineering.zip"; Expand-Archive "$env:TEMP\protocol-reverse-engineering.zip" -DestinationPath "$HOME\.claude\skills" -Force
Claude.ai / desktopDownload the ZIP and upload it under Settings → Capabilities → Skills.
Codex, Cursor, other agentsPoint them at SKILL.md. The other files are plain text.

Connects with Agent Alley MCP · agentalley.io/mcp

Files included

  • SKILL.md12.3 KB
Read the files here
wshobson/4236bb91 file
SKILL.md
Show the full text521 lines

Protocol Reverse Engineering

Comprehensive techniques for capturing, analyzing, and documenting network protocols for security research, interoperability, and debugging.

Traffic Capture

Wireshark Capture
# Capture on specific interface
wireshark -i eth0 -k

# Capture with filter
wireshark -i eth0 -k -f "port 443"

# Capture to file
tshark -i eth0 -w capture.pcap

# Ring buffer capture (rotate files)
tshark -i eth0 -b filesize:100000 -b files:10 -w capture.pcap
tcpdump Capture
# Basic capture
tcpdump -i eth0 -w capture.pcap

# With filter
tcpdump -i eth0 port 8080 -w capture.pcap

# Capture specific bytes
tcpdump -i eth0 -s 0 -w capture.pcap  # Full packet

# Real-time display
tcpdump -i eth0 -X port 80
Man-in-the-Middle Capture
# mitmproxy for HTTP/HTTPS
mitmproxy --mode transparent -p 8080

# SSL/TLS interception
mitmproxy --mode transparent --ssl-insecure

# Dump to file
mitmdump -w traffic.mitm

# Burp Suite
# Configure browser proxy to 127.0.0.1:8080

Protocol Analysis

Wireshark Analysis
# Display filters
tcp.port == 8080
http.request.method == "POST"
ip.addr == 192.168.1.1
tcp.flags.syn == 1 && tcp.flags.ack == 0
frame contains "password"

# Following streams
Right-click > Follow > TCP Stream
Right-click > Follow > HTTP Stream

# Export objects
File > Export Objects > HTTP

# Decryption
Edit > Preferences > Protocols > TLS
  - (Pre)-Master-Secret log filename
  - RSA keys list
tshark Analysis
# Extract specific fields
tshark -r capture.pcap -T fields -e ip.src -e ip.dst -e tcp.port

# Statistics
tshark -r capture.pcap -q -z conv,tcp
tshark -r capture.pcap -q -z endpoints,ip

# Filter and extract
tshark -r capture.pcap -Y "http" -T json > http_traffic.json

# Protocol hierarchy
tshark -r capture.pcap -q -z io,phs
Scapy for Custom Analysis
from scapy.all import *

# Read pcap
packets = rdpcap("capture.pcap")

# Analyze packets
for pkt in packets:
    if pkt.haslayer(TCP):
        print(f"Src: {pkt[IP].src}:{pkt[TCP].sport}")
        print(f"Dst: {pkt[IP].dst}:{pkt[TCP].dport}")
        if pkt.haslayer(Raw):
            print(f"Data: {pkt[Raw].load[:50]}")

# Filter packets
http_packets = [p for p in packets if p.haslayer(TCP)
                and (p[TCP].sport == 80 or p[TCP].dport == 80)]

# Create custom packets
pkt = IP(dst="target")/TCP(dport=80)/Raw(load="GET / HTTP/1.1\r\n")
send(pkt)

Protocol Identification

Common Protocol Signatures
HTTP        - "HTTP/1." or "GET " or "POST " at start
TLS/SSL     - 0x16 0x03 (record layer)
DNS         - UDP port 53, specific header format
SMB         - 0xFF 0x53 0x4D 0x42 ("SMB" signature)
SSH         - "SSH-2.0" banner
FTP         - "220 " response, "USER " command
SMTP        - "220 " banner, "EHLO" command
MySQL       - 0x00 length prefix, protocol version
PostgreSQL  - 0x00 0x00 0x00 startup length
Redis       - "*" RESP array prefix
MongoDB     - BSON documents with specific header
Protocol Header Patterns
+--------+--------+--------+--------+
|  Magic number / Signature         |
+--------+--------+--------+--------+
|  Version       |  Flags          |
+--------+--------+--------+--------+
|  Length        |  Message Type   |
+--------+--------+--------+--------+
|  Sequence Number / Session ID     |
+--------+--------+--------+--------+
|  Payload...                       |
+--------+--------+--------+--------+

Binary Protocol Analysis

Structure Identification
# Common patterns in binary protocols

# Length-prefixed message
struct Message {
    uint32_t length;      # Total message length
    uint16_t msg_type;    # Message type identifier
    uint8_t  flags;       # Flags/options
    uint8_t  reserved;    # Padding/alignment
    uint8_t  payload[];   # Variable-length payload
};

# Type-Length-Value (TLV)
struct TLV {
    uint8_t  type;        # Field type
    uint16_t length;      # Field length
    uint8_t  value[];     # Field data
};

# Fixed header + variable payload
struct Packet {
    uint8_t  magic[4];    # "ABCD" signature
    uint32_t version;
    uint32_t payload_len;
    uint32_t checksum;    # CRC32 or similar
    uint8_t  payload[];
};
Python Protocol Parser
import struct
from dataclasses import dataclass

@dataclass
class MessageHeader:
    magic: bytes
    version: int
    msg_type: int
    length: int

    @classmethod
    def from_bytes(cls, data: bytes):
        magic, version, msg_type, length = struct.unpack(
            ">4sHHI", data[:12]
        )
        return cls(magic, version, msg_type, length)

def parse_messages(data: bytes):
    offset = 0
    messages = []

    while offset < len(data):
        header = MessageHeader.from_bytes(data[offset:])
        payload = data[offset+12:offset+12+header.length]
        messages.append((header, payload))
        offset += 12 + header.length

    return messages

# Parse TLV structure
def parse_tlv(data: bytes):
    fields = []
    offset = 0

    while offset < len(data):
        field_type = data[offset]
        length = struct.unpack(">H", data[offset+1:offset+3])[0]
        value = data[offset+3:offset+3+length]
        fields.append((field_type, value))
        offset += 3 + length

    return fields
Hex Dump Analysis
def hexdump(data: bytes, width: int = 16):
    """Format binary data as hex dump."""
    lines = []
    for i in range(0, len(data), width):
        chunk = data[i:i+width]
        hex_part = ' '.join(f'{b:02x}' for b in chunk)
        ascii_part = ''.join(
            chr(b) if 32 <= b < 127 else '.'
            for b in chunk
        )
        lines.append(f'{i:08x}  {hex_part:<{width*3}}  {ascii_part}')
    return '\n'.join(lines)

# Example output:
# 00000000  48 54 54 50 2f 31 2e 31  20 32 30 30 20 4f 4b 0d  HTTP/1.1 200 OK.
# 00000010  0a 43 6f 6e 74 65 6e 74  2d 54 79 70 65 3a 20 74  .Content-Type: t

Encryption Analysis

Identifying Encryption
# Entropy analysis - high entropy suggests encryption/compression
import math
from collections import Counter

def entropy(data: bytes) -> float:
    if not data:
        return 0.0
    counter = Counter(data)
    probs = [count / len(data) for count in counter.values()]
    return -sum(p * math.log2(p) for p in probs)

# Entropy thresholds:
# < 6.0: Likely plaintext or structured data
# 6.0-7.5: Possibly compressed
# > 7.5: Likely encrypted or random

# Common encryption indicators
# - High, uniform entropy
# - No obvious structure or patterns
# - Length often multiple of block size (16 for AES)
# - Possible IV at start (16 bytes for AES-CBC)
TLS Analysis
# Extract TLS metadata
tshark -r capture.pcap -Y "ssl.handshake" \
    -T fields -e ip.src -e ssl.handshake.ciphersuite

# JA3 fingerprinting (client)
tshark -r capture.pcap -Y "ssl.handshake.type == 1" \
    -T fields -e ssl.handshake.ja3

# JA3S fingerprinting (server)
tshark -r capture.pcap -Y "ssl.handshake.type == 2" \
    -T fields -e ssl.handshake.ja3s

# Certificate extraction
tshark -r capture.pcap -Y "ssl.handshake.certificate" \
    -T fields -e x509sat.printableString
Decryption Approaches
# Pre-master secret log (browser)
export SSLKEYLOGFILE=/tmp/keys.log

# Configure Wireshark
# Edit > Preferences > Protocols > TLS
# (Pre)-Master-Secret log filename: /tmp/keys.log

# Decrypt with private key (if available)
# Only works for RSA key exchange
# Edit > Preferences > Protocols > TLS > RSA keys list

Custom Protocol Documentation

Protocol Specification Template
# Protocol Name Specification

## Overview

Brief description of protocol purpose and design.

## Transport

- Layer: TCP/UDP
- Port: XXXX
- Encryption: TLS 1.2+

## Message Format

### Header (12 bytes)

| Offset | Size | Field   | Description             |
| ------ | ---- | ------- | ----------------------- |
| 0      | 4    | Magic   | 0x50524F54 ("PROT")     |
| 4      | 2    | Version | Protocol version (1)    |
| 6      | 2    | Type    | Message type identifier |
| 8      | 4    | Length  | Payload length in bytes |

### Message Types

| Type | Name      | Description            |
| ---- | --------- | ---------------------- |
| 0x01 | HELLO     | Connection initiation  |
| 0x02 | HELLO_ACK | Connection accepted    |
| 0x03 | DATA      | Application data       |
| 0x04 | CLOSE     | Connection termination |

### Type 0x01: HELLO

| Offset | Size | Field      | Description              |
| ------ | ---- | ---------- | ------------------------ |
| 0      | 4    | ClientID   | Unique client identifier |
| 4      | 2    | Flags      | Connection flags         |
| 6      | var  | Extensions | TLV-encoded extensions   |

## State Machine

[INIT] --HELLO--> [WAIT_ACK] --HELLO_ACK--> [CONNECTED] | DATA/DATA | [CLOSED] <--CLOSE--+


## Examples
### Connection Establishment

Client -> Server: HELLO (ClientID=0x12345678) Server -> Client: HELLO_ACK (Status=OK) Client -> Server: DATA (payload)

Wireshark Dissector (Lua)
-- custom_protocol.lua
local proto = Proto("custom", "Custom Protocol")

-- Define fields
local f_magic = ProtoField.string("custom.magic", "Magic")
local f_version = ProtoField.uint16("custom.version", "Version")
local f_type = ProtoField.uint16("custom.type", "Type")
local f_length = ProtoField.uint32("custom.length", "Length")
local f_payload = ProtoField.bytes("custom.payload", "Payload")

proto.fields = { f_magic, f_version, f_type, f_length, f_payload }

-- Message type names
local msg_types = {
    [0x01] = "HELLO",
    [0x02] = "HELLO_ACK",
    [0x03] = "DATA",
    [0x04] = "CLOSE"
}

function proto.dissector(buffer, pinfo, tree)
    pinfo.cols.protocol = "CUSTOM"

    local subtree = tree:add(proto, buffer())

    -- Parse header
    subtree:add(f_magic, buffer(0, 4))
    subtree:add(f_version, buffer(4, 2))

    local msg_type = buffer(6, 2):uint()
    subtree:add(f_type, buffer(6, 2)):append_text(
        " (" .. (msg_types[msg_type] or "Unknown") .. ")"
    )

    local length = buffer(8, 4):uint()
    subtree:add(f_length, buffer(8, 4))

    if length > 0 then
        subtree:add(f_payload, buffer(12, length))
    end
end

-- Register for TCP port
local tcp_table = DissectorTable.get("tcp.port")
tcp_table:add(8888, proto)

Active Testing

Fuzzing with Boofuzz
from boofuzz import *

def main():
    session = Session(
        target=Target(
            connection=TCPSocketConnection("target", 8888)
        )
    )

    # Define protocol structure
    s_initialize("HELLO")
    s_static(b"\x50\x52\x4f\x54")  # Magic
    s_word(1, name="version")       # Version
    s_word(0x01, name="type")       # Type (HELLO)
    s_size("payload", length=4)     # Length field
    s_block_start("payload")
    s_dword(0x12345678, name="client_id")
    s_word(0, name="flags")
    s_block_end()

    session.connect(s_get("HELLO"))
    session.fuzz()

if __name__ == "__main__":
    main()
Replay and Modification
from scapy.all import *

# Replay captured traffic
packets = rdpcap("capture.pcap")
for pkt in packets:
    if pkt.haslayer(TCP) and pkt[TCP].dport == 8888:
        send(pkt)

# Modify and replay
for pkt in packets:
    if pkt.haslayer(Raw):
        # Modify payload
        original = pkt[Raw].load
        modified = original.replace(b"client", b"CLIENT")
        pkt[Raw].load = modified
        # Recalculate checksums
        del pkt[IP].chksum
        del pkt[TCP].chksum
        send(pkt)

Best Practices

Analysis Workflow
  1. Capture traffic: Multiple sessions, different scenarios
  2. Identify boundaries: Message start/end markers
  3. Map structure: Fixed header, variable payload
  4. Identify fields: Compare multiple samples
  5. Document format: Create specification
  6. Validate understanding: Implement parser/generator
  7. Test edge cases: Fuzzing, boundary conditions
Common Patterns to Look For
  • Magic numbers/signatures at message start
  • Version fields for compatibility
  • Length fields (often before variable data)
  • Type/opcode fields for message identification
  • Sequence numbers for ordering
  • Checksums/CRCs for integrity
  • Timestamps for timing
  • Session/connection identifiers
1---
2name: protocol-reverse-engineering
3description: Master network protocol reverse engineering including packet analysis, protocol dissection, and custom protocol documentation. Use when analyzing network traffic, understanding proprietary protocols, or debugging network communication.
4---
5 
6# Protocol Reverse Engineering
7 
8Comprehensive techniques for capturing, analyzing, and documenting network protocols for security research, interoperability, and debugging.
9 
10## Traffic Capture
11 
12### Wireshark Capture
13 
14```bash
15# Capture on specific interface
16wireshark -i eth0 -k
17 
18# Capture with filter
19wireshark -i eth0 -k -f "port 443"
20 
21# Capture to file
22tshark -i eth0 -w capture.pcap
23 
24# Ring buffer capture (rotate files)
25tshark -i eth0 -b filesize:100000 -b files:10 -w capture.pcap
26```
27 
28### tcpdump Capture
29 
30```bash
31# Basic capture
32tcpdump -i eth0 -w capture.pcap
33 
34# With filter
35tcpdump -i eth0 port 8080 -w capture.pcap
36 
37# Capture specific bytes
38tcpdump -i eth0 -s 0 -w capture.pcap # Full packet
39 
40# Real-time display
41tcpdump -i eth0 -X port 80
42```
43 
44### Man-in-the-Middle Capture
45 
46```bash
47# mitmproxy for HTTP/HTTPS
48mitmproxy --mode transparent -p 8080
49 
50# SSL/TLS interception
51mitmproxy --mode transparent --ssl-insecure
52 
53# Dump to file
54mitmdump -w traffic.mitm
55 
56# Burp Suite
57# Configure browser proxy to 127.0.0.1:8080
58```
59 
60## Protocol Analysis
61 
62### Wireshark Analysis
63 
64```
65# Display filters
66tcp.port == 8080
67http.request.method == "POST"
68ip.addr == 192.168.1.1
69tcp.flags.syn == 1 && tcp.flags.ack == 0
70frame contains "password"
71 
72# Following streams
73Right-click > Follow > TCP Stream
74Right-click > Follow > HTTP Stream
75 
76# Export objects
77File > Export Objects > HTTP
78 
79# Decryption
80Edit > Preferences > Protocols > TLS
81 - (Pre)-Master-Secret log filename
82 - RSA keys list
83```
84 
85### tshark Analysis
86 
87```bash
88# Extract specific fields
89tshark -r capture.pcap -T fields -e ip.src -e ip.dst -e tcp.port
90 
91# Statistics
92tshark -r capture.pcap -q -z conv,tcp
93tshark -r capture.pcap -q -z endpoints,ip
94 
95# Filter and extract
96tshark -r capture.pcap -Y "http" -T json > http_traffic.json
97 
98# Protocol hierarchy
99tshark -r capture.pcap -q -z io,phs
100```
101 
102### Scapy for Custom Analysis
103 
104```python
105from scapy.all import *
106 
107# Read pcap
108packets = rdpcap("capture.pcap")
109 
110# Analyze packets
111for pkt in packets:
112 if pkt.haslayer(TCP):
113 print(f"Src: {pkt[IP].src}:{pkt[TCP].sport}")
114 print(f"Dst: {pkt[IP].dst}:{pkt[TCP].dport}")
115 if pkt.haslayer(Raw):
116 print(f"Data: {pkt[Raw].load[:50]}")
117 
118# Filter packets
119http_packets = [p for p in packets if p.haslayer(TCP)
120 and (p[TCP].sport == 80 or p[TCP].dport == 80)]
121 
122# Create custom packets
123pkt = IP(dst="target")/TCP(dport=80)/Raw(load="GET / HTTP/1.1\r\n")
124send(pkt)
125```
126 
127## Protocol Identification
128 
129### Common Protocol Signatures
130 
131```
132HTTP - "HTTP/1." or "GET " or "POST " at start
133TLS/SSL - 0x16 0x03 (record layer)
134DNS - UDP port 53, specific header format
135SMB - 0xFF 0x53 0x4D 0x42 ("SMB" signature)
136SSH - "SSH-2.0" banner
137FTP - "220 " response, "USER " command
138SMTP - "220 " banner, "EHLO" command
139MySQL - 0x00 length prefix, protocol version
140PostgreSQL - 0x00 0x00 0x00 startup length
141Redis - "*" RESP array prefix
142MongoDB - BSON documents with specific header
143```
144 
145### Protocol Header Patterns
146 
147```
148+--------+--------+--------+--------+
149| Magic number / Signature |
150+--------+--------+--------+--------+
151| Version | Flags |
152+--------+--------+--------+--------+
153| Length | Message Type |
154+--------+--------+--------+--------+
155| Sequence Number / Session ID |
156+--------+--------+--------+--------+
157| Payload... |
158+--------+--------+--------+--------+
159```
160 
161## Binary Protocol Analysis
162 
163### Structure Identification
164 
165```python
166# Common patterns in binary protocols
167 
168# Length-prefixed message
169struct Message {
170 uint32_t length; # Total message length
171 uint16_t msg_type; # Message type identifier
172 uint8_t flags; # Flags/options
173 uint8_t reserved; # Padding/alignment
174 uint8_t payload[]; # Variable-length payload
175};
176 
177# Type-Length-Value (TLV)
178struct TLV {
179 uint8_t type; # Field type
180 uint16_t length; # Field length
181 uint8_t value[]; # Field data
182};
183 
184# Fixed header + variable payload
185struct Packet {
186 uint8_t magic[4]; # "ABCD" signature
187 uint32_t version;
188 uint32_t payload_len;
189 uint32_t checksum; # CRC32 or similar
190 uint8_t payload[];
191};
192```
193 
194### Python Protocol Parser
195 
196```python
197import struct
198from dataclasses import dataclass
199 
200@dataclass
201class MessageHeader:
202 magic: bytes
203 version: int
204 msg_type: int
205 length: int
206 
207 @classmethod
208 def from_bytes(cls, data: bytes):
209 magic, version, msg_type, length = struct.unpack(
210 ">4sHHI", data[:12]
211 )
212 return cls(magic, version, msg_type, length)
213 
214def parse_messages(data: bytes):
215 offset = 0
216 messages = []
217 
218 while offset < len(data):
219 header = MessageHeader.from_bytes(data[offset:])
220 payload = data[offset+12:offset+12+header.length]
221 messages.append((header, payload))
222 offset += 12 + header.length
223 
224 return messages
225 
226# Parse TLV structure
227def parse_tlv(data: bytes):
228 fields = []
229 offset = 0
230 
231 while offset < len(data):
232 field_type = data[offset]
233 length = struct.unpack(">H", data[offset+1:offset+3])[0]
234 value = data[offset+3:offset+3+length]
235 fields.append((field_type, value))
236 offset += 3 + length
237 
238 return fields
239```
240 
241### Hex Dump Analysis
242 
243```python
244def hexdump(data: bytes, width: int = 16):
245 """Format binary data as hex dump."""
246 lines = []
247 for i in range(0, len(data), width):
248 chunk = data[i:i+width]
249 hex_part = ' '.join(f'{b:02x}' for b in chunk)
250 ascii_part = ''.join(
251 chr(b) if 32 <= b < 127 else '.'
252 for b in chunk
253 )
254 lines.append(f'{i:08x} {hex_part:<{width*3}} {ascii_part}')
255 return '\n'.join(lines)
256 
257# Example output:
258# 00000000 48 54 54 50 2f 31 2e 31 20 32 30 30 20 4f 4b 0d HTTP/1.1 200 OK.
259# 00000010 0a 43 6f 6e 74 65 6e 74 2d 54 79 70 65 3a 20 74 .Content-Type: t
260```
261 
262## Encryption Analysis
263 
264### Identifying Encryption
265 
266```python
267# Entropy analysis - high entropy suggests encryption/compression
268import math
269from collections import Counter
270 
271def entropy(data: bytes) -> float:
272 if not data:
273 return 0.0
274 counter = Counter(data)
275 probs = [count / len(data) for count in counter.values()]
276 return -sum(p * math.log2(p) for p in probs)
277 
278# Entropy thresholds:
279# < 6.0: Likely plaintext or structured data
280# 6.0-7.5: Possibly compressed
281# > 7.5: Likely encrypted or random
282 
283# Common encryption indicators
284# - High, uniform entropy
285# - No obvious structure or patterns
286# - Length often multiple of block size (16 for AES)
287# - Possible IV at start (16 bytes for AES-CBC)
288```
289 
290### TLS Analysis
291 
292```bash
293# Extract TLS metadata
294tshark -r capture.pcap -Y "ssl.handshake" \
295 -T fields -e ip.src -e ssl.handshake.ciphersuite
296 
297# JA3 fingerprinting (client)
298tshark -r capture.pcap -Y "ssl.handshake.type == 1" \
299 -T fields -e ssl.handshake.ja3
300 
301# JA3S fingerprinting (server)
302tshark -r capture.pcap -Y "ssl.handshake.type == 2" \
303 -T fields -e ssl.handshake.ja3s
304 
305# Certificate extraction
306tshark -r capture.pcap -Y "ssl.handshake.certificate" \
307 -T fields -e x509sat.printableString
308```
309 
310### Decryption Approaches
311 
312```bash
313# Pre-master secret log (browser)
314export SSLKEYLOGFILE=/tmp/keys.log
315 
316# Configure Wireshark
317# Edit > Preferences > Protocols > TLS
318# (Pre)-Master-Secret log filename: /tmp/keys.log
319 
320# Decrypt with private key (if available)
321# Only works for RSA key exchange
322# Edit > Preferences > Protocols > TLS > RSA keys list
323```
324 
325## Custom Protocol Documentation
326 
327### Protocol Specification Template
328 
329```markdown
330# Protocol Name Specification
331 
332## Overview
333 
334Brief description of protocol purpose and design.
335 
336## Transport
337 
338- Layer: TCP/UDP
339- Port: XXXX
340- Encryption: TLS 1.2+
341 
342## Message Format
343 
344### Header (12 bytes)
345 
346| Offset | Size | Field | Description |
347| ------ | ---- | ------- | ----------------------- |
348| 0 | 4 | Magic | 0x50524F54 ("PROT") |
349| 4 | 2 | Version | Protocol version (1) |
350| 6 | 2 | Type | Message type identifier |
351| 8 | 4 | Length | Payload length in bytes |
352 
353### Message Types
354 
355| Type | Name | Description |
356| ---- | --------- | ---------------------- |
357| 0x01 | HELLO | Connection initiation |
358| 0x02 | HELLO_ACK | Connection accepted |
359| 0x03 | DATA | Application data |
360| 0x04 | CLOSE | Connection termination |
361 
362### Type 0x01: HELLO
363 
364| Offset | Size | Field | Description |
365| ------ | ---- | ---------- | ------------------------ |
366| 0 | 4 | ClientID | Unique client identifier |
367| 4 | 2 | Flags | Connection flags |
368| 6 | var | Extensions | TLV-encoded extensions |
369 
370## State Machine
371```
372 
373[INIT] --HELLO--> [WAIT_ACK] --HELLO_ACK--> [CONNECTED]
374|
375DATA/DATA
376|
377[CLOSED] <--CLOSE--+
378 
379```
380 
381## Examples
382### Connection Establishment
383```
384 
385Client -> Server: HELLO (ClientID=0x12345678)
386Server -> Client: HELLO_ACK (Status=OK)
387Client -> Server: DATA (payload)
388 
389```
390 
391```
392 
393### Wireshark Dissector (Lua)
394 
395```lua
396-- custom_protocol.lua
397local proto = Proto("custom", "Custom Protocol")
398 
399-- Define fields
400local f_magic = ProtoField.string("custom.magic", "Magic")
401local f_version = ProtoField.uint16("custom.version", "Version")
402local f_type = ProtoField.uint16("custom.type", "Type")
403local f_length = ProtoField.uint32("custom.length", "Length")
404local f_payload = ProtoField.bytes("custom.payload", "Payload")
405 
406proto.fields = { f_magic, f_version, f_type, f_length, f_payload }
407 
408-- Message type names
409local msg_types = {
410 [0x01] = "HELLO",
411 [0x02] = "HELLO_ACK",
412 [0x03] = "DATA",
413 [0x04] = "CLOSE"
414}
415 
416function proto.dissector(buffer, pinfo, tree)
417 pinfo.cols.protocol = "CUSTOM"
418 
419 local subtree = tree:add(proto, buffer())
420 
421 -- Parse header
422 subtree:add(f_magic, buffer(0, 4))
423 subtree:add(f_version, buffer(4, 2))
424 
425 local msg_type = buffer(6, 2):uint()
426 subtree:add(f_type, buffer(6, 2)):append_text(
427 " (" .. (msg_types[msg_type] or "Unknown") .. ")"
428 )
429 
430 local length = buffer(8, 4):uint()
431 subtree:add(f_length, buffer(8, 4))
432 
433 if length > 0 then
434 subtree:add(f_payload, buffer(12, length))
435 end
436end
437 
438-- Register for TCP port
439local tcp_table = DissectorTable.get("tcp.port")
440tcp_table:add(8888, proto)
441```
442 
443## Active Testing
444 
445### Fuzzing with Boofuzz
446 
447```python
448from boofuzz import *
449 
450def main():
451 session = Session(
452 target=Target(
453 connection=TCPSocketConnection("target", 8888)
454 )
455 )
456 
457 # Define protocol structure
458 s_initialize("HELLO")
459 s_static(b"\x50\x52\x4f\x54") # Magic
460 s_word(1, name="version") # Version
461 s_word(0x01, name="type") # Type (HELLO)
462 s_size("payload", length=4) # Length field
463 s_block_start("payload")
464 s_dword(0x12345678, name="client_id")
465 s_word(0, name="flags")
466 s_block_end()
467 
468 session.connect(s_get("HELLO"))
469 session.fuzz()
470 
471if __name__ == "__main__":
472 main()
473```
474 
475### Replay and Modification
476 
477```python
478from scapy.all import *
479 
480# Replay captured traffic
481packets = rdpcap("capture.pcap")
482for pkt in packets:
483 if pkt.haslayer(TCP) and pkt[TCP].dport == 8888:
484 send(pkt)
485 
486# Modify and replay
487for pkt in packets:
488 if pkt.haslayer(Raw):
489 # Modify payload
490 original = pkt[Raw].load
491 modified = original.replace(b"client", b"CLIENT")
492 pkt[Raw].load = modified
493 # Recalculate checksums
494 del pkt[IP].chksum
495 del pkt[TCP].chksum
496 send(pkt)
497```
498 
499## Best Practices
500 
501### Analysis Workflow
502 
5031. **Capture traffic**: Multiple sessions, different scenarios
5042. **Identify boundaries**: Message start/end markers
5053. **Map structure**: Fixed header, variable payload
5064. **Identify fields**: Compare multiple samples
5075. **Document format**: Create specification
5086. **Validate understanding**: Implement parser/generator
5097. **Test edge cases**: Fuzzing, boundary conditions
510 
511### Common Patterns to Look For
512 
513- Magic numbers/signatures at message start
514- Version fields for compatibility
515- Length fields (often before variable data)
516- Type/opcode fields for message identification
517- Sequence numbers for ordering
518- Checksums/CRCs for integrity
519- Timestamps for timing
520- Session/connection identifiers
521 
View all files on GitHub →

Details

Updated
Sep 21, 2026
License
MIT
Stars on the repo
★ 39,857
Checked
Source
wshobson/agents ↗
Creator
wshobson · 179 listings
View creator

Similar skills

See all →
SkillGenerate CHANGELOG.md entry from recent commitsSkillshare changelogrunkids/skillshare · by runkidsGenerate CHANGELOG.md entry from recent commits in conventional format. Also syncs the website changelog page. Use this skill whenever the user asks to: generate a changelog, document what changed between tags, or create a new CHANGELOG entry. If you see requests like "write the changelog for v0.17", what changed since last release", this is the skill to use. Do NOT manually edit CHANGELOG.md without this skill — it ensures proper formatting, user-perspective writing, and website changelog sync. For full release workflows (Release PR review, tests, draft assets, publication, announcements), use /release instead.★ 2.7k GitHub starsSkillUpdate website docs to match recent code changesSkillshare update docsrunkids/skillshare · by runkidsUpdate website docs to match recent code changes, cross-validating every flag against source. Use this skill whenever the user asks to: update documentation, sync docs with code, document a new flag or command, fix stale docs, or update the README. This skill covers all website/docs/ categories (commands, reference, understand, how-to, troubleshooting, getting-started) plus the built-in skill description and README. If you just implemented a feature and need to update docs, this is the skill to use. Never manually edit website docs without cross-validating flags against Go source first.★ 2.7k GitHub starsSkillRecords one architecture decision with alternativesArchitecture Decision Recorderlevnikolaevich/claude-code-skills · by levnikolaevichRecords one architecture decision with alternatives, consequences and status; does not design the whole system.★ 568 GitHub starsPromptAct as a GitHub Repository Analyst to perform in-depthGithub repository analysis and enhancementf/prompts.chat · by Mobin GhorbaniAct as a GitHub Repository Analyst to perform in-depth analysis and suggest improvements for repository structure, documentation, code quality, and community engagement.New listingPromptAct as a GitHub Repository Analystf/prompts.chat · by Yury SamAct as a GitHub Repository Analyst. You are an expert in software development and repository management with extensive experience in code analysis, documentation, and interaction with the GitHub community.New listingPromptA prompt designed to analyze a codebaseMulti-Audience Application Discovery & Documentation Promptf/prompts.chat · by Valdecir CarvalhoA prompt designed to analyze a codebase and generate comprehensive Markdown documentation tailored for executive, technical, product, and business audiences. It guides an AI to extract high-level system purpose, architecture, key components, workflows, product features, business domains, and limitations, producing an onboarding and discovery document suitable for both technical and non-technical stakeholders.New listing

More from wshobson

SkillMaster C/.NET backend development patterns for buildingwshobson/agents · by wshobsonMaster C#/.NET backend development patterns for building robust APIs, MCP servers, and enterprise applications. Covers async/await, dependency injection, Entity Framework Core, Dapper, configuration, caching, and testing with xUnit. Use when developing .NET backends, reviewing C# code, or designing API architectures.★ 39.9k GitHub starsSkillImplement WCAG 2.2 compliant interfaces with mobileAccessibility compliancewshobson/agents · by wshobsonImplement WCAG 2.2 compliant interfaces with mobile accessibility, inclusive design patterns, and assistive technology support. Use when auditing accessibility, implementing ARIA patterns, building for screen readers, or ensuring inclusive user experiences.★ 39.9k GitHub starsSkillMaster Material Design 3 and Jetpack Compose patternsAndroid Mobile Designwshobson/agents · by wshobsonMaster Material Design 3 and Jetpack Compose patterns for building native Android apps. Use when designing Android interfaces, implementing Compose UI, or following Google's Material Design guidelines.★ 39.9k GitHub starsSkillMigrate from AngularJS to Angular using hybrid modeAngular migrationwshobson/agents · by wshobsonMigrate from AngularJS to Angular using hybrid mode, incremental component rewriting, and dependency injection updates. Use when upgrading AngularJS applications, planning framework migrations, or modernizing legacy Angular code.★ 39.9k GitHub starsSkillUnderstand anti-reversing, obfuscationAnti reversing techniqueswshobson/agents · by wshobsonUnderstand anti-reversing, obfuscation, and protection techniques encountered during software analysis. Use this skill when analyzing malware evasion techniques, when implementing anti-debugging protections for CTF challenges, when reverse engineering packed binaries, or when building security research tools that need to detect virtualized environments.★ 39.9k GitHub starsSkillBuild production Apache Airflow DAGs with best practicesApache Airflow DAG Patternswshobson/agents · by wshobsonBuild production Apache Airflow DAGs with best practices for operators, sensors, testing, and deployment. Use when creating data pipelines, orchestrating workflows, or scheduling batch jobs.★ 39.9k GitHub stars