Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

動手實作 Android 資源混淆:改寫 AAPT 的 Resource.cpp

編輯:關於 Android 程式設計

美團那篇《Android 資源混淆保護實踐》讀完,方向很清楚,但關鍵的那個函式並沒有公開——它把 getObfuscationName() 當成一個黑盒,實作留給讀者。本文就是想把這個黑盒拆開,寫出可以自己編譯驗證的版本。

一、動刀的位置

以 Android 5.0 的系統原始碼為例,要改的是:

/frameworks/base/tools/aapt/Resource.cpp

改動集中在 makeFileResources() 這個函式裡。原始版本大致如下:

static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
                                  ResourceTable* table,
                                  const sp<ResourceTypeSet>& set,
                                  const char* resType) {
    String8 type8(resType);
    String16 type16(resType);
    bool hasErrors = false;
    ResourceDirIterator it(set, String8(resType));
    ssize_t res;
    while ((res = it.next()) == NO_ERROR) {
        if (bundle->getVerbose()) {
            printf("    (new resource id %s from %s)\n",
                   it.getBaseName().string(),
                   it.getFile()->getPrintableSource().string());
        }
        String16 baseName(it.getBaseName());
        const char16_t* str = baseName.string();
        const char16_t* const end = str + baseName.size();
        while (str < end) {
            if (!((*str >= 'a' && *str <= 'z')
                    || (*str >= '0' && *str <= '9')
                    || *str == '_' || *str == '.')) {
                fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]",
                        it.getPath().string());
                hasErrors = true;
            }
            str++;
        }
        String8 resPath = it.getPath();
        resPath.convertToResPath();
        table->addEntry(SourcePos(it.getPath(), 0),
                        String16(assets->getPackage()),
                        type16, baseName, String16(resPath), NULL, &it.getParams());
        assets->addResource(it.getLeafName(), resPath, it.getFile(), type8);
    }
    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
}

美團給出的差異只有幾行:多了一個 obfuscationPath,然後把原本傳入 resPath 的地方全部換掉。

String8 obfuscationName;
String8 obfuscationPath = getObfuscationName(resPath, obfuscationName);
table->addEntry(SourcePos(it.getPath(), 0),
                String16(assets->getPackage()),
                type16, baseName,
                String16(obfuscationPath),   // 原本: resPath
                NULL, &it.getParams());
assets->addResource(it.getLeafName(),
                    obfuscationPath /*resPath*/,
                    it.getFile(), type8);

所以真正的功課就是把 getObfuscationName() 寫出來。

二、先搞懂手上有哪些材料

要自己拼出路徑,得先知道幾個方法的意義:

getBaseName():資源名稱,不含副檔名,例如 icon。

getLeafName():資源名稱,含副檔名,例如 icon.png。

getParams():限定符,例如 xxhdpi-v4。回傳的是物件,要轉字串得呼叫 toString(),且結果不含前綴的 -。

convertToResPath():把路徑中的反斜線換成正斜線,例如 res\drawable → res/drawable。這個方法屬於 String8。

resType:函式參數傳進來的資源類型,內部已用 String8 type8(resType) 轉好,直接用即可,例如 drawable。注意它同樣不含限定符。

三、把 res 換成 r

預設打包時資源都在 res 目錄下。我們的目標是依一定規則把它們搬到 r 目錄,這樣反編譯工具看到的就只剩一團 r/xx/xx.png,無從對照原始結構。

先取限定符:

String8 params = it.getParams().toString();

限定符可能是空的,所以要分兩路處理。再準備一個用來存放新路徑的字串:

String8 obfuscationPath();

限定符為空時,直接拼接:

if (params.isEmpty()) {
    obfuscationPath.append("r/");              // 目標目錄
    obfuscationPath.append(type8);             // 資源類型
    obfuscationPath.append("/");
    obfuscationPath.append(it.getLeafName());  // 含副檔名的檔名
}

限定符不為空時,中間插入 - 與限定符:

if (params.isEmpty()) {
    // ...上面那段...
} else {
    obfuscationPath.append("r/");
    obfuscationPath.append(type8);
    obfuscationPath.append("-");
    obfuscationPath.append(params);
    obfuscationPath.append("/");
    obfuscationPath.append(it.getLeafName());
}

最後把打包時的 resPath 換成 obfuscationPath:

table->addEntry(SourcePos(it.getPath(), 0),
                String16(assets->getPackage()),
                type16, baseName, String16(obfuscationPath), NULL, &it.getParams());
assets->addResource(it.getLeafName(), obfuscationPath, it.getFile(), type8);

四、完整函式

static status_t makeFileResources(Bundle* bundle, const sp<AaptAssets>& assets,
                                  ResourceTable* table,
                                  const sp<ResourceTypeSet>& set,
                                  const char* resType) {
    String8 type8(resType);
    String16 type16(resType);
    bool hasErrors = false;
    ResourceDirIterator it(set, String8(resType));
    ssize_t res;
    while ((res = it.next()) == NO_ERROR) {
        if (bundle->getVerbose()) {
            printf("    (new resource id %s from %s)\n",
                   it.getBaseName().string(),
                   it.getFile()->getPrintableSource().string());
        }
        String16 baseName(it.getBaseName());
        const char16_t* str = baseName.string();
        const char16_t* const end = str + baseName.size();
        while (str < end) {
            if (!((*str >= 'a' && *str <= 'z')
                    || (*str >= '0' && *str <= '9')
                    || *str == '_' || *str == '.')) {
                fprintf(stderr, "%s: Invalid file name: must contain only [a-z0-9_.]",
                        it.getPath().string());
                hasErrors = true;
            }
            str++;
        }
        String8 resPath = it.getPath();
        resPath.convertToResPath();

        String8 params = it.getParams().toString();
        String8 obfuscationPath();
        if (params.isEmpty()) {
            obfuscationPath.append("r/");
            obfuscationPath.append(type8);
            obfuscationPath.append("/");
            obfuscationPath.append(it.getLeafName());
        } else {
            obfuscationPath.append("r/");
            obfuscationPath.append(type8);
            obfuscationPath.append("-");
            obfuscationPath.append(params);
            obfuscationPath.append("/");
            obfuscationPath.append(it.getLeafName());
        }
        fprintf(stderr, "    our Path:%s\n", obfuscationPath.string());

        table->addEntry(SourcePos(it.getPath(), 0),
                        String16(assets->getPackage()),
                        type16, baseName, String16(obfuscationPath), NULL, &it.getParams());
        assets->addResource(it.getLeafName(), obfuscationPath, it.getFile(), type8);
    }
    return hasErrors ? STATUST(UNKNOWN_ERROR) : NO_ERROR;
}

五、編譯與驗證

改完之後重新編譯出 aapt,用它取代原本的工具再打包一次。

這裡寫圖片描述

如果 apk 裡的資源已經從 res/ 變成 r/,說明改動生效了。

六、真正的混淆還差一步

搬到 r 目錄只是第一步,目錄名稱還是 drawable、layout 這些一看就懂的英文。真正的混淆要模仿 Java 類別混淆的思維:把 anim 映射成 a、color 映射成 b,以此類推;目錄下的檔案也依序改名。a 到 z 不夠用就換成 aa 到 zz,甚至 aaa 到 zzz。

關鍵就在這個「原名 → 混淆名」的對照函式,而它必須是雙射的——因為 resources.arsc 裡存的是資源 ID 與名稱的對應關係,打包時改名,執行期靠 ID 查找,兩邊對得上就不會出問題。實作上通常會準備一份靜態的字元序列產生器,搭配一個 map 記錄映射關係,並把這份對照表另外存檔,方便線上排查時反查。

這部分實作難度並不高,只是瑣碎。有興趣的可以照上面的骨架自己補完——記得改動 AAPT 屬於侵入式修改,每次 Android 版本升級都要重新對齊一次原始碼差異,這點在維護成本上要事先想清楚。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved