Post

TryHackMe: Mayhem

TryHackMe: Mayhem

In this walkthrough, two methods for analyzing a malicious traffic capture (traffic.pcapng) associated with the Havoc Command and Control (C2) framework are explored. The goal is to extract critical forensic details such as encrypted payloads, AES keys, IVs, and agent information.

  • Option 1 involves a manual process using Wireshark and CyberChef.
  • Option 2 leverages an automated Python script (havoc-pcap-parser.py) for faster analysis.

Both methods enable decryption of the traffic and the extraction of key information used by the attacker.

Tryhackme Room Link https://tryhackme.com/room/mayhemroom

Starting

The analysis of traffic.pcapng in Wireshark revealed suspicious traffic, with notepad.exe being downloaded from the Attacker’s IP (10.0.2.37) to the target system (10.0.2.38). After extracting the file and checking its SHA256 hash on VirusTotal, it was flagged as malicious. The file was identified as a Trojan or backdoor, likely part of the Havoc C2 framework, enabling remote access to the compromised system.

After researching, the Havoc Framework GitHub and a detailed guide on Havoc C2 were found. These resources helped in understanding key components of the framework, such as the magic byte, AES key, IV, and agent ID, which were essential for analyzing the traffic and decryption process.

1
2
3
4
5
6
7
8
Here, are the things to focus on:

length field: 00000113
Magic Byte: deadbeef [ ! important ]
Agent ID: 0e9fb7d8...
AES Key: 946cf2f65ac2d2b8683... [64-bits]
IV: 8cd00c3e349290565... [32-bits]
Data: [DATA]

Option 1: Manual Analysis

Wireshark

The traffic.pcapng file was opened in Wireshark, and filters were applied to focus on relevant packets. Specifically, the filter http.request.method == "POST" was used to capture HTTP POST requests, and the deadbeef HEX value was filtered to identify specific traffic related to the Havoc C2 framework.

Wireshark

Cyberchef

The TCP segment data from packet 239 was copied and provided to CyberChef for further analysis. Each TCP segment was then opened in CyberChef to extract and answer the questions.

CyberChef

Option 2: Automation using Havoc-c2-Forensics

Before proceeding make sure pyshark is installed on your system.

We downloaded the havoc-pcap-parser.py script from the Havoc-c2-Forensics GitHub and ran it with the following commands:

1
python3 havoc-pcap-parser.py --pcap traffic.pcapng --save .
1
cat *

Havoc-c2-Forensics

Although the output was somewhat obfuscated, all the necessary information was extracted. For a cleaner output, an additional script provided by 0xb0b is recommended.

Here is the script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
# Copyright (C) 2024 Kev Breen, Immersive Labs
# https://github.com/Immersive-Labs-Sec/HavocC2-Forensics
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:

# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.

# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
import os
import argparse
import struct
import binascii
from binascii import unhexlify

from uuid import uuid4


try:
    import pyshark
except ImportError:
    print("[-] Pyshark not installed, please install with 'pip install pyshark'")
    exit(0)

try:
    from Crypto.Cipher import AES
    from Crypto.Util import Counter
except ImportError:
    print("[-] PyCryptodome not installed, please install with 'pip install pycryptodome'")
    exit(0)



demon_constants = {
    1: "GET_JOB",
    10: 'COMMAND_NOJOB',
    11: 'SLEEP',
    12: 'COMMAND_PROC_LIST',
    15: 'COMMAND_FS',
    20: 'COMMAND_INLINEEXECUTE',
    21: 'COMMAND_JOB',
    22: 'COMMAND_INJECT_DLL',
    24: 'COMMAND_INJECT_SHELLCODE',
    26: 'COMMAND_SPAWNDLL',
    27: 'COMMAND_PROC_PPIDSPOOF',
    40: 'COMMAND_TOKEN',
    99: 'DEMON_INIT',
    100: 'COMMAND_CHECKIN',
    2100: 'COMMAND_NET',
    2500: 'COMMAND_CONFIG',
    2510: 'COMMAND_SCREENSHOT',
    2520: 'COMMAND_PIVOT',
    2530: 'COMMAND_TRANSFER',
    2540: 'COMMAND_SOCKET',
    2550: 'COMMAND_KERBEROS',
    2560: 'COMMAND_MEM_FILE', # Beacon Object File
    4112: 'COMMAND_PROC', # Shell Command
    4113: 'COMMMAND_PS_IMPORT',
    8193: 'COMMAND_ASSEMBLY_INLINE_EXECUTE',
    8195: 'COMMAND_ASSEMBLY_LIST_VERSIONS',
}


# Used to store the AES Keys for each session
sessions = {}


def tsharkbody_to_bytes(hex_string):
    """
    Converts a TShark hex formated string to a byte string.
    
    :param hex_string: The hex string from TShark.
    :return: The byte string.
    """
    # its concatonated strings
    hex_string = hex_string.replace(':', '')
    #unhex it
    hex_bytes = unhexlify(hex_string)
    return hex_bytes



def aes_decrypt_ctr(aes_key, aes_iv, encrypted_payload):
    """
    Decrypts an AES-encrypted payload in CTR mode.

    :param aes_key: The AES key as a byte string.
    :param aes_iv: The AES IV (Initialization Vector) for the counter, as a byte string.
    :param encrypted_payload: The encrypted payload as a byte string.
    :return: The decrypted plaintext as a byte string.
    """
    # Initialize the counter for CTR mode
    ctr = Counter.new(128, initial_value=int.from_bytes(aes_iv, byteorder='big'))

    # Create the cipher in CTR mode
    cipher = AES.new(aes_key, AES.MODE_CTR, counter=ctr)

    # Decrypt the payload
    decrypted_payload = cipher.decrypt(encrypted_payload)

    return decrypted_payload



def parse_header(header_bytes):
    """
    Parses a 20-byte header into an object.

    :param header_bytes: A 20-byte header.
    :return: A dictionary representing the parsed header.
    """
    if len(header_bytes) != 20:
        raise ValueError("Header must be exactly 20 bytes long")

    # Unpack the header
    payload_size, magic_bytes, agent_id, command_id, mem_id = struct.unpack('>I4s4sI4s', header_bytes)

    # Convert bytes to appropriate representations
    magic_bytes_str = binascii.hexlify(magic_bytes).decode('ascii')
    agent_id_str = binascii.hexlify(agent_id).decode('ascii')
    mem_id_str = binascii.hexlify(mem_id).decode('ascii')
    command_name = demon_constants.get(command_id, f'Unknown Command ID: {command_id}')

    return {
        'payload_size': payload_size,
        'magic_bytes': magic_bytes_str,
        'agent_id': agent_id_str,
        'command_id': command_name,
        'mem_id': mem_id_str
    }


def parse_request(http_pair, magic_bytes, save_path):
    request = http_pair['request']
    response = http_pair['response']#

    unique_id = uuid4()

    print("[+] Parsing Request")


    try:
        request_body = tsharkbody_to_bytes(request.get('file_data', ''))
        header_bytes = request_body[:20]
        request_payload = request_body[20:]
        request_header = parse_header(header_bytes)
    except Exception as e:
        print(f"[!] Error parsing request body: {e}")
        return


    # If there is no magic this is not Havoc
    if request_header.get("magic_bytes", '') != magic_bytes:
        return


    if request_header['command_id'] == 'DEMON_INIT':
        print("[+] Found Havoc C2")
        print(f"  [-] Agent ID: {request_header['agent_id']}")
        print(f"  [-] Magic Bytes: {request_header['magic_bytes']}")
        print(f"  [-] C2 Address: {request.get('uri')}")

        aes_key = request_body[20:52]
        aes_iv = request_body[52:68]

        print(f"  [+] Found AES Key")
        print(f"    [-] Key: {binascii.hexlify(aes_key).decode('ascii')}")
        print(f"    [-] IV: {binascii.hexlify(aes_iv).decode('ascii')}")

        if request_header['agent_id'] not in sessions:
            sessions[request_header['agent_id']] = {
                "aes_key": aes_key,
                "aes_iv": aes_iv
            }
        
        # We dont want to process the rest of the request
        response_payload = None

    elif request_header['command_id'] == 'GET_JOB':
        print("  [+] Job Request from Server to Agent")
         # if the pcap did not contain an init or we have manually passed keys add the found keys message
        
        # Grab the response header to get the incoming request. 

        try:
            response_body = tsharkbody_to_bytes(response.get('file_data', ''))

        except Exception as e:
            print(f"[!] Error parsing request body: {e}")
            return


        header_bytes = response_body[:12]
        response_payload = response_body[12:]
        command_id = struct.unpack('<H', header_bytes[:2])[0]

        command = demon_constants.get(command_id, f'Unknown Command ID: {command_id}')

        print(f"    [-] C2 Address: {request.get('uri')}")
        print(f"    [-] Comamnd: {command}")

    else:
        print(f"  [+] Unknown Command: {request_header['command_id']}")
        response_payload = None

    # If we have keys lets decode the payload
    aes_keys = sessions.get(request_header['agent_id'], None)

    if not aes_keys:
        print(f"[!] No AES Keys for Agent with ID {request_header['agent_id']}")
        return

    # If save_path is set, make sure the directory exists
    if save_path and not os.path.exists(save_path):
        print(f"[!] Save path {save_path} does not exist, creating")
        os.makedirs(save_path)

    # Decrypt the Request Body
    if request_payload:
        print("  [+] Decrypting Request Body")
        decrypted_request = aes_decrypt_ctr(aes_keys['aes_key'], aes_keys['aes_iv'], request_payload)
    
        # Always print
        decoded = decrypted_request.decode('utf-8', errors='ignore').strip()
        print(f"\n\033[92m[Decrypted Request]\033[0m\n{decoded}\n\n")

        # Save only if save_path is set
        if save_path:
            save_file = f'{save_path}/{unique_id}-request-{request_header["agent_id"]}.bin'
            with open(save_file, 'wb') as output_file:
                output_file.write(decrypted_request)

    # Decrypt the Response Body
    if response_payload:
        print("  [+] Decrypting Response Body")
        
        decrypted_response = aes_decrypt_ctr(aes_keys['aes_key'], aes_keys['aes_iv'], response_payload)
    
        # Always print
        decoded = decrypted_response.decode('utf-8', errors='ignore').strip()
        print(f"\n\033[94m[Decrypted Response - {command}]\033[0m\n{decoded}\n\n")

        # Save only if save_path is set
        if save_path:
            save_file = f'{save_path}/{unique_id}-response-{request_header["agent_id"]}.bin'
            with open(save_file, 'wb') as output_file:
                output_file.write(decrypted_response)


