Android(-1) 逆向笔记杂记

推荐肉丝r0ysue课程(包含安卓逆向与js逆向):

乱七八糟的一些东西,本地删了,备份

环境搭建

  1. JDK安装及配置

    链接:https://pan.baidu.com/s/146I4vDJdz8YeR0OEqLS8xw 提取码:7h00

  2. SDK环境配置

    链接:https://pan.baidu.com/s/1A8rwqyw8Nn7p93Axqpll3A 提取码:cwv4

  3. NDK环境配置

    链接:https://pan.baidu.com/s/1GBFK8r5R_GPSnIpTwpljKw 提取码:aj1a

  4. eclipse集成开发环境搭建

    链接:https://pan.baidu.com/s/1LSwwRX9KdkPIjMDbdUzTRA 提取码:f224

  5. Android Studio环境搭建

    链接:https://pan.baidu.com/s/1VOzGZZrFy1otg42uxa9Tzg 提取码:rdu6

  6. jadx工具介绍及使用

    链接:https://pan.baidu.com/s/1f6gRO81fGL6RSY8gzsvOwA 提取码:1d97

  7. JEB工具介绍及使用

    链接:https://pan.baidu.com/s/11LDq4DM4PsoTIL9hcy4BmA 提取码:2ukx

JDK配置

参考https://blog.csdn.net/Palmer9/article/details/106518530

SDK配置

添加环境变量

\sdk\platform-tools
\sdk\tools

NDK配置

添加环境变量

\ndk

虚拟机

  • dalvik虚拟机(jlt机制)

    • Android 5.0以下
  • art虚拟机(aot机制)

    • Android 5.0版本及以上
  • 区分是哪种

    # 查看系统目录
    /system/bin/dexopt	# dalvik虚拟机 
    /system/bin/dex2oat	# art虚拟机
    
    .dex -> dexopt -> .odex		# dalvik加载执行odex文件
    .dex -> dex2oat -> .oat		# art加载执行oat文件
    

Apk文件结构

  • assets 打包在apk里的静态资源文件
  • lib 当前app所使用的so文件,so文件采用底层c,c++代码实现
  • META-INF apk的签名校验
    • META-INF/MANIFEST证书签名文件
  • res 存放资源文件,可以被索引
  • AndroidManifest.xml 版本权限,组件声明
  • classes.dex 应用程序的可执行文件
  • resources.arsc 资源索引表,用来描述具有ID值的资源的配置信息

APK打包流程

请添加图片描述

APK安装流程

system/app	系统自带应用程序,获得adb root权限才能删除
data/app	用户程序安装的目录,安装时将apk文件复制到此目录
data/data	存放应用程序的数据
data/dalvik-cache	将apk的dex文件安装到此目录(dex是dalvik虚拟机的可执行文件)
  • 安装过程
    • 复制apk安装包到data/app目录下,解压并扫描安装包,把dex文件保存到dalvik-cache目录,并data/data目录下创建对应的应用数据目录
  • 写在过程
    • 删除安装过程中在上述三个目录下创建的文件及目录

AndroidKiller使用与配置

  1. 配置jdk
  2. 配置新版apktool

修改apk图标名称

AndroidManifest.xml

  • <package> 包名
  • <uses-permission> apk使用的权限
  • <application> 程序入口点
    • android:icon apk图标
    • android:label apk名称
    • android:name 入口界面
    • <provider> 发布者签名
    • <activity> 程序的界面

搜索关键字进行修改

修改包名实现分身

修改<xml>package包名,在后添加

搜索AndroidManifest.xml中的<provider,在,它的每个android:authorities后随便加点什么

(只能实现相同签名应用多开)

修改资源去广告

  • 去除联网权限

  • 去除开屏启动广告

    <!--入口界面activity特征-->
    <activity>
    	<intent-filter>
    		<action android:name="android.intent.action.MAIN"/>
    		<category android:name="android.intent.category.LAUNCHER"/>
    	</intent-filter>
    </activity>
    
    adb devices	#查看当前设备列表
    adb shell dumpsys activity top		# 查看当前顶层activity活动
    

20210321

