本文为看雪论坛优秀文章
看雪论坛作者ID:Imyang
一
Hermes简介
二
前期准备
function hook_ssl() {
Java.perform(function () {
var ClassName = "com.android.org.conscrypt.Platform";
var Platform = Java.use(ClassName);
var targetMethod = "checkServerTrusted";
var len = Platform[targetMethod].overloads.length;
console.log(targetMethod, len);
for (var i = 0; i < len; ++i) {
Platform[targetMethod].overloads[i].implementation = function () {
console.log("class:", ClassName, "target:", targetMethod, " i:", i, arguments);
};
}
var ClassName = "com.android.org.conscrypt.TrustManagerImpl";
var Platform = Java.use(ClassName);
var targetMethod = "checkTrustedRecursive";
var len = Platform[targetMethod].overloads.length;
console.log(targetMethod, len);
var ArrayList = Java.use("java.util.ArrayList")
var X509Certificate = Java.use("java.security.cert.X509Certificate");
for (var i = 0; i < len; ++i) {
Platform[targetMethod].overloads[i].implementation = function () {
console.log("class:", ClassName, "target:", targetMethod, " i:", i, arguments);
return ArrayList.$new();
};
}
});
}
三
signcode分析
Binary file ./files/RN/rnbundle/index.android.bundle matches
cp ./files/RN/rnbundle/index.android.bundle /data/local/tmp/index.android.bundle
chmod 777 /data/local/tmp/index.android.bundle
adb pull /data/local/tmp/index.android.bundle
private native void jniLoadScriptFromAssets(AssetManager assetManager, String assetURL, boolean loadSynchronously);
private native void jniLoadScriptFromFile(String fileName, String sourceURL, boolean loadSynchronously);
[RegisterNatives] java_class: com.facebook.react.bridge.CatalystInstanceImpl name: jniLoadScriptFromAssets sig: (Landroid/content/res/AssetManager;Ljava/lang/String;Z)V fnPtr: 0xb4e99a85 fnOffset: 0x80a85 callee: 0xb4d2021d libhermes-executor-release.so!_ZN8facebook3jni6JClass15registerNativesESt16initializer_listI15JNINativeMethodE+0x20
[RegisterNatives] java_class: com.facebook.react.bridge.CatalystInstanceImpl name: jniLoadScriptFromFile sig: (Ljava/lang/String;Ljava/lang/String;Z)V fnPtr: 0xb4e99aa1 fnOffset: 0x80aa1 callee: 0xb4d2021d libhermes-executor-release.so!_ZN8facebook3jni6JClass15registerNativesESt16initializer_listI15JNINativeMethodE+0x20
这时候会遇到一个问题,callee在libhermes-executor-release.so,使用ida打开libhermes-executor-release.so后,去fnOffset: 0x80a85和fnOffset: 0x80aa1找不到对应的函数。
于是使用frida的 Process.findModuleByAddress(ptr(0xb4e99a85)) 找jniLoadScriptFromAssets函数所在的模块,在libreactnativejni.so里面
{
"base": "0xb4e19000",
"name": "libreactnativejni.so",
"path": "/data/app/~~klydM6uPsWM_heluFCfyKQ==/com.xxxxx.xxx.xxxxxxxxxx.xxxxxx-zC5SUJ_WxA0rwldHieq_fg==/lib/arm/libreactnativejni.so",
"size": 815104
}
function hook_dlopen(module_name, fun) {
var android_dlopen_ext = Module.findExportByName(null, "android_dlopen_ext");
if (android_dlopen_ext) {
Interceptor.attach(android_dlopen_ext, {
onEnter: function (args) {
var pathptr = args[0];
if (pathptr) {
this.path = (pathptr).readCString();
if (this.path.indexOf(module_name) >= 0) {
this.canhook = true;
console.log("android_dlopen_ext:", this.path);
}
}
},
onLeave: function (retval) {
if (this.canhook) {
fun();
}
}
});
}
}
function hook_libreactnativejni() {
let base_libreactnativejni = Module.findBaseAddress("libreactnativejni.so");
if (base_libreactnativejni == null) {
return;
}
let jniLoadScriptFromAssets = base_libreactnativejni.add(0x80a85);
let jniLoadScriptFromFile = base_libreactnativejni.add(0x80aa1);
//private native void jniLoadScriptFromAssets(AssetManager assetManager, String assetURL, boolean loadSynchronously);
Interceptor.attach(jniLoadScriptFromAssets, {
onEnter(args) {
console.log("jniLoadScriptFromAssets:", Java.vm.tryGetEnv().getStringUtfChars(args[3]).readCString())
}
})
//private native void jniLoadScriptFromFile(String fileName, String sourceURL, boolean loadSynchronously);
Interceptor.attach(jniLoadScriptFromFile, {
onEnter(args) {
console.log("jniLoadScriptFromFile:", Java.vm.tryGetEnv().getStringUtfChars(args[2]).readCString(), Java.vm.tryGetEnv().getStringUtfChars(args[3]).readCString())
}
})
}
setImmediate(() => {
hook_dlopen("libreactnativejni.so", hook_libreactnativejni)
hook_libreactnativejni();
})
void CatalystInstanceImpl::jniLoadScriptFromFile(
const std::string &fileName,
const std::string &sourceURL,
bool loadSynchronously) {
auto reactInstance = instance_;
if (!reactInstance) {
return;
}
switch (getScriptTagFromFile(fileName.c_str())) { //根据文件头判断脚本类型,
case ScriptTag::MetroHBCBundle: {
std::unique_ptr<const JSBigFileString> script;
RecoverableError::runRethrowingAsRecoverable<std::system_error>(
[&fileName, &script]() {
script = JSBigFileString::fromPath(fileName);
});
const char *buffer = script->c_str();
uint32_t bufferLength = (uint32_t)script->size();
uint32_t offset = 8;
while (offset < bufferLength) {
uint32_t segment = offset + 4;
uint32_t moduleLength =
bufferLength < segment ? 0 : *(((uint32_t *)buffer) + offset / 4);
reactInstance->loadScriptFromString(
std::make_unique<const JSBigStdString>(
std::string(buffer + segment, buffer + moduleLength + segment)),
sourceURL,
false);
offset += ((moduleLength + 3) & ~3) + 4;
}
break;
}
case ScriptTag::RAMBundle:
instance_->loadRAMBundleFromFile(fileName, sourceURL, loadSynchronously);
break;
case ScriptTag::String:
default: {
std::unique_ptr<const JSBigFileString> script;
RecoverableError::runRethrowingAsRecoverable<std::system_error>(
[&fileName, &script]() {
script = JSBigFileString::fromPath(fileName);
});
instance_->loadScriptFromString(
std::move(script), sourceURL, loadSynchronously);
}
}
}
void Instance::loadScriptFromString(
std::unique_ptr<const JSBigString> string,
std::string sourceURL,
bool loadSynchronously) {
SystraceSection s("Instance::loadScriptFromString", "sourceURL", sourceURL);
if (loadSynchronously) {
loadBundleSync(nullptr, std::move(string), std::move(sourceURL));
} else {
loadBundle(nullptr, std::move(string), std::move(sourceURL));
}
}
let loadScriptFromString = base_libreactnativejni.add(0xA0BF8 + 1);
Interceptor.attach(loadScriptFromString, {
onEnter(args) {
console.log("loadScriptFromString:", (args[1]), ptr(args[2]).add(Process.pointerSize * 2).readPointer().readCString(), args[3])
}
})
void Instance::loadBundle(
std::unique_ptr<RAMBundleRegistry> bundleRegistry,
std::unique_ptr<const JSBigString> string,
std::string sourceURL) {
callback_->incrementPendingJSCalls();
SystraceSection s("Instance::loadBundle", "sourceURL", sourceURL);
nativeToJsBridge_->loadBundle(
std::move(bundleRegistry), std::move(string), std::move(sourceURL));
}
//Instance::loadBundle调用了nativeToJsBridge_->loadBundle,
void NativeToJsBridge::loadBundle(
std::unique_ptr<RAMBundleRegistry> bundleRegistry,
std::unique_ptr<const JSBigString> startupScript,
std::string startupScriptSourceURL) {
runOnExecutorQueue(
[this,
bundleRegistryWrap = folly::makeMoveWrapper(std::move(bundleRegistry)),
startupScript = folly::makeMoveWrapper(std::move(startupScript)),
startupScriptSourceURL =
std::move(startupScriptSourceURL)](JSExecutor *executor) mutable {
auto bundleRegistry = bundleRegistryWrap.move();
if (bundleRegistry) {
executor->setBundleRegistry(std::move(bundleRegistry));
}
try {
executor->loadBundle(
std::move(*startupScript), std::move(startupScriptSourceURL));
} catch (...) {
m_applicationScriptHasFailure = true;
throw;
}
});
}
//NativeToJsBridge::loadBundle里面调用了NativeToJsBridge::runOnExecutorQueue
function hook_loadBundle() {
//根据前面分析RN的一些so,可以发现大部分函数符号都还在so里面,那么我们通过DebugSymbol的findFunctionsMatching,找到所有loadBundle函数,并进行hook
DebugSymbol.findFunctionsMatching("*loadBundle*").map(addr => {
Interceptor.attach(addr, {
onEnter(args) {
console.log("loadBundle:", DebugSymbol.fromAddress(addr));
}
})
})
}
hook 结果如下:
loadBundle: 0xbb70699d libreactnativejni.so!_ZN8facebook5react8Instance10loadBundleENSt6__ndk110unique_ptrINS0_17RAMBundleRegistryENS2_14default_deleteIS4_EEEENS3_IKNS0_11JSBigStringENS5_IS9_EEEENS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEE
loadBundle: 0xbb70a845 libreactnativejni.so!_ZN8facebook5react16NativeToJsBridge10loadBundleENSt6__ndk110unique_ptrINS0_17RAMBundleRegistryENS2_14default_deleteIS4_EEEENS3_IKNS0_11JSBigStringENS5_IS9_EEEENS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEE
loadBundle: 0xbb9a5ec5 libhermes-executor-release.so!_ZN8facebook5react11JSIExecutor10loadBundleENSt6__ndk110unique_ptrIKNS0_11JSBigStringENS2_14default_deleteIS5_EEEENS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEE
最终找到了libhermes-executor-release.so的facebook::react::JSIExecutor::loadBundle函数
void JSIExecutor::loadBundle(
std::unique_ptr<const JSBigString> script,
std::string sourceURL) {
SystraceSection s("JSIExecutor::loadBundle");
bool hasLogger(ReactMarker::logTaggedMarker);
std::string scriptName = simpleBasename(sourceURL);
if (hasLogger) {
ReactMarker::logTaggedMarker(
ReactMarker::RUN_JS_BUNDLE_START, scriptName.c_str());
}
runtime_->evaluateJavaScript(
std::make_unique<BigStringBuffer>(std::move(script)), sourceURL);
flush();
if (hasLogger) {
ReactMarker::logTaggedMarker(
ReactMarker::RUN_JS_BUNDLE_STOP, scriptName.c_str());
}
}
function hook_evaluateJavaScript() {
DebugSymbol.findFunctionsMatching("*evaluateJavaScript*").map(addr => {
Interceptor.attach(addr, {
onEnter(args) {
console.log("evaluateJavaScript:", DebugSymbol.fromAddress(addr), "\r\n", print_native_stack("evaluateJavaScript", this));
}
})
})
}
并没有找到evaluateJavaScript函数,只找到了一个evaluateJavaScriptWithSourceMap函数
evaluateJavaScript: 0xbb866775 libhermes.so!_ZN8facebook6hermes13HermesRuntime31evaluateJavaScriptWithSourceMapERKNSt6__ndk110shared_ptrIKNS_3jsi6BufferEEES9_RKNS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEE
[evaluateJavaScript] called from:
0xbb867431 libhermes.so!0x11431
0xbb6605b9 libhermes-executor-common-release.so!0x1c5b9
0xbb727051 libhermes-executor-release.so!_ZN8facebook5react11JSIExecutor10loadBundleENSt6__ndk110unique_ptrIKNS0_11JSBigStringENS2_14default_deleteIS5_EEEENS2_12basic_stringIcNS2_11char_traitsIcEENS2_9allocatorIcEEEE+0x18c
0xbb4b94e7 libreactnativejni.so!0xa54e7
0xbb4ba133 libreactnativejni.so!_ZNKSt6__ndk18functionIFvPN8facebook5react10JSExecutorEEEclES4_+0x16
0xbb4a5ae1 libreactnativejni.so!0x91ae1
0xbb4961d3 libreactnativejni.so!_ZN8facebook3jni6detail13MethodWrapperIMNS_5react15JNativeRunnableEFvvEXadL_ZNS4_3runEvEES4_vJEE8dispatchENS0_9alias_refIPNS1_8JTypeForINS0_11HybridClassIS4_NS3_8RunnableEE8JavaPartESB_vE11_javaobjectEEE+0xe
0xbb49617f libreactnativejni.so!_ZN8facebook3jni6detail15FunctionWrapperIPFvNS0_9alias_refIPNS1_8JTypeForINS0_11HybridClassINS_5react15JNativeRunnableENS6_8RunnableEE8JavaPartES8_vE11_javaobjectEEEESD_vJEE4callEP7_JNIEnvP8_jobjectSG_+0x26
0xee6708df libart.so!art_quick_generic_jni_trampoline+0x2e
0x71915663 boot-framework.oat!0x54e663
jsi::Value HermesRuntimeImpl::evaluateJavaScript(
const std::shared_ptr<const jsi::Buffer> &buffer,
const std::string &sourceURL) {
return evaluateJavaScriptWithSourceMap(buffer, nullptr, sourceURL);
}
jsi::Value HermesRuntime::evaluateJavaScriptWithSourceMap(
const std::shared_ptr<const jsi::Buffer> &buffer,
const std::shared_ptr<const jsi::Buffer> &sourceMapBuf,
const std::string &sourceURL) {
return impl(this)->evaluatePreparedJavaScript(
impl(this)->prepareJavaScriptWithSourceMap(
buffer, sourceMapBuf, sourceURL));
}
HermesRuntimeImpl::prepareJavaScriptWithSourceMap(
const std::shared_ptr<const jsi::Buffer> &jsiBuffer,
const std::shared_ptr<const jsi::Buffer> &sourceMapBuf,
std::string sourceURL) {
std::pair<std::unique_ptr<hbc::BCProvider>, std::string> bcErr{};
auto buffer = std::make_unique<BufferAdapter>(std::move(jsiBuffer));
vm::RuntimeModuleFlags runtimeFlags{};
runtimeFlags.persistent = true;
bool isBytecode = isHermesBytecode(buffer->data(), buffer->size());
bool HermesRuntime::isHermesBytecode(const uint8_t *data, size_t len) {
return hbc::BCProviderFromBuffer::isBytecodeStream(
llvh::ArrayRef<uint8_t>(data, len));
}
static bool isBytecodeStream(llvh::ArrayRef<uint8_t> aref) {
const auto *header =
reinterpret_cast<const hbc::BytecodeFileHeader *>(aref.data());
return (
aref.size() >= sizeof(hbc::BytecodeFileHeader) &&
header->magic == hbc::MAGIC);
}
const static uint64_t MAGIC = 0x1F1903C103BC1FC6;
BytecodeFileHeader(
uint64_t magic, //0x1F1903C103BC1FC6
uint32_t version, //0x54 表示是84版本,commit 0bac657c61ac47a3a9537d982921f5f6c9630d41 (HEAD, tag: v0.8.1)
......
}
hermes/include/hermes/BCGen/HBC/BytecodeVersion.h路径中有定义BYTECODE_VERSION
const static uint32_t BYTECODE_VERSION = 84;
pip install https://github.com/niosega/hbctool/archive/ac6fabb69a7229ed9764997d153d4f703d1381aa.zip
hbctool disasm index.android.bundle bundle
hbctool asm bundle index.android.bundle.re
function hook_log(a, b) {
window.nativeLoggingHook(a + " " + b, 1);
return " ";
}
function test() {
hook_log("333", "555");
}
./build/bin/hermes -emit-binary -out test.hbc test.js
hbctool disasm test.hbc testdir
Function<hook_log>1(3 params, 14 registers, 0 symbols):
GetGlobalObject Reg8:0 ; 先获取全局变量 Reg8:0
TryGetById Reg8:4, Reg8:0, UInt8:1, UInt16:7 ; 通过window字符串从Reg8:0全局变量中拿到window变量,存放在Reg8:4
; Oper[3]: String(7) 'window'
GetByIdShort Reg8:3, Reg8:4, UInt8:2, UInt8:5 ; 从windows变量中拿nativeLoggingHook,存放在Reg8:3
; Oper[3]: String(5) 'nativeLoggingHook'
LoadParam Reg8:1, UInt8:1
LoadConstString Reg8:0, UInt16:0
; Oper[1]: String(0) ' '
Add Reg8:2, Reg8:1, Reg8:0
LoadParam Reg8:1, UInt8:2
Add Reg8:2, Reg8:2, Reg8:1
LoadConstUInt8 Reg8:1, UInt8:1
Call3 Reg8:1, Reg8:3, Reg8:4, Reg8:2, Reg8:1 ;调用window.nativeLoggingHook函数
Ret Reg8:0
EndFunction
{
"id": 253,
"isUTF16": false,
"value": "window"
},
{
"id": 33087,
"isUTF16": false,
"value": "nativeLoggingHook"
},
{
"id": 18880,
"isUTF16": false,
"value": " "
},
Function<md5>13508(3 params, 14 registers, 0 symbols):
GetGlobalObject Reg8:0
TryGetById Reg8:4, Reg8:0, UInt8:1, UInt16:253 ; 修改字符串id UInt16:7-> UInt16:253
; Oper[3]: String(254) 'window'
GetById Reg8:3, Reg8:4, UInt8:2, UInt16:33087 ;修改字符串id UInt8:5 -> UInt16:33087, 从UInt8改成UInt16, 需要把GetByIdShort修改成GetById指令
; Oper[3]: String(4397) 'nativeLoggingHook'
LoadParam Reg8:1, UInt8:1
LoadConstString Reg8:0, UInt16:18880 ; 修改字符串id UInt16:0 -> UInt16:18880
; Oper[1]: String(674) ' '
Add Reg8:2, Reg8:1, Reg8:0
LoadParam Reg8:1, UInt8:2
Add Reg8:2, Reg8:2, Reg8:1
LoadConstUInt8 Reg8:1, UInt8:1
Call3 Reg8:1, Reg8:3, Reg8:4, Reg8:2, Reg8:1
Ret Reg8:0
EndFunction
hbctool asm bundle index.android.bundle.re
md5sum index.android.bundle.re
7eba6c20134268a82e5a0af948ca550b index.android.bundle.re
adb push index.android.bundle.re /data/local/tmp/index.android.bundle.re
adb shell
su
cd /data/data/com.pcakge.name/files/RN/rnbundle/
cp index.android.bundle index.android.bundle.bak # 对原来的文件备份
cp /data/local/tmp/index.android.bundle.re index.android.bundle
ReactNativeJS: XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXAPPKEYGL_RN_D02F48E720CACLIENTANDROIDDEVICEIDBBC6AD7E-1561-4702-8C1E-3AAC682B4D8BENCRYPT1PASSWORD6666666666TIMESTAMPUINFO666666666VERSION3.1.0XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX undefined
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX脱敏
https://github.com/facebook/react-native.git
https://github.com/lasting-yang/frida_hook_libart
https://github.com/facebook/hermes
https://github.com/bongtrop/hbctool
https://github.com/niosega/hbctool/tree/draft/hbc-v84
看雪ID:Imyang
https://bbs.pediy.com/user-home-548459.htm
# 往期推荐
球分享
球点赞
球在看
点击“阅读原文”,了解更多!