LIAPP脱壳随记

游戏:永恒灵魂 1.34.101
LIAPP版本:v5.1.1.182
链接:没有,网上到处都是,自己下

逆向可参考下面两个,都是具体分析和绕过的,我这里就不细讲了,只讲脱壳方法,不同游戏可能不一样,抛砖引玉。

碎碎念:LIAPP整体看没啥难的,因为只是检测点多,java层调用native做检测,没有上混淆(好吧,so和java上做了简单的字符串混淆,但是交给ai问题不大),且没有对libil2cpp.so做任何处理,只是劫持了字符串常量以及com.liapp.y这些。

特征

如下图,apk中会存在.xxxx.dex,LIAPP.ini,libxxxx.so,加密的头部是LIKEY,AndroidManifest.xml里会把android:name改成com.liapp.x做初始化然后加载检测so,字符串由liapp.y运行时还原,所以脱壳的思路就是:运行时dump明文然后把 y.*(id) 回填就行




.xxxx.dex虽然是dex头,但是实际上是个加密的压缩包(后面就简写叫压缩包了),首次启动后会解压到内部目录的/files下.c15ca97d文件夹里(不同游戏应该不一样),里面会有解密后的jar,打开有个classes.dex,里面就是LIAPP劫持的字符串这些了

在x里, attachBaseContext 加载了 m1551,这个函数大概做了这些:

1.保存 ApplicationInfo、包名、版本、dataDir、sourceDir、ABI、uid、debugger 状态等信息

2.检查REQUEST_DELETE_PACKAGES,REQUEST_INSTALL_PACKAGES,ACCESS_SUPERUSER,SMS 这些权限

3. 加载 libcawwyayy

4.拼接一个逗号分隔的指纹串,调用 native 方法,这里记作 m1523,native 返回 8 段字符串,解析出: 压缩包路径,混淆 key / id,原 Application 类名(如果存在),其它参数巴拉巴拉

5.如果压缩包存在,通过反射插入ClassLoader.pathList.dexElements

6.super.attachBaseContext(context);

脱壳

jadx反编译下,可以看到字符串被改成了 String str = y.ֲֳگܱޭ(576040430); 这种
实际调用大概长这样:

y.<getter>(id) -> x.m1538(cmd=20, id, kind) -> native m1523(...) -> 返回明文字符串

kind < 4,x 把 id跟key异或:

在这个游戏里面f1711是333461951,上面说过,首次调用 native 时会返回 8 段字符串,第 6 段就是key

m1523是 java与native的桥梁,所有命令都走这个,其中cmd20就是用来字符串表查询的,其他的可以自己hook看看作用

LIAPP 把字符串常量分散到 y 的 8 个混淆 int->String getter 里, 还原字符串表时,(method, id) 才是完整 key;method决定 kind,kind决定 native 查询通道以及 kind<4 时的 xor 规则:

"ٱڳܴڭܩ": 0,
"ڳݬ٬ۮݪ": 1,
"׳ֳֳ֬د": 2,
"ׯ״ٲ֬ب": 3,
"״دش۲ݮ": 4,
"حֲݴܳޯ": 5,
"گܱޭ": 6,
"ڴݮگ֮ت": 7,

先用jadx导出反编译源码,然后写脚本提取id,参考脚本如下,执行
python xxx.py extract

from __future__ import annotations

import argparse
import pathlib
import re
import sys

ROOT = pathlib.Path(__file__).resolve().parents[3]
SOURCES = ROOT / "doc/apk/sources"
DUMPS = pathlib.Path(__file__).resolve().parents[1] / "dumps"
TABLE = DUMPS / "y_string_table.tsv"
IDS = DUMPS / "y_ids.tsv"

# payload y.java:m9/m18/m4/m3/m7/m8/m2/m19 -> m1538(cmd=20, id, kind)
KIND_BY_METHOD = {
    "ٱڳܴڭܩ": 0,
    "ڳݬ٬ۮݪ": 1,
    "׳ֳֳ֬د": 2,
    "ׯ״ٲ֬ب": 3,
    "״دش۲ݮ": 4,
    "حֲݴܳޯ": 5,
    "ֲֳگܱޭ": 6,
    "ڴݮگ֮ت": 7,
}

Y_CALL = re.compile(
    r"(?:com\.liapp\.)?y\.(" + "|".join(re.escape(m) for m in KIND_BY_METHOD) + r")\((-?\d+)\)"
)


def java_escape(s: str) -> str:
    return (
        '"'
        + (
            s.replace("\\", "\\\\")
            .replace('"', '\\"')
            .replace("\n", "\\n")
            .replace("\r", "\\r")
            .replace("\t", "\\t")
        )
        + '"'
    )


def load_table(path: pathlib.Path) -> dict[tuple[str, int], str]:
    out: dict[tuple[str, int], str] = {}
    if not path.exists():
        return out
    header_kind = False
    for i, line in enumerate(path.read_text(encoding="utf-8").splitlines()):
        if not line.strip():
            continue
        parts = line.split("\t")
        if i == 0 and parts[0] == "method":
            header_kind = "kind" in parts
            continue
        if len(parts) < 3:
            continue
        text = parts[3] if header_kind and len(parts) >= 4 else parts[-1]
        out[(parts[0], int(parts[1]))] = text
    return out


def scan_sources(root: pathlib.Path) -> list[tuple[pathlib.Path, str, int]]:
    sites: list[tuple[pathlib.Path, str, int]] = []
    for p in root.rglob("*.java"):
        text = p.read_text(encoding="utf-8", errors="replace")
        for m in Y_CALL.finditer(text):
            sites.append((p, m.group(1), int(m.group(2))))
    return sites


def load_ids(path: pathlib.Path) -> list[tuple[str, int]]:
    out: list[tuple[str, int]] = []
    if not path.exists():
        return out
    for i, line in enumerate(path.read_text(encoding="utf-8").splitlines()):
        if not line.strip():
            continue
        parts = line.split("\t")
        if i == 0 and parts[0] == "method":
            continue
        if len(parts) < 2:
            continue
        out.append((parts[0], int(parts[1])))
    return out


def write_generated_js(uniq: list[tuple[str, int]]) -> pathlib.Path:
    gen = pathlib.Path(__file__).resolve().parent / "y_ids.generated.js"
    js = ["var Y_CALL_IDS = ["]
    for method, sid in uniq:
        js.append(f'  ["{method}", {sid}],')
    js.append("];")
    gen.write_text("\n".join(js) + "\n", encoding="utf-8")
    return gen


def cmd_extract(args: argparse.Namespace) -> int:
    sites = scan_sources(SOURCES) if SOURCES.is_dir() else []
    uniq = sorted({(m, i) for _, m, i in sites}, key=lambda x: (x[0], x[1]))
    if uniq:
        IDS.parent.mkdir(parents=True, exist_ok=True)
        lines = ["method\tid\tkind"]
        for method, sid in uniq:
            lines.append(f"{method}\t{sid}\t{KIND_BY_METHOD[method]}")
        IDS.write_text("\n".join(lines) + "\n", encoding="utf-8")
        print(f"wrote {IDS}")
    else:
        uniq = load_ids(IDS)
        print(f"no JADX sources at {SOURCES}; using {IDS} n={len(uniq)}")
    if not uniq:
        print("no ids to write", file=sys.stderr)
        return 1
    gen = write_generated_js(uniq)
    table = load_table(TABLE)
    hit = {(m, i) for m, i in uniq if (m, i) in table}
    print(f"literal_sites={len(sites)} unique={len(uniq)} table={len(table)}")
    print(f"covered={len(hit)} ({100 * len(hit) / len(uniq):.1f}%) missing={len(uniq) - len(hit)}")
    print(f"wrote {gen}")
    return 0


def cmd_backfill(args: argparse.Namespace) -> int:
    table = load_table(TABLE)
    if not table:
        print("empty table", file=sys.stderr)
        return 1
    out_root = pathlib.Path(args.out)
    sites = scan_sources(SOURCES)
    files = sorted({p for p, _, _ in sites})
    n_file = n_repl = 0
    for src in files:
        text = src.read_text(encoding="utf-8", errors="replace")

        def repl(m: re.Match[str]) -> str:
            nonlocal n_repl
            key = (m.group(1), int(m.group(2)))
            if key not in table:
                return m.group(0)
            n_repl += 1
            return java_escape(table[key])

        new = Y_CALL.sub(repl, text)
        if new == text:
            continue
        dest = out_root / src.relative_to(SOURCES)
        dest.parent.mkdir(parents=True, exist_ok=True)
        dest.write_text(new, encoding="utf-8")
        n_file += 1
    print(f"wrote {n_file} files, {n_repl} replacements -> {out_root}")
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__)
    sub = ap.add_subparsers(dest="cmd", required=True)

    sub.add_parser("extract", help="scan JADX sources -> dumps/y_ids.tsv")

    p_bf = sub.add_parser("backfill", help="replace known y.*(id) with string literals")
    p_bf.add_argument(
        "--out",
        type=pathlib.Path,
        default=DUMPS / "sources_restored",
    )

    args = ap.parse_args()
    if args.cmd == "extract":
        return cmd_extract(args)
    if args.cmd == "backfill":
        return cmd_backfill(args)
    return 2


if __name__ == "__main__":
    sys.exit(main())

会生成y_ids.tsv和y_ids.generated.js,接着写frida脚本dump就完事了
frida -U -f com.kakaogames.eversoul -l y_ids.generated.js -l xxx.js

"use strict";

const PKG = "com.kakaogames.eversoul";
const DUMP_DIR = "/data/data/" + PKG + "/files/liapp_dumps";
const SO_NEEDLE = "cawwyayy";
const Y_SKIP = {
  "0123456789ABCDEF": 1,
};

let nativeFnNoted = false;
let dexHooked = false;
let yHooked = false;
let yBusy = false;
let yDumped = false;
let yDumping = false;
const ySeen = {};
const Y_IDS_PATH = DUMP_DIR + "/y_ids.tsv";
const Y_FULL_PATH = DUMP_DIR + "/y_full.tsv";

function log(msg) {
  console.log("[liapp] " + msg);
}

function clip(s, n) {
  if (s === null || s === undefined) return "null";
  s = "" + s;
  return s.length > n ? s.slice(0, n) : s;
}

function moduleOf(ptr) {
  try {
    const m = Process.findModuleByAddress(ptr);
    return m ? m.name : "?";
  } catch (e) {
    return "?";
  }
}

function ensureDir() {
  try {
    const File = Java.use("java.io.File");
    const f = File.$new(DUMP_DIR);
    if (!f.exists()) f.mkdirs();
  } catch (e) {
    log("mkdir failed: " + e);
  }
}

function dumpPath(srcPath) {
  try {
    const File = Java.use("java.io.File");
    const Files = Java.use("java.nio.file.Files");
    const Paths = Java.use("java.nio.file.Paths");
    const src = File.$new(srcPath);
    if (!src.exists()) {
      log("dump skip, missing " + srcPath);
      return;
    }
    const bytes = Files.readAllBytes(Paths.get(srcPath, Java.array("java.lang.String", [])));
    const Fos = Java.use("java.io.FileOutputStream");
    const name = "loadDex_" + (src.getName() || "payload");
    const out = File.$new(DUMP_DIR, name);
    const fos = Fos.$new(out);
    fos.write(bytes);
    fos.close();
    log("dumped " + out.getAbsolutePath() + " size=" + bytes.length);
  } catch (e) {
    log("dumpPath failed: " + e);
  }
}

function notePayloadPath(p) {
  const s = "" + p;
  log("payload " + s);
  const marker = "/files/";
  const i = s.indexOf(marker);
  if (i !== -1) {
    const rel = s.slice(i + marker.length);
    const parts = rel.split("/");
    log(
      "payload rel=" +
        rel +
        " dir=" +
        parts.slice(0, -1).join("/") +
        " jar=" +
        parts[parts.length - 1]
    );
  }
}

function noteNativeFn(fnPtr, label) {
  if (nativeFnNoted) return;
  if (!fnPtr || fnPtr.isNull()) return;
  nativeFnNoted = true;
  const mod = Process.findModuleByAddress(fnPtr);
  const off = mod ? fnPtr.sub(mod.base) : ptr(0);
  log(
    "m1523 registered " +
      fnPtr +
      " (" +
      label +
      ") so=" +
      (mod ? mod.name : "?") +
      " off=" +
      off
  );
}

function hookArtRegisterNatives() {
  const art = Process.findModuleByName("libart.so");
  if (!art) {
    log("libart.so not found yet");
    return 0;
  }
  let n = 0;
  art.enumerateSymbols().forEach(function (s) {
    const name = s.name;
    if (name.indexOf("RegisterNatives") === -1) return;
    if (name.indexOf("CheckJNI") !== -1) return;
    if (name.indexOf("IsRegistered") !== -1) return;
    if (name.indexOf("Unregister") !== -1) return;
    if (!s.address) return;
    try {
      Interceptor.attach(s.address, {
        onEnter: function (args) {
          const methods = args[2];
          const count = args[3].toInt32();
          if (count <= 0 || count > 32 || methods.isNull()) return;
          for (let i = 0; i < count; i++) {
            const slot = methods.add(i * Process.pointerSize * 3);
            const mName = slot.readPointer().readCString();
            const sig = slot.add(Process.pointerSize).readPointer().readCString();
            const fn = slot.add(Process.pointerSize * 2).readPointer();
            const so = moduleOf(fn);
            if (so.indexOf(SO_NEEDLE) === -1 && (!sig || sig.indexOf("Landroid/app/Application;") === -1)) {
              continue;
            }
            log("RegisterNatives " + mName + " " + sig + " fn=" + fn + " so=" + so);
            if (
              sig &&
              sig.indexOf("Landroid/content/Context;") !== -1 &&
              sig.indexOf("III") !== -1 &&
              sig.indexOf("Landroid/app/Application;") !== -1
            ) {
              noteNativeFn(fn, mName);
            }
          }
        },
      });
      n += 1;
      log("hooked art " + name);
    } catch (e) {
      log("RegisterNatives attach skip " + name + ": " + e);
    }
  });
  return n;
}

function hookDexLoaders() {
  if (dexHooked) return;
  dexHooked = true;
  Java.perform(function () {
    ensureDir();

    try {
      const DexFile = Java.use("dalvik.system.DexFile");
      DexFile.loadDex.overload("java.lang.String", "java.lang.String", "int").implementation = function (
        src,
        out,
        flags
      ) {
        log("DexFile.loadDex src=" + src + " out=" + out);
        dumpPath(src);
        return this.loadDex(src, out, flags);
      };
      log("hooked DexFile.loadDex");
    } catch (e) {
      log("DexFile.loadDex: " + e);
    }

    try {
      const DPL = Java.use("dalvik.system.DexPathList");
      DPL.makePathElements.overload("java.util.List", "java.io.File", "java.util.List").implementation =
        function (files, optimized, suppressed) {
          try {
            const it = files.iterator();
            while (it.hasNext()) {
              const f = it.next();
              notePayloadPath(f);
              dumpPath("" + f);
            }
          } catch (e2) {
            log("makePathElements list: " + e2);
          }
          return this.makePathElements(files, optimized, suppressed);
        };
      log("hooked DexPathList.makePathElements");
    } catch (e) {
      log("makePathElements: " + e);
    }

    try {
      const CL = Java.use("java.lang.ClassLoader");
      CL.loadClass.overload("java.lang.String").implementation = function (name) {
        if (
          name &&
          name.indexOf("com.liapp.") === -1 &&
          (name.indexOf("Application") !== -1 ||
            name.indexOf("com.kakao") === 0 ||
            name.indexOf("com.kakaogames") === 0 ||
            name.indexOf("com.unity3d") === 0)
        ) {
          log("loadClass " + name);
        }
        return this.loadClass(name);
      };
      log("hooked ClassLoader.loadClass (filtered)");
    } catch (e) {
      log("loadClass: " + e);
    }
  });
}

function tryHookY() {
  if (yHooked || yBusy) return;
  yBusy = true;
  Java.perform(function () {
    try {
      const Y = Java.use("com.liapp.y");
      let nHook = 0;
      Y.class.getDeclaredMethods().forEach(function (m) {
        if (m.getParameterTypes().length !== 1) return;
        if (String(m.getReturnType()) !== "class java.lang.String") return;
        if (String(m.getParameterTypes()[0]) !== "int") return;
        const name = m.getName();
        Y[name].overload("int").implementation = function (id) {
          const s = this[name](id);
          if (yDumping) return s;
          const key = name + ":" + id;
          if (!ySeen[key] && !Y_SKIP[s]) {
            ySeen[key] = 1;
            log("y." + name + "(" + id + ") => " + clip(s, 160));
          }
          return s;
        };
        nHook += 1;
      });
      yHooked = true;
      log("hooked com.liapp.y string getters: " + nHook);
      setTimeout(dumpAllYFromDevice, 1500);
    } catch (e) {
      yBusy = false;
    }
  });
}

