Sidecar is a runtime hooking tool for intercepting function calls by TypeScript annotation with ease, powered by Frida.RE.
Image source: 1920s Raleigh Box Sidecar Outfit & ShellterProject
Segregating the functionalities of an application into a separate process can be viewed as a Sidecar pattern. The Sidecar design pattern allows you to add a number of capabilities to your application without the need of additional configuration code for 3rd party components.
As a sidecar is attached to a motorcycle, similarly in software architecture a sidecar is attached to a parent application and extends/enhances its functionalities. A Sidecar is loosely coupled with the main application.
— SOURCE: Sidecar Design Pattern in your Microservices Ecosystem, Samir Behara, July 23, 2018
Hook: by intercepting function calls or messages or events passed between software components. — SOURCE: Hooking, Wikipedia
@Call(memoryAddress)
for make a API for calling memory address from the binary@Hook(memoryAddress)
for emit arguments when a memory address is being calledWhen you are running an application on the Linux, Mac, Windows, iPhone, or Android, you might want to make it programmatic, so that your can control it automatically.
The SDK and API are designed for achieving this, if there are any. However, most of the application have very limited functionalities for providing a SDK or API to the developers, or they have neither SDK nor API at all, what we have is only the binary executable application.
How can we make a binary executable application to be able to called from our program? If we can call the function in the application process directly, then we will be able to make the application as our SDK/API, then we can make API call to control the application, or hook function inside the application to get to know what happened.
I have the above question and I want to find an universal way to solve it: Frida is for rescue. Frida is a dynamic instrumentation toolkit for developers and reverse-engineers, which can help us easily call the internal function from a process, or hook any internal function inside the process. And it has a nice Node.js binding and TypeScript support, which is nice to me because I love TypeScript much.
That's why I start build this project: Sidecar. Sidecar is a runtime hooking tool for intercepting function calls by decorate a TypeScript class with annotation.
Here's an example code example for demostration that how easy it can help you to hook a exiting application.
@Sidecar('chatbox')
class ChatboxSidecar extends SidecarBody {
@Call(0x11c9)
@RetType('void')
mo (
@ParamType('pointer', 'Utf8String') content: string,
): Promise<string> { return Ret(content) }
@Hook(0x11f4)
mt (
@ParamType('pointer', 'Utf8String') content: string,
) { return Ret(content) }
}
async function main () {
const sidecar = new ChatboxSidecar()
await attach(sidecar)
sidecar.on('hook', ({ method, args }) => {
console.log('method:', method)
console.log('args:', args)
sidecar.mo('Hello from Sidecar'),
})
process.on('SIGINT', () => detach(sidecar))
process.on('SIGTERM', () => detach(sidecar))
}
main().catch(console.error)
Learn more from the sidecar example: https://github.com/huan/sidecar/blob/main/examples
Intercepter.attach()
a NativeCallback()
@Name()
support for specify parameter names in @Hook()
-ed method args.Memory.alloc()
in sidecar agent scripts automatically.When we are running a Sidecar Class, the following steps will happend:
@Sidecar()
: <src/decorators/sidecar/sidecar.ts>, <src/decorators/sidecar/build-sidecar-metadata.ts>@Call()
: <src/decorators/call/call.ts>@ParamType()
: <src/decorators/param-type/param-type.ts>@RetType()
: <src/decorators/ret-type/ret-type.ts>@Hook()
, @Name
, etc.SidecarBody
(<src/sidecar-body/sidecar-body.ts>) base class will generate agentSource
:
getMetadataSidecar()
(<src/decorators/sidecar/metadata-sidecar.ts>) for get the sidecar metadata from the classbuildAgentSource()
(<src/agent/build-agent-source.ts>) for generate the agent source code for the whole sidecar system.attach()
method to attach the sidecar to the targetdetach()
method to detach the sidecar to the target@Sidecar(sidecarTarget, initAgentScript)
sidecarTarget
: SidecarTarget
,initAgentScript
? : string
,The class decorator.
sidecarTarget
is the executable binary name,
and the initAgentScript
is a Frida agent script
that help you to do whatever you want to do
with Frida system.
Example:
import { Sidecar } from 'sidecar'
@Sidecar('chatbox')
class ChatboxSidecar {}
It is possible to load a init agent script, for example:
const initAgentScript = 'console.log("this will be runned when the sidecar class initiating")'
@Sidecar(
'chatbox',
initAgentScript,
)
sidecarTarget
supports Spawn
mode, by specifing the sidecarTarget
as a array
:
@Sidecar([
'/bin/sleep', // command
[10], // args
])
To learn more about the power of initAgentScript
, see also this great repo with lots of examples: Hand-crafted Frida examples
class SidecarBody
Base class for the Sidecar
class. All Sidecar
class need to extends
from the SidecarBody
, or the system will throw an error.
Example:
import { SidecarBody } from 'sidecar'
class ChatboxSidecar extends SidecarBody {}
@Call(functionTarget)
functionTarget
: FunctionTarget
The native call method decorator.
functionTarget
is the address (in number
type) of the function which we need to call in the executable binary.
Example:
import { Call } from 'sidecar'
class ChatboxSidecar {
@Call(0x11c9) mo () {}
}
If the functionTarget
is not the type of number
, then it can be string
or an FunctionTarget
object. See FunctionTarget
section to learn more about the advanced usage of FunctionTarget
.
@Hook(functionTarget)
functionTarget
: FunctionTarget
The hook method decorator.
functionTarget
is the address (in number
type) of the function which we need to hook in the executable binary.
Example:
import { Hook } from 'sidecar'
class ChatboxSidecar {
@Hook(0x11f4) mt () {}
}
If the functionTarget
is not the type of number
, then it can be string
or an FunctionTarget
object. See FunctionTarget
section to learn more about the advanced usage of FunctionTarget
.
@RetType(nativeType, ...pointerTypeList)
nativeType
: NativeType
pointerTypeList
: PointerType[]
import { RetType } from 'sidecar'
class ChatboxSidecar {
@RetType('void') mo () {}
@ParamType(nativeType, ...pointerTypeList)
nativeType
: NativeType
pointerTypeList
: PointerType[]
import { ParamType } from 'sidecar'
class ChatboxSidecar {
mo (
@ParamType('pointer', 'Utf8String') content: string,
) {}
Name(parameterName)
TODO: to be implemented.
parameterName
: string
The parameter name.
This is especially useful for Hook
methods.
The hook
event will be emit with the method name and the arguments array.
If the Name(parameterName)
has been set,
then the event will have additional information for the parameter names.
import { Name } from 'sidecar'
class ChatboxSidecar {
mo (
@Name('content') content: string,
) {}
Ret(...args)
args
: any[]
Example:
import { Ret } from 'sidecar'
class ChatboxSidecar {
mo () { return Ret() }
FunctionTarget
The FunctionTarget
is where @Call
or @Hook
to be located. It can be created by the following factory helper functions:
addressTarget(address: number, module?: string)
: memory address. i.e. 0x369adf
. Can specify a second module
to call address
in a specified moduleagentTarget(funcName: string)
: the JavaScript function name in initAgentScript
to be usedexportTarget(exportName: string, exportModule?: string)
: export name of a function. Can specify a second moduleName
to load exportName
from it.objcTarget
: to be addedjavaTarget
: to be addedFor convenice, the number
and string
can be used as FunctionTarget
as an alias of addressTarget()
and agentTarget()
. When we are defining the @Call(target)
and @Hook(target)
:
number
, then it will be converted to addressTarget(target)
string
, then it will be converted to agentTarget(target)
Example:
import {
Call,
addressTarget,
} from 'sidecar'
class ChatboxSidecar {
@Call(
addressTarget(0x11c9)
)
mo () {}
}
agentTarget(funcName: string)
agentTarget
let you specify a funcName
in the initAgentScript
source code, and will use it directly for advanced users.
There's two type of the AgentTarget
usage: @Call
and @Hook
.
AgentTarget
with @Call
: the funcName
should be a JavaScript function instance in the initAgentScript
. The decorated method call that function.AgentTarget
with @Hook
: the funcName
should be a NativeCallback
instance in the initAgentScript
. The decorated method hook that callback.Notes:
NativeFunction
passed to @Call
must pay attention to
the Garbage Collection of the JavaScript inside Frida.
You have to hold a reference to all the memory you alloced by yourself,
for example, store them in a Object
like const refHolder = { buf }
,
then make sure the refHolder
will be hold
unless you can free
the memory that you have alloced before. (See also: Frida Best Practices)NativeCallback
passed to @Hook
is recommended to be a empty function,
like () => {}
because it will be replaced by Sidecar/Frida.
So you should not put any code inside it,sidecar-dump
Sidecar provide a utility named sidecar-dump
for viewing the metadata of the sidecar class, or debuging the frida agent init source code.
You can run this util by the following command:
$ npx sidecar-dump --help
sidecar-dump <subcommand>
> Sidecar utility for dumping metadata/source for a sidecar class
where <subcommand> can be one of:
- metadata - Dump sidecar metadata
- source - Dump sidecar agent source
For more help, try running `sidecar-dump <subcommand> --help`
sidecar-dump
support two sub commands:
metadata
: dump the metadata for a sidecar classsource
: dump the generated frida agent source code for a sidecar classsidecar-dump metadata
Sidecar is using decorators heavily, for example, we are using @Call()
for specifying the process target, @ParamType()
for specifying the parameter data type, etc.
Internally, sidecar organize all the decorated information as metadata and save them into the class.
the sidecar-dump metadata
command is to viewing this metadata information, so that we can review and debug them.
For example, the following is the metadata showed by sidecar-dump for our ChatboxSidecar
class from examples/chatbox-sidecar.ts.
$ sidecar-dump metadata examples/chatbox-sidecar.ts
{
"initAgentScript": "console.log('inited...')",
"interceptorList": [
{
"agent": {
"name": "mt",
"paramTypeList": [
[
"pointer",
"Utf8String"
]
],
"target": "agentMt_PatchCode",
"type": "agent"
}
}
],
"nativeFunctionList": [
{
"agent": {
"name": "mo",
"paramTypeList": [
[
"pointer",
"Utf8String"
],
[
"pointer",
"Utf8String"
]
],
"retType": [
"void"
],
"target": "agentMo",
"type": "agent"
}
}
],
"sidecarTarget": "/tmp/t/examples/chatbox/chatbox-linux"
}
sidecar-dump source
Sidecar is using Frida to connect to the program process and make communication with it.
In order to make the connection, sidecar will generate a frida agent source code, and using this agent as the bridge between the sidecar, frida, and the target program process.
the sidecar-dump source
command is to viewing this frida agent source, so that we can review and debug them.
For example, the following is the source code showed by sidecar-dump for our ChatboxSidecar
class from examples/chatbox-sidecar.ts.
$ sidecar-dump source examples/chatbox-sidecar.ts
...
const __sidecar__mo_Function_wrapper = (() => {
const nativeFunctionAddress =
__sidecar__moduleBaseAddress
.add(0x11e9)
const nativeFunction = new NativeFunction(
nativeFunctionAddress,
'int',
['pointer'],
)
return function (...args) {
log.verbose(
'SidecarAgent',
'mo(%s)',
args.join(', '),
)
// pointer type for arg[0] -> Utf8String
const mo_NativeArg_0 = Memory.alloc(1024 /*Process.pointerSize*/)
mo_NativeArg_0.writeUtf8String(args[0])
const ret = nativeFunction(...[mo_NativeArg_0])
return Number(ret)
}
})()
;(() => {
const interceptorTarget =
__sidecar__moduleBaseAddress
.add(0x121f)
Interceptor.attach(
interceptorTarget,
{
onEnter: args => {
log.verbose(
'SidecarAgent',
'Interceptor.attach(0x%s) onEnter()',
Number(0x121f).toString(16),
)
send(__sidecar__payloadHook(
'mt',
[ args[0].readUtf8String() ]
), null)
},
}
)
})()
rpc.exports = {
mo: __sidecar__mo_Function_wrapper,
}
You can dump the sidecar agent source code to a javascript file, then using it with frida directly for debugging & testing.
$ sidecar-dump source chatbox-sidecar.ts > agent.js
$ frida chatbox -l agent.js
____
/ _ | Frida 14.2.18 - A world-class dynamic instrumentation toolkit
| (_| |
> _ | Commands:
/_/ |_| help -> Displays the help system
. . . . object? -> Display information about 'object'
. . . . exit/quit -> Exit
. . . .
. . . . More info at https://frida.re/docs/home/
[Local::chatbox]-> rpc.exports.mo('hello from frida cli')
0xf
is not valid, use 0x0f
instead)I have another NPM module named ffi-adapter, which is a Foreign Function Interface Adapter Powered by Decorator & TypeScript.
Learn more about FFI from its examples at https://github.com/huan/ffi-adapter/tree/master/tests/fixtures/library
[![Powered by Sidecar](https://img.shields.io/badge/Powered%20By-Sidecar-brightgreen.svg)](https://github.com/huan/sidecar)
We have created different demos that work-out-of-box for some use cases.
You can visit them at Sidecar Demos if you are interested.
hook
event for all hooked methodsPublish to NPM as sidecar package name!
AgentTarget
not to be decorated by neither @ParamType
nor @RetType
for prevent confusing.agentTarget
now point to JavaScript function in initAgentScript
instead of NativeFunction
scripts/post-install.ts
to double check frida_binding.node
existance and run prebuild-install
with cdn if needed (#14)agentTarget
will use NativeFunction
instead of a plain javascript function__sidecar__
namespace for all variable names@Sidecar()
to support spawn target. e.g. @Sidecar(['/bin/sleep', [10]])
.so
& .DLL
library example for Linux & Windows (Dynamic Library Example)pointer
typesidecar-dump
utility: it dump the sidecar metadata
and source
from a class defination file now.sidecar-dump
to make sure it works under Liniux, Mac, and Windows.agent
type support to FunctionTarget
so that both @Call
and @Hook
can use a pre-defined native function ptr defined from the initAgentScript
. (more types like java
, objc
, name
, and module
to be added)First worked version, published to NPM as sidecar
.
Repo created.
initAgentScript
If sidecar tells you that there's some script error internally, you should use sidecar-dump
utility to dump the source of the frida agent script to a agent.js
file, and use frida -l agent.js
to debug it to get a clearly insight.
$ sidecar-dump source your-sidecar-class.ts > agent.js
$ frida -l agent.js
# by this way, you can locate the error inside the agent.js
# for easy debug and fix.
Thanks to Quinton Ashley @quinton-ashley who is the previous owner of NPM name sidecar
and he transfer this beautify name to me for publishing this project after I requested via email. Appreciate it! (Jun 29, 2021)
Huan LI (李卓桓), Microsoft Regional Director, zixia@zixia.net