def read_pcap_and_get_http_pairs(pcap_file, magic_bytes, save_path):
    capture = pyshark.FileCapture(pcap_file, display_filter='http')
    http_pairs = {}
    current_stream = None
    request_data = None

    print("[+] Parsing Packets")

    for packet in capture:
        try:
            # Check if we are still in the same TCP stream
            if current_stream != packet.tcp.stream:
                # Reset for a new stream
                current_stream = packet.tcp.stream
                request_data = None

            if 'HTTP' in packet:
                if hasattr(packet.http, 'request_method'):
                    # This is a request
                    request_data = {
                        'method': packet.http.request_method,
                        'uri': packet.http.request_full_uri,
                        'headers': packet.http.get_field_value('request_line'),
                        'file_data': packet.http.file_data if hasattr(packet.http, 'file_data') else None
                    }
                elif hasattr(packet.http, 'response_code') and request_data:
                    # This is a response paired with the previous request
                    response_data = {
                        'code': packet.http.response_code,
                        'phrase': packet.http.response_phrase,
                        'headers': packet.http.get_field_value('response_line'),
                        'file_data': packet.http.file_data if hasattr(packet.http, 'file_data') else None
                    }
                    # Pair them together in a dictionary
                    http_pairs[f"{current_stream}_{packet.http.request_in}"] = {
                        'request': request_data,
                        'response': response_data
                    }

                    parse_request(http_pairs[f"{current_stream}_{packet.http.request_in}"], magic_bytes, save_path)

                    #print(http_pairs[f"{current_stream}_{packet.http.request_in}"])

                    request_data = None  # Reset request data after pairing
        except AttributeError as e:
            # Ignore packets that don't have the necessary HTTP fields
            pass



if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='Extract Havoc Traffic from a PCAP')

    parser.add_argument(
        '--pcap',
        help='Path to pcap file',
        required=True)
    

    parser.add_argument(
        "--aes-key", 
        help="AES key", 
        required=False)
    
    parser.add_argument(
        "--aes-iv", 
        help="AES initialization vector", 
        required=False)
    
    parser.add_argument(
        "--agent-id", 
        help="Agent ID", 
        required=False)

    parser.add_argument(
        '--save',
        help='Save decrypted payloads to file',
        default=False,
        required=False)

    parser.add_argument(
        '--magic',
        help='Set the magic bytes marker for the Havoc C2 traffic',
        default='deadbeef',
        required=False)


    # Parse the arguments
    args = parser.parse_args()

    # Custom check for the optional values
    if any([args.aes_key, args.aes_iv, args.agent_id]) and not all([args.aes_key, args.aes_iv, args.agent_id]):
        parser.error("[!] If you provide one of 'aes-key', 'aes-iv', or 'agent-id', you must provide all three.")
    
    if args.agent_id and args.aes_key and args.aes_iv:
        sessions[args.agent_id] = {
            "aes_key": unhexlify(args.aes_key),
            "aes_iv": unhexlify(args.aes_iv)
        }
        print(f"[+] Added session keys for Agent ID {args.agent_id}")

    #find_havoc_packets(packets, args.save)


    # Usage example
    http_pairs = read_pcap_and_get_http_pairs(args.pcap, args.magic, args.save)