function readDeviceTsv(path) {
  const File = Java.use("java.io.File");
  const f = File.$new(path);
  if (!f.exists()) return [];
  const br = Java.use("java.io.BufferedReader").$new(
    Java.use("java.io.InputStreamReader").$new(Java.use("java.io.FileInputStream").$new(f), "UTF-8")
  );
  const rows = [];
  let line;
  while ((line = br.readLine()) !== null) {
    if (line.indexOf("\t") === -1 || line.indexOf("method") === 0) continue;
    const p = line.split("\t");
    if (p.length < 2) continue;
    rows.push([p[0], parseInt(p[1], 10)]);
  }
  br.close();
  return rows;
}

function writeDeviceText(path, text) {
  const Fos = Java.use("java.io.FileOutputStream");
  const fos = Fos.$new(path);
  fos.write(Java.use("java.lang.String").$new(text).getBytes("UTF-8"));
  fos.close();
}

function loadDumpRows() {
  if (typeof Y_CALL_IDS !== "undefined" && Y_CALL_IDS && Y_CALL_IDS.length) {
    return Y_CALL_IDS;
  }
  return [];
}

function dumpAllYFromDevice() {
  if (yDumped || !yHooked) return;
  Java.perform(function () {
    try {
      const rows = loadDumpRows();
      yDumped = true;
      yDumping = true;
      const Y = Java.use("com.liapp.y");
      let ok = 0;
      const out = ["method\tid\tstring"];
      for (let i = 0; i < rows.length; i++) {
        const name = rows[i][0];
        const id = rows[i][1];
        try {
          const s = ("" + Y[name](id)).replace(/\t/g, " ").replace(/\r?\n/g, "\\n");
          out.push(name + "\t" + id + "\t" + s);
          ok += 1;
          log("Y\t" + name + "\t" + id + "\t" + s);
        } catch (e1) {
          log("Yfail\t" + name + "\t" + id + "\t" + e1);
        }
      }
      yDumping = false;
      writeDeviceText(Y_FULL_PATH, out.join("\n") + "\n");
      log("dump-all y done " + ok + "/" + rows.length + " -> " + Y_FULL_PATH);
    } catch (e) {
      yDumping = false;
      log("dump-all failed: " + e);
    }
  });
}

function watchCawwyayy() {
  const t = setInterval(function () {
    const mod = Process.findModuleByName("libcawwyayy.so");
    if (!mod) return;
    clearInterval(t);
    log("libcawwyayy.so base=" + mod.base + " size=" + mod.size);
  }, 50);
}

setImmediate(function () {
  const n = hookArtRegisterNatives();
  hookDexLoaders();
  watchCawwyayy();
  const yPoll = setInterval(function () {
    tryHookY();
    if (yHooked) clearInterval(yPoll);
  }, 800);
});

id dump全后,拉回来执行python xxx.py backfill 就可以回填字符串了
如果你不会藏frida,这里有个最简单方法过LIAPP的检测,具体的自己看看native就知道了

const targetSoName = "libcawwyayy.so";

const dummyThreadFunc = new NativeCallback(
    function () {
        return ptr(0);
    },
    "pointer",
    []
);

const pthreadCreatePtr = Module.findExportByName("libc.so", "pthread_create");
if (pthreadCreatePtr) {
    Interceptor.attach(pthreadCreatePtr, {
        onEnter: function (args) {
            const startRoutine = args[2];
            const module = Process.findModuleByAddress(startRoutine);
            if (module && module.name === targetSoName) {
                const offset = startRoutine.sub(module.base);
                args[2] = dummyThreadFunc;
            }
        }
    });
}

下面就是愉快的删壳重打包时间了

还原前后对比,这里入口点我改成了我自己写的集成离线了:


3 个赞

不过不知道是不是官方也看了看雪的那篇文章,后面对于崩溃函数的玩法就多了起来
46秒延迟崩溃


写空段错误

向AndroidRuntime 写数据段错误崩溃?

此外还加了看门狗

但是吧,它检测大部分靠新建线程来做,而且不校验返回。。。

只能说成也pthread_create,败也pthread_create了属于了

1 个赞

能力全点反调试和环境检测上面去了,so加密都不带加密的,global-metadata.dat的LIKEY容器也不算很难

2 个赞

是这样,替换pthread_create就基本全过,而且韩国手游还特喜欢用这个

1 个赞