使用apktool反编译对程序进行调试

  1. 对apk进行反编译(异常报错,暂未成功)

    apktool d -d xx.apk -o xxdir
    # 参考官网apktool用法https://ibotpeaches.github.io/Apktool/install/
    

    xx.apk:需要反编译的目标apk

    xxdir:存放反编译结果的目标目录

    能反编译的最高apktool版本为apktool_2.0.3.jar

    SmaliDebugging has been removed in 2.1.0 onward.

  2. 修改AndroidManifest.xmlapplication节点,添加android:debuggable="true"属性

  3. 在入口点类的onCreate方法中添加invoke-static{},Landroid/os/Debug;->waitForDebugger()V

  4. 对apk进行回编译

    apktool b -d xxdir -o new.apk
    
  5. 对apk文件进行签名

    java -jar signakp.jar xx.pem xx.pk8
    
  6. AndroidStudio导入编译后的文件目录,下断点

  7. 设置远程调试Run -> Debug Congigurations -> Remote Java Application Host:localhost:8700

使用AndroidKiller反编译配合AndroidStudio对程序进行调试

  1. AndroidStudio安装smalidea(设置高亮及断点)

    在Settings中

  2. 使用AndroidKiller对apk进行反编译

  3. 【工程管理器】->【项目名】->【右键->打开方式->打开文件路径】

  4. 复制【文件路径\Project】到AndroidStudio打开【Open an Existing Project】

  5. Configure Framework,默认OK

  6. AS添加远程调试

    1. 菜单栏->Run->Edit Configurations
    2. 点【+】,添加【Remote】,修改端口localhost:8700
  7. adb启动调试apk(需先安装调试apk)

    adb shell am start -D -n {package}/{name}
    # AndroidManifest.xml
    # {package}:<manifest>节点 package属性
    # {name}:主<activity>节点 android:name属性
    
  8. 打开Android Device Monitor,点击模拟器下的{package}来设置端口

    • AS4.0版本已经没有快捷按钮,路径:sdk\tools\monitor.bat

    • 如果模拟器下无对应包,重启adb服务,并重新进行第【7】步

      adb kill-server
      adb start-server
      
  9. AS在smali下 行号前双击 设置断点,点击调试按钮进行调试

tips

  • AndroidKiller中smali文件修改
    • 可直接注释跳转修改apk运行流程
    • 可 右键->插入代码,插入log方便调试

20210322

Android Device Monitor

添加Log过滤

LogCat标签 -> Saved Filters -> + ,可设置各种过滤条件

视频去启动广告

抓包找到广告网址全局替换为空

Q&A

resource spec: 0x01010540

apktool d反编译报错resource spec: 0x01010540