We ran the script and don’t need to save the results.

1
hui_0_07@kali[mayhem]$ python3 havoc-pcap-parser.py --pcap traffic.pcapng
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
[+] Parsing Packets
[+] Parsing Request
[!] Error parsing request body: 'NoneType' object has no attribute 'replace'
[+] Parsing Request
[!] Error parsing request body: 'NoneType' object has no attribute 'replace'
[+] Parsing Request
[!] Error parsing request body: 'NoneType' object has no attribute 'replace'
[+] Parsing Request
[+] Found Havoc C2
  [-] Agent ID: 0e9fb7d8
  [-] Magic Bytes: deadbeef
  [-] C2 Address: http://10.0.2.37/
  [+] Found AES Key
    [-] Key: 946cf2f65ac2d2b8...
    [-] IV: 8cd00c3e3492...
  [+] Decrypting Request Body

[Decrypted Request]
1g\{콩MnsA_l3c-!G8
JY\(tA@ԥc }thu-,
                եEXS4

                     /@Zsb!q\Fd#
lOllYS▒9ȭ6\-'[~a6
#       ]#PTVS-N`ijƷ    3(eƨ.j!


[+] Parsing Request
  [+] Job Request from Server to Agent
    [-] C2 Address: http://10.0.2.37/
    [-] Comamnd: COMMAND_NOJOB
[+] Parsing Request
  [+] Job Request from Server to Agent
    [-] C2 Address: http://10.0.2.37/
    [-] Comamnd: COMMAND_NOJOB
[+] Parsing Request
  [+] Job Request from Server to Agent
    [-] C2 Address: http://10.0.2.37/
    [-] Comamnd: COMMAND_NOJOB
  ...
  [Decrypted Request]

    Mz^a
        HQI
    UserName                SID
    ====================== ====================================
    CLIENTSERVER\paco       S-1-5-21-[REDACTED]
  ...
  Ethernet adapter Ethernet:

   Connection-specific DNS Suffix  . : home
   Link-local IPv6 Address . . . . . : fe80::[REDACTED]
   IPv4 Address. . . . . . . . . . . : 10.0.2.38
   Subnet Mask . . . . . . . . . . . : 255.255.255.0
   Default Gateway . . . . . . . . . : 10.0.2.1
  ...
  [Decrypted Response - COMMAND_PROC]
    8c:\windows\system32\cmd.exe`/c echo THM{HavOc_C2_[REDACTED]_Fun_FUN}
  ...
  [Decrypted Response - COMMAND_PROC]
    8c:\windows\system32\cmd.exeV/c net user admin[REDACTED] /add
  ...
  [Decrypted Response - COMMAND_PROC]
    8c:\windows\system32\cmd.exe`/c type C:\Users\[REDACTED]
  ...
    ...
    wrait9,THM{I_[REDACTED]_ToOk},fgoodall9@clientserver.thm
    ...
  ...
)

Answers

✅ Answer 1

Q: What is the SID of the user that the attacker is executing everything under?
Ans - S-1-5-21-[REDACTED]

✅ Answer 2

Q: What is the Link-local IPv6 Address of the server? Enter the answer exactly as you see it.
Ans - fe80::[REDACTED]

✅ Answer 3

Q: The attacker printed a flag for us to see. What is that flag?
Ans - THM{HavOc_C2_[REDACTED]_Fun_FUN}

✅ Answer 4

Q: The attacker added a new account as a persistence mechanism. What is the username and password of that account? Format is username:password
Ans - admin[REDACTED]

✅ Answer 5

Q: The attacker found an important file on the server. What is the full path of that file?
Ans - C:\Users\[REDACTED]

✅ Answer 6

Q: What is the flag found inside the file from question 5?
Ans - THM{I_[REDACTED]_ToOk}

This post is licensed under CC BY 4.0 by the author.