implement method code setter in apk struct

This commit is contained in:
Jean-Marie 'Histausse' Mineau 2024-01-23 17:08:37 +01:00
parent 8dce87d569
commit 3a6edf1aa2
Signed by: histausse
GPG key ID: B66AEEDA9B645AD2
3 changed files with 37 additions and 12 deletions

View file

@ -2342,12 +2342,26 @@ impl Apk {
}
#[pyo3(name = "add_dex_file")]
fn py_add_dex_file(&mut self, data: &[u8]) -> Result<()> {
pub fn py_add_dex_file(&mut self, data: &[u8]) -> Result<()> {
self.add_dex_file(data)
}
pub fn set_method_code(&mut self, method_id: IdMethod, code: Option<Code>) -> Result<()> {
let class = self
.classes
.get_mut(&method_id.class_)
.ok_or_else(|| anyhow!("Class {} not found", method_id.class_.__repr__()))?;
let method = class
.direct_methods
.get_mut(&method_id)
.or_else(|| class.virtual_methods.get_mut(&method_id))
.ok_or_else(|| anyhow!("Method {} not found", method_id.__repr__()))?;
method.code = code;
Ok(())
}
#[pyo3(name = "gen_raw_dex")] //Sad GIL noise
fn py_gen_raw_dex(&self, py: Python<'_>) -> Result<Vec<PyObject>> {
pub fn py_gen_raw_dex(&self, py: Python<'_>) -> Result<Vec<PyObject>> {
Ok(self
.gen_raw_dex()?
.into_iter()

View file

@ -2753,7 +2753,7 @@ enum Section {
}
impl Section {
const VARIANT_LIST: &[Self] = &[
const VARIANT_LIST: &'static [Self] = &[
Self::HeaderItem,
Self::StringIdItem,
Self::TypeIdItem,

29
test.py
View file

@ -9,7 +9,7 @@ import zipfile as z
from androscalpel import *
# APK_NAME = "test.apk"
APK_NAME = "/home/histausse/workspace/androscalpel/apk_frauder/app-release.apk"
APK_NAME = __file__.removesuffix("test.py") + "/apk_frauder/app-release.apk"
DEX_NAME = "classes.dex"
with z.ZipFile(APK_NAME) as zipf:
@ -25,13 +25,16 @@ method_id = IdMethod("text_gen", proto_id, clazz_id)
clazz = apk.classes[clazz_id]
method = clazz.virtual_methods[method_id]
code = method.code
print("Code of {method_id}")
for i in method.code.insns:
logging.getLogger().setLevel(logging.ERROR)
print(f"Code of {method_id}")
for i in code.insns:
print(i)
new_insns = []
for i in method.code.insns:
for i in code.insns:
if isinstance(i, asc.ins.ConstString):
if i.lit == "Hello":
i.lit = DexString("Degemer Mat")
@ -40,11 +43,19 @@ for i in method.code.insns:
new_insns.append(i)
# This need improving!
new_code = method.code
new_code.insns = new_insns
method.code = new_code
clazz.virtual_methods[method_id] = method
apk.classes[clazz_id] = clazz
code.insns = new_insns
apk.set_method_code(method_id, code)
# apk.set_method_code(method.descriptor, code)
clazz = apk.classes[clazz_id]
method = clazz.virtual_methods[method_id]
code = method.code
print(f"Code of {method_id}")
for i in code.insns:
print(i)
dex_raw = apk.gen_raw_dex()
assert len(dex_raw) == 1
with open(DEX_NAME + ".out", "wb") as file:
file.write(dex_raw[0])