我想在运行时以以下方式修补类似文本编辑器的应用程序:当用户打开任何文件时,/tmp/predefined
应该打开我预定义的文件(例如)而不是用户的原始文件。对于此任务,我使用带有 JavaScript API 的 Frida 工具包。我拦截所有open()
系统调用,决定是否需要进行替换,如果需要,则用我预定义的参数替换第一个open()
参数(要打开的文件的路径)。
脚本patcher.js
:
function main()
{
Interceptor.attach(Module.getExportByName(null, 'open'), {
onEnter(args) {
const originalPath = args[0].readCString();
if (shouldReplace(originalPath)){
args[0].writeUtf8String('/tmp/predefined'); // (1)
//args[0] = Memory.allocUtf8String("/tmp/predefined"); (2)
}
},
});
}
function shouldReplace(path) {
if (!path) return false;
// Do not replace essential system or config files:
if (path.startsWith("/usr/") || path.startsWith("/etc/") || path.startsWith("/lib") ||
path.startsWith("/var/") || path.startsWith("/proc/") || path.startsWith("/sys/") ||
path.startsWith("/dev/") || path.startsWith("/run/") || path.startsWith("/home/user/.config/")
|| path.startsWith("/home/user/.cache") || path.startsWith("/home/user/.local") ) {
return false;
}
// Avoid replacing if it's already the predefined file (prevent infinite loop)
if (path === "/tmp/predefined") {
return false;
}
// Otherwise, assume it's a user-requested file and should be repalced
return true;
}
main()
作为文本编辑器,我使用gnome-text-editor
Run frida 作为:./frida -l patcher.js -f /usr/bin/gnome-text-editor /tmp/originalFile
这似乎有效:/tmp/predefined
打开而不是/tmp/originalFile
。但是,如果我想为字符串“/tmp/predefined”分配新内存,并将指向此新内存的指针分配给 args[0],而不是重写 args[0] 指向的内存的内容(取消注释 (2) 行,注释掉 (1) 行),我会收到错误:
- 编辑器无法打开
/tmp/predefined
并写入Could Not Open File You do not have permissions to open the file
- 在终端中:
(gnome-text-editor:9036): editor-document-WARNING **: 11:11:33.542: Failed to load file: Error opening file /tmp/originalFile: No such file or directory
,但是/tmp/originalFile
存在。
由于这些错误仅当我尝试为字符串分配新内存并更改args[0]
指针的值时才会发生,所以我想知道我是否正确使用了 Frida 的 JavaScript API 中的内存分配?