883 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
189 lines
8.5 KiB
Python
189 lines
8.5 KiB
Python
#!/usr/bin/env python3
|
|
"""One changed boundary: actual installer on a mock RX page and row append."""
|
|
import ctypes as C
|
|
from pathlib import Path
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
sys.path.insert(0, str(ROOT / 'ops'))
|
|
import native_namespace_probe as namespace
|
|
|
|
|
|
class FakeNamespace(namespace.NamespaceProbe):
|
|
def __init__(self, realm):
|
|
self.module = 0x180000000
|
|
names = ['gw_bridge_callback', 'gw_registration_get_state',
|
|
'gw_registration_data', 'gw_registration_rows',
|
|
'gw_registration_name', 'gw_bridge_data']
|
|
if realm:
|
|
names += list(namespace.REALM_EXPORTS)
|
|
self.exports = {name: self.module + 0x100 + i * 0x100 for i, name in enumerate(names)}
|
|
self.adapter_targets = namespace.callback_adapters(self.exports)
|
|
self.memory = {address: b'\xcc' * 12 for address in
|
|
(namespace.READY_ADAPTER, namespace.GETTER_ADAPTER,
|
|
namespace.SNAPSHOT_ADAPTER, namespace.REQUEST_ADAPTER)}
|
|
self.original = b''.join(struct.pack('<QQ', 0x144A00100 + i * 32,
|
|
namespace.READY if i == 25 else 0x140010000 + i * 64) for i in range(29))
|
|
self.state = 0
|
|
self.adapters = []
|
|
self.events = []
|
|
self.writes = []
|
|
self.registers = {}
|
|
|
|
def locate_module(self):
|
|
pass
|
|
|
|
def read(self, address, size):
|
|
if address == namespace.TABLE:
|
|
return self.original[:size]
|
|
if address == namespace.LUA_GLOBAL:
|
|
return struct.pack('<Q', 0x12345000)
|
|
if address == 0x1008:
|
|
return struct.pack('<Q', 0x140001234)
|
|
if address == self.exports['gw_registration_data']:
|
|
return struct.pack('<II', 1, 56)
|
|
if address == self.exports['gw_registration_data'] + 8:
|
|
return struct.pack('<I', self.state)
|
|
return self.memory[address][:size]
|
|
|
|
def write_owned(self, address, data):
|
|
assert self.module <= address < address + len(data) <= self.module + 0x10000
|
|
self.writes.append((address, bytes(data)))
|
|
self.memory[address] = bytes(data)
|
|
if address == self.exports['gw_registration_data']:
|
|
for site, target in self.adapter_targets:
|
|
self.memory[site] = b'\x48\xb8' + struct.pack('<Q', target) + b'\xff\xe0'
|
|
self.state = 2
|
|
|
|
def ptrace(self, *args):
|
|
pass
|
|
|
|
def debug(self, index, value=None):
|
|
if value is not None:
|
|
self.registers[index] = value
|
|
return self.registers.get(index, 0)
|
|
|
|
def record(self, status, **kwargs):
|
|
self.recorded_status = status
|
|
|
|
|
|
class RealmAdapterBoundary(unittest.TestCase):
|
|
def test_one_grouped_installer_and_namespace_boundary(self):
|
|
for realm, count in [(False, 30), (True, 32)]:
|
|
with self.subTest(realm=realm):
|
|
probe = FakeNamespace(realm)
|
|
registers = namespace.Registers()
|
|
registers.rcx = namespace.TABLE
|
|
registers.rdx = 29
|
|
registers.rsp = 0x1008
|
|
probe.install(registers)
|
|
rows = probe.memory[probe.exports['gw_registration_rows']]
|
|
self.assertEqual(len(rows), count * 16)
|
|
expected = bytearray(probe.original)
|
|
struct.pack_into('<Q', expected, 25 * 16 + 8, namespace.READY_ADAPTER)
|
|
self.assertEqual(rows[:29 * 16], bytes(expected))
|
|
self.assertEqual(struct.unpack_from('<QQ', rows, 29 * 16),
|
|
(probe.exports['gw_registration_name'], namespace.GETTER_ADAPTER))
|
|
if realm:
|
|
self.assertEqual(struct.unpack_from('<QQ', rows, 30 * 16),
|
|
(probe.exports['gw_registration_realm_snapshot_name'], namespace.SNAPSHOT_ADAPTER))
|
|
self.assertEqual(struct.unpack_from('<QQ', rows, 31 * 16),
|
|
(probe.exports['gw_registration_realm_request_name'], namespace.REQUEST_ADAPTER))
|
|
self.assertEqual(registers.rdx, count)
|
|
data = probe.memory[probe.exports['gw_registration_data']]
|
|
self.assertEqual(struct.unpack_from('<II', data, 28), (29, count))
|
|
self.assertEqual(len(probe.adapters), 4 if realm else 2)
|
|
self.assertEqual(probe.memory[probe.exports['gw_bridge_data'] + 24],
|
|
struct.pack('<Q', namespace.READY))
|
|
partial = FakeNamespace(False).exports.copy()
|
|
partial[namespace.REALM_EXPORTS[0]] = 0x180002000
|
|
with self.assertRaisesRegex(RuntimeError, 'Incomplete realm facade'):
|
|
namespace.callback_adapters(partial)
|
|
corrupt = FakeNamespace(True)
|
|
corrupt.memory[namespace.SNAPSHOT_ADAPTER] = b'\x90' + b'\xcc' * 11
|
|
registers = namespace.Registers()
|
|
registers.rcx, registers.rdx, registers.rsp = namespace.TABLE, 29, 0x1008
|
|
with self.assertRaisesRegex(RuntimeError, 'padding changed'):
|
|
corrupt.install(registers)
|
|
self.assertEqual(corrupt.writes, [])
|
|
|
|
# Compile the actual changed function without the gateway or native
|
|
# client. Its real mprotect/RX and rollback logic runs in this child.
|
|
source = (ROOT / 'native/engine_bridge.cpp').read_text()
|
|
start = source.index('bool install_callback_adapters(')
|
|
opening = source.index('{', start)
|
|
depth = 1
|
|
end = opening + 1
|
|
while depth:
|
|
depth += (source[end] == '{') - (source[end] == '}')
|
|
end += 1
|
|
function = source[start:end]
|
|
prefix = r'''
|
|
#include <array>
|
|
#include <atomic>
|
|
#include <cstdint>
|
|
#include <cstring>
|
|
#include <fstream>
|
|
#include <sstream>
|
|
#include <string>
|
|
#include <utility>
|
|
#include <sys/mman.h>
|
|
#include <cassert>
|
|
static bool fail_restore=false;
|
|
static unsigned protection_calls=0;
|
|
int mocked_mprotect(void* p,size_t n,int flags){
|
|
if(++protection_calls==2 && fail_restore && flags==(PROT_READ|PROT_EXEC))return -1;
|
|
return ::mprotect(p,n,flags);
|
|
}
|
|
#define mprotect mocked_mprotect
|
|
'''
|
|
suffix = r'''
|
|
#undef mprotect
|
|
int main(){
|
|
constexpr uintptr_t page=0x144597000;
|
|
constexpr uintptr_t sites[]={0x144597493,0x1445979a4,0x144597f22,0x144597fe2};
|
|
constexpr uintptr_t targets[]={0x180000200,0x180000100,0x180000300,0x180000400};
|
|
void* p=mmap(reinterpret_cast<void*>(page),4096,PROT_READ|PROT_WRITE,
|
|
MAP_PRIVATE|MAP_ANONYMOUS|MAP_FIXED_NOREPLACE,-1,0);
|
|
assert(p==reinterpret_cast<void*>(page));
|
|
auto reset=[&](){assert(!::mprotect(p,4096,PROT_READ|PROT_WRITE));
|
|
std::memset(p,0xcc,4096);assert(!::mprotect(p,4096,PROT_READ|PROT_EXEC));
|
|
protection_calls=0;fail_restore=false;};
|
|
auto pristine=[&](uintptr_t a){for(unsigned i=0;i<12;++i)assert(*reinterpret_cast<uint8_t*>(a+i)==0xcc);};
|
|
reset();
|
|
assert(!::mprotect(p,4096,PROT_READ|PROT_WRITE));
|
|
*reinterpret_cast<uint8_t*>(sites[3])=0x90;
|
|
assert(!::mprotect(p,4096,PROT_READ|PROT_EXEC));
|
|
assert(!install_callback_adapters(targets[1],targets[0],targets[2],targets[3]));
|
|
assert(protection_calls==0);for(unsigned i=0;i<3;++i)pristine(sites[i]);
|
|
reset();assert(install_callback_adapters(targets[1],targets[0],targets[2],targets[3]));
|
|
for(unsigned i=0;i<4;++i){auto* c=reinterpret_cast<uint8_t*>(sites[i]);uintptr_t target=0;
|
|
std::memcpy(&target,c+2,8);assert(c[0]==0x48&&c[1]==0xb8&&c[10]==0xff&&c[11]==0xe0&&target==targets[i]);}
|
|
reset();assert(install_callback_adapters(targets[1],targets[0]));
|
|
pristine(sites[2]);pristine(sites[3]);
|
|
reset();assert(!install_callback_adapters(targets[1],targets[0],targets[2],0));
|
|
assert(protection_calls==0);for(auto a:sites)pristine(a);
|
|
reset();fail_restore=true;
|
|
assert(!install_callback_adapters(targets[1],targets[0],targets[2],targets[3]));
|
|
assert(protection_calls==3);for(auto a:sites)pristine(a);
|
|
assert(!munmap(p,4096));
|
|
}
|
|
'''
|
|
with tempfile.TemporaryDirectory() as temporary:
|
|
directory = Path(temporary)
|
|
cpp, binary = directory / 'boundary.cpp', directory / 'boundary'
|
|
cpp.write_text(prefix + function + suffix)
|
|
built = subprocess.run(['c++', '-std=c++20', '-O0', str(cpp), '-o', str(binary)],
|
|
capture_output=True, text=True)
|
|
self.assertEqual(built.returncode, 0, built.stderr)
|
|
ran = subprocess.run([str(binary)], capture_output=True, text=True)
|
|
self.assertEqual(ran.returncode, 0, ran.stderr)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|