├── docs ├── requirements.txt ├── usage │ ├── installation.rst │ ├── features.rst │ ├── as_plugin.rst │ ├── as_module.rst │ └── usage.rst ├── api │ ├── adb.rst │ ├── java.rst │ ├── frida.rst │ ├── plugins.rst │ ├── bundle.rst │ ├── gadget.rst │ ├── apktool.rst │ ├── download.rst │ ├── manifest.rst │ ├── logger.rst │ ├── uber_apk_signer.rst │ ├── dependencies.rst │ └── apkinjector.rst ├── usage.rst ├── api.rst ├── index.rst └── conf.py ├── .gitignore ├── requirements.txt ├── apkinjector ├── arch.py ├── frida.py ├── __init__.py ├── utils.py ├── plugins.py ├── logger.py ├── java.py ├── download.py ├── manifest.py ├── uber_apk_signer.py ├── gadget.py ├── dependencies.py ├── injector.py ├── adb.py ├── apktool.py ├── bundle.py └── __main__.py ├── plugins ├── plugins.json └── plugin_example.py ├── .github ├── workflows │ ├── publish.yaml │ └── doc.yaml └── pull_request_template.md ├── Makefile ├── setup.py ├── README.md └── LICENSE /docs/requirements.txt: -------------------------------------------------------------------------------- 1 | apkinjector -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | apkinjector/__pycache__ 2 | build -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | requests 2 | appdirs 3 | install-jdk 4 | click 5 | pyelftools 6 | colorama 7 | asn1crypto -------------------------------------------------------------------------------- /apkinjector/arch.py: -------------------------------------------------------------------------------- 1 | class ARCH: 2 | ARM = 'arm' 3 | ARM64 = 'arm64' 4 | X86 = 'x86' 5 | X64 = 'x86_64' 6 | -------------------------------------------------------------------------------- /docs/usage/installation.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============ 3 | 4 | Just install via pip:: 5 | 6 | pip3 install apkinjector -------------------------------------------------------------------------------- /docs/api/adb.rst: -------------------------------------------------------------------------------- 1 | Adb 2 | === 3 | 4 | .. automodule:: apkinjector.adb 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/java.rst: -------------------------------------------------------------------------------- 1 | Java 2 | ==== 3 | 4 | .. automodule:: apkinjector.java 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/frida.rst: -------------------------------------------------------------------------------- 1 | Frida 2 | ===== 3 | 4 | .. automodule:: apkinjector.frida 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/plugins.rst: -------------------------------------------------------------------------------- 1 | Plugins 2 | ======= 3 | 4 | .. autofunction:: apkinjector.plugins.main 5 | 6 | .. autosummary:: 7 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/bundle.rst: -------------------------------------------------------------------------------- 1 | Bundle 2 | ======= 3 | 4 | .. automodule:: apkinjector.bundle 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/gadget.rst: -------------------------------------------------------------------------------- 1 | Gadget 2 | ====== 3 | 4 | .. automodule:: apkinjector.gadget 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/apktool.rst: -------------------------------------------------------------------------------- 1 | Apktool 2 | ======= 3 | 4 | .. automodule:: apkinjector.apktool 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/download.rst: -------------------------------------------------------------------------------- 1 | Download 2 | ======== 3 | 4 | .. automodule:: apkinjector.download 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/manifest.rst: -------------------------------------------------------------------------------- 1 | Manifest 2 | ======== 3 | 4 | .. automodule:: apkinjector.manifest 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/logger.rst: -------------------------------------------------------------------------------- 1 | ApkInjectorLogger 2 | ================= 3 | 4 | .. automodule:: apkinjector.logger 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/uber_apk_signer.rst: -------------------------------------------------------------------------------- 1 | UberApkSigner 2 | ============= 3 | 4 | .. automodule:: apkinjector.uber_apk_signer 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/api/dependencies.rst: -------------------------------------------------------------------------------- 1 | DependenciesManager 2 | =================== 3 | 4 | .. automodule:: apkinjector.dependencies 5 | :members: 6 | 7 | .. autosummary:: 8 | :toctree: generated -------------------------------------------------------------------------------- /docs/usage.rst: -------------------------------------------------------------------------------- 1 | Installation and Use 2 | ==================== 3 | 4 | .. toctree:: 5 | :maxdepth: 1 6 | 7 | usage/installation 8 | usage/features 9 | usage/usage 10 | usage/as_module 11 | usage/as_plugin -------------------------------------------------------------------------------- /docs/usage/features.rst: -------------------------------------------------------------------------------- 1 | Features 2 | ======== 3 | 4 | * Insert libraries and load them when an activity starts. 5 | * Frida support with support to load frida scripts either from disc or codeshare. 6 | * Bundle support. Apks exported from SAI or XApks downloaded from apkpure. 7 | * Plugins support. Check plugins/plugins.json and plugin_example.py. -------------------------------------------------------------------------------- /plugins/plugins.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "hello-world", 4 | "author": "apkinjector", 5 | "description": "Example plugin. Adds 2 example commands: hello-world, and uname.", 6 | "url": "https://raw.githubusercontent.com/nitanmarcel/apkinjector/main/plugins/plugin_example.py", 7 | "version": "1.0.0" 8 | } 9 | ] -------------------------------------------------------------------------------- /docs/api.rst: -------------------------------------------------------------------------------- 1 | API Reference 2 | ============= 3 | 4 | .. toctree:: 5 | :maxdepth: 1 6 | 7 | api/apkinjector 8 | api/logger 9 | api/dependencies 10 | api/adb 11 | api/java 12 | api/apktool 13 | api/uber_apk_signer 14 | api/bundle 15 | api/manifest 16 | api/frida 17 | api/gadget 18 | api/download 19 | api/plugins -------------------------------------------------------------------------------- /docs/api/apkinjector.rst: -------------------------------------------------------------------------------- 1 | apkinjector 2 | =========== 3 | 4 | .. currentmodule:: apkinjector 5 | 6 | .. autodata:: LOG 7 | :annotation: apkpatcher.logger.ApkInjectorLogger 8 | 9 | .. autodata:: DEPENDENCIES 10 | :annotation: apkpatcher.dependencies.DependenciesManager 11 | 12 | .. autodata:: USER_DIRECTORIES 13 | :annotation: appdir.AppDirs -------------------------------------------------------------------------------- /docs/index.rst: -------------------------------------------------------------------------------- 1 | APK Injector 2 | ============ 3 | 4 | APK Injector is a pluginable tool designed to automate the injection of libraries into APKs. It supports unpacking, repacking, and handling of bundles. 5 | 6 | Visit our GitHub repository: `APK Injector GitHub Repository `_ 7 | 8 | .. contents:: Table of Contents 9 | :local: 10 | 11 | .. toctree:: 12 | :maxdepth: 2 13 | 14 | usage 15 | api -------------------------------------------------------------------------------- /.github/workflows/publish.yaml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | on: 3 | push: 4 | paths: 5 | - setup.py 6 | jobs: 7 | publish: 8 | runs-on: ubuntu-latest 9 | steps: 10 | - uses: actions/checkout@v3 11 | - uses: actions/setup-python@v4 12 | with: 13 | python-version: 3.11 14 | - run: | 15 | pip install twine 16 | python setup.py sdist 17 | - uses: pypa/gh-action-pypi-publish@release/v1 18 | with: 19 | user: ${{ secrets.PYPI_USER}} 20 | password: ${{ secrets.PYPI_PASSWORD}} 21 | skip-existing: true 22 | print-hash: true -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | # Minimal makefile for Sphinx documentation 2 | # 3 | 4 | # You can set these variables from the command line, and also 5 | # from the environment for the first two. 6 | SPHINXOPTS ?= 7 | SPHINXBUILD ?= sphinx-build 8 | SOURCEDIR = docs/ 9 | BUILDDIR = build 10 | 11 | # Put it first so that "make" without argument is like "make help". 12 | help: 13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 14 | 15 | .PHONY: help Makefile 16 | 17 | # Catch-all target: route all unknown targets to Sphinx using the new 18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS). 19 | %: Makefile 20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O) 21 | -------------------------------------------------------------------------------- /.github/workflows/doc.yaml: -------------------------------------------------------------------------------- 1 | name: Build docs 2 | on: 3 | push: 4 | paths: 5 | - setup.py 6 | workflow_dispatch: 7 | jobs: 8 | docs: 9 | runs-on: ubuntu-latest 10 | steps: 11 | - uses: actions/checkout@v3 12 | - uses: actions/setup-python@v4 13 | with: 14 | python-version: 3.11 15 | - uses: ammaraskar/sphinx-action@master 16 | with: 17 | build-command: "sphinx-build -b html . _build" 18 | docs-folder: "docs/" 19 | - uses: peaceiris/actions-gh-pages@v3 20 | with: 21 | github_token: ${{ secrets.GITHUB_TOKEN }} 22 | publish_dir: docs/_build -------------------------------------------------------------------------------- /.github/pull_request_template.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | --- 6 | name: Plugin contribution 7 | about: Submit a pull request for a new plugin or plugin update. 8 | 9 | --- 10 | 11 | ## Overview 12 | 13 | Please provide a brief overview of your plugin (or changes if this an update PR) 14 | 15 | ## Plugin: [Name] 16 | 17 | ## Purpose 18 | 19 | What does this plugin aim to achieve? 20 | 21 | ## Examples of usage 22 | 23 | Provide clear examples demonstrating how to use this plugin. 24 | 25 | ## Checklist: 26 | 27 | * [ ] I have included documentation about the usage of the plugin. (in plugins/pluginname.md) 28 | -------------------------------------------------------------------------------- /apkinjector/frida.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | 3 | import requests 4 | 5 | from . import DEPENDENCIES 6 | 7 | 8 | class Frida: 9 | """ 10 | A utility class for running Frida commands. 11 | """ 12 | 13 | @staticmethod 14 | def version(): 15 | """ 16 | Obtain the version of frida. 17 | 18 | :return: The stdout from the command execution. 19 | :rtype: str 20 | """ 21 | if DEPENDENCIES.frida is not None: 22 | process = subprocess.run( 23 | f'{DEPENDENCIES.frida} --version', shell=True, capture_output=True, text=True) 24 | return process.stdout.strip() 25 | uri = f"https://api.github.com/repos/frida/frida/releases/latest" 26 | response = requests.get(uri) 27 | js = response.json() 28 | return js['tag_name'] 29 | 30 | 31 | DEPENDENCIES.add_dependency('frida', required=False) 32 | -------------------------------------------------------------------------------- /apkinjector/__init__.py: -------------------------------------------------------------------------------- 1 | import logging 2 | import os 3 | 4 | from appdirs import AppDirs 5 | 6 | from .dependencies import DependenciesManager 7 | from .logger import ApkInjectorLogger 8 | 9 | LOG = ApkInjectorLogger(__name__) 10 | 11 | USER_DIRECTORIES: AppDirs = AppDirs(__name__, 'nitanmarcel') 12 | 13 | if not os.path.isdir(USER_DIRECTORIES.user_data_dir): 14 | os.makedirs(USER_DIRECTORIES.user_data_dir) 15 | if not os.path.isdir(USER_DIRECTORIES.user_cache_dir): 16 | os.makedirs(USER_DIRECTORIES.user_cache_dir) 17 | 18 | 19 | DEPENDENCIES = DependenciesManager(USER_DIRECTORIES.user_data_dir) 20 | 21 | __APKTOOL_VERSION__ = '2.9.0' 22 | __UBER_SIGNER_VERSION__ = '1.3.0' 23 | __JAVA_VERSION__ = '17' 24 | 25 | __PLUGIN_DATA__ = 'https://raw.githubusercontent.com/nitanmarcel/apkinjector/main/plugins/plugins.json' 26 | 27 | if DEPENDENCIES.has_missing_required_dependency(): 28 | LOG.error('Some dependencies are missing.') 29 | -------------------------------------------------------------------------------- /docs/usage/as_plugin.rst: -------------------------------------------------------------------------------- 1 | Usage as a plugin 2 | ================= 3 | 4 | .. code-block:: python 5 | 6 | # Can use the same methods as a it would been included in a separate module. 7 | 8 | from apkinjector import LOG 9 | 10 | # Adding a new command to the `apkinjector` application: 11 | 12 | from apkinjector.plugins import main 13 | 14 | # Define a new command. It uses click under the hood. See more at https://click.palletsprojects.com/en/8.1.x/ 15 | # Check plugins/plugin_example.py for a full example. 16 | @main.command(help='Prints hello world to the console.') 17 | def hello_world(): 18 | LOG.info('Hello World') # prints info 19 | LOG.warning("Hello World") # prints warning 20 | LOG.error('Hello World') # prints error and calls sys.exit(1) 21 | 22 | # This will be usable with `apkinjector hello_world` 23 | # 24 | # apkinjector hello-world --help 25 | # Usage: python -m apkinjector hello-world [OPTIONS] 26 | 27 | # Prints hello world to the console. 28 | 29 | # Options: 30 | # --help Show this message and exit. -------------------------------------------------------------------------------- /docs/usage/as_module.rst: -------------------------------------------------------------------------------- 1 | Usage as a module 2 | ================= 3 | 4 | .. code-block:: python 5 | 6 | from apkinjector import LOG 7 | 8 | LOG.info("This has been printed using apkinjector logging") 9 | 10 | 11 | # Also comes with runners for apktool, uber-apk-signer, etc/ 12 | 13 | from apkinjector.apktool import ApkTool 14 | 15 | from apkinjector.uber_apk_signer import UberApkSigner 16 | 17 | # Automatically download and setup apktool. 18 | ApkTool.install() 19 | 20 | # Decompile apk 21 | ApkTool.decode(...) 22 | 23 | # Automatically download and setup uber-apk-signer 24 | UberApkSigner.install() 25 | 26 | # Sign apk 27 | UberApkSigner.sign(...) 28 | 29 | 30 | # Check if a dependency is in path 31 | 32 | from apkinjector import DEPENDENCIES_MANAGER 33 | 34 | # Add a new dependency 35 | java = DEPENDENCIES_MANAGER.add_dependency('java', required=True) # Return Depedency(name, path, required) 36 | 37 | # Check if a dependency is path 38 | # Returns the path to the binary if found, if not returns None 39 | # See apkpatcher/apkpatcher to see how dependencies are automatically handled 40 | in_path = DEPENDENCIES_MANAGER.java -------------------------------------------------------------------------------- /plugins/plugin_example.py: -------------------------------------------------------------------------------- 1 | from apkinjector import LOG, DEPENDENCIES 2 | from apkinjector.plugins import main 3 | import click 4 | import subprocess 5 | 6 | 7 | # Define a new command. It uses click under the hood. See more at https://click.palletsprojects.com/en/8.1.x/ 8 | @main.command(help='Prints hello world to the console.') 9 | def hello_world(): 10 | LOG.info('Hello World') # prints info 11 | LOG.warning("Hello World") # prints warning 12 | LOG.error('Hello World') # prints error and calls sys.exit(1) 13 | 14 | 15 | @main.command(help='Calls uname') 16 | @click.option('--a', is_flag=True, help='Calls uname with the argument -a') 17 | def uname(a): 18 | # Adds a new dependency `uname`. 19 | DEPENDENCIES.add_dependency('uname', required=True) 20 | if DEPENDENCIES.uname: # Checks if the depedency `uname` is installed. 21 | if a: 22 | process = subprocess.run( 23 | f'uname -a', shell=True, capture_output=True, text=True) 24 | else: 25 | process = subprocess.run( 26 | f'uname', shell=True, capture_output=True, text=True) 27 | # Outputs the output of uname to console 28 | LOG.info('uname result: {}', process.stdout) 29 | -------------------------------------------------------------------------------- /apkinjector/utils.py: -------------------------------------------------------------------------------- 1 | from typing import Union 2 | 3 | from .arch import ARCH 4 | 5 | 6 | def abi_to_arch(abi: str) -> Union[ARCH, None]: 7 | """Convert abi string to architecture 8 | 9 | Args: 10 | abi (str): Abi string 11 | 12 | Returns: 13 | Union[ARCH, None]: Converted abi to apkinjector.arch.Arch or None if the abi is not recognized. 14 | """ 15 | mappings = { 16 | 'armeabi-v7a': ARCH.ARM, 17 | 'arm64_v8a': ARCH.ARM64, 18 | 'x86': ARCH.X86, 19 | 'x86_64': ARCH.X64, 20 | 'arm64-v8a': ARCH.ARM64, 21 | 'armeabi_v7a': ARCH.ARM 22 | } 23 | if abi in mappings.keys(): 24 | return mappings[abi] 25 | return None 26 | 27 | 28 | def arch_to_abi(arch: ARCH) -> Union[str, None]: 29 | """Convert apkinjector.arch.ARCH string to abi 30 | 31 | Args: 32 | arch (str): apkinjector.arch.ARCH 33 | 34 | Returns: 35 | Union[ARCH, None]: Converted apkinjector.arch.ARCH to abi string or None if the apkinjector.arch.ARCH is not recognized. 36 | """ 37 | mappings = { 38 | ARCH.ARM: 'armeabi-v7a', 39 | ARCH.ARM64: 'arm64-v8a', 40 | ARCH.X86: 'x86', 41 | ARCH.X64: 'x86_64' 42 | } 43 | if arch in mappings.keys(): 44 | return mappings[arch] 45 | return None 46 | -------------------------------------------------------------------------------- /apkinjector/plugins.py: -------------------------------------------------------------------------------- 1 | import importlib.util 2 | import os 3 | 4 | import click 5 | import requests 6 | 7 | 8 | @click.group() 9 | @click.version_option() 10 | @click.pass_context 11 | def main(ctx): 12 | """ 13 | Entry point for apkinjector application. Use as decorator @main.command() to add new terminal commands: https://click.palletsprojects.com/en/8.1.x 14 | """ 15 | pass 16 | 17 | 18 | class _PluginLoader: 19 | def __init__(self, plugin_folder: str) -> None: 20 | self.plugin_folder = plugin_folder 21 | self.plugins = self.load_plugins() 22 | 23 | def load_plugins(self): 24 | plugins = {} 25 | for filename in os.listdir(self.plugin_folder): 26 | if filename.endswith('.py'): 27 | module_name = filename[:-3] 28 | plugin_module = self.import_module_from_file( 29 | os.path.join(self.plugin_folder, filename)) 30 | plugins[module_name] = plugin_module 31 | return plugins 32 | 33 | def import_module_from_file(self, full_path): 34 | module_spec = importlib.util.spec_from_file_location( 35 | os.path.basename(full_path), full_path) 36 | module = importlib.util.module_from_spec(module_spec) 37 | module_spec.loader.exec_module(module) 38 | return module 39 | -------------------------------------------------------------------------------- /docs/conf.py: -------------------------------------------------------------------------------- 1 | # Configuration file for the Sphinx documentation builder. 2 | # 3 | # For the full list of built-in configuration values, see the documentation: 4 | # https://www.sphinx-doc.org/en/master/usage/configuration.html 5 | 6 | # -- Project information ----------------------------------------------------- 7 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information 8 | 9 | import os 10 | import sys 11 | 12 | sys.path.insert(0, os.path.abspath('..')) 13 | sys.path.insert(0, os.path.abspath('../apkinjector')) 14 | 15 | project = 'apkinjector' 16 | copyright = '2023, Marcel Alexandru Nitan' 17 | author = 'Marcel Alexandru Nitan' 18 | release = '2023' 19 | 20 | # -- General configuration --------------------------------------------------- 21 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration 22 | 23 | extensions = [ 24 | 'sphinx.ext.duration', 25 | 'sphinx.ext.doctest', 26 | 'sphinx.ext.autodoc', 27 | 'sphinx.ext.autosummary' 28 | ] 29 | 30 | templates_path = ['_templates'] 31 | exclude_patterns = [] 32 | 33 | 34 | 35 | # -- Options for HTML output ------------------------------------------------- 36 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output 37 | 38 | html_theme = 'classic' 39 | html_static_path = ['_static'] -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | from setuptools import setup, find_packages 2 | from pathlib import Path 3 | 4 | this_directory = Path(__file__).parent 5 | long_description = (this_directory / "README.md").read_text() 6 | 7 | setup( 8 | name='apkinjector', 9 | version='1.1.6', 10 | description='Utilities to help injecting libraries and frida in apks.', 11 | long_description=long_description, 12 | long_description_content_type='text/markdown', 13 | author='Marcel Alexandru Nitan', 14 | author_email='nitan.marcel@gmail.com', 15 | url='https://nitanmarcel.github.io/apkinjector', 16 | keywords=['FRIDA', 'APK', 'INJECTION', 'INJECT'], 17 | packages=find_packages(), 18 | entry_points={ 19 | 'console_scripts': [ 20 | 'apkinjector = apkinjector.__main__:start' 21 | ] 22 | }, 23 | install_requires=[ 24 | 'requests', 25 | 'appdirs', 26 | 'install-jdk', 27 | 'click', 28 | 'pyelftools', 29 | 'colorama' 30 | ], 31 | classifiers=[ 32 | 'License :: OSI Approved :: GNU General Public License v2 (GPLv2)', 33 | 'Programming Language :: Python :: 3.6', 34 | 'Programming Language :: Python :: 3.7', 35 | 'Programming Language :: Python :: 3.8', 36 | 'Programming Language :: Python :: 3.9', 37 | 'Programming Language :: Python :: 3.10', 38 | 'Programming Language :: Python :: 3.11', 39 | 40 | ] 41 | ) 42 | -------------------------------------------------------------------------------- /apkinjector/logger.py: -------------------------------------------------------------------------------- 1 | import sys 2 | 3 | import click 4 | 5 | from typing import List, Tuple, Union 6 | 7 | 8 | class ApkInjectorLogger: 9 | """ 10 | Fstring like logging. e.g: log.info('Hello {}', 'World') 11 | """ 12 | def __init__(self, name : str): 13 | """ 14 | Initializes the logger. 15 | 16 | :param name: Name of the logger. 17 | :type name: str 18 | """ 19 | self.__name__ = name 20 | 21 | def info(self, message: str, *args : Union[Tuple[str], List[str]]): 22 | """ 23 | Prints info log message in green. 24 | 25 | :param message: Message to print. 26 | :type message: str 27 | """ 28 | message = message.format(*args) 29 | click.echo(click.style(f'[+] {self.__name__} - {message}', fg='green')) 30 | 31 | def warning(self, message: str, *args : Union[Tuple[str], List[str]]): 32 | """ 33 | Prints warning log message in yellow. 34 | 35 | :param message: Message to print. 36 | :type message: str 37 | """ 38 | message = message.format(*args) 39 | click.echo(click.style( 40 | f'[!] {self.__name__} - {message}', fg='yellow')) 41 | 42 | def error(self, message: str, *args : Union[Tuple[str], List[str]]): 43 | """ 44 | Prints error message in red and calls sys.exit(1). 45 | 46 | :param message: Message to print. 47 | :type message: str 48 | """ 49 | message = message.format(*args) 50 | click.echo(click.style(f'[*] {self.__name__} - {message}', fg='red')) 51 | sys.exit(1) 52 | -------------------------------------------------------------------------------- /apkinjector/java.py: -------------------------------------------------------------------------------- 1 | import glob 2 | import os 3 | import shutil 4 | import subprocess 5 | 6 | import jdk 7 | import time 8 | 9 | from . import __JAVA_VERSION__, DEPENDENCIES, USER_DIRECTORIES 10 | from .download import ProgressUnknown 11 | 12 | from typing import Callable 13 | 14 | 15 | def _download_java(progress_callback): 16 | pattern = os.path.join(USER_DIRECTORIES.user_data_dir, 17 | f'jdk-{__JAVA_VERSION__}*', 'bin', 'java') 18 | paths = glob.glob(pattern) 19 | if paths: 20 | return paths[-1] 21 | if progress_callback: 22 | pregress = ProgressUnknown('java', None) 23 | progress_callback(pregress) 24 | tmp_directory = os.path.join(USER_DIRECTORIES.user_cache_dir) 25 | if os.path.isdir(tmp_directory): 26 | shutil.rmtree(tmp_directory) 27 | path = jdk.install(str(__JAVA_VERSION__), jre=True, 28 | path=tmp_directory) 29 | if path: 30 | shutil.move(path, USER_DIRECTORIES.user_data_dir) 31 | return os.path.join(USER_DIRECTORIES.user_data_dir, 'bin', 'java') 32 | return None 33 | 34 | class Java: 35 | """ 36 | A utility class for running Java commands. 37 | """ 38 | 39 | @staticmethod 40 | def run_jar(jar_file : str, command : str) -> str: 41 | """Execute a jar file with the provided command. 42 | 43 | :param jar_file: Path to the jar file to be executed. 44 | :type jar_file: str 45 | :param command: Command to be passed when executing the jar file. 46 | :type command: str 47 | :return: Stdout of the command. 48 | :rtype: str 49 | """ 50 | process = subprocess.run( 51 | f'{DEPENDENCIES.java} -jar {jar_file} {command}', shell=True, capture_output=True, text=True) 52 | return process.stdout 53 | 54 | @staticmethod 55 | def install(path: str = None, progress_callback: Callable = None) -> None: 56 | """ 57 | Installs java 58 | 59 | :param path: Path to existing java if not found will use the system installed one or download it. Defaults to None. 60 | :type path: str, optional 61 | :param progress_callback: Callback to be called when install progress changes. Defaults to None. 62 | :type progress_callback: Callable, optional. 63 | 64 | """ 65 | DEPENDENCIES.add_dependency( 66 | 'java', path=path, fallback=_download_java, fallback_args=(progress_callback,)) 67 | -------------------------------------------------------------------------------- /docs/usage/usage.rst: -------------------------------------------------------------------------------- 1 | Usage 2 | ===== 3 | 4 | :: 5 | 6 | apkinjector [OPTIONS] COMMAND [ARGS]... 7 | 8 | Options: 9 | --help Show this message and exit. 10 | 11 | Commands: 12 | apk Apk utils 13 | frida Inject a frida gadget in a target apk. 14 | inject Inject a shared library (.so) in a target apk. 15 | plugins Manage plugins 16 | 17 | Frida 18 | ----- 19 | 20 | :: 21 | 22 | Usage: python -m apkinjector frida [OPTIONS] APK 23 | 24 | Inject a frida gadget in a target apk. 25 | 26 | Options: 27 | --gadget TEXT Path to custom gadget. 28 | --script TEXT Inject a javascript to be loaded when the gadget starts. 29 | --codeshare TEXT Same as --script but uses Frida Codeshare as the source 30 | javascript. 31 | --arch TEXT Architecture to inject for. If empty --adb or --gadget 32 | must be specified. 33 | --adb Use adb (if installed) to detect device architecture. 34 | --activity TEXT Name of the activity to inject into. If unspecified, the 35 | main activity will be injected. 36 | --output Custom path where the patched apk should be saved. 37 | --force Force delete destination directory. 38 | --help Show this message and exit. 39 | 40 | Inject 41 | ------ 42 | 43 | :: 44 | 45 | Usage: python -m apkinjector inject [OPTIONS] APK 46 | 47 | Inject a shared library (*.so) in a target apk. 48 | 49 | Options: 50 | --library TEXT Shared library (*.so) to inject. [required] 51 | --include TEXT Extra files to include in the lib folder. Can be used 52 | multiple times to include more files. 53 | --arch TEXT Architecture to inject for. If empty --adb or --library 54 | must be specified. 55 | --adb Use adb (if installed) to detect device architecture. 56 | --activity TEXT Name of the activity to inject into. If unspecified, the 57 | main activity will be injected. 58 | --output Custom path where the patched apk should be saved. 59 | --force Force delete destination directory. 60 | --help Show this message and exit. 61 | 62 | Apk utils 63 | --------- 64 | 65 | :: 66 | 67 | Usage: python -m apkinjector apk [OPTIONS] APK 68 | 69 | Apk utils 70 | 71 | Options: 72 | --activities Gets all activities 73 | --permissions Gets all permissions 74 | --libraries Gets all libraries 75 | --recievers Gets all receivers 76 | --help Show this message and exit. -------------------------------------------------------------------------------- /apkinjector/download.py: -------------------------------------------------------------------------------- 1 | from dataclasses import dataclass 2 | from typing import Callable, Optional 3 | 4 | import os 5 | import shutil 6 | import requests 7 | 8 | from . import LOG, USER_DIRECTORIES 9 | 10 | 11 | @dataclass 12 | class ProgressDownloading: 13 | filename: str 14 | progress: int 15 | 16 | 17 | @dataclass 18 | class ProgressFailed: 19 | filename: str 20 | status_code: int 21 | 22 | 23 | @dataclass 24 | class ProgressCompleted: 25 | filename: str 26 | path: str 27 | 28 | @dataclass 29 | class ProgressUnknown: 30 | filename: str 31 | path: str 32 | 33 | 34 | def download_file(url: str, target_path: str, progress_callback: Optional[Callable] = None) -> str: 35 | """ 36 | Download a file from a given URL and save it on the target path. 37 | 38 | :param url: The URL from where file needs to be downloaded. 39 | :type url: str 40 | :param target_path: The path on local system where the downloaded file should be saved. 41 | :type target_path: str 42 | :param progress_callback: Function to call when the progress changes, defaults to None. 43 | :type progress_callback: Optional[Callable] 44 | :return: The target path where the file has been downloaded. 45 | :rtype: str 46 | """ 47 | def _callable(args): 48 | if progress_callback is not None: 49 | progress_callback(args) 50 | file_name = target_path.split('/')[-1] 51 | tmp_path = os.path.join(USER_DIRECTORIES.user_cache_dir, "downloads") 52 | if not os.path.exists(tmp_path): 53 | os.mkdir(tmp_path) 54 | 55 | tmp_path = os.path.join(tmp_path, file_name) 56 | 57 | if os.path.isfile(tmp_path): 58 | os.remove(tmp_path) 59 | response = requests.get(url, stream=bool(progress_callback)) 60 | total_length = response.headers.get('content-length') 61 | total_length = int(total_length) 62 | 63 | if response.status_code != 200: 64 | _callable(ProgressFailed(filename=file_name, 65 | status_code=response.status_code)) 66 | return 67 | _callable(ProgressDownloading(filename=file_name, progress=0)) 68 | with open(tmp_path, 'wb') as f: 69 | if not bool(progress_callback): 70 | f.write(response.content) 71 | else: 72 | downloaded = 0 73 | for chunk in response.iter_content(chunk_size=1020): 74 | if chunk: 75 | downloaded += len(chunk) 76 | percentage = int(downloaded * 100 / total_length) 77 | _callable(ProgressDownloading(file_name, percentage)) 78 | f.write(chunk) 79 | if os.path.isfile(tmp_path): 80 | shutil.move(tmp_path, target_path) 81 | _callable(ProgressCompleted(file_name, target_path)) 82 | 83 | return target_path 84 | -------------------------------------------------------------------------------- /apkinjector/manifest.py: -------------------------------------------------------------------------------- 1 | from xml.dom.minidom import parseString 2 | 3 | from typing import List 4 | 5 | class Manifest: 6 | """ 7 | AndroidManifest.xml utils used across the project 8 | """ 9 | @staticmethod 10 | def get_activities(manifest : str) -> List[str]: 11 | """ 12 | Get a list of activities declared in the target manifest. 13 | 14 | :param manifest: Path to the decoded AndroidManifest.xml. 15 | :type manifest: str 16 | :return: A sorted list of activities. 17 | :rtype: List[str] 18 | """ 19 | data = "" 20 | with open(manifest, 'r') as m: 21 | data = m.read() 22 | dom = parseString(data) 23 | nodes = dom.getElementsByTagName('activity') 24 | activities = [node.getAttribute("android:name") for node in nodes] 25 | return sorted(activities) 26 | @staticmethod 27 | def get_main_activity(manifest : str) -> str: 28 | """ 29 | Get the main activity declared in the target manifest. 30 | 31 | :param manifest: Path to the decoded AndroidManifest.xml. 32 | :type manifest: str 33 | :return: The name of the main activity 34 | :rtype: str 35 | """ 36 | main_activity = None 37 | data = "" 38 | with open(manifest, 'r') as m: 39 | data = m.read() 40 | dom = parseString(data) 41 | nodes = dom.getElementsByTagName('activity') 42 | for node in nodes: 43 | intent_filters = node.getElementsByTagName('intent-filter') 44 | if intent_filters: 45 | for intent_filder in intent_filters: 46 | actions = intent_filder.getElementsByTagName('action') 47 | categories = intent_filder.getElementsByTagName('category') 48 | for action in actions: 49 | if action.getAttribute('android:name') == 'android.intent.action.MAIN': 50 | for category in categories: 51 | if category.getAttribute('android:name') == 'android.intent.category.LAUNCHER': 52 | main_activity = node.getAttribute("android:name") 53 | return main_activity 54 | 55 | @staticmethod 56 | def get_permissions(manifest : str) -> List[str]: 57 | """ 58 | Get a list of permissions declared in the target manifest. 59 | 60 | :param manifest: Path to the decoded AndroidManifest.xml. 61 | :type manifest: str 62 | :return: A sorted list of permissions. 63 | :rtype: List[str] 64 | """ 65 | data = "" 66 | with open(manifest, 'r') as m: 67 | data = m.read() 68 | dom = parseString(data) 69 | nodes = dom.getElementsByTagName('uses-permission') 70 | nodes.extend(dom.getElementsByTagName('uses-permission-sdk-23')) 71 | permissions = [node.getAttribute("android:name") for node in nodes] 72 | return sorted(permissions) 73 | @staticmethod 74 | def get_libraries(manifest : str) -> List[str]: 75 | """ 76 | Get a list of activities declared in the target manifest. 77 | 78 | :param manifest: Path to the decoded AndroidManifest.xml. 79 | :type manifest: str 80 | :return: A sorted list of activities. 81 | :rtype: List[str] 82 | """ 83 | data = "" 84 | with open(manifest, 'r') as m: 85 | data = m.read() 86 | dom = parseString(data) 87 | nodes = dom.getElementsByTagName('uses-library') 88 | libraries = [node.getAttribute("android:name") for node in nodes] 89 | return sorted(libraries) -------------------------------------------------------------------------------- /apkinjector/uber_apk_signer.py: -------------------------------------------------------------------------------- 1 | import os 2 | from typing import Callable, List, Optional 3 | 4 | from . import __UBER_SIGNER_VERSION__, DEPENDENCIES, USER_DIRECTORIES 5 | from .download import download_file 6 | from .java import Java 7 | 8 | 9 | def _download_uberapksigner(progress_callback=None): 10 | path = os.path.join(USER_DIRECTORIES.user_data_dir, 11 | f'uber-apk-signer-{__UBER_SIGNER_VERSION__}.jar') 12 | if not os.path.isfile(path): 13 | uri = f'https://github.com/patrickfav/uber-apk-signer/releases/download/v{__UBER_SIGNER_VERSION__}/uber-apk-signer-{__UBER_SIGNER_VERSION__}.jar' 14 | return download_file(uri, path, progress_callback) 15 | return path 16 | 17 | 18 | class UberApkSigner: 19 | """ 20 | Execute uber-apk-signer commands 21 | """ 22 | @staticmethod 23 | def version(): 24 | """ 25 | Obtain the version of uber-apk-signer. 26 | 27 | :return: The stdout from the command execution. 28 | :rtype: str 29 | """ 30 | return Java.run_jar(DEPENDENCIES.uber_apk_signer, '--version') 31 | 32 | @staticmethod 33 | def sign(apks: List[str], allow_resign: Optional[bool] = False, debug: Optional[bool] = False, 34 | dry_run: Optional[bool] = False, ks: Optional[str] = None, ks_alias: Optional[str] = None, 35 | ks_debug: Optional[str] = None, ks_key_pass: Optional[str] = None, ks_pass: Optional[str] = None, 36 | lineage: Optional[str] = None, out: Optional[str] = None, overwrite: Optional[bool] = False, 37 | skip_zip_align: Optional[bool] = False, only_verify: Optional[bool] = False, 38 | zip_align_path: Optional[str] = None, verify_sha256: Optional[str] = None) -> str: 39 | """ 40 | Sign an APK or a set of APKs. 41 | 42 | :return: The stdout from the command execution. 43 | :rtype: str 44 | """ 45 | 46 | command = '-a {}'.format(' '.join(apks)) 47 | 48 | if allow_resign: 49 | command += " --allowResign" 50 | 51 | if debug: 52 | command += " --debug" 53 | 54 | if dry_run: 55 | command += " --dryRun" 56 | 57 | if ks: 58 | command += f' --ks {ks}' 59 | 60 | if ks_alias: 61 | command += f' --ksAlias {ks_alias}' 62 | 63 | if ks_debug: 64 | command += f' --ksDebug {ks_debug}' 65 | 66 | if ks_key_pass: 67 | command += f' --ksKeyPass {ks_key_pass}' 68 | 69 | if ks_pass: 70 | command += f' --ksPass {ks_pass}' 71 | 72 | if lineage: 73 | command += f' -l {lineage}' 74 | 75 | if out: 76 | command += f' -o {out}' 77 | 78 | if overwrite: 79 | command += " --overwrite" 80 | 81 | if skip_zip_align: 82 | command += " --skipZipAlign" 83 | 84 | if only_verify: 85 | command += " -y" 86 | 87 | if zip_align_path: 88 | command += f' --zipAlignPath {zip_align_path}' 89 | 90 | if verify_sha256: 91 | command += f' --verifySha256 {verify_sha256}' 92 | 93 | return Java.run_jar(DEPENDENCIES.uber_apk_signer, command) 94 | 95 | @staticmethod 96 | def install(path: str = None, progress_callback: Callable = None) -> None: 97 | """ 98 | Install uber-apk-signer. 99 | 100 | :param path: Path to existing uber-apk-signer.jar. If not found, will use the system installed one or download it. Defaults to None. 101 | :type path: str, optional 102 | :param progress_callback: Callback to be called when install progress changes, defaults to None. 103 | :type progress_callback: callable, optional 104 | """ 105 | DEPENDENCIES.add_dependency( 106 | 'uber-apk-signer', path=path, fallback=_download_uberapksigner, fallback_args=(progress_callback,), use_path=False) 107 | -------------------------------------------------------------------------------- /apkinjector/gadget.py: -------------------------------------------------------------------------------- 1 | import lzma 2 | import os 3 | import shutil 4 | from typing import Callable, Union 5 | 6 | import requests 7 | 8 | from . import USER_DIRECTORIES 9 | from .arch import ARCH 10 | from .download import download_file 11 | from .frida import Frida 12 | 13 | 14 | class Gadget: 15 | """ 16 | Frida Gadget utils. 17 | """ 18 | @staticmethod 19 | def version() -> str: 20 | """ 21 | Get recommended gadget version. 22 | 23 | :return: The recommended gadget version as string. 24 | :rtype: str 25 | """ 26 | return Frida.version() 27 | 28 | @staticmethod 29 | def update(progress_callback: Callable = None) -> bool: 30 | """ 31 | Downloads and updates the gadgets. 32 | 33 | :param progress_callback: Function to call when download progress changes, defaults to None. 34 | :type progress_callback: Callable, optional 35 | :return: True if the gadgets were successfully downloaded, False otherwise. 36 | :rtype: bool 37 | """ 38 | version = Gadget.version() 39 | uri = 'https://api.github.com/repos/frida/frida/releases' 40 | response = requests.get(uri) 41 | response.raise_for_status() 42 | js = response.json() 43 | uri = None 44 | for release in js: 45 | if release['tag_name'] == version: 46 | uri = release['url'] 47 | if not uri: 48 | return False 49 | response = requests.get(uri) 50 | response.raise_for_status() 51 | js = response.json() 52 | assets = js['assets'] 53 | gadgets = [] 54 | for asset in assets: 55 | if 'gadget' in asset['name'] and 'android' in asset['name']: 56 | gadgets.append( 57 | [asset['name'], asset['browser_download_url']] 58 | ) 59 | 60 | path = os.path.join(USER_DIRECTORIES.user_data_dir, 'gadgets', version) 61 | if os.path.isdir(path): 62 | shutil.rmtree(path) 63 | os.makedirs(path) 64 | for gadget in gadgets: 65 | target_path = os.path.join(path, gadget[0]) 66 | output_path = download_file( 67 | gadget[1], target_path, progress_callback=progress_callback) 68 | with lzma.open(output_path) as _in, open(output_path.replace(".xz", ""), 'wb') as _out: 69 | _out.write(_in.read()) 70 | os.remove(output_path) 71 | return True 72 | 73 | @staticmethod 74 | def get_gadget_path(arch: ARCH) -> Union[str, None]: 75 | """ 76 | Gets the gadget path for the specified architecture. 77 | 78 | :param arch: The target architecture. 79 | :type arch: apkinjector.arch.ARCH 80 | :return: The path to the gadgets file if found, otherwise None. 81 | :rtype: Union[str, None] 82 | """ 83 | version = Gadget.version() 84 | mappings = { 85 | ARCH.ARM: f'frida-gadget-{version}-android-arm.so', 86 | ARCH.ARM64: f'frida-gadget-{version}-android-arm64.so', 87 | ARCH.X64: f'frida-gadget-{version}-android-x86_64.so', 88 | ARCH.X86: f'frida-gadget-{version}-android-x86.so' 89 | } 90 | if arch not in mappings.keys(): 91 | return None 92 | path = Gadget.get_gadget_dir() 93 | if not path: 94 | return path 95 | path = os.path.join(path, mappings[arch]) 96 | if not os.path.exists(path): 97 | return None 98 | return path 99 | 100 | @staticmethod 101 | def get_gadget_dir() -> Union[str, None]: 102 | """ 103 | Get the path where the gadgets are saved. 104 | 105 | :return: The path to the gadgets directory if found, otherwise None. 106 | :rtype: Union[str, None] 107 | """ 108 | version = Frida.version() 109 | path = os.path.join(USER_DIRECTORIES.user_data_dir, 'gadgets', version) 110 | if os.path.isdir(path): 111 | return path 112 | return None 113 | -------------------------------------------------------------------------------- /apkinjector/dependencies.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | from dataclasses import dataclass 4 | from typing import Callable, Optional, Union 5 | 6 | 7 | @dataclass 8 | class Dependency: 9 | name: str 10 | path: str 11 | required: bool 12 | 13 | 14 | class DependenciesManager: 15 | """ 16 | This class manages system-level dependencies by tracking them, 17 | and their status within a provided directory. 18 | """ 19 | 20 | def __init__(self, dependencies_directory: str) -> None: 21 | """ 22 | Initializes the Dependencies Manager. 23 | 24 | :param dependencies_directory: The directory containing the dependencies. 25 | "type dependencies_directory: str 26 | """ 27 | self.dependencies_directory = dependencies_directory 28 | self.dependencies = [] # List to store the tracked dependencies. 29 | 30 | def add_dependency(self, name: str, path: str = None, required: bool = False, fallback: Optional[Callable] = None, fallback_args: tuple = None, use_path: bool = True) -> Dependency: 31 | """ 32 | Adds a new dependency to the tracked list. 33 | 34 | :param name: The name of the dependency. 35 | :type name: str 36 | :param path: Path to existing dependency. If left None, it will detect the system dependency or call fallback function, defaults to None. 37 | :type path: str, optional 38 | :param required: Indicates if the dependency is required, defaults to False. 39 | :type required: bool 40 | :param fallback: The fallback function if the dependency is not found, defaults to None. 41 | :type fallback: Callable, optional 42 | :param fallback_args: Arguments to be passed to the fallback function, defaults to (). 43 | :type fallback_args: tuple, optional 44 | :param use_path: Use binary from path if exists. defaults to True 45 | :type use_path: bool, optional 46 | :return: The newly added dependency. 47 | :rtype: Dependency 48 | """ 49 | path = path or (shutil.which(name) if use_path else None) 50 | if not path or not os.path.isfile(path): 51 | if callable(fallback): 52 | if fallback_args and isinstance(fallback_args, (tuple, list)): 53 | path = fallback(*fallback_args) 54 | elif fallback_args: 55 | path = fallback(fallback_args) 56 | dependency = Dependency(name, path, required) 57 | self.dependencies.append(dependency) 58 | return dependency 59 | 60 | def get_dependency(self, name: str) -> Dependency: 61 | """ 62 | Retrieves a tracked dependency by name. 63 | 64 | :param name: The name of the dependency. 65 | :type name: str 66 | :return: The corresponding Dependency object if it is found, None otherwise. 67 | :rtype: Dependency 68 | """ 69 | dependency = [ 70 | x for x in self.dependencies if x.path is not None and x.name == name] 71 | if dependency: 72 | return dependency[0] 73 | return None 74 | 75 | def has_missing_required_dependency(self) -> bool: 76 | """ 77 | Checks if there is any required dependency missing. 78 | 79 | :return: True if a required dependency is missing, False otherwise. 80 | :rtype: bool 81 | """ 82 | dependency = [ 83 | x for x in self.dependencies if x.path is None and x.required] 84 | if dependency: 85 | return True 86 | return False 87 | 88 | def __getattr__(self, name: str) -> str: 89 | """ 90 | Overwrites the default Python attribute getter (__getattr__). 91 | It allows us to get a dependency as an object attribute. 92 | 93 | :param name: The name of the attribute (constructed from the dependency's name). 94 | :type name: str 95 | :return: Path to dependency executable. 96 | :rtype: str 97 | """ 98 | name = name.replace('_', '-') 99 | dependency = self.get_dependency(name) 100 | if dependency: 101 | return dependency.path 102 | return None 103 | -------------------------------------------------------------------------------- /apkinjector/injector.py: -------------------------------------------------------------------------------- 1 | import os 2 | import shutil 3 | from typing import List 4 | 5 | from elftools.elf.elffile import ELFFile 6 | 7 | from .arch import ARCH 8 | from .utils import arch_to_abi 9 | 10 | 11 | class Injector: 12 | @staticmethod 13 | def inject_library(source: str, unpack_path: str, smali_path: str = None, extra_files: List[str] = None, skip_copy=False) -> None: 14 | """ 15 | Injects a library into an unpacked apk. 16 | 17 | :param source: The path to the shared library to inject. 18 | :type source: str 19 | :param unpack_path: The path to the apktool unpacked apk. 20 | :type unpack_path: str 21 | :param smali_path: The path to the smali file to inject into. Leave empty to skip this step. Defaults to None. 22 | :type smali_path: str, optional 23 | :param extra_files: Extra files to copy over the to the apk lib/ folder. Defaults to None. 24 | :type extra_files: list of str, optional 25 | :param skip_copy: Whatever to copy the library into target, or skip and just edit the smali. Defaults to False. 26 | :type skip_copy: bool, optional 27 | 28 | :return: If the injection was successful or not. 29 | :rtype: bool 30 | """ 31 | lib, _ = os.path.splitext(os.path.basename(source)) 32 | lib = lib.split('lib', 1)[-1] 33 | lines = [] 34 | injected = False 35 | if smali_path and not os.path.isfile(smali_path): 36 | return injected 37 | 38 | arch = Injector.guess_arch_from_lib(source) 39 | abi = arch_to_abi(arch.lower()) 40 | 41 | if not skip_copy: 42 | path = os.path.join(unpack_path, 'lib', abi) 43 | if not os.path.isdir(path): 44 | os.makedirs(path) 45 | paths = [] 46 | paths.append(source) 47 | if extra_files: 48 | paths.extend(extra_files) 49 | for file in paths: 50 | name = os.path.basename(file) 51 | dest = os.path.join(path, name) 52 | if os.path.isfile(dest): 53 | os.remove(dest) 54 | shutil.copyfile(file, dest) 55 | 56 | injected = not bool(smali_path) 57 | if smali_path: 58 | with open(smali_path, 'r') as smali: 59 | lines = smali.readlines() 60 | matches = [] 61 | for line in lines: 62 | if 'const-string v0, "{}"\n'.format(lib) in line: 63 | matches.append(line) 64 | if matches and 'invoke-static {v0}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V\n' in line: 65 | matches.append(line) 66 | if len(matches) >= 2: 67 | return True 68 | for line in lines: 69 | if line.startswith('.method public constructor ()V') or line.startswith('.method static constructor ()V'): 70 | index = lines.index(line) 71 | if lines[index + 1].startswith(' .locals'): 72 | lines.insert( 73 | index + 2, ' const-string v0, "{}"\n'.format(lib)) 74 | lines.insert( 75 | index + 3, ' invoke-static {v0}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V\n') 76 | injected = True 77 | break 78 | else: 79 | lines.insert( 80 | index + 1, ' const-string v0, "{}"\n'.format(lib)) 81 | lines.insert( 82 | index + 2, ' invoke-static {v0}, Ljava/lang/System;->loadLibrary(Ljava/lang/String;)V\n') 83 | injected = True 84 | break 85 | with open(smali_path, 'w') as smali: 86 | smali.writelines(lines) 87 | return injected 88 | 89 | @staticmethod 90 | def guess_arch_from_lib(lib_path: str) -> ARCH: 91 | with open(lib_path, 'rb') as libfile: 92 | elffile = ELFFile(libfile) 93 | arch = elffile.get_machine_arch() 94 | if arch.lower() in ['aarch64', 'arm64']: 95 | arch = ARCH.ARM64 96 | if arch.lower() in ['x64']: 97 | arch = ARCH.X64 98 | return arch 99 | -------------------------------------------------------------------------------- /apkinjector/adb.py: -------------------------------------------------------------------------------- 1 | import subprocess 2 | from typing import Callable, Union 3 | 4 | from . import DEPENDENCIES, USER_DIRECTORIES, utils 5 | from .arch import ARCH 6 | from .download import download_file 7 | 8 | import os 9 | import platform 10 | import zipfile 11 | 12 | def _download_adb(progress_callback=None): 13 | def _get_bin(): 14 | if plat in ['Linux', 'Darwin']: 15 | exe = os.path.join(USER_DIRECTORIES.user_data_dir, 'platform-tools', 'adb') 16 | os.chmod(exe, 0o755) # set executable permission 17 | return exe 18 | if plat == 'Windows': 19 | return os.path.join(USER_DIRECTORIES.user_data_dir, 'platform-tools', 'adb') 20 | return None 21 | plat = platform.system() 22 | if platform.machine() not in ['x86_64', 'amd64']: 23 | return None 24 | uri = None 25 | if plat == 'Linux': 26 | uri = 'https://dl.google.com/android/repository/platform-tools_r29.0.5-linux.zip' 27 | if plat == 'Windows': 28 | uri = 'https://dl.google.com/android/repository/platform-tools_r29.0.5-windows.zip' 29 | if plat == 'Darwin': 30 | uri = 'https://dl.google.com/android/repository/platform-tools_r29.0.5-darwin.zip' 31 | 32 | path = os.path.join(USER_DIRECTORIES.user_data_dir, 'platform-tools') 33 | if os.path.isdir(path): 34 | return _get_bin() 35 | downloaded = download_file(uri, f'{path}.zip', progress_callback) 36 | with zipfile.ZipFile(downloaded, 'r') as ref: 37 | ref.extractall(USER_DIRECTORIES.user_data_dir) 38 | return _get_bin() 39 | 40 | 41 | class Adb: 42 | """ 43 | A utility class for running adb commands. 44 | """ 45 | @staticmethod 46 | def get_architecture() -> Union[ARCH, None]: 47 | """ 48 | Get phone architecture as apkpatcher.arch.ARCH. 49 | 50 | This function serves as a shorthand for ``apkpatcher.utils.abi_to_arch(apkpatcher.adb.Adb.get_prop('ro.product.cpu.abi'))``. 51 | 52 | :return: apkpatcher.arch.ARCH if adb is installed and a device is connected. Otherwise, it returns None. 53 | :rtype: Union[str, None] 54 | """ 55 | res = Adb.get_prop('ro.product.cpu.abi') 56 | if not res: 57 | return None 58 | return utils.abi_to_arch(res) 59 | 60 | @staticmethod 61 | def get_prop(prop: str) -> Union[str, None]: 62 | """ 63 | Calls ``adb shell getprop {prop}``. 64 | 65 | :param prop: Prop to retrieve 66 | :type prop: str 67 | :return: Returns prop from device if adb is installed and a device is connected. Otherwise, it returns None. 68 | :rtype: Union[str, None] 69 | """ 70 | return Adb.shell(f'getprop {prop}') 71 | 72 | @staticmethod 73 | def wait_for_device() -> None: 74 | """ 75 | Waits for a device to be connected. If adb is not installed, it will skip without waiting. 76 | """ 77 | if not DEPENDENCIES.adb: 78 | return None 79 | return Adb.run(f'wait-for-device') 80 | 81 | @staticmethod 82 | def shell(command: str) -> str: 83 | """ 84 | Run an adb shell command. 85 | 86 | :param command: Command to be ran. 87 | :type command: str 88 | :return: Output of the command if adb is installed and a device is connected. Otherwise, it returns None. 89 | :rtype: str 90 | """ 91 | return Adb.run(f'shell {command}') 92 | 93 | @staticmethod 94 | def run(command: str) -> Union[str, None]: 95 | """ 96 | Bare method to run adb commands. 97 | 98 | :param command: Command to be run. 99 | :type command: str 100 | :return: Output of the command if adb is installed and a device is connected. Otherwise, it returns None. 101 | :rtype: Union[str, None] 102 | """ 103 | if not DEPENDENCIES.adb: 104 | return None 105 | try: 106 | process = subprocess.run( 107 | f'{DEPENDENCIES.adb} {command}', shell=True, capture_output=True, text=True, timeout=5) 108 | return process.stdout.strip() 109 | except subprocess.TimeoutExpired: 110 | return None 111 | 112 | @staticmethod 113 | def install(path: str = None, progress_callback: Callable = None) -> None: 114 | """ 115 | Install adb tools. 116 | 117 | :param path: Path to existing adb executable. If not found, will use the system installed one or download it. Defaults to None. 118 | :type path: str, optional 119 | :param progress_callback: Callback to be called when install progress changes, defaults to None. 120 | :type progress_callback: callable, optional 121 | """ 122 | DEPENDENCIES.add_dependency( 123 | 'adb', path=path, fallback=_download_adb, fallback_args=(progress_callback,)) 124 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # APK Injector 2 | 3 | Pluginable tool to automate injection of libraries in apks, with support for unpack, repack, and bundles. 4 | 5 | - [APK Injector](#apk-injector) 6 | - [Features](#features) 7 | - [Installation](#installation) 8 | - [Usage](#usage) 9 | - [Frida](#frida) 10 | - [Inject](#inject) 11 | - [Apk utils](#apk-utils) 12 | - [Plugins](#plugins) 13 | - [Using as a module](#using-as-a-module) 14 | - [Usage as a plugin](#usage-as-a-plugin) 15 | 16 | ### Features 17 | - Insert libraries and load them when an activity starts. 18 | - Frida support with support to load frida scripts either from disc or codeshare. 19 | - Bundle support. Apks exported from SAI or XApks downloaded from apkpure. 20 | - Plugins support. Check plugins/plugins.json and plugin_example.py 21 | 22 | ### Installation 23 | `pip3 install apkinjector` 24 | 25 | ### Usage 26 | ``` 27 | apkinjector [OPTIONS] COMMAND [ARGS]... 28 | 29 | Options: 30 | --help Show this message and exit. 31 | 32 | Commands: 33 | apk Apk utils 34 | frida Inject a frida gadget in a target apk. 35 | inject Inject a shared library (*.so) in a target apk. 36 | plugins Manage plugins 37 | ``` 38 | 39 | 40 | #### Frida 41 | ``` 42 | Usage: python -m apkinjector frida [OPTIONS] APK 43 | 44 | Inject a frida gadget in a target apk. 45 | 46 | Options: 47 | --gadget TEXT Path to custom gadget. 48 | --script TEXT Inject a javascript to be loaded when the gadget starts. 49 | --codeshare TEXT Same as --script but uses Frida Codeshare as the source 50 | javascript. 51 | --arch TEXT Architecture to inject for. If empty --adb or --gadget 52 | must be specified. 53 | --adb Use adb (if installed) to detect device architecture. 54 | --activity TEXT Name of the activity to inject into. If unspecified, the 55 | main activity will be injected. 56 | --output Custom path where the patched apk should be saved. 57 | --force Force delete destination directory. 58 | --help Show this message and exit. 59 | ``` 60 | 61 | #### Inject 62 | ``` 63 | Usage: python -m apkinjector inject [OPTIONS] APK 64 | 65 | Inject a shared library (*.so) in a target apk. 66 | 67 | Options: 68 | --library TEXT Shared library (*.so) to inject. [required] 69 | --include TEXT Extra files to include in the lib folder. Can be used 70 | multiple times to include more files. 71 | --arch TEXT Architecture to inject for. If empty --adb or --library 72 | must be specified. 73 | --adb Use adb (if installed) to detect device architecture. 74 | --activity TEXT Name of the activity to inject into. If unspecified, the 75 | main activity will be injected. 76 | --output Custom path where the patched apk should be saved. 77 | --force Force delete destination directory. 78 | --help Show this message and exit. 79 | ``` 80 | 81 | #### Apk utils 82 | ``` 83 | Usage: python -m apkinjector apk [OPTIONS] APK 84 | 85 | Apk utils 86 | 87 | Options: 88 | --activities Gets all activities 89 | --permissions Gets all permissions 90 | --libraries Gets all libraries 91 | --recievers Gets all receivers 92 | --help Show this message and exit. 93 | ``` 94 | 95 | #### Plugins 96 | ``` 97 | Usage: python -m apkinjector plugins [OPTIONS] 98 | 99 | Manage plugins 100 | 101 | Options: 102 | --list List all installed and available plugins. 103 | --install TEXT Installs a plugin by name. 104 | --remove TEXT Removes an installed plugin. 105 | --help Show this message and exit. 106 | ``` 107 | 108 | 109 | ### Using as a module 110 | 111 | ```python 112 | from apkinjector import LOG 113 | 114 | 115 | LOG.info("This has been printed using apkinjector logging") 116 | 117 | 118 | # Also comes with runners for apktool, uber-apk-signer, etc/ 119 | 120 | from apkinjector.apktool import ApkTool 121 | 122 | from apkinjector.uber_apk_signer import UberApkSigner 123 | 124 | # Automatically download and setup apktool. 125 | ApkTool.install() 126 | 127 | # Decompile apk 128 | ApkTool.decode(...) 129 | 130 | # Automatically download and setup uber-apk-signer 131 | UberApkSigner.install() 132 | 133 | # Sign apk 134 | UberApkSigner.sign(...) 135 | 136 | 137 | # Check if a dependency is in path 138 | 139 | from apkinjector import DEPENDENCIES_MANAGER 140 | 141 | # Add a new dependency 142 | java = DEPENDENCIES_MANAGER.add_dependency('java', required=True) # Return Depedency(name, path, required) 143 | 144 | # Check if a dependency is path 145 | # Returns the path to the binary if found, if not returns None 146 | # See apkpatcher/apkpatcher to see how dependencies are automatically handled 147 | in_path = DEPENDENCIES_MANAGER.java 148 | ``` 149 | 150 | ### Usage as a plugin 151 | 152 | ```python 153 | 154 | # Can use the same methods as a it would been included in a separate module. 155 | 156 | from apkinjector import LOG 157 | 158 | # Adding a new command to the `apkinjector` application: 159 | 160 | from apkinjector.plugins import main 161 | 162 | # Define a new command. It uses click under the hood. See more at https://click.palletsprojects.com/en/8.1.x/ 163 | # Check plugins/plugin_example.py for a full example. 164 | @main.command(help='Prints hello world to the console.') 165 | def hello_world(): 166 | LOG.info('Hello World') # prints info 167 | LOG.warning("Hello World") # prints warning 168 | LOG.error('Hello World') # prints error and calls sys.exit(1) 169 | 170 | # This will be usable with `apkinjector hello_world` 171 | # 172 | # apkinjector hello-world --help 173 | # Usage: python -m apkinjector hello-world [OPTIONS] 174 | 175 | # Prints hello world to the console. 176 | 177 | # Options: 178 | # --help Show this message and exit. 179 | ``` -------------------------------------------------------------------------------- /apkinjector/apktool.py: -------------------------------------------------------------------------------- 1 | import os 2 | import subprocess 3 | from typing import Callable 4 | 5 | from . import __APKTOOL_VERSION__, DEPENDENCIES, USER_DIRECTORIES 6 | from .download import download_file 7 | from .java import Java 8 | 9 | 10 | def _download_apktool(progress_callback=None): 11 | path = os.path.join(USER_DIRECTORIES.user_data_dir, 12 | f'apktool_{__APKTOOL_VERSION__}.jar') 13 | if not os.path.isfile(path): 14 | uri = f'https://github.com/iBotPeaches/Apktool/releases/download/v{__APKTOOL_VERSION__}/apktool_{__APKTOOL_VERSION__}.jar' 15 | return download_file(uri, path, progress_callback) 16 | return path 17 | 18 | 19 | class Apktool: 20 | """ 21 | A wrapper class for the different Apktool commands. 22 | """ 23 | 24 | @staticmethod 25 | def advanced(): 26 | """ 27 | Obtain advanced information of the Apktool. 28 | 29 | :return: The stdout from the command execution. 30 | :rtype: str 31 | """ 32 | return Apktool._run('--advanced') 33 | 34 | @staticmethod 35 | def version(): 36 | """ 37 | Obtain the version of the Apktool. 38 | 39 | :return: The stdout from the command execution. 40 | :rtype: str 41 | """ 42 | return Apktool._run('--version') 43 | 44 | @staticmethod 45 | def install_framework(framework_apk, framework_path=None, tag=None): 46 | """ 47 | Install framework with provided options. 48 | 49 | :param framework_apk: The APK framework file to be installed. 50 | :type framework_apk: str 51 | :param framework_path: The directory where to store framework files, defaults to None. 52 | :type framework_path: str, optional 53 | :param tag: The tag for the framework file, defaults to None. 54 | :type tag: str, optional 55 | :return: The stdout from the command execution. 56 | :rtype: str 57 | """ 58 | command = f'if {framework_apk}' 59 | if framework_path: 60 | command += f' --frame-path {framework_path}' 61 | if tag: 62 | command += f' --tag {tag}' 63 | return Apktool._run(command) 64 | 65 | @staticmethod 66 | def decode(file_apk, force=False, output=None, framework_path=None, no_res=False, no_src=False, tag=None, force_manifest=False): 67 | """ 68 | Decode an APK file with provided options. 69 | 70 | :param file_apk: The APK file to be decoded. 71 | :type file_apk: str 72 | :param force: Whether to force delete the destination directory, defaults to False. 73 | :type force: bool, optional 74 | :param output: The name of the output folder, defaults to None. 75 | :type output: str, optional 76 | :param framework_path: The directory containing framework files, defaults to None. 77 | :type framework_path: str, optional 78 | :param no_res: Whether to not decode resources, defaults to False. 79 | :type no_res: bool, optional 80 | :param no_src: Whether to not decode sources, defaults to False. 81 | :type no_src: bool, optional 82 | :param tag: A tag for the framework file, defaults to None. 83 | :type tag: str, optional 84 | :param force_manifest: Forces decode of AndroidManifest.xml regardless of decoding of resources parameter. 85 | :type force_manifest: str, optional 86 | :return: The stdout from the command execution. 87 | :rtype: str 88 | """ 89 | command = f'd {file_apk}' 90 | if force: 91 | command += ' --force' 92 | if output: 93 | command += f' --output {output}' 94 | if framework_path: 95 | command += f' --frame-path {framework_path}' 96 | if no_res: 97 | command += ' --no-res' 98 | if no_src: 99 | command += ' --no-src' 100 | if tag: 101 | command += f' --frame-tag {tag}' 102 | if force_manifest: 103 | command += f' --force-manifest' 104 | return Apktool._run(command) 105 | 106 | @staticmethod 107 | def build(app_path, force_all=False, output=None, framework_path=None, use_aapt2=False): 108 | """ 109 | Build the unpacked apk from the given path with the provided options. 110 | 111 | :param app_path: The path of the app to build. 112 | :type app_path: str 113 | :param force_all: Whether to skip changes detection and build all files, defaults to False. 114 | :type force_all: bool, optional 115 | :param output: The name of the output APK file, defaults to None. 116 | :type output: str, optional 117 | :param framework_path: The directory containing framework files, defaults to None. 118 | :type framework_path: str, optional 119 | :param use_aapt2: Whether to use aapt 2 or no, defaults to False. 120 | :type use_aapt2: bool, optional. 121 | :return: The stdout from the command execution. 122 | :rtype: str 123 | """ 124 | command = f'b {app_path}' 125 | if force_all: 126 | command += ' --force-all' 127 | if output: 128 | command += f' --output {output}' 129 | if framework_path: 130 | command += f' --frame-path {framework_path}' 131 | if use_aapt2: 132 | command += ' --use-aapt2' 133 | return Apktool._run(command) 134 | 135 | @staticmethod 136 | def _run(command): 137 | if not DEPENDENCIES.apktool: 138 | return 139 | if DEPENDENCIES.apktool.endswith('.jar'): 140 | return Java.run_jar(DEPENDENCIES.apktool, command) 141 | process = subprocess.run( 142 | f'{DEPENDENCIES.apktool} {command}', shell=True, capture_output=True, text=True) 143 | return process.stdout 144 | 145 | @staticmethod 146 | def install(path: str = None, progress_callback: Callable = None) -> None: 147 | """ 148 | Install apktool. 149 | 150 | :param path: Path to existing apktool.jar. If not found, will use the system installed one or download it. Defaults to None. 151 | :type path: str, optional 152 | :param progress_callback: Callback to be called when install progress changes, defaults to None. 153 | :type progress_callback: callable, optional 154 | """ 155 | DEPENDENCIES.add_dependency( 156 | 'apktool', path=path, fallback=_download_apktool, fallback_args=(progress_callback,)) 157 | -------------------------------------------------------------------------------- /apkinjector/bundle.py: -------------------------------------------------------------------------------- 1 | 2 | from typing import List, Union 3 | import json 4 | import re 5 | import os 6 | import zipfile 7 | 8 | from dataclasses import dataclass 9 | from .arch import ARCH 10 | from .utils import arch_to_abi 11 | 12 | @dataclass 13 | class ConfigArch: 14 | """ 15 | A Data class representing the architecture information in a split APK file. 16 | 17 | :param str file_name: The name of the APK file. 18 | :param str arch: The architecture type of the APK file ('ARM', 'ARM64', 'X86', 'X64'). 19 | """ 20 | 21 | file_name: str 22 | arch: str 23 | 24 | @dataclass 25 | class ConfigLocale: 26 | """ 27 | A Data class representing the locale information in a split APK file. 28 | 29 | :param str file_name: A string representing the name of the APK file. 30 | :param str locale: A string indicating the locale config of the APK file. 31 | """ 32 | 33 | file_name: str 34 | locale: str 35 | 36 | @dataclass 37 | class ConfigDpi: 38 | """ 39 | A Data class representing the DPI information in a split APK file. 40 | 41 | :param str file_name: The name of the APK file. 42 | :param str dpi: A string representing the screen DPI config of the APK. 43 | """ 44 | 45 | file_name: str 46 | dpi: str 47 | 48 | @dataclass 49 | class BundleInfo: 50 | """ 51 | A data class representing general information about an Android Bundle file. 52 | 53 | :param str base_apk: The name of the base APK file extracted from the Android Bundle. 54 | :param List[Union[ConfigDpi, ConfigLocale, ConfigArch]] configs: Configurations of the APK files extracted from the Android Bundle. 55 | """ 56 | 57 | base_apk: str 58 | configs: List[Union[ConfigDpi, ConfigLocale, ConfigArch]] 59 | 60 | class Bundle: 61 | """ 62 | Tools to work with apk bundles (xapk and apks) 63 | """ 64 | @staticmethod 65 | def extract(source: str, output_path: str) -> BundleInfo: 66 | """ 67 | Extract a bundle (xapk and apks) to a given path. 68 | 69 | :param source: Path to the bundle. 70 | :type source: str 71 | :param output_path: Destination of the bundled. 72 | :type output_path: str 73 | :return: BundleInfo class containing the name of the base apk and configuration ifno. 74 | :rtype: BundleInfo 75 | """ 76 | name = os.path.basename(source)[:-5] 77 | base_apk = None 78 | if os.path.exists(output_path): 79 | output_path = os.path.join(output_path, name) 80 | os.makedirs(output_path) 81 | with zipfile.ZipFile(source) as zip: 82 | zip.extractall(output_path) 83 | sai_manifestv1 = os.path.join(output_path, 'meta.sai_v1.json') 84 | sai_manifestv2 = os.path.join(output_path, 'meta.sai_v2.json') 85 | apkm_installer_url = os.path.join(output_path, 'APKM_installer.url') 86 | base_apk = None 87 | configs = [] 88 | matches = [None] 89 | 90 | if os.path.isfile(sai_manifestv1) or os.path.isfile(sai_manifestv2) or os.path.isfile(apkm_installer_url): 91 | base_apk = 'base.apk' 92 | else: 93 | manifest = os.path.join(output_path, 'manifest.json') 94 | with open(manifest, 'r') as m_file: 95 | manifest = json.load(m_file) 96 | for apk in manifest['split_apks']: 97 | if apk['id'] == 'base': 98 | base_apk = apk['file'] 99 | files = os.listdir(output_path) 100 | for file in files: 101 | if file.endswith('.apk'): 102 | if f'.{arch_to_abi(ARCH.ARM64)}.' in file and file not in matches: 103 | configs.append(ConfigArch(file, ARCH.ARM64)) 104 | matches.append(file) 105 | if f'.{arch_to_abi(ARCH.ARM)}.' in file and file not in matches: 106 | configs.append(ConfigArch(file, ARCH.ARM)) 107 | matches.append(file) 108 | 109 | if f'.{arch_to_abi(ARCH.ARM64).replace("-", "_")}.' in file and file not in matches: 110 | configs.append(ConfigArch(file, ARCH.ARM64)) 111 | matches.append(file) 112 | if f'.{arch_to_abi(ARCH.ARM).replace("-", "_")}.' in file and file not in matches: 113 | configs.append(ConfigArch(file, ARCH.ARM)) 114 | matches.append(file) 115 | 116 | if f'.{arch_to_abi(ARCH.X64)}.' in file and file not in matches: 117 | configs.append(ConfigArch(file, ARCH.X64)) 118 | matches.append(file) 119 | if f'.{arch_to_abi(ARCH.X86)}.' in file and file not in matches: 120 | configs.append(ConfigArch(file, ARCH.X86)) 121 | matches.append(file) 122 | 123 | # Check for locale 124 | locale_match = re.search(r'config\.([a-z]{2}(?:_r[A-Z]{2})?)\.apk', file) 125 | if locale_match and file not in matches: 126 | configs.append(ConfigLocale(file, locale_match.group(1))) 127 | 128 | # Check for dpi 129 | dpi_match = re.search(r'config\.(.*?)\.apk', file) 130 | if dpi_match and dpi_match.group(1).endswith('dpi') and file not in matches: 131 | configs.append(ConfigDpi(file, dpi_match.group(1).replace('dpi', ''))) 132 | matches.append(file) 133 | info = BundleInfo(base_apk, configs) 134 | return info 135 | 136 | @staticmethod 137 | def repack(source: str, output_path: str) -> str: 138 | """ 139 | Repacks a bundle (xapk and apks) to a given path. 140 | 141 | :param source: Path to the extracted bundle. 142 | :type source: str 143 | :param output_path: Path to where to save the bundle file. 144 | :type output_path: str 145 | :return: Location of the repacked bundle. 146 | """ 147 | with zipfile.ZipFile(output_path, 'w', zipfile.ZIP_DEFLATED) as zip: 148 | for foldername, subfolders, filenames in os.walk(source): 149 | for filename in filenames: 150 | abspath = os.path.join(foldername, filename) 151 | relpath = os.path.relpath(abspath, source) 152 | zip.write(abspath, arcname=relpath) 153 | return output_path 154 | 155 | @staticmethod 156 | def is_bundle(source: str) -> bool: 157 | """ 158 | Checks if the source is a bundle or not. 159 | 160 | :param source: Source to check. 161 | :type source: str 162 | :return: True if it's a bundle, False otherwise. 163 | :rtype: bool 164 | """ 165 | name = os.path.basename(source) 166 | return name.endswith('.xapk') or name.endswith('.apks') or name.endswith('.apkm') 167 | -------------------------------------------------------------------------------- /apkinjector/__main__.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | import time 4 | import zipfile 5 | 6 | import click 7 | import json 8 | import shutil 9 | import requests 10 | import tempfile 11 | from colorama import Fore 12 | 13 | from . import LOG, USER_DIRECTORIES, __PLUGIN_DATA__ 14 | from .adb import Adb 15 | from .apktool import Apktool 16 | from .java import Java 17 | from .arch import ARCH 18 | from .download import ProgressCompleted, ProgressDownloading, ProgressFailed, ProgressUnknown 19 | from .frida import Frida 20 | from .gadget import Gadget 21 | from .injector import Injector 22 | from .plugins import _PluginLoader, main 23 | from .uber_apk_signer import UberApkSigner 24 | from .bundle import Bundle, ConfigArch, ConfigDpi, ConfigLocale 25 | from .download import download_file 26 | from .manifest import Manifest 27 | 28 | def _clear_cache(func): 29 | def inner(*args, **kwargs): 30 | func(*args, **kwargs) 31 | shutil.rmtree(USER_DIRECTORIES.user_cache_dir) 32 | os.makedirs(USER_DIRECTORIES.user_cache_dir) 33 | return inner 34 | 35 | 36 | def _install_callback(progress): 37 | if isinstance(progress, ProgressDownloading): 38 | sys.stdout.write( 39 | Fore.GREEN + f'\r[+] Downloading {progress.filename} - {progress.progress:03d}%') 40 | sys.stdout.flush() 41 | if isinstance(progress, ProgressFailed): 42 | sys.stdout.write( 43 | Fore.RED + f'[*] Download failed with status: {progress.status_code}') 44 | if isinstance(progress, ProgressCompleted): 45 | sys.stdout.write('\n') 46 | if isinstance(progress, ProgressUnknown): 47 | LOG.info('Downloading {} this might take a while...', progress.filename) 48 | 49 | 50 | @_clear_cache 51 | def _inject(apk, libraries, include, activity, output, override, use_aapt): 52 | if not os.path.isfile(apk): 53 | LOG.error('{} - not such file.', apk) 54 | for lib in libraries: 55 | if not os.path.isfile(lib): 56 | LOG.error('{} - not such file.', lib) 57 | 58 | if include: 59 | for i in include: 60 | if not os.path.isfile(i): 61 | LOG.error('Include {} is not a valid file.', include) 62 | 63 | apk_name, ext = os.path.splitext(apk) 64 | workdir = os.path.join(USER_DIRECTORIES.user_cache_dir, apk_name) 65 | 66 | libraries = list(libraries) 67 | entry_lib = libraries[0] 68 | 69 | _, _ext = os.path.splitext(output) 70 | if not _ext: 71 | # is file 72 | tmp_output = output 73 | if os.path.isdir(output): 74 | tmp_output = os.path.join(output, f'{apk_name}_patched{ext}' if not override else apk) 75 | else: 76 | if tmp_output.endswith(os.sep): 77 | tmp_output = tmp_output.rsplit(os.sep, 1)[0] 78 | if os.path.exists(tmp_output): 79 | timestamp = int(time.time()) 80 | tmp_output = os.path.join(output, f'{apk_name}_patched_{timestamp}{ext}') 81 | output = tmp_output 82 | else: 83 | if os.path.exists(output) and not override: 84 | LOG.error('{} already exists.', output) 85 | 86 | is_bundle = Bundle.is_bundle(apk) 87 | 88 | output_bundle = None 89 | bundle_info = None 90 | 91 | if is_bundle: 92 | LOG.info('Extracting split apks...') 93 | output_bundle = f'{workdir}_bundle' 94 | if os.path.exists(output_bundle): 95 | shutil.rmtree(output_bundle) 96 | bundle_info = Bundle.extract(apk, output_bundle) 97 | 98 | targets = [] 99 | 100 | if bundle_info and bundle_info.configs: 101 | for config in bundle_info.configs: 102 | if isinstance(config, ConfigArch): 103 | for lib in libraries.copy(): 104 | lib_arch = Injector.guess_arch_from_lib(lib) 105 | if lib_arch == config.arch: 106 | target_split = os.path.join(output_bundle, config.file_name) 107 | targets.append([target_split, lib]) 108 | libraries.remove(lib) 109 | for lib in libraries: 110 | if is_bundle: 111 | target_split = os.path.join(output_bundle, bundle_info.base_apk) 112 | targets.append([target_split, lib]) 113 | else: 114 | targets.append([output, lib]) 115 | 116 | Apktool.install(progress_callback=_install_callback) 117 | LOG.info('Using apktool: {}', Apktool.version()) 118 | 119 | base = os.path.join(output_bundle, bundle_info.base_apk) if is_bundle else apk 120 | # extract base 121 | LOG.info('Extracting {}', base) 122 | Apktool.decode(base, force=True, output=workdir, framework_path=f'{workdir}_framework') 123 | 124 | manifest_path = os.path.join(workdir, 'AndroidManifest.xml') 125 | target_activity = None 126 | if activity: 127 | for activities in Manifest.get_activities(manifest_path): 128 | for i in activities: 129 | if activity in i: 130 | target_activity = i 131 | break 132 | else: 133 | target_activity = Manifest.get_main_activity(manifest_path) 134 | if not target_activity: 135 | LOG.error('{} did not match any activities', activity) 136 | 137 | LOG.info('Found target activity {}', target_activity) 138 | 139 | entrypoint = None 140 | for file in os.listdir(workdir): 141 | if file.startswith('smali'): 142 | entrypoint_tmp = os.path.join( 143 | workdir, file, target_activity.replace('.', '/') + '.smali') 144 | if os.path.isfile(entrypoint_tmp): 145 | entrypoint = entrypoint_tmp 146 | break 147 | if not entrypoint: 148 | LOG.error('Failed to find smali file for activity {}', target_activity) 149 | 150 | LOG.info('Injecting smali loader into {}.', target_activity) 151 | injected = Injector.inject_library(entry_lib, workdir, entrypoint, include, skip_copy=True) # Copying will be done for each target bellow 152 | if not injected: 153 | LOG.error('Something wen\'t wrong when injecting into target..') 154 | LOG.info('Repacking {} -> {}', base if is_bundle else apk, base if is_bundle else output) 155 | Apktool.build(workdir, output=base if is_bundle else output, framework_path=f'{workdir}_framework', use_aapt2=use_aapt) 156 | 157 | for target in targets: 158 | apk_target = target[0] 159 | lib_target = target[1] 160 | if os.path.exists(workdir): 161 | shutil.rmtree(workdir) 162 | os.makedirs(workdir) 163 | LOG.info('Extracting {}', apk_target) 164 | with zipfile.ZipFile(apk_target, 'r') as ref: 165 | ref.extractall(workdir) 166 | LOG.info('Injecting {} in {}', lib_target, apk_target) 167 | injected = Injector.inject_library(lib_target, workdir, smali_path=None, extra_files=include) 168 | if not injected: 169 | LOG.error('Something wen\'t wrong when injecting into target..') 170 | LOG.info('Repacking {} -> {}', apk_target, apk_target if is_bundle else output) 171 | with zipfile.ZipFile(apk_target if is_bundle else output, 'w') as ref: 172 | for root, dirs, files in os.walk(workdir): 173 | for file in files: 174 | ref.write(os.path.join(root, file), 175 | os.path.relpath(os.path.join(root, file), 176 | workdir)) 177 | 178 | apks = [] 179 | if is_bundle: 180 | apks = [os.path.join(output_bundle, apk) for apk in os.listdir(output_bundle) if apk.endswith('.apk')] 181 | else: 182 | apks = [output,] 183 | 184 | LOG.info('Signing {}', ' '.join([os.path.basename(apk) for apk in apks])) 185 | UberApkSigner.install(progress_callback=_install_callback) 186 | 187 | LOG.info('Using uber-apk-signer {}', UberApkSigner.version()) 188 | 189 | UberApkSigner.sign(apks, allow_resign=True, overwrite=True) 190 | 191 | if is_bundle: 192 | LOG.info('Repacking bundle') 193 | cache_bundle = os.path.join(USER_DIRECTORIES.user_cache_dir, f'cached.{ext}') 194 | Bundle.repack(f'{workdir}_bundle', cache_bundle) 195 | if os.path.isfile(output): 196 | os.remove(output) 197 | shutil.copyfile(cache_bundle, output) 198 | LOG.info('DONE! {}', output) 199 | 200 | ### Clear cache 201 | 202 | @main.command(help='Inject a shared library (*.so) in a target apk.') 203 | @click.argument('apk') 204 | @click.option('--library', required=True, multiple=True, help='Shared library (*.so) to inject. If multiple are given, only the first one will be automatically loaded.') 205 | @click.option('--include', multiple=True, required=False, help='Extra files to include in the lib folder. Can be used multiple times to include more files.') 206 | @click.option('--activity', required=False, help='Name of the activity to inject into. If unspecified, the main activity will be injected.') 207 | @click.option('--output', required=False, default=os.getcwd(), help='Custom path where the patched apk should be saved.') 208 | @click.option('--override', is_flag=True, help='Override apk in place.') 209 | @click.option('--aapt2', required=False, help='Either to use aapt2 when building the apk or not.') 210 | def inject(apk, library, include, activity, output, override, aapt2): 211 | Java.install(progress_callback=_install_callback) 212 | _inject(apk, library, include, activity, output, override, aapt2) 213 | 214 | 215 | @main.command(help='Inject a frida gadget in a target apk.') 216 | @click.argument('apk') 217 | @click.option('--script', required=False, help='Inject a javascript to be loaded when the gadget starts.') 218 | @click.option('--codeshare', required=False, help='Same as --script but uses Frida Codeshare as the source javascript.') 219 | @click.option('--arch', required=False, help='Architecture to inject for. If empty --all, --adb or --gadget must be specified.') 220 | @click.option('--adb', is_flag=True, help='Use adb (if installed) to detect device architecture.') 221 | @click.option('--activity', required=False, help='Name of the activity to inject into. If unspecified, the main activity will be injected.') 222 | @click.option('--output', required=False, default=os.getcwd(), help='Custom path where the patched apk should be saved.') 223 | @click.option('--override', is_flag=True, help='Override apk in place.') 224 | @click.option('--aapt2', required=False, help='Either to use aapt2 when building the apk or not.') 225 | def frida(apk, script, codeshare, arch, adb, activity, output, override, aapt2): 226 | if arch: 227 | if arch not in [ARCH.ARM, ARCH.ARM64, ARCH.X86, ARCH.X64]: 228 | LOG.error('{} not a supported arch: {}, {}, {}, {}', 229 | arch, ARCH.ARM, ARCH.ARM64, ARCH.X86, ARCH.X64) 230 | Java.install(progress_callback=_install_callback) 231 | gadget = Gadget.get_gadget_path(arch) 232 | if not gadget: 233 | Gadget.update(_install_callback) 234 | gadget = Gadget.get_gadget_path(arch) 235 | elif adb: 236 | Adb.install(None, _install_callback) 237 | arch = Adb.get_architecture() 238 | if not arch: 239 | LOG.info('Waiting for adb device...') 240 | Adb.wait_for_device() 241 | arch = Adb.get_architecture() 242 | if not arch: 243 | LOG.error( 244 | 'Failed to connect to any device. Make sure you have adb installed, and the device is properly connected.') 245 | gadget = Gadget.get_gadget_path(arch) 246 | if not gadget: 247 | Gadget.update(_install_callback) 248 | gadget = Gadget.get_gadget_path(arch) 249 | else: 250 | LOG.error('--arch or --adb is missing.') 251 | if os.path.exists(gadget): 252 | gadget_tmp = os.path.join( 253 | USER_DIRECTORIES.user_cache_dir, 'libfrida-gadget.so') 254 | shutil.copy(gadget, gadget_tmp) 255 | if script: 256 | if not os.path.isfile(script): 257 | LOG.error('Not a valid script file: {}', script) 258 | script_tmp = os.path.join( 259 | USER_DIRECTORIES.user_cache_dir, 'libhook.js.so') 260 | shutil.copyfile(script, script_tmp) 261 | script = [script_tmp,] 262 | if codeshare: 263 | if codeshare.endswith('/'): 264 | uri = codeshare[:-1] 265 | project_url = f"https://codeshare.frida.re/api/project/{uri}/" 266 | script = [ os.path.join( 267 | USER_DIRECTORIES.user_cache_dir, 'libhook.js.so') ] 268 | download_file(project_url, script[-1], _install_callback) 269 | if script or codeshare: 270 | config = { 271 | "interaction": 272 | { 273 | "type": "script", 274 | "address": "127.0.0.1", 275 | "port": 27042, 276 | "path": "./libhook.js.so", 277 | "on_port_conflict": "pick-next", 278 | "on_load": "resume" 279 | } 280 | } 281 | config_path = os.path.join( 282 | USER_DIRECTORIES.user_cache_dir, 'libfrida-gadget.config.so') 283 | with open(config_path, 'w') as f: 284 | f.write(json.dumps(config)) 285 | script.append(config_path) 286 | _inject(apk, [gadget_tmp,], script, activity, output, override, aapt2) 287 | 288 | 289 | @main.command(help='Apk utils') 290 | @click.argument('apk') 291 | @click.option('--activities', is_flag=True, help='Gets all activities') 292 | @click.option('--permissions', is_flag=True, help='Gets all permissions') 293 | @click.option('--libraries', is_flag=True, help='Gets all libraries') 294 | @click.option('--recievers', is_flag=True, help='Gets all receivers') 295 | def apk(apk, activities, permissions, libraries, recievers): 296 | def _parse_apk(): 297 | Java.install(progress_callback=_install_callback) 298 | Apktool.install(progress_callback=_install_callback) 299 | 300 | decoded_dir = os.path.join(USER_DIRECTORIES.user_cache_dir, 'decoded_tmp') 301 | 302 | Apktool.decode(apk, output=decoded_dir, framework_path=f'{decoded_dir}_framework', no_res=True, no_src=True, force_manifest=True) 303 | manifest_path = os.path.join(decoded_dir, 'AndroidManifest.xml') 304 | if activities: 305 | for activity in Manifest.get_activities(manifest_path): 306 | LOG.info(activity) 307 | if permissions: 308 | for permission in Manifest.get_permissions(manifest_path): 309 | LOG.info(permission) 310 | if libraries: 311 | for library in Manifest.get_libraries(manifest_path): 312 | LOG.info(library) 313 | if recievers: 314 | for reciever in Manifest.get_receivers(manifest_path): 315 | LOG.info('{}', reciever) 316 | if not os.path.isfile(apk): 317 | LOG.error('{} - not such file.', apk) 318 | if Bundle.is_bundle(apk): 319 | with tempfile.TemporaryDirectory() as tmp: 320 | apk, base = Bundle.extract(apk, tmp) 321 | apk = os.path.join(apk, base) 322 | return _parse_apk() 323 | _parse_apk() 324 | 325 | 326 | @main.command(help='Manage plugins') 327 | @click.option('--list', is_flag=True, help='List all installed and available plugins.') 328 | @click.option('--install', required=False, help='Installs a plugin by name.') 329 | @click.option('--remove', required=False, help='Removes an installed plugin.') 330 | def plugins(list, install, remove): 331 | plugin_path = os.path.join(USER_DIRECTORIES.user_data_dir, "plugins") 332 | online_plugins = None 333 | 334 | if list: 335 | response = requests.get(__PLUGIN_DATA__) 336 | if response.status_code == 200: 337 | online_plugins = response.json() 338 | LOG.warning('INSTALLED PLUGINS') 339 | for plugin in os.listdir(plugin_path): 340 | if plugin.endswith('.py'): 341 | LOG.info(plugin[:-3]) 342 | LOG.warning('AVAILABLE PLUGINS') 343 | if online_plugins: 344 | for plugin in online_plugins: 345 | LOG.info(plugin['name']) 346 | LOG.info('\tauthor: {}', plugin['author']) 347 | LOG.info('\tdescription: {}', plugin['description']) 348 | LOG.info('\tversion: {}', plugin['version']) 349 | LOG.info('\turl: {}', plugin['url']) 350 | 351 | if install: 352 | response = requests.get(__PLUGIN_DATA__) 353 | if response.status_code == 200: 354 | online_plugins = response.json() 355 | if online_plugins: 356 | for plugin in online_plugins: 357 | if plugin['name'] == install: 358 | LOG.info('Installing {} by {} version {}', 359 | plugin['name'], plugin['author'], plugin['version']) 360 | response = requests.get(plugin['url']) 361 | if response.status_code != 200: 362 | LOG.error( 363 | 'Failed to download {}. Request failed with: {}', install, response.status_code) 364 | out = os.path.join(plugin_path, f'{plugin["name"]}.py') 365 | with open(out, 'w') as out_f: 366 | out_f.write(response.text) 367 | if remove: 368 | for plugin in os.listdir(plugin_path): 369 | if plugin.endswith('.py'): 370 | name = plugin[:-3] 371 | if name == remove: 372 | path = os.path.join(plugin_path, plugin) 373 | os.remove(path) 374 | LOG.info('Removed {}', path) 375 | 376 | 377 | def start(): 378 | plugin_folder = os.path.join(USER_DIRECTORIES.user_data_dir, 'plugins') 379 | if not os.path.exists(plugin_folder): 380 | os.makedirs(plugin_folder) 381 | _PluginLoader(plugin_folder) 382 | main() 383 | 384 | 385 | if __name__ == '__main__': 386 | start() 387 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------