winhex 字节形式搜索报错的16进制数的小端字节(就是40050101替换成8f040101

resource spec: 0x01010543

apktool d反编译报错resource spec: 0x01010540

使用十六进制编辑器 字节形式搜索报错的16进制数的小端字节(就是12345678写成78564312
这里我们搜索43050101,然后把它前面的字节0x02修改为0x03,保存后替换进apk即可

20210323

写了写java代码

Q&A

AndroidStudio 报错中文乱码

AndroidStudio 报错中文乱码

AndroidStudio安装目录bin目录下,找到以下两个文件

Android Studio\bin\studio64.exe.vmoptions
Android Studio\bin\studio.exe.vmoptions

notepad++打开末尾添加

-Dfile.encoding=UTF-8

解决

20210326-学习随笔

Q&A

IDEA警告Wrong tag

IDEA警告 Wrong tag

方法【1】给自定义标签添加描述

Alt+Enter,Add Description to custom tags

方法【2】忽略这个警告类型

Settings -> Editor -> Inspections -> java -> javadoc -> Declaration has javadoc problems -> No highlighting, only fix

20210331-学习随笔

Q&A

IDEA Tomcat与控制台 乱码

Tomcat命令行窗口乱码

  • 通过注册表修改Tomcat命令窗口的默认字符编码为UTF-8即可解决
    • 第一步:Windows+R打开运行,输入regedit进入注册表编辑器

    • 第二步:路径 计算机\HKEY_CURRENT_USER\Console\Tomcat,如果没有,在Console下新建项Tomcat

    • 第三步:新建DWORD值CodePage,右键->修改->10进制65001

    • 可以解决Tomcat startup.bat乱码

IDEA控制台乱码解决

首先要分清是tomcat日志编码,与idea的日志显示控制台编码

  • tomcat日志编码:tomcat根目录\bin\catalina.bat

    • 首行添加chcp 65001切换cmd为utf8
    • chcp 936切换cmd为gbk(题外话,不需要做)
    • 确定tomcat日志编码,一般因为tomcat/conf/logging.propertiesjava.util.logging.ConsoleHandler.encoding = UTF-8已设置为utf8

    做了上一步,可以不做这一步

  • idea显示编码:windows默认用gbk所以idea显示默认为gbk编码

    • 【一定】在 Help-- custom vm options 添加
    -Dfile.encoding=UTF-8
    
    • 强制为utf8编码显示,不要自己改.vmoptions,可能位置不对,idea会在用户目录复制一个
    • 【切忌】自己改tomcat的logging.properties 为GBK 会导致调试时IDEA get/post参数乱码

20210408-学习随笔

DEX文件结构

dex文件整体结构

结构名称解释
dex headerdex文件头部,记录整个dex文件的相关属性
string_ids字符串数据索引,记录了每个字符串的偏移量
type_ids数据类型数组,记录了每个类型在string_ids数组中的的字符串索引
proto_ids方法声明的偏移量,记录了方法声明的字符串,返回类型字符串,参数列表
field_ids字段数据索引,记录了所属类,类型以及方法名
method_ids类方法索引,记录方法所属类名,方法声明以及方法名等信息
class_defs类定义数据索引,记录指定类各类信息,包括接口,超类,类数据偏移量
data数据区,保存了各个类的真实数据
link_data静态链接数据区

dex header

struct DexHeader {
    u1  magic[8];           /* 版本标识 */
    u4  checksum;           /* adler32 检验 */
    u1  signature[kSHA1DigestLen]; /* SHA-1 哈希值 */
    u4  fileSize;           /* 整个文件大小 */
    u4  headerSize;         /* DexHeader 大小 */
    u4  endianTag;          /* 字节序标记 */
    u4  linkSize;           /* 链接段大小 */
    u4  linkOff;            /* 链接段偏移 */
    u4  mapOff;             /* DexMapList 的文件偏移 */
    u4  stringIdsSize;      /* DexStringId 的个数 */
    u4  stringIdsOff;       /* DexStringId 的文件偏移 */
    u4  typeIdsSize;        /* DexTypeId 的个数 */
    u4  typeIdsOff;         /* DexTypeId 的文件偏移 */
    u4  protoIdsSize;       /* DexProtoId 的个数 */
    u4  protoIdsOff;        /* DexProtoId 的文件偏移 */
    u4  fieldIdsSize;       /* DexFieldId 的个数 */
    u4  fieldIdsOff;        /* DexFieldId 的文件偏移 */
    u4  methodIdsSize;      /* DexMethodId 的个数 */
    u4  methodIdsOff;       /* DexMethodId 的文件偏移 */
    u4  classDefsSize;      /* DexClassDef 的个数 */
    u4  classDefsOff;       /* DexClassDef 的文件偏移 */
    u4  dataSize;           /* 数据段的大小 */
    u4  dataOff;            /* 数据段的文件偏移 */
};
  • magicdex.035
  • checksum :dex文件的校验和,用来判断dex文件是否损坏或被篡改
  • signature : SHA校验
  • fileSize :整个dex文件的大小(byte)
  • headerSize : 记录了Header占用的字节数
  • endianTag:指定CPU字节序,默认为ENDIAN_CONSTANT 0x12345678(小端序)
  • mapOff : 指定了map_list结构的文件便宜
  • stringIdsSizestring_ids结构的字节数
  • stringIdsOffstring_ids结构的文件偏移
  • 其余同…

string_ids

struct DexStringId {
    u4 stringDataOff;      // 字符串数据的文件字节偏移
};

存放字符串所在位置的偏移

其中偏移对应的位置,字符串第(1-5)个字节保存着字符串的长度,之后是一个char数组,以00结尾

type_ids

struct DexTypeId {
    u4  descriptorIdx;      /* 在String_ids数组中的索引 */
};

是用到的类型数组,每个元素为用到的类型(类),存放的数据为在string_ids数组中的索引

proto_ids

方法原型声明的数组

struct DexProtoId {
    u4 shortyIdx;		// 返回类型 string_ids 的索引
    u4 returnTypeIdx;	// 返回类型 type_ids 的索引
    u4 parametersOff;	/* 指向参数类型列表的文件偏移量
    没有参数则为0 非0则指向的数据应满足type_item格式*/
}
// parametersOff指向一个typeList结构体
struct DexTypeList {
    u4  size;               /* 列表中元素的个数 */
    DexTypeItem list[1];    /* 元素的列表 */
};

struct DexTypeItem {
    u2  typeIdx;            /* type_ids 的索引 */
};

field_ids

struct filed_id_item{
  ushort class_idx;		// 字段所属的class type_ids的索引
  ushort type_idx;		// 字段的类型 type_ids的索引
  uint name_idx;		// 字段的名称 string_ids的索引
}

method_ids

struct method_id_item{
  ushort class_idx;		// 方法所属的class type_ids的索引
  ushort proto_idx;		// 方法的原型 proto_ids的索引
  uint name_idx;		// 方法的名称 string_ids的索引
}

class_defs

struct class_def_item {
  uint class_idx;			// 类的类型,type_ids的索引
  uint access_flags; 		// 访问标志
  uint superclass_idx; 		// 父类类型 type_ids的索引
  uint interfaces_off;		// 接口 之想type_list的偏移,没有为0
  uint source_file_idx; 	// 源文件名 string_ids的索引
  uint annotations_off; 	// 注解
  uint class_data_off; 		// 指向 class_data结构的文件偏移
  uint static_value_off;	// 
}

struct class_data_item{
  uleb128 static_fields_size;     //静态字段
  uleb128 instance_fields_size;   //实例字段
  uleb128 direct_methods_size;    //直接方法(private或者构造方法)
  uleb128 virtual_methods_size;   //虚方法(非private、static、final,非构造方法)
  encoded_field static_fields[static_fields_size];        //静态字段
  encoded_field instance_fields[instance_fields_size];    //实例字段
  encoded_method direct_methods[direct_method_size];      //直接方法
  encoded_method virtual_methods[virtual_methods_size];   //虚方法
}

struct encoded_field{
  uleb128 filed_idx_diff;
  uleb128 access_flags;
}

struct encoded_method{
  uleb128 method_idx_diff;	// method_ids的索引
  uleb128 access_flags;		// 访问权限
  uleb128 code_off;			// 本方法的代码实现,指向data区
}

map_list

// map_list 结构
struct DexMapList {
    u4 size;			// DexMapItem结构的个数
    DexMapItem list[l];	// DexMapItem结构
}

size表明 DexMapItem结构的个数

struct DexMapItem {
    u2 type;		// 整体结构中的结构类型
    u2 unused;		// 用于字节对齐
    u4 size;		// 类型的个数
    u4 offset;		// 类型数据的文件偏移
}

Q&A

安装APK报错Failure [INSTALL_FAILED_TEST_ONLY]

安装APK报错Failure [INSTALL_FAILED_TEST_ONLY]

安装失败!调用者不被允许测试的测试程序

修改AndroidManifest.xml

application标签中删去 android:testOnly="true"属性

AndroidStudio使用smaliidea

安装smaliidea插件后

然后在Android Studio -> Preference(windows是File -> setting) -> Editor -> file Types 里面找smali,给图标为【黑色S】的smali添加.smali,去掉自带的smali的.smali

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
https://github.com/iBotPeaches/Apktool Introduction Basic First lets take a lesson into apk files. apks are nothing more than a zip file containing resources and compiled java. If you were to simply unzip an apk like so, you would be left with files such as classes.dex and resources.arsc. $ unzip testapp.apk Archive: testapp.apk inflating: AndroidManifest.xml inflating: classes.dex extracting: res/drawable-hdpi/ic_launcher.png inflating: res/xml/literals.xml inflating: res/xml/references.xml extracting: resources.arsc However, at this point you have simply inflated compiled sources. If you tried to view AndroidManifest.xml. You'd be left viewing this. P4F0\fnversionCodeversionNameandroid*http://schemas.android.com/apk/res/androidpackageplatformBuildVersionCodeplatformBuildVersionNamemanifestbrut.apktool.testapp1.021APKTOOL Obviously, editing or viewing a compiled file is next to impossible. That is where Apktool comes into play. $ apktool d testapp.apk I: Using Apktool 2.0.0 on testapp.apk I: Loading resource table... I: Decoding AndroidManifest.xml with resources... I: Loading resource table from file: 1.apk I: Regular manifest package... I: Decoding file-resources... I: Decoding values */* XMLs... I: Baksmaling classes.dex... I: Copying assets and libs... $ Viewing AndroidManifest.xml again results in something much more human readable <?xml version="1.0" encoding="utf-8" standalone="no"?> <manifest xmlns:android="https://schemas.android.com/apk/res/android" package="brut.apktool.testapp" platformBuildVersionCode="21" platformBuildVersionName="APKTOOL"/> In addition to XMLs, resources such as 9 patch images, layouts, strings and much more are correctly decoded to source form. Decoding The decode option on Apktool can be invoked either from d or decode like shown below. $ apktool d foo.jar // decodes foo.jar to foo.jar.out folder $ apktool decode foo.jar // decodes foo.jar to foo.jar.out folder $ apktool d bar.apk // decodes bar.apk to bar folder $ apktool decode bar.apk // decodes bar.apk to bar folder $ apktool d bar.apk -o baz // decodes bar.apk to baz folder Building The build option can be invoked either from b or build like shown below $ apktool b foo.jar.out // builds foo.jar.out folder into foo.jar.out/dist/foo.jar file $ apktool build foo.jar.out // builds foo.jar.out folder into foo.jar.out/dist/foo.jar file $ apktool b bar // builds bar folder into bar/dist/bar.apk file $ apktool b . // builds current directory into ./dist $ apktool b bar -o new_bar.apk // builds bar folder into new_bar.apk $ apktool b bar.apk // WRONG: brut.androlib.AndrolibException: brut.directory.PathNotExist: apktool.yml // Must use folder, not apk/jar file InfoIn order to run a rebuilt application. You must resign the application. Android documentation can help with this. Frameworks Frameworks can be installed either from if or install-framework, in addition two parameters -p, --frame-path <dir> - Store framework files into <dir> -t, --tag <tag> - Tag frameworks using <tag> Allow for a finer control over how the files are named and how they are stored. $ apktool if framework-res.apk I: Framework installed to: 1.apk // pkgId of framework-res.apk determines number (which is 0x01) $ apktool if com.htc.resources.apk I: Framework installed to: 2.apk // pkgId of com.htc.resources is 0x02 $ apktool if com.htc.resources.apk -t htc I: Framework installed to: 2-htc.apk // pkgId-tag.apk $ apktool if framework-res.apk -p foo/bar I: Framework installed to: foo/bar/1.apk $ apktool if framework-res.apk -t baz -p foo/bar I: Framework installed to: foo/bar/1-baz.apk Migration Instructions v2.1.1 -> v2.2.0 Run the following commands to migrate your framework directory Apktool will work fine without running these commands, this will just cleanup abandoned files unix - mkdir -p ~/.local/share; mv ~/apktool ~/.local/share windows - move %USERPROFILE%\apktool %USERPROFILE%\AppData\Local v2.0.1 -> v2.0.2 Update apktool to v2.0.2 Remove framework file $HOME/apktool/framework/1.apk due to internal API update (Android Marshmallow) v1.5.x -> v2.0.0 Java 1.7 is required Update apktool to v2.0.0 aapt is now included inside the apktool binary. It's not required to maintain your own aapt install under $PATH. (However, features like -a / --aapt are still used and can override the internal aapt) The addition of aapt replaces the need for separate aapt download packages. Helper Scripts may be found here Remove framework $HOME/apktool/framework/1.apk Eagle eyed users will notice resources are now decoded before sources now. This is because we need to know the API version via the manifest for decoding the sources Parameter Changes Smali/baksmali 2.0 are included. This is a big change from 1.4.2. Please read the smali updates here for more information -o / --output is now used for the output of apk/directory -t / --tag is required for tagging framework files -advance / --advanced will launch advance parameters and information on the usage output -m / --match-original is a new feature for apk analysis. This retains the apk is nearly original format, but will make rebuild more than likely not work due to ignoring the changes that newer aapt requires After [d]ecode, there will be new folders (original / unknown) in the decoded apk folder original = META-INF folder / AndroidManifest.xml, which are needed to retain the signature of apks to prevent needing to resign. Used with -c / --copy-original on [b]uild unknown = Files / folders that are not part of the standard AOSP build procedure. These files will be injected back into the rebuilt APK. apktool.yml collects more information than last version SdkInfo - Used to repopulate the sdk information in AndroidManifest.xml since newer aapt requires version information to be passed via parameter packageInfo - Used to help support Android 4.2 renamed manifest feature. Automatically detects differences between resource and manifest and performs automatic --rename-manifest-package on [b]uild versionInfo - Used to repopulate the version information in AndroidManifest.xml since newer aapt requires version information to be passed via parameter compressionType - Used to determine the compression that resources.arsc had on the original apk in order to replicate during [b]uild unknownFiles - Used to record name/location of non-standard files in an apk in order to place correctly on rebuilt apk sharedLibrary - Used to help support Android 5 shared library feature by automatically detecting shared libraries and using --shared-lib on [b]uild Examples of new usage in 2.0 vs 1.5.x Old (Apktool 1.5.x) New (Apktool 2.0.x) apktool if framework-res.apk tag apktool if framework-res.apk -t tag apktool d framework-res.apk output apktool d framework.res.apk -o output apktool b output new.apk apktool b output -o new.apk v1.4.x -> v1.5.1 Update apktool to v1.5.1 Update aapt manually or use package r05-ibot via downloading Mac, Windows or Linux Remove framework file $HOME/apktool/framework/1.apk Intermediate Framework Files As you probably know, Android apps utilize code and resources that are found on the Android OS itself. These are known as framework resources and Apktool relies on these to properly decode and build apks. Every Apktool release contains internally the most up to date AOSP framework at the time of the release. This allows you to decode and build most apks without a problem. However, manufacturers add their own framework files in addition to the regular AOSP ones. To use apktool against these manufacturer apks you must first install the manufacturer framework files. Example Lets say you want to decode HtcContacts.apk from an HTC device. If you try you will get an error message. $ apktool d HtcContacts.apk I: Loading resource table... I: Decoding resources... I: Loading resource table from file: 1.apk W: Could not decode attr value, using undecoded value instead: ns=android, name=drawable W: Could not decode attr value, using undecoded value instead: ns=android, name=icon Can't find framework resources for package of id: 2. You must install proper framework files, see project website for more info. We must get HTC framework resources before decoding this apk. We pull com.htc.resources.apk from our device and install it $ apktool if com.htc.resources.apk I: Framework installed to: 2.apk Now we will try this decode again. $ apktool d HtcContacts.apk I: Loading resource table... I: Decoding resources... I: Loading resource table from file: /home/brutall/apktool/framework/1.apk I: Loading resource table from file: /home/brutall/apktool/framework/2.apk I: Copying assets and libs... As you can see. Apktool leveraged both 1.apk and 2.apk framework files in order to properly decode this application. Finding Frameworks For the most part any apk in /system/framework on a device will be a framework file. On some devices they might reside in /data/system-framework and even cleverly hidden in /system/app or /system/priv-app. They are usually named with the naming of "resources", "res" or "framework". Example HTC has a framework called com.htc.resources.apk, LG has one called lge-res.apk After you find a framework file you could pull it via adb pull /path/to/file or use a file manager application. After you have the file locally, pay attention to how Apktool installs it. The number that the framework is named during install corresponds to the pkgId of the application. These values should range from 1 to 9. Any APK that installs itself as 127 is 0x7F which is an internal pkgId. Internal Frameworks Apktool comes with an internal framework like mentioned above. This file is copied to $HOME/apktool/framework/1.apk during use. Warning Apktool has no knowledge of what version of framework resides there. It will assume its up to date, so delete the file during Apktool upgrades Managing framework files Frameworks are stored in $HOME/apktool/framework for Windows and Unix systems. Mac OS X has a slightly different folder location of $HOME/Library/apktool/framework. If these directories are not available it will default to java.io.tmpdir which is usually /tmp. This is a volatile directory so it would make sense to take advantage of the parameter --frame-path to select an alternative folder for framework files. Note Apktool has no control over the frameworks once installed, but you are free to manage these files on your own. Tagging framework files Frameworks are stored in the naming convention of: <id>-<tag>.apk. They are identified by pkgId and optionally custom tag. Usually tagging frameworks isn't necessary, but if you work on apps from many different devices and they have incompatible frameworks, you will need some way to easily switch between them. You could tag frameworks by: $ apktool if com.htc.resources.apk -t hero I: Framework installed to: /home/brutall/apktool/framework/2-hero.apk $ apktool if com.htc.resources.apk -t desire I: Framework installed to: /home/brutall/apktool/framework/2-desire.apk Then: $ apktool d HtcContacts.apk -t hero I: Loading resource table... I: Decoding resources... I: Loading resource table from file: /home/brutall/apktool/framework/1.apk I: Loading resource table from file: /home/brutall/apktool/framework/2-hero.apk I: Copying assets and libs... $ apktool d HtcContacts.apk -t desire I: Loading resource table... I: Decoding resources... I: Loading resource table from file: /home/brutall/apktool/framework/1.apk I: Loading resource table from file: /home/brutall/apktool/framework/2-desire.apk I: Copying assets and libs... You don't have to select a tag when building apk - apktool automatically uses the same tag, as when decoding. Smali Debugging Warning SmaliDebugging has been marked as deprecated in 2.0.3, and removed in 2.1. Please check SmaliIdea for a debugger. Apktool makes possible to debug smali code step by step, watch variables, set breakpoints, etc. General information Generally we need several things to run Java debugging session: debugger server (usually Java VM) debugger client (usually IDE like IntelliJ, Eclipse or Netbeans) client must have sources of debugged application server must have binaries compiled with debugging symbols referencing these sources sources must be java files with at least package and class definitions, to properly connect them with debugging symbols In our particular situation we have: server: Monitor (Previously DDMS), part of Android SDK, standard for debugging Android applications - explained here client: any JPDA client - most of decent IDEs have support for this protocol. sources: smali code modified by apktool to satisfy above requirements (".java" extension, class declaration, etc.). Apktool modifies them when decoding apk in debug mode. binaries: when building apk in debug mode, apktool removes original symbols and adds new, which are referencing smali code (line numbers, registers/variables, etc.) Info To successfully run debug sessions, the apk must be both decoded and built in debug mode. Decoding with debug decodes the application differently to allow the debug rebuild option to inject lines allowing the debugger to identify variables and types.-d / --debug General instructions Above information is enough to debug smali code using apktool, but if you aren't familiar with DDMS and Java debugging, then you probably still don't know how to do it. Below are simple instructions for doing it using IntelliJ or Netbeans. Decode apk in debug mode: $ apktool d -d -o out app.apk Build new apk in debug mode: $ apktool b -d out Sign, install and run new apk. Follow sub-instructions below depending on IDE. IntelliJ (Android Studio) instructions In IntelliJ add new Java Module Project selecting the "out" directory as project location and the "smali" subdirectory as content root dir. Run Monitor (Android SDK /tools folder), find your application on a list and click it. Note port information in last column - it should be something like "86xx / 8700". In IntelliJ: Debug -> Edit Configurations. Since this is a new project, you will have to create a Debugger. Create a Remote Debugger, with the settings on "Attach" and setting the Port to 8700 (Or whatever Monitor said). The rest of fields should be ok, click "Ok". Start the debugging session. You will see some info in a log and debugging buttons will show up in top panel. Set breakpoint. You must select line with some instruction, you can't set breakpoint on lines starting with ".", ":" or "#". Trigger some action in application. If you run at breakpoint, then thread should stop and you will be able to debug step by step, watch variables, etc. Netbeans instructions In Netbeans add new Java Project with Existing Sources, select "out" directory as project root and "smali" subdirectory as sources dir. Run DDMS, find your application on a list and click it. Note port information in last column - it should be something like "86xx / 8700". In Netbeans: Debug -> Attach Debugger -> select JPDA and set Port to 8700 (or whatever you saw in previous step). Rest of fields should be ok, click "Ok". Debugging session should start: you will see some info in a log and debugging buttons will show up in top panel. Set breakpoint. You must select line with some instruction, you can't set breakpoint on lines starting with ".", ":" or "#". Trigger some action in application. If you run at breakpoint, then thread should stop and you will be able to debug step by step, watch variables, etc. Limitations/Issues Because IDE doesn't have full sources, it doesn't know about class members and such. Variables watching works because most of data could be read from memory (objects in Java know about their types), but if for example, you watch an object and it has some nulled member, then you won't see, what type this member is. 9Patch Images Docs exist for the mysterious 9patch images here and there. (Read these first). These docs though are meant for developers and lack information for those who work with already compiled 3rd party applications. There you can find information how to create them, but no information about how they actually work. I will try and explain it here. The official docs miss one point that 9patch images come in two forms: source & compiled. source - You know this one. You find it in the source of an application or freely available online. These are images with a black border around them. compiled - The mysterious form found in apk files. There are no borders and the 9patch data is written into a binary chunk called npTc. You can't see or modify it easily, but Android OS can as its quicker to read. There are problems related to the above two points. You can't move 9patch images between both types without a conversion. If you try and unpack 9patch images from an apk and use it in the source of another, you will get errors during build. Also vice versa, you cannot take source 9patch images directly into an apk. 9patch binary chunk isn't recognized by modern image processing tools. So modifying the compiled image will more than likely break the npTc chunk, thus breaking the image on the device. The only solution to this problem is to easily convert between these two types. The encoder (which takes source to compiled) is built into the aapt tool and is automatically used during build. This means we only need to build a decoder which has been in apktool since v1.3.0 and is automatically ran on all 9patch images during decode. So if you want to modify 9patch images, don't do it directly. Use apktool to decode the application (including the 9patch images) and then modify the images. At that point when you build the application back, the source 9patch images will be compiled. Other FAQ What about the -j switch shown from the original YouTube videos? Read Issue 199. In short - it doesn't exist. Is it possible to run apktool on a device? Sadly not. There are some incompatibilities with SnakeYAML, java.nio and aapt Where can I download sources of apktool? From our Github or Bitbucket project. Resulting apk file is much smaller than original! Is there something missing? There are a couple of reasons that might cause this. Apktool builds unsigned apks. This means an entire directory META-INF is missing. New aapt binary. Newer versions of apktool contain a newer aapt which optimizes images differently. These points might have contributed to a smaller than normal apk There is no META-INF dir in resulting apk. Is this ok? Yes. META-INF contains apk signatures. After modifying the apk it is no longer signed. You can use -c / --copy-original to retain these signatures. However, using -c uses the original AndroidManifest.xml file, so changes to it will be lost. What do you call "magic apks"? For some reason there are apks that are built using modified build tools. These apks don't work on a regular AOSP Android build, but usually are accompanied by a modified system that can read these modified apks. Apktool cannot handle these apks, therefore they are "magic". Could I integrate apktool into my own tool? Could I modify apktool sources? Do I have to credit you? Actually the Apache License, which apktool uses, answers all these questions. Yes you can redistribute and/or modify apktool without my permission. However, if you do it would be nice to add our contributors (brut.all, iBotPeaches and JesusFreke) into your credits but it's not required. Where does apktool store its framework files? unix - $HOME/.local/share/apktool mac - $HOME/Library/apktool windows - $HOME/AppData/Local/apktool Options Utility Options that can be executed at any time. -version, --version Outputs current version. (Ex: 1.5.2) -v, --verbose Verbose output. Must be first parameter -q, --quiet Quiet output. Must be first parameter -advance, --advanced Advance usage output Decode These are all the options when decoding an apk. --api <API> The numeric api-level of the smali files to generate (defaults to targetSdkVersion) -b, --no-debug-info Prevents baksmali from writing out debug info (.local, .param, .line, etc). Preferred to use if you are comparing smali from the same APK of different versions. The line numbers and debug will change among versions, which can make DIFF reports a pain. -f, --force Force delete destination directory. Use when trying to decode to a folder that already exists --keep-broken-res - Advanced If there is an error like "Invalid Config Flags Detected. Dropping Resources...". This means that APK has a different structure then Apktool can handle. This might be a newer Android version or a random APK that doesn't match standards. Running this will allow the decode, but then you have to manually fix the folders with -ERR in them. -m, --match-original - Used for analysis Matches files closest as possible to original, but prevents rebuild. -o, --output <DIR> The name of the folder that apk gets written to -p, --frame-path <DIR> The folder location where framework files should be stored/read from -r, --no-res This will prevent the decompile of resources. This keeps the resources.arsc intact without any decode. If only editing Java (smali) then this is the recommend for faster decompile & rebuild -s, --no-src This will prevent the disassemble of the dex files. This keeps the apk classes.dex file and simply moves it during build. If your only editing the resources. This is recommended for faster decompile & rebuild -t, --frame-tag <TAG> Uses framework files tagged via <TAG> Rebuild These are all the options when building an apk. -a, --aapt <FILE> Loads aapt from the specified file location, instead of relying on path. Falls back to $PATH loading, if no file found -c, --copy-original - Will still require signature resign post API18 Copies original AndroidManifest.xml and META-INF folder into built apk -d, --debug Adds debuggable="true" to AndroidManifest file. -f, --force-all Overwrites existing files during build, reassembling the resources.arsc file and classes.dex file -o, --output <FILE> The name and location of the apk that gets written -p, --frame-path <DIR> The location where framework files are loaded from

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Forgo7ten

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值