883 files, from working commit b1a079a. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
220 lines
10 KiB
Python
220 lines
10 KiB
Python
"""Real owned-child fixture for existing and cloned thread writer observation."""
|
|
from __future__ import annotations
|
|
|
|
import os
|
|
import hashlib
|
|
from pathlib import Path
|
|
import struct
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import threading
|
|
import unittest
|
|
|
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'ops'))
|
|
from loader_writer_thread_probe import (WriterEntryObserver, discover_loader_base,
|
|
process_identity, sanitized_failure,
|
|
LOADER_ENTRY_PREFIX, LOADER_ENTRY_RVA,
|
|
LOADER_IMAGE_SIZE, LOADER_IDENTITY_BITS)
|
|
|
|
SOURCE = r'''
|
|
#include <pthread.h>
|
|
#include <sched.h>
|
|
#include <stdio.h>
|
|
#include <stdint.h>
|
|
#include <fcntl.h>
|
|
#include <sys/mman.h>
|
|
#include <unistd.h>
|
|
#include <string.h>
|
|
volatile int observed;
|
|
volatile int release_worker;
|
|
__attribute__((noinline)) int writer_entry(int a,int b,int c,int d,int e,int status) {
|
|
observed = status;
|
|
return status;
|
|
}
|
|
static void *worker(void *unused) {
|
|
(void)unused;
|
|
writer_entry(0,0,0,0,0,0x302);
|
|
while (!release_worker) sched_yield();
|
|
return NULL;
|
|
}
|
|
int main(int argc, char **argv) {
|
|
pthread_t thread;
|
|
unsigned char prefix[16] = {0x41,0x57,0x41,0x56,0x41,0x55,0x41,0x54,
|
|
0x56,0x57,0x55,0x53,0x48,0x81,0xec,0x88};
|
|
if (argc != 2) return 6;
|
|
int fd = open(argv[1], O_RDONLY);
|
|
if (fd < 0) return 7;
|
|
char *image = mmap(NULL, 0x29a0000, PROT_READ|PROT_WRITE,
|
|
MAP_PRIVATE|MAP_ANONYMOUS, -1, 0);
|
|
if (image == MAP_FAILED || pread(fd, image, 512, 0) != 512) return 8;
|
|
close(fd);
|
|
memcpy(image + 0xa27ca0, prefix, 16);
|
|
if (mprotect((void *)((uintptr_t)(image + 0xa27ca0) & ~(uintptr_t)4095),
|
|
4096, PROT_READ|PROT_EXEC)) return 9;
|
|
setvbuf(stdout, NULL, _IONBF, 0);
|
|
printf("%p %p\n", (void *)(uintptr_t)&writer_entry, (void *)image);
|
|
if (getchar() != 'G') return 2;
|
|
writer_entry(0,0,0,0,0,0x301);
|
|
if (pthread_create(&thread, NULL, worker, NULL)) return 3;
|
|
if (getchar() != 'Q') return 5;
|
|
release_worker = 1;
|
|
if (pthread_join(thread, NULL)) return 4;
|
|
return 0;
|
|
}
|
|
'''
|
|
|
|
|
|
class OwnedWriterFixture(unittest.TestCase):
|
|
def test_existing_nonmatch_and_new_thread_match_restore(self):
|
|
with tempfile.TemporaryDirectory(prefix='loader-writer-thread-fixture-') as folder:
|
|
directory = Path(folder)
|
|
source = directory / 'fixture.c'
|
|
binary = directory / 'fixture'
|
|
synthetic = directory / 'synthetic-loader.bin'
|
|
image = bytearray(512)
|
|
image[:2] = b'MZ'
|
|
struct.pack_into('<I', image, 0x3c, 0x80)
|
|
image[0x80:0x84] = b'PE\0\0'
|
|
struct.pack_into('<H', image, 0x84, 0x8664)
|
|
struct.pack_into('<H', image, 0x86, 1)
|
|
struct.pack_into('<I', image, 0x88, 0x12345678)
|
|
struct.pack_into('<H', image, 0x98, 0x20b)
|
|
struct.pack_into('<I', image, 0xd0, LOADER_IMAGE_SIZE)
|
|
synthetic.write_bytes(image)
|
|
synthetic_sha = hashlib.sha256(image).hexdigest()
|
|
source.write_text(SOURCE)
|
|
subprocess.run(['gcc', '-O0', '-fno-omit-frame-pointer', '-no-pie',
|
|
'-pthread', str(source), '-o', str(binary)],
|
|
check=True, stdout=subprocess.DEVNULL)
|
|
child = subprocess.Popen([str(binary), str(synthetic)], stdin=subprocess.PIPE,
|
|
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,
|
|
text=True, bufsize=1)
|
|
try:
|
|
entry_text, image_text = child.stdout.readline().split()
|
|
entry, image_base = int(entry_text, 16), int(image_text, 16)
|
|
parent, starttime = process_identity(child.pid)
|
|
self.assertEqual(parent, os.getpid())
|
|
self.assertLessEqual(discover_loader_base(child.pid, starttime, binary), entry)
|
|
fd = os.open(f'/proc/{child.pid}/mem', os.O_RDONLY)
|
|
try:
|
|
prefix = os.pread(fd, 16, entry)
|
|
finally:
|
|
os.close(fd)
|
|
def start_observer(timeout, cancel=None, *, target_entry=None,
|
|
target_prefix=None, **extra):
|
|
ready = threading.Event()
|
|
outcome = {}
|
|
def run():
|
|
probe = WriterEntryObserver(child.pid, starttime,
|
|
target_entry or entry,
|
|
target_prefix or prefix,
|
|
timeout=timeout,
|
|
max_nonmatching=4, **extra)
|
|
try:
|
|
outcome['admission'] = probe.arm()
|
|
except BaseException as error:
|
|
outcome['error'] = error
|
|
ready.set()
|
|
return
|
|
ready.set()
|
|
try:
|
|
outcome['result'] = probe.observe(cancel)
|
|
except BaseException as error:
|
|
outcome['error'] = error
|
|
finally:
|
|
probe.close()
|
|
thread = threading.Thread(target=run, name='owned-ptrace-observer')
|
|
thread.start()
|
|
self.assertTrue(ready.wait(3))
|
|
if 'error' in outcome:
|
|
raise outcome['error']
|
|
return thread, outcome
|
|
|
|
observer_thread, outcome = start_observer(5)
|
|
self.assertEqual(outcome['admission']['initial_thread_count'], 1)
|
|
child.stdin.write('G')
|
|
child.stdin.flush()
|
|
observer_thread.join(6)
|
|
self.assertFalse(observer_thread.is_alive())
|
|
if 'error' in outcome:
|
|
raise outcome['error']
|
|
result = outcome['result']
|
|
self.assertEqual(result['status'], 'matched')
|
|
self.assertEqual(result['writer_input'], 0x302)
|
|
self.assertEqual(result['nonmatching_hits'], 1)
|
|
self.assertEqual(result['clone_thread_count'], 1)
|
|
self.assertGreaterEqual(result['restored_thread_count'], 2)
|
|
self.assertTrue(result['debug_registers_restored'])
|
|
self.assertIsNotNone(result['caller_return'], result)
|
|
timeout_thread, timeout_outcome = start_observer(.1)
|
|
self.assertEqual(timeout_outcome['admission']['initial_thread_count'], 2)
|
|
timeout_thread.join(3)
|
|
self.assertFalse(timeout_thread.is_alive())
|
|
if 'error' in timeout_outcome:
|
|
raise timeout_outcome['error']
|
|
timeout_result = timeout_outcome['result']
|
|
self.assertEqual(timeout_result['status'], 'timeout')
|
|
self.assertEqual(timeout_result['restored_thread_count'], 2)
|
|
self.assertTrue(timeout_result['debug_registers_restored'])
|
|
cancel = threading.Event()
|
|
cancel_thread, cancel_outcome = start_observer(5, cancel)
|
|
self.assertEqual(cancel_outcome['admission']['initial_thread_count'], 2)
|
|
cancel.set()
|
|
cancel_thread.join(3)
|
|
self.assertFalse(cancel_thread.is_alive())
|
|
if 'error' in cancel_outcome:
|
|
raise cancel_outcome['error']
|
|
cancel_result = cancel_outcome['result']
|
|
self.assertEqual(cancel_result['status'], 'cancelled')
|
|
self.assertEqual(cancel_result['restored_thread_count'], 2)
|
|
self.assertTrue(cancel_result['debug_registers_restored'])
|
|
trusted_cancel = threading.Event()
|
|
trusted_thread, trusted_outcome = start_observer(
|
|
5, trusted_cancel,
|
|
target_entry=image_base + LOADER_ENTRY_RVA,
|
|
target_prefix=LOADER_ENTRY_PREFIX,
|
|
module_path=synthetic, module_sha256=synthetic_sha,
|
|
trusted_loader_base=image_base,
|
|
trusted_loader_size=LOADER_IMAGE_SIZE,
|
|
trusted_identity_bits=LOADER_IDENTITY_BITS)
|
|
self.assertEqual(trusted_outcome['admission']['initial_thread_count'], 2)
|
|
trusted_cancel.set()
|
|
trusted_thread.join(3)
|
|
self.assertFalse(trusted_thread.is_alive())
|
|
if 'error' in trusted_outcome:
|
|
raise trusted_outcome['error']
|
|
trusted_result = trusted_outcome['result']
|
|
self.assertEqual(trusted_result['status'], 'cancelled')
|
|
self.assertEqual(trusted_result['restored_thread_count'], 2)
|
|
self.assertTrue(trusted_result['debug_registers_restored'])
|
|
try:
|
|
discover_loader_base(child.pid, starttime, source)
|
|
except ValueError as error:
|
|
failure = sanitized_failure(error)
|
|
else:
|
|
self.fail('Unmapped loader path admitted')
|
|
self.assertEqual(failure['error_predicate'], 'loader_header_unavailable')
|
|
self.assertTrue(failure['clean_unarmed'])
|
|
rejected = WriterEntryObserver(child.pid, starttime, entry + 1,
|
|
prefix, timeout=.1)
|
|
with self.assertRaises(ValueError) as captured:
|
|
rejected.arm()
|
|
failure = sanitized_failure(captured.exception, rejected)
|
|
self.assertEqual(failure['error_phase'], 'loader-code-admission')
|
|
self.assertEqual(failure['error_predicate'], 'writer_prefix_mismatch')
|
|
self.assertTrue(failure['clean_unarmed'])
|
|
child.stdin.write('Q')
|
|
child.stdin.flush()
|
|
self.assertEqual(child.wait(timeout=3), 0)
|
|
finally:
|
|
if child.poll() is None:
|
|
child.kill()
|
|
child.wait(timeout=3)
|
|
child.stdin.close()
|
|
child.stdout.close()
|
|
|
|
|
|
if __name__ == '__main__':
|
|
unittest.main()
|