Renef v0.4.0

The largest release so far. The wire protocol gained real message boundaries, hook output got its own channel, the native hook engine was reworked to survive bulk and hot-path hooking, and the Python client was rewritten. Released together with r2renef 0.2.0.

Old and new parts keep working together: a 0.4.0 server still accepts the line protocol of older clients, and the new clients fall back to it on an older server.


New: Hook Output Has Its Own Channel

Before this release, what a hook printed ended up in front of the reply to whatever command you ran next. Now the agent sends hook and syscall-trace output over a separate connection, and the server holds it until you ask.

  • watch shows what has been waiting, then follows new output live
  • every other command prints only its own result, plus one line when hook output is waiting
  • hooks shows a hits= counter per hook, counted by the agent itself
renef> hooks
Active hooks: 1
  [0] target=0x7b0a45af0c hits=820
(334 lines of hook output waiting - `watch` shows them)

See Real-time Monitoring.


New: Framed Requests

Commands and replies can now be framed (@req <id> <len> / @done <id>), so a reply ends exactly where it ends:

  • multi-line commands and large scripts are delivered intact (the 64 KB command limit is gone)
  • a slow command no longer has its late reply shown as the answer to the next one
  • exec and rpc take --timeout <seconds>

The CLI, the Python client and r2renef use framing automatically when the server supports it. Details in Architecture.


New: Python Client, Rewritten

bindings/python is now pure Python and talks to renef_server directly: no native library to build or locate, and it works on macOS as well as Linux.

import renef

with renef.connect().spawn("com.example.app") as s:
    libc = s.Module.find("libc.so")
    print(s.Memory.read(libc, 4))                       # b'\x7fELF'

    def on_open(event):
        print("open(%r)" % event.data.get("path"))

    s.hook("libc.so", "open", on_enter=on_open,
           capture={"path": "Memory.readStr(args[0])"})
    s.poll(wait=5)
  • exceptions instead of silent None/-1, typed results
  • hooks with Python callbacks, capture expressions evaluated during the call
  • rpc() returns Lua values as Python data; eval() returns output and the Lua error text
  • unreadable addresses raise an error instead of crashing the target
  • the old Renef / RenefSession names and return conventions still work

See Python Binding.


New Lua APIs

API What it does
Interceptor.replace(lib, offset, fn [, caller]) Replace a native function; the callback’s return value becomes the result
Interceptor.revert(lib, offset) Remove a hook or replacement again without respawning
NativeFunction(addr [, ret [, argTypes]]) Call native code from Lua, including float/double arguments and results
hook(..., { async = true, onEnter = ... }) Fire-and-forget hooks for hot functions: the callback runs on a worker thread
send(table) Structured events ([event] {...}) for scripts and clients
Module.disassemble(addr [, count]) ARM64 disassembly from a script
Module.findExportByName(lib, pattern) Export lookup with */? wildcards
Process.enumerateRanges(), Process.enumerateThreads() Memory map and thread list
Java.enumerateLoadedClasses() Class names from the app’s dex files

Also: hooks on a library that is not loaded yet are installed the moment it loads (the agent watches dlopen), IFUNC symbols such as strlen/strcmp resolve to the code that actually runs, and Java.array() works for primitive types.

See the Hook API, Module API, Process API and Java API.


New Commands and Options

   
rpc <lua expression> Evaluate an expression and get its value back as one JSON line
events [wait_ms] Fetch held hook output without blocking like watch
exec --json <code> One JSON line (ok, output, timed_out) instead of free text
memdump <pid> --maps \| <start>-<end> Read any process’s memory without injecting into it
mcp connect \| list-tools \| call Call tools of a local MCP server from the Renef prompt
plugins, plugin load/unload/list, format Plugin management and pluggable output formats
--headless, --timeout <s> Run without the interactive shell, for CI and pipelines
RENEF_PORT, RENEF_ADB_FORWARD=off Use another host port, or leave adb forward alone - for a second device or a server in TCP mode
--memdump-pid, --memdump-range, --memdump-maps, --out The passive memory read from the host command line

md now reads through the server, so it works on execute-only code and stays correct while hooks are printing.

See Script Execution, Memory Operations and Utility Commands.


Improved: Native Hook Engine

The engine was reworked after systematic testing with thousands of hooks on a real device.

  • One-instruction patch. A hooked function is redirected with a single branch instead of a 16-byte sequence, so short functions can be hooked and no thread is ever caught inside a half-written patch.
  • Bulk hooking. All of libc’s roughly 1500 exports were hooked, batch by batch, without a crash; a session can now hold 128 native hooks at a time (was 32).
  • Hot paths. Functions the agent itself depends on (malloc, pthread_mutex_lock, write…) can be hooked: calls made by the agent never enter hooks, and the Lua VM uses its own allocator.
  • Correct relocation. PC-relative instructions in a moved prologue (ADRP, ADR, literal loads, B.cond, CBZ…) are rewritten properly.
  • Execute-only code. Hooking functions in execute-only memory no longer crashes the target.
  • Floating-point arguments and results (q0-q7) survive a hook.
  • A callback that cannot get the Lua VM in time is skipped and reported instead of freezing the app.

Improved: Java Hooks

Java method hooks were rebuilt on a different mechanism (Android 12 and later). A hooked method is now routed through a real JNI native method, and the original runs through a copy of the method record - so ART can always walk the stack, which the previous design could not guarantee.

  • No more crashes on exceptions. Hooking a method that throws, or whose callees throw and catch (File.exists() on a missing file is enough), used to kill the app. The same applied to a garbage collection at the wrong moment.
  • Exceptions reach the caller. The old engine swallowed an exception thrown by the original method; the caller got a meaningless value instead.
  • All argument types. float/double parameters and methods with more arguments than fit in registers are passed on correctly.
  • The hook stays in place while the original runs, so calls from other threads are no longer missed.
  • Listed and removable. Java hooks appear in hooks as [jN] with a call counter, and unhook jN / unhook all remove them.
  • Removed safely when the session ends. Hooks left installed when the client disconnects are taken out without disturbing the app.
  • Clear errors. hook() says why it failed: class or method not found, method is abstract, method already hooked.
  • Callbacks wait at most half a second for the Lua VM, so a long-running script cannot freeze an app thread that calls a hooked method.

Behaviour that changed: interface and abstract methods are refused (they never ran a hook anyway - hook the implementing class), and a method can carry one hook at a time.

See the Hook API.


Improved: Injection

The agent is now loaded through a code cave: only one instruction of malloc() changes while the agent is being loaded, instead of several. In our tests the previous method crashed the target in 4 of 40 spawns, the new one in none. RENEF_NO_CODE_CAVE=1 selects the previous method.

The loader also tells the CPU about the code it writes before running it. On processors with separate instruction and data caches (seen on an Exynos 990) the target could otherwise die with SIGILL right after injection - there, 5 of 6 spawns failed before the fix and 55 of 55 worked after it.

In apps that are not debuggable the agent now patches code the same way as in debuggable ones (through /proc/self/mem) instead of making code pages writable.


New: Plugins and Recipes

  • Plugin types EXTERNAL_TOOL and FORMATTER, a claim model that lets a plugin see every command, and structured JSON results. Example plugins: Redex, a JSON formatter, and a static protector fingerprint (DexGuard / DexProtector). See Plugin Development.
  • A library of ready-to-run pentest scripts in scripts/recipes/: SSL pinning bypass, root / Frida / emulator detection bypass, taint filter, in-memory engine capture, Java reflection dump. See Pentest Recipes.

Fixed

  • Syscall.trace("openat") (and other functions exported under an alias) installed no hooks
  • watch showed nothing and could not be left when a hook printed continuously; leaving it could also block the server
  • hooks crashed the target with about 40 or more hooks installed
  • hookn never worked (it reported “Unknown command”); it now hooks by offset or symbol name and logs every call
  • ms crashed the target on devices whose GPU driver maps device memory into the app (seen with Mali), reported “no response” on large apps after 10 seconds, and accepted invalid hex patterns
  • rpc dropped a false result; a slow rpc could have its result returned by the next call
  • Spawning could kill the target with SIGILL right after injection on some processors (see Injection above)
  • Output containing NUL bytes was cut off in the CLI
  • Commands containing // (Lua integer division, URLs) were rejected as unknown

Known Limitations

  • Java hooks on Android 10 and 11 still use the previous mechanism: a hooked method that throws, or a garbage collection at the wrong moment, can crash the app there.
  • Inlined calls are not seen by Java hooks. When ART has copied a small method into its callers, those callers never enter the method. The hits= counter in hooks shows whether a hook is being reached.
  • Injection can occasionally fail. Seen once in about 150 spawns on one device: the agent was not loaded and the app crashed. Spawning again works. The instruction-cache fix above removes one cause of exactly this; whether it was the only one is not known.
  • Apps that run as the system user (Settings, for example) could not load the agent on a Samsung with SELinux enforcing: the spawn fails and the app restarts.
  • Verified on Android 13 (API 33; a debuggable and an ordinary app) and Android 16 (API 36; a debuggable app). Other releases were not re-tested for this version.

r2renef 0.2.0

The Radare2 plugin was rewritten alongside this release:

  • the target’s memory ranges become io maps; modules, exports and symbols become flags
  • :hook hooks the function under the cursor (inline or PLT/GOT), with :hooks, :unhook, :bt, :hookgen
  • :strace, :/x and :/ run inside the target
  • execute-only code is read through the server and disassembles normally
  • :watch follows hook output; other commands stay clean and say when output is waiting
  • framed protocol with automatic fallback for older servers

See r2renef.


Back to top

Renef - Dynamic Instrumentation Toolkit for Android