language
stringlengths
0
24
filename
stringlengths
9
214
code
stringlengths
99
9.93M
YAML
hackingtool/.github/workflows/lint_python.yml
name: lint_python on: pull_request: branches: [master] push: branches: [master] jobs: lint_python: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: 3.x - run: pip install --upgrade pip ruff setuptools wheel - name: "Ruff: Show stopper (must-fix) issues" run: ruff . --select=E9,F63,F7,F82,PLE,YTT --show-source . - name: "Ruff: All issues" run: ruff --exit-zero --select=ALL --statistics --target-version=py37 . - name: "Ruff: All fixable (ruff --fix) issues" run: ruff --exit-zero --select=ALL --ignore=ANN204,COM812,ERA001,RSE102 --statistics --target-version=py37 . | grep "\[\*\]" - run: pip install black codespell mypy pytest safety - run: black --check . || true - run: codespell - run: pip install -r requirements.txt || pip install --editable . || pip install . || true - run: mkdir --parents --verbose .mypy_cache - run: mypy --ignore-missing-imports --install-types --non-interactive . || true - run: pytest . || true - run: pytest --doctest-modules . || true - run: safety check
YAML
hackingtool/.github/workflows/test_install.yml
name: test_install on: pull_request: branches: [master] push: branches: [master] jobs: test_install: runs-on: ubuntu-latest env: TERM: "linux" strategy: fail-fast: false matrix: commands: # Enter hackingtool starting from the main menu with \n as the delimiter. - "17\n0\n1\n\n99\n99\n99" # Install, run, update, update system, press ENTER to continue, back to main menu, quit - "17\n0\n2\n\n99\n99\n99" # Install, run, update, update hackingtool, press ENTER to continue, back to main menu, quit - "17\n1\n1\n" # Install, run, uninstall, press ENTER to continue - "99" # Install, run, quit steps: - uses: actions/checkout@v3 - uses: actions/setup-python@v4 with: python-version: 3.x cache: 'pip' - run: pip install --upgrade pip - run: pwd && ls -hal - run: sudo ./install.sh 1 - run: pwd && ls -hal # Typing "1" will allow us to manually enter the filepath to hackingtool. # Provide the filepath ${HOME}/work/hackingtool/hackingtool # Type the matrix.commands. - run: echo -e "1\n${HOME}/work/hackingtool/hackingtool\n${{ matrix.commands }}\n" | hackingtool - run: pwd && ls -hal
Python
hackingtool/tools/anonsurf.py
# coding=utf-8 import os from core import HackingTool from core import HackingToolsCollection class AnonymouslySurf(HackingTool): TITLE = "Anonymously Surf" DESCRIPTION = "It automatically overwrites the RAM when\n" \ "the system is shutting down and also change Ip." INSTALL_COMMANDS = [ "sudo git clone https://github.com/Und3rf10w/kali-anonsurf.git", "cd kali-anonsurf && sudo ./installer.sh && cd .. && sudo rm -r kali-anonsurf" ] RUN_COMMANDS = ["sudo anonsurf start"] PROJECT_URL = "https://github.com/Und3rf10w/kali-anonsurf" def __init__(self): super(AnonymouslySurf, self).__init__([('Stop', self.stop)]) def stop(self): os.system("sudo anonsurf stop") class Multitor(HackingTool): TITLE = "Multitor" DESCRIPTION = "How to stay in multi places at the same time" INSTALL_COMMANDS = [ "sudo git clone https://github.com/trimstray/multitor.git", "cd multitor;sudo bash setup.sh install" ] RUN_COMMANDS = ["multitor --init 2 --user debian-tor --socks-port 9000 --control-port 9900 --proxy privoxy --haproxy"] PROJECT_URL = "https://github.com/trimstray/multitor" def __init__(self): super(Multitor, self).__init__(runnable = False) class AnonSurfTools(HackingToolsCollection): TITLE = "Anonymously Hiding Tools" DESCRIPTION = "" TOOLS = [ AnonymouslySurf(), Multitor() ]
Python
hackingtool/tools/ddos.py
# coding=utf-8 import os import subprocess from core import HackingTool from core import HackingToolsCollection class ddos(HackingTool): TITLE = "ddos" DESCRIPTION = ( "Best DDoS Attack Script With 36 Plus Methods." "DDoS attacks\n\b " "for SECURITY TESTING PURPOSES ONLY! " ) INSTALL_COMMANDS = [ "git clone https://github.com/the-deepnet/ddos.git", "cd ddos;sudo pip3 install -r requirements.txt", ] PROJECT_URL = "https://github.com/the-deepnet/ddos.git" def run(self): method = input("Enter Method >> ") url = input("Enter URL >> ") threads = input("Enter Threads >> ") proxylist = input(" Enter ProxyList >> ") multiple = input(" Enter Multiple >> ") timer = input(" Enter Timer >> ") os.system("cd ddos;") subprocess.run( [ "sudo", "python3 ddos", method, url, "socks_type5.4.1", threads, proxylist, multiple, timer, ] ) class SlowLoris(HackingTool): TITLE = "SlowLoris" DESCRIPTION = ( "Slowloris is basically an HTTP Denial of Service attack." "It send lots of HTTP Request" ) INSTALL_COMMANDS = ["sudo pip3 install slowloris"] def run(self): target_site = input("Enter Target Site:- ") subprocess.run(["slowloris", target_site]) class Asyncrone(HackingTool): TITLE = "Asyncrone | Multifunction SYN Flood DDoS Weapon" DESCRIPTION = ( "aSYNcrone is a C language based, mulltifunction SYN Flood " "DDoS Weapon.\nDisable the destination system by sending a " "SYN packet intensively to the destination." ) INSTALL_COMMANDS = [ "git clone https://github.com/fatih4842/aSYNcrone.git", "cd aSYNcrone;sudo gcc aSYNcrone.c -o aSYNcrone -lpthread", ] PROJECT_URL = "https://github.com/fatihsnsy/aSYNcrone" def run(self): source_port = input("Enter Source Port >> ") target_ip = input("Enter Target IP >> ") target_port = input("Enter Target port >> ") os.system("cd aSYNcrone;") subprocess.run( ["sudo", "./aSYNcrone", source_port, target_ip, target_port, 1000] ) class UFONet(HackingTool): TITLE = "UFOnet" DESCRIPTION = ( "UFONet - is a free software, P2P and cryptographic " "-disruptive \n toolkit- that allows to perform DoS and " "DDoS attacks\n\b " "More Usage Visit" ) INSTALL_COMMANDS = [ "sudo git clone https://github.com/epsylon/ufonet.git", "cd ufonet;sudo python3 setup.py install;sudo pip3 install GeoIP;sudo pip3 install python-geoip;sudo pip3 install pygeoip;sudo pip3 install requests;sudo pip3 install pycrypto;sudo pip3 install pycurl;sudo pip3 install whois;sudo pip3 install scapy-python3", ] RUN_COMMANDS = ["sudo python3 ufonet --gui"] PROJECT_URL = "https://github.com/epsylon/ufonet" class GoldenEye(HackingTool): TITLE = "GoldenEye" DESCRIPTION = ( "GoldenEye is a python3 app for SECURITY TESTING PURPOSES ONLY!\n" "GoldenEye is a HTTP DoS Test Tool." ) INSTALL_COMMANDS = [ "sudo git clone https://github.com/jseidl/GoldenEye.git;" "chmod -R 755 GoldenEye" ] PROJECT_URL = "https://github.com/jseidl/GoldenEye" def run(self): os.system("cd GoldenEye ;sudo ./goldeneye.py") print("\033[96m Go to Directory \n [*] USAGE: ./goldeneye.py <url> [OPTIONS]") class Saphyra(HackingTool): TITLE = "SaphyraDDoS" DESCRIPTION = "A complex python code to DDoS any website with a very easy usage.!\n" INSTALL_COMMANDS = [ "sudo su", "git clone https://github.com/anonymous24x7/Saphyra-DDoS.git", "cd Saphyra-DDoS", "chmod +x saphyra.py", "python saphyra.py", ] PROJECT_URL = "https://github.com/anonymous24x7/Saphyra-DDoS" def run(self): url = input("Enter url>>> ") try: os.system("python saphyra.py " + url) except Exception: print("Enter a valid url.") class DDOSTools(HackingToolsCollection): TITLE = "DDOS Attack Tools" TOOLS = [SlowLoris(), Asyncrone(), UFONet(), GoldenEye(), Saphyra()]
Python
hackingtool/tools/exploit_frameworks.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection from tools.webattack import Web2Attack class RouterSploit(HackingTool): TITLE = "RouterSploit" DESCRIPTION = "The RouterSploit Framework is an open-source exploitation " \ "framework dedicated to embedded devices" INSTALL_COMMANDS = [ "sudo git clone https://github.com/threat9/routersploit.git", "cd routersploit && sudo python3 -m pip install -r requirements.txt" ] RUN_COMMANDS = ["cd routersploit && sudo python3 rsf.py"] PROJECT_URL = "https://github.com/threat9/routersploit" class WebSploit(HackingTool): TITLE = "WebSploit" DESCRIPTION = "Websploit is an advanced MITM framework." INSTALL_COMMANDS = [ "sudo git clone https://github.com/The404Hacking/websploit.git;cd websploit/Setup;sudo chmod +x install.sh && sudo bash install.sh" ] RUN_COMMANDS = ["sudo websploit"] PROJECT_URL = "https://github.com/The404Hacking/websploit " class Commix(HackingTool): TITLE = "Commix" DESCRIPTION = "Automated All-in-One OS command injection and exploitation " \ "tool.\nCommix can be used from web developers, penetration " \ "testers or even security researchers\n in order to test " \ "web-based applications with the view to find bugs,\n " \ "errors or vulnerabilities related to command injection " \ "attacks.\n Usage: python commix.py [option(s)]" INSTALL_COMMANDS = [ "git clone https://github.com/commixproject/commix.git commix", "cd commix;sudo python setup.py install" ] RUN_COMMANDS = ["sudo python commix.py --wizard"] PROJECT_URL = "https://github.com/commixproject/commix" def __init__(self): super(Commix, self).__init__(runnable = False) class ExploitFrameworkTools(HackingToolsCollection): TITLE = "Exploit framework" TOOLS = [ RouterSploit(), WebSploit(), Commix(), Web2Attack() ]
Python
hackingtool/tools/forensic_tools.py
# coding=utf-8 import os from core import HackingTool from core import HackingToolsCollection class Autopsy(HackingTool): TITLE = "Autopsy" DESCRIPTION = "Autopsy is a platform that is used by Cyber Investigators.\n" \ "[!] Works in any OS\n" \ "[!] Recover Deleted Files from any OS & Media \n" \ "[!] Extract Image Metadata" RUN_COMMANDS = ["sudo autopsy"] def __init__(self): super(Autopsy, self).__init__(installable = False) class Wireshark(HackingTool): TITLE = "Wireshark" DESCRIPTION = "Wireshark is a network capture and analyzer \n" \ "tool to see what’s happening in your network.\n " \ "And also investigate Network related incident" RUN_COMMANDS = ["sudo wireshark"] def __init__(self): super(Wireshark, self).__init__(installable = False) class BulkExtractor(HackingTool): TITLE = "Bulk extractor" DESCRIPTION = "Extract useful information without parsing the file system" PROJECT_URL = "https://github.com/simsong/bulk_extractor" def __init__(self): super(BulkExtractor, self).__init__([ ('GUI Mode (Download required)', self.gui_mode), ('CLI Mode', self.cli_mode) ], installable = False, runnable = False) def gui_mode(self): os.system( "sudo git clone https://github.com/simsong/bulk_extractor.git") os.system("ls src/ && cd .. && cd java_gui && ./BEViewer") print( "If you getting error after clone go to /java_gui/src/ And Compile .Jar file && run ./BEViewer") print( "Please Visit For More Details About Installation >> https://github.com/simsong/bulk_extractor") def cli_mode(self): os.system("sudo apt install bulk-extractor") print("bulk_extractor and options") os.system("bulk_extractor -h") os.system( 'echo "bulk_extractor [options] imagefile" | boxes -d headline | lolcat') class Guymager(HackingTool): TITLE = "Disk Clone and ISO Image Acquire" DESCRIPTION = "Guymager is a free forensic imager for media acquisition." INSTALL_COMMANDS = ["sudo apt install guymager"] RUN_COMMANDS = ["sudo guymager"] PROJECT_URL = "https://guymager.sourceforge.io/" class Toolsley(HackingTool): TITLE = "Toolsley" DESCRIPTION = "Toolsley got more than ten useful tools for investigation.\n" \ "[+]File signature verifier\n" \ "[+]File identifier \n" \ "[+]Hash & Validate \n" \ "[+]Binary inspector \n " \ "[+]Encode text \n" \ "[+]Data URI generator \n" \ "[+]Password generator" PROJECT_URL = "https://www.toolsley.com/" def __init__(self): super(Toolsley, self).__init__(installable = False, runnable = False) class ForensicTools(HackingToolsCollection): TITLE = "Forensic tools" TOOLS = [ Autopsy(), Wireshark(), BulkExtractor(), Guymager(), Toolsley() ]
Python
hackingtool/tools/information_gathering_tools.py
# coding=utf-8 import os import socket import subprocess import webbrowser from core import HackingTool from core import HackingToolsCollection from core import clear_screen class NMAP(HackingTool): TITLE = "Network Map (nmap)" DESCRIPTION = "Free and open source utility for network discovery and security auditing" INSTALL_COMMANDS = [ "sudo git clone https://github.com/nmap/nmap.git", "sudo chmod -R 755 nmap && cd nmap && sudo ./configure && make && sudo make install" ] PROJECT_URL = "https://github.com/nmap/nmap" def __init__(self): super(NMAP, self).__init__(runnable = False) class Dracnmap(HackingTool): TITLE = "Dracnmap" DESCRIPTION = "Dracnmap is an open source program which is using to \n" \ "exploit the network and gathering information with nmap help." INSTALL_COMMANDS = [ "sudo git clone https://github.com/Screetsec/Dracnmap.git", "cd Dracnmap && chmod +x dracnmap-v2.2-dracOs.sh dracnmap-v2.2.sh" ] RUN_COMMANDS = ["cd Dracnmap;sudo ./dracnmap-v2.2.sh"] PROJECT_URL = "https://github.com/Screetsec/Dracnmap" # def __init__(self): # super(Dracnmap, self).__init__(runnable = False) class PortScan(HackingTool): TITLE = "Port scanning" def __init__(self): super(PortScan, self).__init__(installable = False) def run(self): clear_screen() target = input('Select a Target IP: ') subprocess.run(["sudo", "nmap", "-O", "-Pn", target]) class Host2IP(HackingTool): TITLE = "Host to IP " def __init__(self): super(Host2IP, self).__init__(installable = False) def run(self): clear_screen() host = input("Enter host name (e.g. www.google.com):- ") ips = socket.gethostbyname(host) print(ips) class XeroSploit(HackingTool): TITLE = "Xerosploit" DESCRIPTION = "Xerosploit is a penetration testing toolkit whose goal is to perform\n" \ "man-in-the-middle attacks for testing purposes" INSTALL_COMMANDS = [ "git clone https://github.com/LionSec/xerosploit.git", "cd xerosploit && sudo python install.py" ] RUN_COMMANDS = ["sudo xerosploit"] PROJECT_URL = "https://github.com/LionSec/xerosploit" class RedHawk(HackingTool): TITLE = "RED HAWK (All In One Scanning)" DESCRIPTION = "All in one tool for Information Gathering and Vulnerability Scanning." INSTALL_COMMANDS = [ "git clone https://github.com/Tuhinshubhra/RED_HAWK.git"] RUN_COMMANDS = ["cd RED_HAWK;php rhawk.php"] PROJECT_URL = "https://github.com/Tuhinshubhra/RED_HAWK" class ReconSpider(HackingTool): TITLE = "ReconSpider(For All Scanning)" DESCRIPTION = "ReconSpider is most Advanced Open Source Intelligence (OSINT)" \ " Framework for scanning IP Address, Emails, \n" \ "Websites, Organizations and find out information from" \ " different sources.\n" INSTALL_COMMANDS = [ "sudo git clone https://github.com/bhavsec/reconspider.git", "sudo apt install python3 python3-pip && cd reconspider && sudo python3 setup.py install" ] RUN_COMMANDS = ["cd reconspider;python3 reconspider.py"] PROJECT_URL = "https://github.com/bhavsec/reconspider" # def __init__(self): # super(ReconSpider, self).__init__(runnable = False) class IsItDown(HackingTool): TITLE = "IsItDown (Check Website Down/Up)" DESCRIPTION = "Check Website Is Online or Not" def __init__(self): super(IsItDown, self).__init__( [('Open', self.open)], installable = False, runnable = False) def open(self): webbrowser.open_new_tab("https://www.isitdownrightnow.com/") class Infoga(HackingTool): TITLE = "Infoga - Email OSINT" DESCRIPTION = "Infoga is a tool gathering email accounts information\n" \ "(ip, hostname, country,...) from different public source" INSTALL_COMMANDS = [ "git clone https://github.com/m4ll0k/Infoga.git", "cd Infoga;sudo python3 setup.py install" ] RUN_COMMANDS = ["cd Infoga;python3 infoga.py"] PROJECT_URL = "https://github.com/m4ll0k/Infoga" class ReconDog(HackingTool): TITLE = "ReconDog" DESCRIPTION = "ReconDog Information Gathering Suite" INSTALL_COMMANDS = ["git clone https://github.com/s0md3v/ReconDog.git"] RUN_COMMANDS = ["cd ReconDog;sudo python dog"] PROJECT_URL = "https://github.com/s0md3v/ReconDog" class Striker(HackingTool): TITLE = "Striker" DESCRIPTION = "Recon & Vulnerability Scanning Suite" INSTALL_COMMANDS = [ "git clone https://github.com/s0md3v/Striker.git", "cd Striker && pip3 install -r requirements.txt" ] PROJECT_URL = "https://github.com/s0md3v/Striker" def run(self): site = input("Enter Site Name (example.com) >> ") os.chdir("Striker") subprocess.run(["sudo", "python3", "striker.py", site]) class SecretFinder(HackingTool): TITLE = "SecretFinder (like API & etc)" DESCRIPTION = "SecretFinder - A python script for find sensitive data \n" \ "like apikeys, accesstoken, authorizations, jwt,..etc \n " \ "and search anything on javascript files.\n\n " \ "Usage: python SecretFinder.py -h" INSTALL_COMMANDS = [ "git clone https://github.com/m4ll0k/SecretFinder.git secretfinder", "cd secretfinder; sudo pip3 install -r requirements.txt" ] PROJECT_URL = "https://github.com/m4ll0k/SecretFinder" def __init__(self): super(SecretFinder, self).__init__(runnable = False) class Shodan(HackingTool): TITLE = "Find Info Using Shodan" DESCRIPTION = "Get ports, vulnerabilities, information, banners,..etc \n " \ "for any IP with Shodan (no apikey! no rate limit!)\n" \ "[X] Don't use this tool because your ip will be blocked by Shodan!" INSTALL_COMMANDS = ["git clone https://github.com/m4ll0k/Shodanfy.py.git"] PROJECT_URL = "https://github.com/m4ll0k/Shodanfy.py" def __init__(self): super(Shodan, self).__init__(runnable = False) class PortScannerRanger(HackingTool): TITLE = "Port Scanner - rang3r" DESCRIPTION = "rang3r is a python script which scans in multi thread\n " \ "all alive hosts within your range that you specify." INSTALL_COMMANDS = [ "git clone https://github.com/floriankunushevci/rang3r.git;" "sudo pip install termcolor"] PROJECT_URL = "https://github.com/floriankunushevci/rang3r" def run(self): ip = input("Enter Ip >> ") os.chdir("rang3r") subprocess.run(["sudo", "python", "rang3r.py", "--ip", ip]) class Breacher(HackingTool): TITLE = "Breacher" DESCRIPTION = "An advanced multithreaded admin panel finder written in python." INSTALL_COMMANDS = ["git clone https://github.com/s0md3v/Breacher.git"] PROJECT_URL = "https://github.com/s0md3v/Breacher" def run(self): domain = input("Enter domain (example.com) >> ") os.chdir("Breacher") subprocess.run(["python3", "breacher.py", "-u", domain]) class InformationGatheringTools(HackingToolsCollection): TITLE = "Information gathering tools" TOOLS = [ NMAP(), Dracnmap(), PortScan(), Host2IP(), XeroSploit(), RedHawk(), ReconSpider(), IsItDown(), Infoga(), ReconDog(), Striker(), SecretFinder(), Shodan(), PortScannerRanger(), Breacher() ]
Python
hackingtool/tools/other_tools.py
# coding=utf-8 import os import subprocess from core import HackingTool from core import HackingToolsCollection from tools.others.android_attack import AndroidAttackTools from tools.others.email_verifier import EmailVerifyTools from tools.others.hash_crack import HashCrackingTools from tools.others.homograph_attacks import IDNHomographAttackTools from tools.others.mix_tools import MixTools from tools.others.payload_injection import PayloadInjectorTools from tools.others.socialmedia import SocialMediaBruteforceTools from tools.others.socialmedia_finder import SocialMediaFinderTools from tools.others.web_crawling import WebCrawlingTools from tools.others.wifi_jamming import WifiJammingTools class HatCloud(HackingTool): TITLE = "HatCloud(Bypass CloudFlare for IP)" DESCRIPTION = "HatCloud build in Ruby. It makes bypass in CloudFlare for " \ "discover real IP." INSTALL_COMMANDS = ["git clone https://github.com/HatBashBR/HatCloud.git"] PROJECT_URL = "https://github.com/HatBashBR/HatCloud" def run(self): site = input("Enter Site >> ") os.chdir("HatCloud") subprocess.run(["sudo", "ruby", "hatcloud.rb", "-b", site]) class OtherTools(HackingToolsCollection): TITLE = "Other tools" TOOLS = [ SocialMediaBruteforceTools(), AndroidAttackTools(), HatCloud(), IDNHomographAttackTools(), EmailVerifyTools(), HashCrackingTools(), WifiJammingTools(), SocialMediaFinderTools(), PayloadInjectorTools(), WebCrawlingTools(), MixTools() ]
Python
hackingtool/tools/payload_creator.py
import os from core import HackingTool from core import HackingToolsCollection class TheFatRat(HackingTool): TITLE = "The FatRat" DESCRIPTION = "TheFatRat Provides An Easy way to create Backdoors and \n" \ "Payload which can bypass most anti-virus" INSTALL_COMMANDS = [ "sudo git clone https://github.com/Screetsec/TheFatRat.git", "cd TheFatRat && sudo chmod +x setup.sh" ] RUN_COMMANDS = ["cd TheFatRat && sudo bash setup.sh"] PROJECT_URL = "https://github.com/Screetsec/TheFatRat" def __init__(self): super(TheFatRat, self).__init__([ ('Update', self.update), ('Troubleshoot', self.troubleshoot) ]) def update(self): os.system( "cd TheFatRat && bash update && chmod +x setup.sh && bash setup.sh") def troubleshoot(self): os.system("cd TheFatRat && sudo chmod +x chk_tools && ./chk_tools") class Brutal(HackingTool): TITLE = "Brutal" DESCRIPTION = "Brutal is a toolkit to quickly create various payload," \ "powershell attack,\nvirus attack and launch listener for " \ "a Human Interface Device" INSTALL_COMMANDS = [ "sudo git clone https://github.com/Screetsec/Brutal.git", "cd Brutal && sudo chmod +x Brutal.sh" ] RUN_COMMANDS = ["cd Brutal && sudo bash Brutal.sh"] PROJECT_URL = "https://github.com/Screetsec/Brutal" def show_info(self): super(Brutal, self).show_info() print(""" [!] Requirement >> Arduino Software (I used v1.6.7) >> TeensyDuino >> Linux udev rules >> Copy and paste the PaensyLib folder inside your Arduino libraries [!] Kindly Visit below link for Installation for Arduino >> https://github.com/Screetsec/Brutal/wiki/Install-Requirements """) class Stitch(HackingTool): TITLE = "Stitch" DESCRIPTION = "Stitch is Cross Platform Python Remote Administrator Tool\n\t" \ "[!] Refer Below Link For Wins & MAc Os" INSTALL_COMMANDS = [ "sudo git clone https://github.com/nathanlopez/Stitch.git", "cd Stitch && sudo pip install -r lnx_requirements.txt" ] RUN_COMMANDS = ["cd Stitch && sudo python main.py"] PROJECT_URL = "https://nathanlopez.github.io/Stitch" class MSFVenom(HackingTool): TITLE = "MSFvenom Payload Creator" DESCRIPTION = "MSFvenom Payload Creator (MSFPC) is a wrapper to generate \n" \ "multiple types of payloads, based on users choice.\n" \ "The idea is to be as simple as possible (only requiring " \ "one input) \nto produce their payload." INSTALL_COMMANDS = [ "sudo git clone https://github.com/g0tmi1k/msfpc.git", "cd msfpc;sudo chmod +x msfpc.sh" ] RUN_COMMANDS = ["cd msfpc;sudo bash msfpc.sh -h -v"] PROJECT_URL = "https://github.com/g0tmi1k/msfpc" class Venom(HackingTool): TITLE = "Venom Shellcode Generator" DESCRIPTION = "venom 1.0.11 (malicious_server) was build to take " \ "advantage of \n apache2 webserver to deliver payloads " \ "(LAN) using a fake webpage written in html" INSTALL_COMMANDS = [ "sudo git clone https://github.com/r00t-3xp10it/venom.git", "sudo chmod -R 775 venom*/ && cd venom*/ && cd aux && sudo bash setup.sh", "sudo ./venom.sh -u" ] RUN_COMMANDS = ["cd venom && sudo ./venom.sh"] PROJECT_URL = "https://github.com/r00t-3xp10it/venom" class Spycam(HackingTool): TITLE = "Spycam" DESCRIPTION = "Script to generate a Win32 payload that takes the webcam " \ "image every 1 minute and send it to the attacker" INSTALL_COMMANDS = [ "sudo git clone https://github.com/indexnotfound404/spycam.git", "cd spycam && bash install.sh && chmod +x spycam" ] RUN_COMMANDS = ["cd spycam && ./spycam"] PROJECT_URL = "https://github.com/indexnotfound404/spycam" class MobDroid(HackingTool): TITLE = "Mob-Droid" DESCRIPTION = "Mob-Droid helps you to generate metasploit payloads in " \ "easy way\n without typing long commands and save your time" INSTALL_COMMANDS = [ "git clone https://github.com/kinghacker0/mob-droid.git"] RUN_COMMANDS = ["cd mob-droid;sudo python mob-droid.py"] PROJECT_URL = "https://github.com/kinghacker0/Mob-Droid" class Enigma(HackingTool): TITLE = "Enigma" DESCRIPTION = "Enigma is a Multiplatform payload dropper" INSTALL_COMMANDS = [ "sudo git clone https://github.com/UndeadSec/Enigma.git"] RUN_COMMANDS = ["cd Enigma;sudo python enigma.py"] PROJECT_URL = "https://github.com/UndeadSec/Enigma" class PayloadCreatorTools(HackingToolsCollection): TITLE = "Payload creation tools" TOOLS = [ TheFatRat(), Brutal(), Stitch(), MSFVenom(), Venom(), Spycam(), MobDroid(), Enigma() ]
Python
hackingtool/tools/phising_attack.py
# coding=utf-8 import os from core import HackingTool from core import HackingToolsCollection class autophisher(HackingTool): TITLE = "Autophisher RK" DESCRIPTION = "Automated Phishing Toolkit" INSTALL_COMMANDS = [ "sudo git clone https://github.com/CodingRanjith/autophisher.git", "cd autophisher" ] RUN_COMMANDS = ["cd autophisher;sudo bash autophisher.sh"] PROJECT_URL = "https://github.com/CodingRanjith/autophisher" class Pyphisher(HackingTool): TITLE = "Pyphisher" DESCRIPTION = "Easy to use phishing tool with 77 website templates" INSTALL_COMMANDS = [ "sudo git clone https://github.com/KasRoudra/PyPhisher", "cd PyPhisher/files", "pip3 install -r requirements.txt" ] RUN_COMMANDS = ["cd PyPhisher;sudo python3 pyphisher.py"] PROJECT_URL = "git clone https://github.com/KasRoudra/PyPhisher" class AdvPhishing(HackingTool): TITLE = "AdvPhishing" DESCRIPTION = "This is Advance Phishing Tool ! OTP PHISHING" INSTALL_COMMANDS = [ "sudo git clone https://github.com/Ignitetch/AdvPhishing.git", "cd AdvPhishing;chmod 777 *;bash Linux-Setup.sh"] RUN_COMMANDS = ["cd AdvPhishing && sudo bash AdvPhishing.sh"] PROJECT_URL = "https://github.com/Ignitetch/AdvPhishing" class Setoolkit(HackingTool): TITLE = "Setoolkit" DESCRIPTION = "The Social-Engineer Toolkit is an open-source penetration\n" \ "testing framework designed for social engine" INSTALL_COMMANDS = [ "git clone https://github.com/trustedsec/social-engineer-toolkit/", "cd social-engineer-toolkit && sudo python3 setup.py" ] RUN_COMMANDS = ["sudo setoolkit"] PROJECT_URL = "https://github.com/trustedsec/social-engineer-toolkit" class SocialFish(HackingTool): TITLE = "SocialFish" DESCRIPTION = "Automated Phishing Tool & Information Collector NOTE: username is 'root' and password is 'pass'" INSTALL_COMMANDS = [ "sudo git clone https://github.com/UndeadSec/SocialFish.git && sudo apt-get install python3 python3-pip python3-dev -y", "cd SocialFish && sudo python3 -m pip install -r requirements.txt" ] RUN_COMMANDS = ["cd SocialFish && sudo python3 SocialFish.py root pass"] PROJECT_URL = "https://github.com/UndeadSec/SocialFish" class HiddenEye(HackingTool): TITLE = "HiddenEye" DESCRIPTION = "Modern Phishing Tool With Advanced Functionality And " \ "Multiple Tunnelling Services \n" \ "\t [!]https://github.com/DarkSecDevelopers/HiddenEye" INSTALL_COMMANDS = [ "sudo git clone https://github.com/Morsmalleo/HiddenEye.git ;sudo chmod 777 HiddenEye", "cd HiddenEye;sudo pip3 install -r requirements.txt;sudo pip3 install requests;pip3 install pyngrok" ] RUN_COMMANDS = ["cd HiddenEye;sudo python3 HiddenEye.py"] PROJECT_URL = "https://github.com/Morsmalleo/HiddenEye.git" class Evilginx2(HackingTool): TITLE = "Evilginx2" DESCRIPTION = "evilginx2 is a man-in-the-middle attack framework used " \ "for phishing login credentials along with session cookies,\n" \ "which in turn allows to bypass 2-factor authentication protection.\n\n\t " \ "[+]Make sure you have installed GO of version at least 1.14.0 \n" \ "[+]After installation, add this to your ~/.profile, assuming that you installed GO in /usr/local/go\n\t " \ "[+]export GOPATH=$HOME/go \n " \ "[+]export PATH=$PATH:/usr/local/go/bin:$GOPATH/bin \n" \ "[+]Then load it with source ~/.profiles." INSTALL_COMMANDS = [ "sudo apt-get install git make;go get -u github.com/kgretzky/evilginx2", "cd $GOPATH/src/github.com/kgretzky/evilginx2;make", "sudo make install;sudo evilginx" ] RUN_COMMANDS = ["sudo evilginx"] PROJECT_URL = "https://github.com/kgretzky/evilginx2" class ISeeYou(HackingTool): TITLE = "I-See_You" DESCRIPTION = "[!] ISeeYou is a tool to find Exact Location of Victom By" \ " User SocialEngineering or Phishing Engagement..\n" \ "[!] Users can expose their local servers to the Internet " \ "and decode the location coordinates by looking at the log file" INSTALL_COMMANDS = [ "sudo git clone https://github.com/Viralmaniar/I-See-You.git", "cd I-See-You && sudo chmod u+x ISeeYou.sh" ] RUN_COMMANDS = ["cd I-See-You && sudo bash ISeeYou.sh"] PROJECT_URL = "https://github.com/Viralmaniar/I-See-You" class SayCheese(HackingTool): TITLE = "SayCheese" DESCRIPTION = "Take webcam shots from target just sending a malicious link" INSTALL_COMMANDS = ["sudo git clone https://github.com/hangetzzu/saycheese"] RUN_COMMANDS = ["cd saycheese && sudo bash saycheese.sh"] PROJECT_URL = "https://github.com/hangetzzu/saycheese" class QRJacking(HackingTool): TITLE = "QR Code Jacking" DESCRIPTION = "QR Code Jacking (Any Website)" INSTALL_COMMANDS = [ "sudo git clone https://github.com/cryptedwolf/ohmyqr.git && sudo apt -y install scrot"] RUN_COMMANDS = ["cd ohmyqr && sudo bash ohmyqr.sh"] PROJECT_URL = "https://github.com/cryptedwolf/ohmyqr" class WifiPhisher(HackingTool): TITLE = "WifiPhisher" DESCRIPTION = "The Rogue Access Point Framework" INSTALL_COMMANDS = [ "sudo git clone https://github.com/wifiphisher/wifiphisher.git", "cd wifiphisher"] RUN_COMMANDS = ["cd wifiphisher && sudo python setup.py"] PROJECT_URL = "https://github.com/wifiphisher/wifiphisher" class BlackEye(HackingTool): TITLE = "BlackEye" DESCRIPTION = "The ultimate phishing tool with 38 websites available!" INSTALL_COMMANDS = [ "sudo git clone https://github.com/thelinuxchoice/blackeye", "cd blackeye "] RUN_COMMANDS = ["cd blackeye && sudo bash blackeye.sh"] PROJECT_URL = "https://github.com/An0nUD4Y/blackeye" class ShellPhish(HackingTool): TITLE = "ShellPhish" DESCRIPTION = "Phishing Tool for 18 social media" INSTALL_COMMANDS = ["git clone https://github.com/An0nUD4Y/shellphish.git"] RUN_COMMANDS = ["cd shellphish;sudo bash shellphish.sh"] PROJECT_URL = "https://github.com/An0nUD4Y/shellphish" class Thanos(HackingTool): TITLE = "Thanos" DESCRIPTION = "Browser to Browser Phishingtoolkit" INSTALL_COMMANDS = [ "sudo git clone https://github.com/TridevReddy/Thanos.git", "cd Thanos && sudo chmod -R 777 Thanos.sh" ] RUN_COMMANDS = ["cd Thanos;sudo bash Thanos.sh"] PROJECT_URL = "https://github.com/TridevReddy/Thanos" class QRLJacking(HackingTool): TITLE = "QRLJacking" DESCRIPTION = "QRLJacking" INSTALL_COMMANDS = [ "git clone https://github.com/OWASP/QRLJacking.git", "cd QRLJacking", "git clone https://github.com/mozilla/geckodriver.git", "chmod +x geckodriver", "sudo mv -f geckodriver /usr/local/share/geckodriver", "sudo ln -s /usr/local/share/geckodriver /usr/local/bin/geckodriver", "sudo ln -s /usr/local/share/geckodriver /usr/bin/geckodriver", "cd QRLJacker;pip3 install -r requirements.txt" ] RUN_COMMANDS = ["cd QRLJacking/QRLJacker;python3 QrlJacker.py"] PROJECT_URL = "https://github.com/OWASP/QRLJacking" class Maskphish(HackingTool): TITLE = "Miskphish" DESCRIPTION = "Hide phishing URL under a normal looking URL (google.com or facebook.com)" INSTALL_COMMANDS = [ "sudo git clone https://github.com/jaykali/maskphish.git", "cd maskphish"] RUN_COMMANDS = ["cd maskphish;sudo bash maskphish.sh"] PROJECT_URL = "https://github.com/jaykali/maskphish" class BlackPhish(HackingTool): TITLE = "BlackPhish" INSTALL_COMMANDS = [ "sudo git clone https://github.com/iinc0gnit0/BlackPhish.git", "cd BlackPhish;sudo bash install.sh" ] RUN_COMMANDS = ["cd BlackPhish;sudo python3 blackphish.py"] PROJECT_URL = "https://github.com/iinc0gnit0/BlackPhish" def __init__(self): super(BlackPhish, self).__init__([('Update', self.update)]) def update(self): os.system("cd BlackPhish;sudo bash update.sh") class dnstwist(HackingTool): Title='dnstwist' Install_commands=['sudo git clone https://github.com/elceef/dnstwist.git','cd dnstwist'] Run_commands=['cd dnstwist;sudo python3 dnstwist.py'] project_url='https://github.com/elceef/dnstwist' class PhishingAttackTools(HackingToolsCollection): TITLE = "Phishing attack tools" TOOLS = [ autophisher(), Pyphisher(), AdvPhishing(), Setoolkit(), SocialFish(), HiddenEye(), Evilginx2(), ISeeYou(), SayCheese(), QRJacking(), BlackEye(), ShellPhish(), Thanos(), QRLJacking(), BlackPhish(), Maskphish(), dnstwist() ]
Python
hackingtool/tools/post_exploitation.py
# coding=utf-8 import os from core import HackingTool from core import HackingToolsCollection class Vegile(HackingTool): TITLE = "Vegile - Ghost In The Shell" DESCRIPTION = "This tool will set up your backdoor/rootkits when " \ "backdoor is already setup it will be \n" \ "hidden your specific process,unlimited your session in " \ "metasploit and transparent." INSTALL_COMMANDS = [ "sudo git clone https://github.com/Screetsec/Vegile.git", "cd Vegile && sudo chmod +x Vegile" ] RUN_COMMANDS = ["cd Vegile && sudo bash Vegile"] PROJECT_URL = "https://github.com/Screetsec/Vegile" def before_run(self): os.system('echo "You can Use Command: \n' '[!] Vegile -i / --inject [backdoor/rootkit] \n' '[!] Vegile -u / --unlimited [backdoor/rootkit] \n' '[!] Vegile -h / --help"|boxes -d parchment') class ChromeKeyLogger(HackingTool): TITLE = "Chrome Keylogger" DESCRIPTION = "Hera Chrome Keylogger" INSTALL_COMMANDS = [ "sudo git clone https://github.com/UndeadSec/HeraKeylogger.git", "cd HeraKeylogger && sudo apt-get install python3-pip -y && sudo pip3 install -r requirements.txt" ] RUN_COMMANDS = ["cd HeraKeylogger && sudo python3 hera.py"] PROJECT_URL = "https://github.com/UndeadSec/HeraKeylogger" class PostExploitationTools(HackingToolsCollection): TITLE = "Post exploitation tools" TOOLS = [ Vegile(), ChromeKeyLogger() ]
Python
hackingtool/tools/remote_administration.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class Stitch(HackingTool): TITLE = "Stitch" DESCRIPTION = "Stitch is a cross platform python framework.\n" \ "which allows you to build custom payloads\n" \ "For Windows, Mac and Linux." INSTALL_COMMANDS = [ "sudo git clone https://github.com/nathanlopez/Stitch.git", "cd Stitch;sudo pip install -r lnx_requirements.txt" ] RUN_COMMANDS = ["cd Stitch;python main.py"] PROJECT_URL = "https://github.com/nathanlopez/Stitch" class Pyshell(HackingTool): TITLE = "Pyshell" DESCRIPTION = "Pyshell is a Rat Tool that can be able to download & upload " \ "files,\n Execute OS Command and more.." INSTALL_COMMANDS = [ "sudo git clone https://github.com/knassar702/Pyshell.git;" "sudo pip install pyscreenshot python-nmap requests" ] RUN_COMMANDS = ["cd Pyshell;./Pyshell"] PROJECT_URL = "https://github.com/knassar702/pyshell" class RemoteAdministrationTools(HackingToolsCollection): TITLE = "Remote Administrator Tools (RAT)" TOOLS = [ Stitch(), Pyshell() ]
Python
hackingtool/tools/reverse_engineering.py
# coding=utf-8 import subprocess from core import HackingTool from core import HackingToolsCollection class AndroGuard(HackingTool): TITLE = "Androguard" DESCRIPTION = "Androguard is a Reverse engineering, Malware and goodware " \ "analysis of Android applications and more" INSTALL_COMMANDS = ["sudo pip3 install -U androguard"] PROJECT_URL = "https://github.com/androguard/androguard " def __init__(self): super(AndroGuard, self).__init__(runnable = False) class Apk2Gold(HackingTool): TITLE = "Apk2Gold" DESCRIPTION = "Apk2Gold is a CLI tool for decompiling Android apps to Java" INSTALL_COMMANDS = [ "sudo git clone https://github.com/lxdvs/apk2gold.git", "cd apk2gold;sudo bash make.sh" ] PROJECT_URL = "https://github.com/lxdvs/apk2gold " def run(self): uinput = input("Enter (.apk) File >> ") subprocess.run(["sudo", "apk2gold", uinput]) class Jadx(HackingTool): TITLE = "JadX" DESCRIPTION = "Jadx is Dex to Java decompiler.\n" \ "[*] decompile Dalvik bytecode to java classes from APK, dex," \ " aar and zip files\n" \ "[*] decode AndroidManifest.xml and other resources from " \ "resources.arsc" INSTALL_COMMANDS = [ "sudo git clone https://github.com/skylot/jadx.git", "cd jadx;./gradlew dist" ] PROJECT_URL = "https://github.com/skylot/jadx" def __init__(self): super(Jadx, self).__init__(runnable = False) class ReverseEngineeringTools(HackingToolsCollection): TITLE = "Reverse engineering tools" TOOLS = [ AndroGuard(), Apk2Gold(), Jadx() ]
Python
hackingtool/tools/sql_tools.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class Sqlmap(HackingTool): TITLE = "Sqlmap tool" DESCRIPTION = "sqlmap is an open source penetration testing tool that " \ "automates the process of \n" \ "detecting and exploiting SQL injection flaws and taking " \ "over of database servers \n " \ "[!] python3 sqlmap.py -u [<http://example.com>] --batch --banner \n " \ "More Usage [!] https://github.com/sqlmapproject/sqlmap/wiki/Usage" INSTALL_COMMANDS = [ "sudo git clone --depth 1 https://github.com/sqlmapproject/sqlmap.git sqlmap-dev"] RUN_COMMANDS = ["cd sqlmap-dev;python3 sqlmap.py --wizard"] PROJECT_URL = "https://github.com/sqlmapproject/sqlmap" class NoSqlMap(HackingTool): TITLE = "NoSqlMap" DESCRIPTION = "NoSQLMap is an open source Python tool designed to \n " \ "audit for as well as automate injection attacks and exploit.\n " \ "\033[91m " \ "[*] Please Install MongoDB \n " INSTALL_COMMANDS = [ "git clone https://github.com/codingo/NoSQLMap.git", "sudo chmod -R 755 NoSQLMap;cd NoSQLMap;python setup.py install" ] RUN_COMMANDS = ["python NoSQLMap"] PROJECT_URL = "https://github.com/codingo/NoSQLMap" class SQLiScanner(HackingTool): TITLE = "Damn Small SQLi Scanner" DESCRIPTION = "Damn Small SQLi Scanner (DSSS) is a fully functional SQL " \ "injection\nvulnerability scanner also supporting GET and " \ "POST parameters.\n" \ "[*]python3 dsss.py -h[help] | -u[URL]" INSTALL_COMMANDS = ["git clone https://github.com/stamparm/DSSS.git"] PROJECT_URL = "https://github.com/stamparm/DSSS" def __init__(self): super(SQLiScanner, self).__init__(runnable = False) class Explo(HackingTool): TITLE = "Explo" DESCRIPTION = "Explo is a simple tool to describe web security issues " \ "in a human and machine readable format.\n " \ "Usage:- \n " \ "[1] explo [--verbose|-v] testcase.yaml \n " \ "[2] explo [--verbose|-v] examples/*.yaml" INSTALL_COMMANDS = [ "git clone https://github.com/dtag-dev-sec/explo.git", "cd explo;sudo python setup.py install" ] PROJECT_URL = "https://github.com/dtag-dev-sec/explo" def __init__(self): super(Explo, self).__init__(runnable = False) class Blisqy(HackingTool): TITLE = "Blisqy - Exploit Time-based blind-SQL injection" DESCRIPTION = "Blisqy is a tool to aid Web Security researchers to find " \ "Time-based Blind SQL injection \n on HTTP Headers and also " \ "exploitation of the same vulnerability.\n " \ "For Usage >> \n" INSTALL_COMMANDS = ["git clone https://github.com/JohnTroony/Blisqy.git"] PROJECT_URL = "https://github.com/JohnTroony/Blisqy" def __init__(self): super(Blisqy, self).__init__(runnable = False) class Leviathan(HackingTool): TITLE = "Leviathan - Wide Range Mass Audit Toolkit" DESCRIPTION = "Leviathan is a mass audit toolkit which has wide range " \ "service discovery,\nbrute force, SQL injection detection " \ "and running custom exploit capabilities. \n " \ "[*] It Requires API Keys \n " \ "More Usage [!] https://github.com/utkusen/leviathan/wiki" INSTALL_COMMANDS = [ "git clone https://github.com/leviathan-framework/leviathan.git", "cd leviathan;sudo pip install -r requirements.txt" ] RUN_COMMANDS = ["cd leviathan;python leviathan.py"] PROJECT_URL = "https://github.com/leviathan-framework/leviathan" class SQLScan(HackingTool): TITLE = "SQLScan" DESCRIPTION = "sqlscan is quick web scanner for find an sql inject point." \ " not for educational, this is for hacking." INSTALL_COMMANDS = [ "sudo apt install php php-bz2 php-curl php-mbstring curl", "sudo curl https://raw.githubusercontent.com/Cvar1984/sqlscan/dev/build/main.phar --output /usr/local/bin/sqlscan", "chmod +x /usr/local/bin/sqlscan" ] RUN_COMMANDS = ["sudo sqlscan"] PROJECT_URL = "https://github.com/Cvar1984/sqlscan" class SqlInjectionTools(HackingToolsCollection): TITLE = "SQL Injection Tools" TOOLS = [ Sqlmap(), NoSqlMap(), SQLiScanner(), Explo(), Blisqy(), Leviathan(), SQLScan() ]
Python
hackingtool/tools/steganography.py
# coding=utf-8 import subprocess from core import HackingTool from core import HackingToolsCollection from core import validate_input class SteganoHide(HackingTool): TITLE = "SteganoHide" INSTALL_COMMANDS = ["sudo apt-get install steghide -y"] def run(self): choice_run = input( "[1] Hide\n" "[2] Extract\n" "[99]Cancel\n" ">> ") choice_run = validate_input(choice_run, [1, 2, 99]) if choice_run is None: print("Please choose a valid input") return self.run() if choice_run == 99: return if choice_run == 1: file_hide = input("Enter Filename you want to Embed (1.txt) >> ") file_to_be_hide = input("Enter Cover Filename(test.jpeg) >> ") subprocess.run( ["steghide", "embed", "-cf", file_to_be_hide, "-ef", file_hide]) elif choice_run == "2": from_file = input("Enter Filename From Extract Data >> ") subprocess.run(["steghide", "extract", "-sf", from_file]) class StegnoCracker(HackingTool): TITLE = "StegnoCracker" DESCRIPTION = "SteganoCracker is a tool that uncover hidden data inside " \ "files\n using brute-force utility" INSTALL_COMMANDS = [ "pip3 install stegcracker && pip3 install stegcracker -U --force-reinstall"] def run(self): filename = input("Enter Filename:- ") passfile = input("Enter Wordlist Filename:- ") subprocess.run(["stegcracker", filename, passfile]) class StegoCracker(HackingTool): TITLE = "StegoCracker" DESCRIPTION = "StegoCracker is a tool that let's you hide data into image or audio files and can retrieve from a file " INSTALL_COMMANDS = [ "sudo git clone https://github.com/W1LDN16H7/StegoCracker.git", "sudo chmod -R 755 StegoCracker" ] RUN_COMMANDS = ["cd StegoCracker && python3 -m pip install -r requirements.txt ", "./install.sh" ] PROJECT_URL = "https://github.com/W1LDN16H7/StegoCracker" class Whitespace(HackingTool): TITLE = "Whitespace" DESCRIPTION = "Use whitespace and unicode chars for steganography" INSTALL_COMMANDS = [ "sudo git clone https://github.com/beardog108/snow10.git", "sudo chmod -R 755 snow10" ] RUN_COMMANDS = ["cd snow10 && ./install.sh"] PROJECT_URL = "https://github.com/beardog108/snow10" class SteganographyTools(HackingToolsCollection): TITLE = "Steganograhy tools" TOOLS = [ SteganoHide(), StegnoCracker(), StegoCracker(), Whitespace() ]
Python
hackingtool/tools/tool_manager.py
# coding=utf-8 import os import sys from time import sleep from core import HackingTool from core import HackingToolsCollection class UpdateTool(HackingTool): TITLE = "Update Tool or System" DESCRIPTION = "Update Tool or System" def __init__(self): super(UpdateTool, self).__init__([ ("Update System", self.update_sys), ("Update Hackingtool", self.update_ht) ], installable = False, runnable = False) def update_sys(self): os.system("sudo apt update && sudo apt full-upgrade -y") os.system( "sudo apt-get install tor openssl curl && sudo apt-get update tor openssl curl") os.system("sudo apt-get install python3-pip") def update_ht(self): os.system("sudo chmod +x /etc/;" "sudo chmod +x /usr/share/doc;" "sudo rm -rf /usr/share/doc/hackingtool/;" "cd /etc/;" "sudo rm -rf /etc/hackingtool/;" "mkdir hackingtool;" "cd hackingtool;" "git clone https://github.com/Z4nzu/hackingtool.git;" "cd hackingtool;" "sudo chmod +x install.sh;" "./install.sh") class UninstallTool(HackingTool): TITLE = "Uninstall HackingTool" DESCRIPTION = "Uninstall HackingTool" def __init__(self): super(UninstallTool, self).__init__([ ('Uninstall', self.uninstall) ], installable = False, runnable = False) def uninstall(self): print("hackingtool started to uninstall..\n") sleep(1) os.system("sudo chmod +x /etc/;" "sudo chmod +x /usr/share/doc;" "sudo rm -rf /usr/share/doc/hackingtool/;" "cd /etc/;" "sudo rm -rf /etc/hackingtool/;") print("\nHackingtool Successfully Uninstalled... Goodbye.") sys.exit() class ToolManager(HackingToolsCollection): TITLE = "Update or Uninstall | Hackingtool" TOOLS = [ UpdateTool(), UninstallTool() ]
Python
hackingtool/tools/webattack.py
# coding=utf-8 import subprocess from core import HackingTool from core import HackingToolsCollection class Web2Attack(HackingTool): TITLE = "Web2Attack" DESCRIPTION = "Web hacking framework with tools, exploits by python" INSTALL_COMMANDS = [ "sudo git clone https://github.com/santatic/web2attack.git"] RUN_COMMANDS = ["cd web2attack && sudo python3 w2aconsole"] PROJECT_URL = "https://github.com/santatic/web2attack" class Skipfish(HackingTool): TITLE = "Skipfish" DESCRIPTION = "Skipfish – Fully automated, active web application " \ "security reconnaissance tool \n " \ "Usage: skipfish -o [FolderName] targetip/site" RUN_COMMANDS = [ "sudo skipfish -h", 'echo "skipfish -o [FolderName] targetip/site"|boxes -d headline | lolcat' ] def __init__(self): super(Skipfish, self).__init__(installable = False) class SubDomainFinder(HackingTool): TITLE = "SubDomain Finder" DESCRIPTION = "Sublist3r is a python tool designed to enumerate " \ "subdomains of websites using OSINT \n " \ "Usage:\n\t" \ "[1] python3 sublist3r.py -d example.com \n" \ "[2] python3 sublist3r.py -d example.com -p 80,443" INSTALL_COMMANDS = [ "sudo pip3 install requests argparse dnspython", "sudo git clone https://github.com/aboul3la/Sublist3r.git", "cd Sublist3r && sudo pip3 install -r requirements.txt" ] RUN_COMMANDS = ["cd Sublist3r && python3 sublist3r.py -h"] PROJECT_URL = "https://github.com/aboul3la/Sublist3r" class CheckURL(HackingTool): TITLE = "CheckURL" DESCRIPTION = "Detect evil urls that uses IDN Homograph Attack.\n\t" \ "[!] python3 checkURL.py --url google.com" INSTALL_COMMANDS = [ "sudo git clone https://github.com/UndeadSec/checkURL.git"] RUN_COMMANDS = ["cd checkURL && python3 checkURL.py --help"] PROJECT_URL = "https://github.com/UndeadSec/checkURL" class Blazy(HackingTool): TITLE = "Blazy(Also Find ClickJacking)" DESCRIPTION = "Blazy is a modern login page bruteforcer" INSTALL_COMMANDS = [ "sudo git clone https://github.com/UltimateHackers/Blazy.git", "cd Blazy && sudo pip2.7 install -r requirements.txt" ] RUN_COMMANDS = ["cd Blazy && sudo python2.7 blazy.py"] PROJECT_URL = "https://github.com/UltimateHackers/Blazy" class SubDomainTakeOver(HackingTool): TITLE = "Sub-Domain TakeOver" DESCRIPTION = "Sub-domain takeover vulnerability occur when a sub-domain " \ "\n (subdomain.example.com) is pointing to a service " \ "(e.g: GitHub, AWS/S3,..)\n" \ "that has been removed or deleted.\n" \ "Usage:python3 takeover.py -d www.domain.com -v" INSTALL_COMMANDS = [ "git clone https://github.com/m4ll0k/takeover.git", "cd takeover;sudo python3 setup.py install" ] PROJECT_URL = "https://github.com/m4ll0k/takeover" def __init__(self): super(SubDomainTakeOver, self).__init__(runnable = False) class Dirb(HackingTool): TITLE = "Dirb" DESCRIPTION = "DIRB is a Web Content Scanner. It looks for existing " \ "(and/or hidden) Web Objects.\n" \ "It basically works by launching a dictionary based " \ "attack against \n a web server and analyzing the response." INSTALL_COMMANDS = [ "sudo git clone https://gitlab.com/kalilinux/packages/dirb.git", "cd dirb;sudo bash configure;make" ] PROJECT_URL = "https://gitlab.com/kalilinux/packages/dirb" def run(self): uinput = input("Enter Url >> ") subprocess.run(["sudo", "dirb", uinput]) class WebAttackTools(HackingToolsCollection): TITLE = "Web Attack tools" DESCRIPTION = "" TOOLS = [ Web2Attack(), Skipfish(), SubDomainFinder(), CheckURL(), Blazy(), SubDomainTakeOver(), Dirb() ]
Python
hackingtool/tools/wireless_attack_tools.py
# coding=utf-8 import os from core import HackingTool from core import HackingToolsCollection class WIFIPumpkin(HackingTool): TITLE = "WiFi-Pumpkin" DESCRIPTION = "The WiFi-Pumpkin is a rogue AP framework to easily create " \ "these fake networks\n" \ "all while forwarding legitimate traffic to and from the " \ "unsuspecting target." INSTALL_COMMANDS = [ "sudo apt install libssl-dev libffi-dev build-essential", "sudo git clone https://github.com/P0cL4bs/wifipumpkin3.git", "chmod -R 755 wifipumpkin3", "sudo apt install python3-pyqt5", "cd wifipumpkin3;sudo python3 setup.py install" ] RUN_COMMANDS = ["sudo wifipumpkin3"] PROJECT_URL = "https://github.com/P0cL4bs/wifipumpkin3" class pixiewps(HackingTool): TITLE = "pixiewps" DESCRIPTION = "Pixiewps is a tool written in C used to bruteforce offline " \ "the WPS pin\n " \ "exploiting the low or non-existing entropy of some Access " \ "Points, the so-called pixie dust attack" INSTALL_COMMANDS = [ "sudo git clone https://github.com/wiire/pixiewps.git && apt-get -y install build-essential", "cd pixiewps*/ && make", "cd pixiewps*/ && sudo make install && wget https://pastebin.com/y9Dk1Wjh" ] PROJECT_URL = "https://github.com/wiire/pixiewps" def run(self): os.system( 'echo "' '1.> Put your interface into monitor mode using ' '\'airmon-ng start {wireless interface}\n' '2.> wash -i {monitor-interface like mon0}\'\n' '3.> reaver -i {monitor interface} -b {BSSID of router} -c {router channel} -vvv -K 1 -f"' '| boxes -d boy') print("You Have To Run Manually By USing >>pixiewps -h ") class BluePot(HackingTool): TITLE = "Bluetooth Honeypot GUI Framework" DESCRIPTION = "You need to have at least 1 bluetooth receiver " \ "(if you have many it will work with those, too).\n" \ "You must install/libbluetooth-dev on " \ "Ubuntu/bluez-libs-devel on Fedora/bluez-devel on openSUSE" INSTALL_COMMANDS = [ "sudo wget https://raw.githubusercontent.com/andrewmichaelsmith/bluepot/master/bin/bluepot-0.2.tar.gz" "sudo tar xfz bluepot-0.2.tar.gz;sudo rm bluepot-0.2.tar.gz" ] RUN_COMMANDS = ["cd bluepot && sudo java -jar bluepot.jar"] PROJECT_URL = "https://github.com/andrewmichaelsmith/bluepot" class Fluxion(HackingTool): TITLE = "Fluxion" DESCRIPTION = "Fluxion is a remake of linset by vk496 with enhanced functionality." INSTALL_COMMANDS = [ "git clone https://github.com/FluxionNetwork/fluxion.git", "cd fluxion && sudo chmod +x fluxion.sh", ] RUN_COMMANDS = ["cd fluxion;sudo bash fluxion.sh -i"] PROJECT_URL = "https://github.com/FluxionNetwork/fluxion" class Wifiphisher(HackingTool): TITLE = "Wifiphisher" DESCRIPTION = """ Wifiphisher is a rogue Access Point framework for conducting red team engagements or Wi-Fi security testing. Using Wifiphisher, penetration testers can easily achieve a man-in-the-middle position against wireless clients by performing targeted Wi-Fi association attacks. Wifiphisher can be further used to mount victim-customized web phishing attacks against the connected clients in order to capture credentials (e.g. from third party login pages or WPA/WPA2 Pre-Shared Keys) or infect the victim stations with malware..\n For More Details Visit >> https://github.com/wifiphisher/wifiphisher """ INSTALL_COMMANDS = [ "git clone https://github.com/wifiphisher/wifiphisher.git", "cd wifiphisher;sudo python3 setup.py install" ] RUN_COMMANDS = ["cd wifiphisher;sudo wifiphisher"] PROJECT_URL = "https://github.com/wifiphisher/wifiphisher" class Wifite(HackingTool): TITLE = "Wifite" DESCRIPTION = "Wifite is an automated wireless attack tool" INSTALL_COMMANDS = [ "sudo git clone https://github.com/derv82/wifite2.git", "cd wifite2 && sudo python3 setup.py install" ] RUN_COMMANDS = ["cd wifite2; sudo wifite"] PROJECT_URL = "https://github.com/derv82/wifite2" class EvilTwin(HackingTool): TITLE = "EvilTwin" DESCRIPTION = "Fakeap is a script to perform Evil Twin Attack, by getting" \ " credentials using a Fake page and Fake Access Point" INSTALL_COMMANDS = ["sudo git clone https://github.com/Z4nzu/fakeap.git"] RUN_COMMANDS = ["cd fakeap && sudo bash fakeap.sh"] PROJECT_URL = "https://github.com/Z4nzu/fakeap" class Fastssh(HackingTool): TITLE = "Fastssh" DESCRIPTION = "Fastssh is an Shell Script to perform multi-threaded scan" \ " \n and brute force attack against SSH protocol using the " \ "most commonly credentials." INSTALL_COMMANDS = [ "sudo git clone https://github.com/Z4nzu/fastssh.git && cd fastssh && sudo chmod +x fastssh.sh", "sudo apt-get install -y sshpass netcat" ] RUN_COMMANDS = ["cd fastssh && sudo bash fastssh.sh --scan"] PROJECT_URL = "https://github.com/Z4nzu/fastssh" class Howmanypeople(HackingTool): TITLE = "Howmanypeople" DESCRIPTION = "Count the number of people around you by monitoring wifi " \ "signals.\n" \ "[@] WIFI ADAPTER REQUIRED* \n[*]" \ "It may be illegal to monitor networks for MAC addresses, \n" \ "especially on networks that you do not own. " \ "Please check your country's laws" INSTALL_COMMANDS = [ "sudo apt-get install tshark" ";sudo python3 -m pip install howmanypeoplearearound" ] RUN_COMMANDS = ["howmanypeoplearearound"] class WirelessAttackTools(HackingToolsCollection): TITLE = "Wireless attack tools" DESCRIPTION = "" TOOLS = [ WIFIPumpkin(), pixiewps(), BluePot(), Fluxion(), Wifiphisher(), Wifite(), EvilTwin(), Fastssh(), Howmanypeople() ]
Python
hackingtool/tools/wordlist_generator.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class Cupp(HackingTool): TITLE = "Cupp" DESCRIPTION = "WlCreator is a C program that can create all possibilities of passwords,\n " \ "and you can choose Length, Lowercase, Capital, Numbers and Special Chars" INSTALL_COMMANDS = ["git clone https://github.com/Mebus/cupp.git"] RUN_COMMANDS = ["cd cupp && python3 cupp.py -i"] PROJECT_URL = "https://github.com/Mebus/cupp" class WlCreator(HackingTool): TITLE = "WordlistCreator" DESCRIPTION = "WlCreator is a C program that can create all possibilities" \ " of passwords,\n and you can choose Length, Lowercase, " \ "Capital, Numbers and Special Chars" INSTALL_COMMANDS = ["sudo git clone https://github.com/Z4nzu/wlcreator.git"] RUN_COMMANDS = [ "cd wlcreator && sudo gcc -o wlcreator wlcreator.c && ./wlcreator 5"] PROJECT_URL = "https://github.com/Z4nzu/wlcreator" class GoblinWordGenerator(HackingTool): TITLE = "Goblin WordGenerator" DESCRIPTION = "Goblin WordGenerator" INSTALL_COMMANDS = [ "sudo git clone https://github.com/UndeadSec/GoblinWordGenerator.git"] RUN_COMMANDS = ["cd GoblinWordGenerator && python3 goblin.py"] PROJECT_URL = "https://github.com/UndeadSec/GoblinWordGenerator.git" class showme(HackingTool): TITLE = "Password list (1.4 Billion Clear Text Password)" DESCRIPTION = "This tool allows you to perform OSINT and reconnaissance on " \ "an organisation or an individual. It allows one to search " \ "1.4 Billion clear text credentials which was dumped as " \ "part of BreachCompilation leak. This database makes " \ "finding passwords faster and easier than ever before." INSTALL_COMMANDS = [ "sudo git clone https://github.com/Viralmaniar/SMWYG-Show-Me-What-You-Got.git", "cd SMWYG-Show-Me-What-You-Got && pip3 install -r requirements.txt" ] RUN_COMMANDS = ["cd SMWYG-Show-Me-What-You-Got && python SMWYG.py"] PROJECT_URL = "https://github.com/Viralmaniar/SMWYG-Show-Me-What-You-Got" class WordlistGeneratorTools(HackingToolsCollection): TITLE = "Wordlist Generator" TOOLS = [ Cupp(), WlCreator(), GoblinWordGenerator(), showme() ]
Python
hackingtool/tools/xss_attack.py
# coding=utf-8 import os import subprocess from core import HackingTool from core import HackingToolsCollection class Dalfox(HackingTool): TITLE = "DalFox(Finder of XSS)" DESCRIPTION = "XSS Scanning and Parameter Analysis tool." INSTALL_COMMANDS = [ "sudo apt-get install golang", "sudo git clone https://github.com/hahwul/dalfox", "cd dalfox;go install" ] RUN_COMMANDS = [ "~/go/bin/dalfox", 'echo "You Need To Run manually by using [!]~/go/bin/dalfox [options]"' ] PROJECT_URL = "https://github.com/hahwul/dalfox" class XSSPayloadGenerator(HackingTool): TITLE = "XSS Payload Generator" DESCRIPTION = "XSS PAYLOAD GENERATOR -XSS SCANNER-XSS DORK FINDER" INSTALL_COMMANDS = [ "git clone https://github.com/capture0x/XSS-LOADER.git", "cd XSS-LOADER;sudo pip3 install -r requirements.txt" ] RUN_COMMANDS = ["cd XSS-LOADER;sudo python3 payloader.py"] PROJECT_URL = "https://github.com/capture0x/XSS-LOADER.git" class XSSFinder(HackingTool): TITLE = "Extended XSS Searcher and Finder" DESCRIPTION = "Extended XSS Searcher and Finder" INSTALL_COMMANDS = [ "git clone https://github.com/Damian89/extended-xss-search.git"] PROJECT_URL = "https://github.com/Damian89/extended-xss-search" def after_install(self): print("""\033[96m Follow This Steps After Installation:- \033[31m [*] Go To extended-xss-search directory, and Rename the example.app-settings.conf to app-settings.conf """) input("Press ENTER to continue") def run(self): print("""\033[96m You have To Add Links to scan \033[31m[!] Go to extended-xss-search [*] config/urls-to-test.txt [!] python3 extended-xss-search.py """) class XSSFreak(HackingTool): TITLE = "XSS-Freak" DESCRIPTION = "XSS-Freak is an XSS scanner fully written in python3 from scratch" INSTALL_COMMANDS = [ "git clone https://github.com/PR0PH3CY33/XSS-Freak.git", "cd XSS-Freak;sudo pip3 install -r requirements.txt" ] RUN_COMMANDS = ["cd XSS-Freak;sudo python3 XSS-Freak.py"] PROJECT_URL = "https://github.com/PR0PH3CY33/XSS-Freak" class XSpear(HackingTool): TITLE = "XSpear" DESCRIPTION = "XSpear is XSS Scanner on ruby gems" INSTALL_COMMANDS = ["gem install XSpear"] RUN_COMMANDS = ["XSpear -h"] PROJECT_URL = "https://github.com/hahwul/XSpear" class XSSCon(HackingTool): TITLE = "XSSCon" INSTALL_COMMANDS = [ "git clone https://github.com/menkrep1337/XSSCon.git", "sudo chmod 755 -R XSSCon" ] PROJECT_URL = "https://github.com/menkrep1337/XSSCon" def run(self): website = input("Enter Website >> ") os.system("cd XSSCon;") subprocess.run(["python3", "xsscon.py", "-u", website]) class XanXSS(HackingTool): TITLE = "XanXSS" DESCRIPTION = "XanXSS is a reflected XSS searching tool\n " \ "that creates payloads based from templates" INSTALL_COMMANDS = ["git clone https://github.com/Ekultek/XanXSS.git"] PROJECT_URL = "https://github.com/Ekultek/XanXSS" def run(self): os.system("cd XanXSS ;python xanxss.py -h") print("\033[96m You Have to run it manually By Using\n" " [!]python xanxss.py [Options]") class XSSStrike(HackingTool): TITLE = "Advanced XSS Detection Suite" DESCRIPTION = "XSStrike is a python script designed to detect and exploit XSS vulnerabilities." INSTALL_COMMANDS = [ "sudo rm -rf XSStrike", "git clone https://github.com/UltimateHackers/XSStrike.git " "&& cd XSStrike && pip install -r requirements.txt" ] PROJECT_URL = "https://github.com/UltimateHackers/XSStrike" def __init__(self): super(XSSStrike, self).__init__(runnable = False) class RVuln(HackingTool): TITLE = "RVuln" DESCRIPTION = "RVuln is multi-threaded and Automated Web Vulnerability " \ "Scanner written in Rust" INSTALL_COMMANDS = [ "sudo git clone https://github.com/iinc0gnit0/RVuln.git;" "curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh;" "source $HOME/.cargo/env;" "sudo apt install librust-openssl-dev;" "cd RVuln;sudo su;cargo build --release;mv target/release/RVuln" ] RUN_COMMANDS = ["RVuln"] PROJECT_URL = "https://github.com/iinc0gnit0/RVuln" class XSSAttackTools(HackingToolsCollection): TITLE = "XSS Attack Tools" TOOLS = [ Dalfox(), XSSPayloadGenerator(), XSSFinder(), XSSFreak(), XSpear(), XSSCon(), XanXSS(), XSSStrike(), RVuln() ]
Python
hackingtool/tools/others/android_attack.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class Keydroid(HackingTool): TITLE = "Keydroid" DESCRIPTION = "Android Keylogger + Reverse Shell\n" \ "[!] You have to install Some Manually Refer Below Link:\n " \ "[+] https://github.com/F4dl0/keydroid" INSTALL_COMMANDS = ["sudo git clone https://github.com/F4dl0/keydroid.git"] RUN_COMMANDS = ["cd keydroid && bash keydroid.sh"] PROJECT_URL = "https://github.com/F4dl0/keydroid" class MySMS(HackingTool): TITLE = "MySMS" DESCRIPTION = "Script that generates an Android App to hack SMS through WAN \n" \ "[!] You have to install Some Manually Refer Below Link:\n\t " \ "[+] https://github.com/papusingh2sms/mysms" INSTALL_COMMANDS = [ "sudo git clone https://github.com/papusingh2sms/mysms.git"] RUN_COMMANDS = ["cd mysms && bash mysms.sh"] PROJECT_URL = "https://github.com/papusingh2sms/mysms" class LockPhish(HackingTool): TITLE = "Lockphish (Grab target LOCK PIN)" DESCRIPTION = "Lockphish it's the first tool for phishing attacks on the " \ "lock screen, designed to\n Grab Windows credentials,Android" \ " PIN and iPhone Passcode using a https link." INSTALL_COMMANDS = [ "sudo git clone https://github.com/JasonJerry/lockphish.git"] RUN_COMMANDS = ["cd lockphish && bash lockphish.sh"] PROJECT_URL = "https://github.com/JasonJerry/lockphish" class Droidcam(HackingTool): TITLE = "DroidCam (Capture Image)" DESCRIPTION = "Powerful Tool For Grab Front Camera Snap Using A Link" INSTALL_COMMANDS = [ "sudo git clone https://github.com/kinghacker0/WishFish.git;" "sudo apt install php wget openssh-client" ] RUN_COMMANDS = ["cd WishFish && sudo bash wishfish.sh"] PROJECT_URL = "https://github.com/kinghacker0/WishFish" class EvilApp(HackingTool): TITLE = "EvilApp (Hijack Session)" DESCRIPTION = "EvilApp is a script to generate Android App that can " \ "hijack authenticated sessions in cookies." INSTALL_COMMANDS = [ "sudo git clone https://github.com/crypticterminal/EvilApp.git"] RUN_COMMANDS = ["cd EvilApp && bash evilapp.sh"] PROJECT_URL = "https://github.com/crypticterminal/EvilApp" class AndroidAttackTools(HackingToolsCollection): TITLE = "Android Hacking tools" TOOLS = [ Keydroid(), MySMS(), LockPhish(), Droidcam(), EvilApp() ]
Python
hackingtool/tools/others/email_verifier.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class KnockMail(HackingTool): TITLE = "Knockmail" DESCRIPTION = "KnockMail Tool Verify If Email Exists" INSTALL_COMMANDS = [ "git clone https://github.com/heywoodlh/KnockMail.git", "cd KnockMail;sudo pip3 install -r requirements.txt" ] RUN_COMMANDS = ["cd KnockMail;python3 knockmail.py"] PROJECT_URL = "https://github.com/heywoodlh/KnockMail" class EmailVerifyTools(HackingToolsCollection): TITLE = "Email Verify tools" TOOLS = [KnockMail()]
Python
hackingtool/tools/others/hash_crack.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class HashBuster(HackingTool): TITLE = "Hash Buster" DESCRIPTION = "Features: \n " \ "Automatic hash type identification \n " \ "Supports MD5, SHA1, SHA256, SHA384, SHA512" INSTALL_COMMANDS = [ "git clone https://github.com/s0md3v/Hash-Buster.git", "cd Hash-Buster;make install" ] RUN_COMMANDS = ["buster -h"] PROJECT_URL = "https://github.com/s0md3v/Hash-Buster" class HashCrackingTools(HackingToolsCollection): TITLE = "Hash cracking tools" TOOLS = [HashBuster()]
Python
hackingtool/tools/others/homograph_attacks.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class EvilURL(HackingTool): TITLE = "EvilURL" DESCRIPTION = "Generate unicode evil domains for IDN Homograph Attack " \ "and detect them." INSTALL_COMMANDS = ["git clone https://github.com/UndeadSec/EvilURL.git"] RUN_COMMANDS = ["cd EvilURL;python3 evilurl.py"] PROJECT_URL = "https://github.com/UndeadSec/EvilURL" class IDNHomographAttackTools(HackingToolsCollection): TITLE = "IDN Homograph Attack" TOOLS = [EvilURL()]
Python
hackingtool/tools/others/mix_tools.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class TerminalMultiplexer(HackingTool): TITLE = "Terminal Multiplexer" DESCRIPTION = "Terminal Multiplexer is a tiling terminal emulator that " \ "allows us to open \n several terminal sessions inside one " \ "single window." INSTALL_COMMANDS = ["sudo apt-get install tilix"] def __init__(self): super(TerminalMultiplexer, self).__init__(runnable = False) class MixTools(HackingToolsCollection): TITLE = "Mix tools" TOOLS = [TerminalMultiplexer()]
Python
hackingtool/tools/others/payload_injection.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class DebInject(HackingTool): TITLE = "Debinject" DESCRIPTION = "Debinject is a tool that inject malicious code into *.debs" INSTALL_COMMANDS = [ "sudo git clone https://github.com/UndeadSec/Debinject.git"] RUN_COMMANDS = ["cd Debinject;python debinject.py"] PROJECT_URL = "https://github.com/UndeadSec/Debinject" class Pixload(HackingTool): TITLE = "Pixload" DESCRIPTION = "Pixload -- Image Payload Creating tools \n " \ "Pixload is Set of tools for creating/injecting payload into images." INSTALL_COMMANDS = [ "sudo apt install libgd-perl libimage-exiftool-perl libstring-crc32-perl", "sudo git clone https://github.com/chinarulezzz/pixload.git" ] PROJECT_URL = "https://github.com/chinarulezzz/pixload" def __init__(self): # super(Pixload, self).__init__([ # ('How To Use', self.show_project_page) # ], runnable = False) super(Pixload, self).__init__(runnable = False) class PayloadInjectorTools(HackingToolsCollection): TITLE = "Payload Injector" TOOLS = [ DebInject(), Pixload() ]
Python
hackingtool/tools/others/socialmedia.py
# coding=utf-8 import contextlib import os import subprocess from core import HackingTool from core import HackingToolsCollection class InstaBrute(HackingTool): TITLE = "Instagram Attack" DESCRIPTION = "Brute force attack against Instagram" INSTALL_COMMANDS = [ "sudo git clone https://github.com/chinoogawa/instaBrute.git", "cd instaBrute;sudo pip2.7 install -r requirements.txt" ] PROJECT_URL = "https://github.com/chinoogawa/instaBrute" def run(self): name = input("Enter Username >> ") wordlist = input("Enter wordword list >> ") os.chdir("instaBrute") subprocess.run( ["sudo", "python", "instaBrute.py", "-u", f"{name}", "-d", f"{wordlist}"]) class BruteForce(HackingTool): TITLE = "AllinOne SocialMedia Attack" DESCRIPTION = "Brute_Force_Attack Gmail Hotmail Twitter Facebook Netflix \n" \ "[!] python3 Brute_Force.py -g <[email protected]> -l <File_list>" INSTALL_COMMANDS = [ "sudo git clone https://github.com/Matrix07ksa/Brute_Force.git", "cd Brute_Force;sudo pip3 install proxylist;pip3 install mechanize" ] RUN_COMMANDS = ["cd Brute_Force;python3 Brute_Force.py -h"] PROJECT_URL = "https://github.com/Matrix07ksa/Brute_Force" class Faceshell(HackingTool): TITLE = "Facebook Attack" DESCRIPTION = "Facebook BruteForcer" INSTALL_COMMANDS = [ "sudo git clone https://github.com/Matrix07ksa/Brute_Force.git", "cd Brute_Force;sudo pip3 install proxylist;pip3 install mechanize" ] PROJECT_URL = "https://github.com/Matrix07ksa/Brute_Force" def run(self): name = input("Enter Username >> ") wordlist = input("Enter Wordlist >> ") # Ignore a FileNotFoundError if we are already in the Brute_Force directory with contextlib.suppress(FileNotFoundError): os.chdir("Brute_Force") subprocess.run( ["python3", "Brute_Force.py", "-f", f"{name}", "-l", f"{wordlist}"]) class AppCheck(HackingTool): TITLE = "Application Checker" DESCRIPTION = "Tool to check if an app is installed on the target device through a link." INSTALL_COMMANDS = [ "sudo git clone https://github.com/jakuta-tech/underhanded.git", "cd underhanded && sudo chmod +x underhanded.sh" ] RUN_COMMANDS = ["cd underhanded;sudo bash underhanded.sh"] PROJECT_URL = "https://github.com/jakuta-tech/underhanded" class SocialMediaBruteforceTools(HackingToolsCollection): TITLE = "SocialMedia Bruteforce" TOOLS = [ InstaBrute(), BruteForce(), Faceshell(), AppCheck() ]
Python
hackingtool/tools/others/socialmedia_finder.py
# coding=utf-8 import os import subprocess from core import HackingTool from core import HackingToolsCollection class FacialFind(HackingTool): TITLE = "Find SocialMedia By Facial Recognation System" DESCRIPTION = "A Social Media Mapping Tool that correlates profiles\n " \ "via facial recognition across different sites." INSTALL_COMMANDS = [ "sudo apt install -y software-properties-common", "sudo add-apt-repository ppa:mozillateam/firefox-next && sudo apt update && sudo apt upgrade", "sudo git clone https://github.com/Greenwolf/social_mapper.git", "sudo apt install -y build-essential cmake libgtk-3-dev libboost-all-dev", "cd social_mapper/setup", "sudo python3 -m pip install --no-cache-dir -r requirements.txt", 'echo "[!]Now You have To do some Manually\n' '[!] Install the Geckodriver for your operating system\n' '[!] Copy & Paste Link And Download File As System Configuration\n' '[#] https://github.com/mozilla/geckodriver/releases\n' '[!!] On Linux you can place it in /usr/bin "| boxes | lolcat' ] PROJECT_URL = "https://github.com/Greenwolf/social_mapper" def run(self): os.system("cd social_mapper/setup") os.system("sudo python social_mapper.py -h") print("""\033[95m You have to set Username and password of your AC Or Any Fack Account [#] Type in Terminal nano social_mapper.py """) os.system( 'echo "python social_mapper.py -f [<imageFoldername>] -i [<imgFolderPath>] -m fast [<AcName>] -fb -tw"| boxes | lolcat') class FindUser(HackingTool): TITLE = "Find SocialMedia By UserName" DESCRIPTION = "Find usernames across over 75 social networks" INSTALL_COMMANDS = [ "sudo git clone https://github.com/xHak9x/finduser.git", "cd finduser && sudo chmod +x finduser.sh" ] RUN_COMMANDS = ["cd finduser && sudo bash finduser.sh"] PROJECT_URL = "https://github.com/xHak9x/finduser" class Sherlock(HackingTool): TITLE = "Sherlock" DESCRIPTION = "Hunt down social media accounts by username across social networks \n " \ "For More Usage \n" \ "\t >>python3 sherlock --help" INSTALL_COMMANDS = [ "git clone https://github.com/sherlock-project/sherlock.git", "cd sherlock;sudo python3 -m pip install -r requirements.txt" ] PROJECT_URL = "https://github.com/sherlock-project/sherlock" def run(self): name = input("Enter Username >> ") os.chdir('sherlock') subprocess.run(["sudo", "python3", "sherlock", f"{name}"]) class SocialScan(HackingTool): TITLE = "SocialScan | Username or Email" DESCRIPTION = "Check email address and username availability on online " \ "platforms with 100% accuracy" INSTALL_COMMANDS = ["sudo pip install socialscan"] PROJECT_URL = "https://github.com/iojw/socialscan" def run(self): name = input( "Enter Username or Emailid (if both then please space between email & username) >> ") subprocess.run(["sudo", "socialscan", f"{name}"]) class SocialMediaFinderTools(HackingToolsCollection): TITLE = "SocialMedia Finder" TOOLS = [ FacialFind(), FindUser(), Sherlock(), SocialScan() ]
Python
hackingtool/tools/others/web_crawling.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class GoSpider(HackingTool): TITLE = "Gospider" DESCRIPTION = "Gospider - Fast web spider written in Go" INSTALL_COMMANDS = ["sudo go get -u github.com/jaeles-project/gospider"] PROJECT_URL = "https://github.com/jaeles-project/gospider" def __init__(self): super(GoSpider, self).__init__(runnable = False) class WebCrawlingTools(HackingToolsCollection): TITLE = "Web crawling" TOOLS = [GoSpider()]
Python
hackingtool/tools/others/wifi_jamming.py
# coding=utf-8 from core import HackingTool from core import HackingToolsCollection class WifiJammerNG(HackingTool): TITLE = "WifiJammer-NG" DESCRIPTION = "Continuously jam all wifi clients and access points within range." INSTALL_COMMANDS = [ "sudo git clone https://github.com/MisterBianco/wifijammer-ng.git", "cd wifijammer-ng;sudo pip install -r requirements.txt" ] RUN_COMMANDS = [ 'echo "python wifijammer.py [-a AP MAC] [-c CHANNEL] [-d] [-i INTERFACE] [-m MAXIMUM] [-k] [-p PACKETS] [-s SKIP] [-t TIME INTERVAL] [-D]"| boxes | lolcat', "cd wifijammer-ng;sudo python wifijammer.py" ] PROJECT_URL = "https://github.com/MisterBianco/wifijammer-ng" class KawaiiDeauther(HackingTool): TITLE = "KawaiiDeauther" DESCRIPTION = "Kawaii Deauther is a pentest toolkit whose goal is to perform \n " \ "jam on WiFi clients/routers and spam many fake AP for testing purposes." INSTALL_COMMANDS = [ "sudo git clone https://github.com/aryanrtm/KawaiiDeauther.git", "cd KawaiiDeauther;sudo bash install.sh" ] RUN_COMMANDS = ["cd KawaiiDeauther;sudo bash KawaiiDeauther.sh"] PROJECT_URL = "https://github.com/aryanrtm/KawaiiDeauther" class WifiJammingTools(HackingToolsCollection): TITLE = "Wifi Deauthenticate" TOOLS = [ WifiJammerNG(), KawaiiDeauther() ]
Apktool/.editorconfig
root = true [*] charset = utf-8 indent_size = 4 indent_style = space insert_final_newline = true trim_trailing_whitespace = true [*.java] ij_java_use_single_class_imports = true [*.yml] indent_size = 2
Apktool/.gitattributes
* text=auto eol=lf *.bat text eol=crlf *.jar binary /brut.apktool/apktool-lib/src/main/resources/prebuilt/windows/* binary /brut.apktool/apktool-lib/src/main/resources/prebuilt/macosx/* binary /brut.apktool/apktool-lib/src/main/resources/prebuilt/linux/* binary
Apktool/.gitignore
# Gradle .gradle/ bin/ gradle.properties # Build **/build/ # Eclipse **/nbproject/private/ *.project *.classpath *.settings *.setting # Tmp Files *.kate-swp *~ *.DS_Store # IntelliJ *.iml .idea/* **/out/ # Patches *.patch
YAML
Apktool/.jitpack.yml
jdk: - openjdk9 install: - echo "This is not supported. See iBotPeaches/Apktool#2102" - ./gradlew invalid-command-to-crash-out
Apktool/build.gradle.kts
import java.io.ByteArrayOutputStream val baksmaliVersion by extra("3.0.3") val commonsCliVersion by extra("1.5.0") val commonsIoVersion by extra("2.13.0") val commonsLangVersion by extra("3.13.0") val commonsTextVersion by extra("1.10.0") val guavaVersion by extra("32.0.1-jre") val junitVersion by extra("4.13.2") val smaliVersion by extra("3.0.3") val xmlpullVersion by extra("1.1.4c") val xmlunitVersion by extra("2.9.1") val version = "2.8.2" val suffix = "SNAPSHOT" // Strings embedded into the build. var gitRevision by extra("") var apktoolVersion by extra("") defaultTasks("build", "shadowJar", "proguard") // Functions val gitDescribe: String? by lazy { val stdout = ByteArrayOutputStream() try { rootProject.exec { commandLine("git", "describe", "--tags") standardOutput = stdout } stdout.toString().trim().replace("-g", "-") } catch (e: Exception) { null } } val gitBranch: String? by lazy { val stdout = ByteArrayOutputStream() try { rootProject.exec { commandLine("git", "rev-parse", "--abbrev-ref", "HEAD") standardOutput = stdout } stdout.toString().trim() } catch (e: Exception) { null } } if ("release" !in gradle.startParameter.taskNames) { val hash = this.gitDescribe if (hash == null) { gitRevision = "dirty" apktoolVersion = "$version-dirty" project.logger.lifecycle("Building SNAPSHOT (no .git folder found)") } else { gitRevision = hash apktoolVersion = "$hash-SNAPSHOT" project.logger.lifecycle("Building SNAPSHOT ($gitBranch): $gitRevision") } } else { gitRevision = "" apktoolVersion = if (suffix.isNotEmpty()) "$version-$suffix" else version; project.logger.lifecycle("Building RELEASE ($gitBranch): $apktoolVersion") } plugins { id("com.github.johnrengelman.shadow") version "8.1.1" `java-library` `maven-publish` signing } java { sourceCompatibility = JavaVersion.VERSION_1_8 targetCompatibility = JavaVersion.VERSION_1_8 } tasks.withType<JavaCompile> { options.compilerArgs.add("-Xlint:-options") options.compilerArgs.add("--release 8") options.encoding = "UTF-8" } allprojects { repositories { mavenCentral() google() } } subprojects { apply(plugin = "java") apply(plugin = "java-library") val mavenProjects = arrayOf("apktool-lib", "apktool-cli", "brut.j.common", "brut.j.util", "brut.j.dir") if (project.name in mavenProjects) { apply(plugin = "maven-publish") apply(plugin = "signing") java { withJavadocJar() withSourcesJar() } publishing { repositories { maven { url = if (suffix.contains("SNAPSHOT")) { uri("https://s01.oss.sonatype.org/content/repositories/snapshots/") } else { uri("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") } credentials { username = (project.properties["ossrhUsername"] ?: "").toString() password = (project.properties["ossrhPassword"] ?: "").toString() } } } publications { register("mavenJava", MavenPublication::class) { from(components["java"]) groupId = "org.apktool" artifactId = project.name version = apktoolVersion pom { name = "Apktool" description = "A tool for reverse engineering Android apk files." url = "https://apktool.org" licenses { license { name = "The Apache License 2.0" url = "https://opensource.org/licenses/Apache-2.0" } } developers { developer { id = "iBotPeaches" name = "Connor Tumbleson" email = "[email protected]" } developer { id = "brutall" name = "Ryszard WiÅ›niewski" email = "[email protected]" } } scm { connection = "scm:git:git://github.com/iBotPeaches/Apktool.git" developerConnection = "scm:git:[email protected]:iBotPeaches/Apktool.git" url = "https://github.com/iBotPeaches/Apktool" } } } } } tasks.withType<Javadoc>() { (options as StandardJavadocDocletOptions).addStringOption("Xdoclint:none", "-quiet") } signing { sign(publishing.publications["mavenJava"]) } } } // Used for official releases. task("release") { dependsOn("build") finalizedBy("publish") }
Markdown
Apktool/CONTRIBUTORS.md
# Apktool Contributors This product includes software developed by: * Connor Tumbleson ([email protected]) * Ryszard WiÅ›niewski ([email protected]) * Google (https://github.com/google/smali) * JesusFreke (https://github.com/JesusFreke/smali) * Dmitry Skiba (https://code.google.com/p/android4me/) * Tahseen Ur Rehman (https://code.google.com/p/radixtree/) * Android Open Source Project (https://source.android.com/) * The Apache Software Foundation (https://www.apache.org/)
Apktool/gradlew
#!/bin/sh # # Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ############################################################################## # # Gradle start up script for POSIX generated by Gradle. # # Important for running: # # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is # noncompliant, but you have some other compliant shell such as ksh or # bash, then to run this script, type that shell name before the whole # command line, like: # # ksh Gradle # # Busybox and similar reduced shells will NOT work, because this script # requires all of these POSIX shell features: # * functions; # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», # «${var#prefix}», «${var%suffix}», and «$( cmd )»; # * compound commands having a testable exit status, especially «case»; # * various built-in commands including «command», «set», and «ulimit». # # Important for patching: # # (2) This script targets any POSIX shell, so it avoids extensions provided # by Bash, Ksh, etc; in particular arrays are avoided. # # The "traditional" practice of packing multiple parameters into a # space-separated string is a well documented source of bugs and security # problems, so this is (mostly) avoided, by progressively accumulating # options in "$@", and eventually passing that to Java. # # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; # see the in-line comments for details. # # There are tweaks for specific operating systems such as AIX, CygWin, # Darwin, MinGW, and NonStop. # # (3) This script is generated from the Groovy template # https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt # within the Gradle project. # # You can find Gradle at https://github.com/gradle/gradle/. # ############################################################################## # Attempt to set APP_HOME # Resolve links: $0 may be a link app_path=$0 # Need this for daisy-chained symlinks. while APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path [ -h "$app_path" ] do ls=$( ls -ld "$app_path" ) link=${ls#*' -> '} case $link in #( /*) app_path=$link ;; #( *) app_path=$APP_HOME$link ;; esac done # This is normally unused # shellcheck disable=SC2034 APP_BASE_NAME=${0##*/} # Discard cd standard output in case $CDPATH is set (https://github.com/gradle/gradle/issues/25036) APP_HOME=$( cd "${APP_HOME:-./}" > /dev/null && pwd -P ) || exit # Use the maximum available, or set MAX_FD != -1 to use that value. MAX_FD=maximum warn () { echo "$*" } >&2 die () { echo echo "$*" echo exit 1 } >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false case "$( uname )" in #( CYGWIN* ) cygwin=true ;; #( Darwin* ) darwin=true ;; #( MSYS* | MINGW* ) msys=true ;; #( NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar # Determine the Java command to use to start the JVM. if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables JAVACMD=$JAVA_HOME/jre/sh/java else JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else JAVACMD=java if ! command -v java >/dev/null 2>&1 then die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi fi # Increase the maximum file descriptors if we can. if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then case $MAX_FD in #( max*) # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC3045 MAX_FD=$( ulimit -H -n ) || warn "Could not query maximum file descriptor limit" esac case $MAX_FD in #( '' | soft) :;; #( *) # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. # shellcheck disable=SC3045 ulimit -n "$MAX_FD" || warn "Could not set maximum file descriptor limit to $MAX_FD" esac fi # Collect all arguments for the java command, stacking in reverse order: # * args from the command line # * the main class name # * -classpath # * -D...appname settings # * --module-path (only if needed) # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java if "$cygwin" || "$msys" ; then APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) JAVACMD=$( cygpath --unix "$JAVACMD" ) # Now convert the arguments - kludge to limit ourselves to /bin/sh for arg do if case $arg in #( -*) false ;; # don't mess with options #( /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath [ -e "$t" ] ;; #( *) false ;; esac then arg=$( cygpath --path --ignore --mixed "$arg" ) fi # Roll the args list around exactly as many times as the number of # args, so each arg winds up back in the position where it started, but # possibly modified. # # NB: a `for` loop captures its iteration list before it begins, so # changing the positional parameters here affects neither the number of # iterations, nor the values presented in `arg`. shift # remove old arg set -- "$@" "$arg" # push replacement arg done fi # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' # Collect all arguments for the java command; # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of # shell script including quotes and variable substitutions, so put them in # double quotes to make sure that they get re-expanded; and # * put everything else in single quotes, so that it's not re-expanded. set -- \ "-Dorg.gradle.appname=$APP_BASE_NAME" \ -classpath "$CLASSPATH" \ org.gradle.wrapper.GradleWrapperMain \ "$@" # Stop when "xargs" is not available. if ! command -v xargs >/dev/null 2>&1 then die "xargs is not available" fi # Use "xargs" to parse quoted args. # # With -n1 it outputs one arg per line, with the quotes and backslashes removed. # # In Bash we could simply go: # # readarray ARGS < <( xargs -n1 <<<"$var" ) && # set -- "${ARGS[@]}" "$@" # # but POSIX shell has neither arrays nor command substitution, so instead we # post-process each arg (as a line of input to sed) to backslash-escape any # character that might be a shell metacharacter, then use eval to reverse # that process (while maintaining the separation between arguments), and wrap # the whole thing up as a single "set" statement. # # This will of course break if any of these variables contains a newline or # an unmatched quote. # eval "set -- $( printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | xargs -n1 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | tr '\n' ' ' )" '"$@"' exec "$JAVACMD" "$@"
Apktool/gradlew.bat
@rem @rem Copyright 2015 the original author or authors. @rem @rem Licensed under the Apache License, Version 2.0 (the "License"); @rem you may not use this file except in compliance with the License. @rem You may obtain a copy of the License at @rem @rem https://www.apache.org/licenses/LICENSE-2.0 @rem @rem Unless required by applicable law or agreed to in writing, software @rem distributed under the License is distributed on an "AS IS" BASIS, @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @rem See the License for the specific language governing permissions and @rem limitations under the License. @rem @if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @rem @rem ########################################################################## @rem Set local scope for the variables with windows NT shell if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 if "%DIRNAME%"=="" set DIRNAME=. @rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @rem Resolve any "." and ".." in APP_HOME to make it shorter. for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" @rem Find java.exe if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :findJavaFromJavaHome set JAVA_HOME=%JAVA_HOME:"=% set JAVA_EXE=%JAVA_HOME%/bin/java.exe if exist "%JAVA_EXE%" goto execute echo. echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% echo. echo Please set the JAVA_HOME variable in your environment to match the echo location of your Java installation. goto fail :execute @rem Setup the command line set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar @rem Execute Gradle "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* :end @rem End local scope for the variables with windows NT shell if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! set EXIT_CODE=%ERRORLEVEL% if %EXIT_CODE% equ 0 set EXIT_CODE=1 if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal :omega
Markdown
Apktool/INTERNAL.md
# Releasing a new version. The steps taken for slicing an official release of Apktool. ### Ensuring proper license headers _Currently broken after movement to kotlin dsl._ ### Tagging the release. Inside `build.gradle` there are two lines. apktoolversion_major apktoolversion_minor The major variable should be left unchanged. If done correctly, it will already be the version you are about to release. In this case `2.2.2`. The minor variable should read `SNAPSHOT` as the `2.2.2` release up until this point was `SNAPSHOT` releases (Unofficial). We need to remove the `SNAPSHOT` portion and leave the minor version blank. An example can be found [here](https://github.com/iBotPeaches/Apktool/commit/96b70d0be7513c5a1e5d3a3b9a75e4e2b076ad79). After we remove `SNAPSHOT` we need to make the version commit. Organization and following patterns is crucial here. This commit should have 1 change only - the change above. Now commit this change with the commit message - `version bump (x.x.x)`. At this point we now have the commit of the release, but we need to tag it using the following message. git tag -a vx.x.x -m "changed version to vx.x.x" For example for the `2.2.1` release. git tag -a v2.2.1 -m "changed version to v2.2.1" ### Prepare for publishing. New to Apktool is publishing releases to Maven, so plugin authors can directly integrate. You need a `gradle.properties` file in root with the structure: ``` signing.keyId={gpgKeyId} signing.password={gpgPassphrase} signing.secretKeyRingFile={gpgSecretKingRingLocation} ossrhUsername={sonatypeUsername} ossrhPassword={sonatypePassword} ``` Release with maven with `./gradlew build shadowJar release publish`. ### Building the binary. In order to maintain a clean slate. Run `gradlew clean` to start from a clean slate. Now lets build the new binary version. We should not have any new commits since the tagged commit. ./gradlew build shadowJar proguard release The build should tell you what version you are building and it should match the commits you made previously. ➜ Apktool git:(master) ./gradlew build shadowJar proguard release Building RELEASE (master): 2.2.2 ### Testing the binary. Now the release binary is built in the same location as all other builds. Run this version against some of the fixed bugs in this release. This is a simple test to ensure the build had no errors. Copy the jar to any location to prep for uploading. The pattern we name the jars is apktool_x.x.x.jar Or in the case of the last release - `apktool_2.2.1.jar` Once you have the jar in this form. Record the md5 hash & sha256 hash of it. This can be done using `md5sum` and `sha256sum` on unix systems. This can be shown for the `2.2.2` release like so ➜ Desktop md5sum apktool_2.2.2.jar 1e6be08d3f9bb4b442bb85cf4e21f1c1 apktool_2.2.2.jar ➜ Desktop sha256sum apktool-2.2.2.jar 1f1f186edcc09b8677bc1037f3f812dff89077187b24c8558ca2a89186ea3251 apktool-2.2.2.jar Remember these hashes. These are the local hashes. These are our master hashes. All others (Bitbucket, Backup) must match these. If they do not - they are invalid. ### Lets get uploading. Lets make sure we actually pushed these release changes to the repo (Both Github & Bitbucket) git push origin master git push origin vx.x.x git push bitbucket master git push bitbucket vx.x.x We upload the binaries into 3 places. 1. [Bitbucket Downloads](https://bitbucket.org/iBotPeaches/apktool/downloads) 2. [Github Releases](https://github.com/iBotPeaches/Apktool/releases) - Since `2.2.1`. 3. [Backup Mirror](https://connortumbleson.com/apktool/) 4. [Sonatype (Maven)](https://oss.sonatype.org) #### Bitbucket This one is pretty easy. Head to the URL attached to the hyperlink #1 above. There will be a "Add Files" button on the top right of the page. Upload the `apktool_x.x.x.jar` file. After it is uploaded. Immediately visit the page and download it. Check the `md5` for a match. #### GitHub This option will not work until the tag is pushed. You can head to this [page](https://github.com/iBotPeaches/Apktool/releases/new) to draft a new release. The `Tag version` dropdown will have the new tag. In this case `v2.2.2`. Select that option and make the title `Apktool vx.x.x`. There will be a description field on this release. Hold tight, we link the release blog post in this field, but we can edit the release after the fact to add this. Upload the binary `apktool_x.x.x.jar` and submit the release. #### Backup Server Access to this server is probably limited so this option may not be possible. SSH into the `connortumbleson.com` server with username `connor`. Head to `public_html/apktool` and upload the `apktool_x.x.x.jar` to it. Now re-generate the md5/sha256 hashes for these files. md5sum *.jar > md5.md5sum sha256 *.jar > sha256.shasum Check the `md5.md5sum` file for the hashes. The file will look something like this. 6de3e097943c553da5db2e604bced332 apktool_1.4.10.jar ... 1e6be08d3f9bb4b442bb85cf4e21f1c1 apktool_2.2.2.jar Additionally check the `sha256.shasum` file for the hashes. This file will look almost identical to the above except for containing sha256 hashes. The hashes match so we are good with the backup server. #### Sonatype You'll want to log in and view the Staging repositories and confirm you see the recently made build. You'll want to: * Close it (Wait for audit report email) * Release it (Drop the staging repository) * Wait 20min - 2 hours for it to appear [here](https://mvnrepository.com/artifact/org.apktool/apktool-lib) With those done, time to get writing the release post. We currently blog the releases on the [Connor Tumbleson personal blog](https://connortumbleson.com/). This may change and the formatting of these release posts change over time. Some recent releases for understanding the pattern can be found below. 1. [2.2.1](https://connortumbleson.com/2016/10/18/apktool-v2-2-1-released/) 2. [2.2.0](https://connortumbleson.com/2016/08/07/apktool-v2-2-0-released/) 3. [2.0.2](https://connortumbleson.com/2015/10/12/apktool-v2-0-2-released/) 4. [2.0.0](https://connortumbleson.com/2015/04/20/apktool-v2-0-0-released/) For obtaining commit authors and counts. The following command does the legwork: git shortlog -s -n --all --no-merges --since="05 Sept 2018" Obviously replacing the date with the release date of the last version. So write the post. I tend to always include the following: 1. Image of release for featured image when reshared on socials. 2. Quick sentence or two for SEO to describe the meat of this release. 3. Commit count and total for this release with author names. 4. Changelog linking to the bugs that were fixed. 5. Download including the md5/sha256 hash. 6. Link dump to Project Site, GitHub, Bug Tracker and XDA Thread. Now that you've written this post. We need to go post it in places and update places where Apktool is released. ### XDA Thread We have a [thread](https://forum.xda-developers.com/showthread.php?t=1755243) on XDA Developers. This thread follows the same pattern for all releases. When writing a response to the XDA thread we follow another pattern of release notes. These examples can be found below: 1. [2.2.2](https://forum.xda-developers.com/showpost.php?p=70687935&postcount=4635) 2. [2.2.1](http://forum.xda-developers.com/showpost.php?p=69188139&postcount=4478) 3. [2.0.0](http://forum.xda-developers.com/showpost.php?p=60255972&postcount=3063) ### Apktool Website The Apktool project website has a few locations to update: 1. The homepage intro 2. The download link in header 3. Migrating `unreleased.mx` to a new blog post. The easiest way to describe this is to just link to a [previous release](https://github.com/iBotPeaches/Apktool/pull/3146/files). ### Update Milestones Now that we've released a version, we should hopefully have no more tickets in the release just published. If there are, move those tickets to the next milestone. You can head to [milestones](https://github.com/iBotPeaches/Apktool/milestones) to close the just released version and create another. I tend to create the next release (In this case `2.2.3`) with an ETA of 3 months in the future. This is just a guideline but helps me to release a new version every 3 months. ### Social Spam The final step is to send this release into the wild via some social posting. Head to the blog where the release post was and send that link to Twitter, Google and whatever else you use. Relax and watch the bug tracker. # Building aapt binaries. The steps taken for building our modified aapt binaries for apktool. ### Getting the modified `frameworks/base` repo. First step is using the [platform_frameworks_base](https://github.com/iBotPeaches/platform_frameworks_base) repo. While previously unorganized, the repo now follows the branch naming convention depending on the current Android version. So `apktool_7.1` corresponds to the 7.1 Android release. This branch should work for all `android-7.1.x` tags for AOSP. We didn't follow this naming convention until Android 7.1. So don't go looking for older versions. The current version is `apktool-9.0.0`, which corresponds to the Android 9.0 (Pie) release. This repo has a variety of changes applied. These changes range from disabling optimizations to lessening the rules that aapt regularly has. We do this because apktool's job is to not fix apks, but rather keep them as close to the original as they were. ### First we need the AOSP source As cheesy as it is, just follow this [downloading](https://source.android.com/source/downloading.html) link in order to get the source downloaded. This is no small download, expect to use 150-250GB. Some optimization techniques for a smaller clone: * `~/bin/repo init -u https://android.googlesource.com/platform/manifest -b master --partial-clone` - Partial clone * `repo sync -c` - Only current branch After that, you need to build AOSP via this [documentation](https://source.android.com/source/building.html) guide. Now we aren't building the entire AOSP package, the initial build is to just see if you are capable of building it. We check out a certain tag or branch. Currently we use * aapt2 - `master`. * aapt1 - `master`. ### Including our modified `frameworks/base` package. There is probably a more automated way to do this, but for now: 1. `cd frameworks/base` 2. `git remote add origin [email protected]:iBotPeaches/platform_frameworks_base.git` 3. `git fetch origin -v` 4. `git checkout origin/master` #### Mac Patch Normally you'll be building this on a recent Mac OS that isn't supported. You'll want to follow these steps: 1. `vim build/soong/cc/config/darwin_host.go` 2. Find `darwinSupportedSdkVersions` array. 3. Add number that corresponds to output of: `find /Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs -iname "*.sdk"` ### Building the aapt1 (Legacy) binary. The steps below are different per flavor and operating system. #### Linux / Windows 1. `source build/envsetup.sh` 2. `lunch sdk-eng` 3. `m aapt` 4. `strip out/host/linux-x86/bin/aapt` 5. `strip out/host/linux-x86/bin/aapt_64` 6. `strip out/host/windows-x86/bin/aapt.exe` 7. `strip out/host/windows-x86/bin/aapt_64.exe` #### Mac 1. `source build/envsetup.sh` 2. `m aapt` 3. `strip out/host/darwin-x86/bin/aapt_64` 32/64 bit binaries will be built for Linux and Windows. ### Building the aapt2 binary. The steps below are different per flavor and operating system. #### Linux / Windows 1. `m aapt2` 2. `strip out/host/linux-x86/bin/aapt2` 3. `strip out/host/linux-x86/bin/aapt2_64` 4. `strip out/host/windows-x86/bin/aapt2.exe` 5. `strip out/host/windows-x86/bin/aapt2_64.exe` #### Mac 1. `export ANDROID_JAVA_HOME=/Path/To/Jdk` 2. `source build/envsetup.sh` 3. `m aapt2` 4. `strip out/host/darwin-x86/bin/aapt2_64` #### Confirming aapt/aapt2 builds are static There are some issues with some dependencies (namely `libc++`) in which they are built in the shared state. This is alright in the scope and context of AOSP/Android Studio, but once you leave those two behind and start using aapt on its own, you encounter some issues. The key is to force `libc++` to be built statically which takes some tweaks with the AOSP build systems as that dependency isn't standard like `libz` and others. You can test the finalized project using tools like `ldd` (unix) and `otool -L` (mac) for testing the binaries looking for shared dependencies. # Gradle Tips n Tricks ./gradlew build shadowJar proguard -x test This skips the testing suite (which currently takes 2-4 minutes). Use this when making quick builds and save the testing suite before pushing to GitHub. ./gradlew test --debug-jvm This enables debugging on the test suite. This starts the debugger on port 5005 which you can connect with IntelliJ. ./gradlew :brut.apktool:apktool-lib:test ---tests "*BuildAndDecodeTest" This runs the library project of Apktool, selecting a specific test to run. Comes in handy when writing a new test and only wanting to run that one. The asterisk is used to the full path to the test can be ignored. You can additionally match this with the debugging parameter to debug a specific test. This command can be found below. ./gradlew :brut.apktool:apktool-lib:test --tests "*BuildAndDecodeTest" --debug-jvm
Markdown
Apktool/LICENSE.md
Apache License Version 2.0, January 2004 https://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS Copyright 2010 Ryszard Wiśniewski Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.
Markdown
Apktool/README.md
### Apktool **This is the repository for Apktool. If you are looking for the Apktool website. Click [here](https://github.com/iBotPeaches/Apktool/tree/docs).** [![CI](https://github.com/iBotPeaches/Apktool/actions/workflows/build.yml/badge.svg)](https://github.com/iBotPeaches/Apktool/actions/workflows/test.yml) [![Software License](https://img.shields.io/badge/license-Apache%202.0-brightgreen.svg)](https://github.com/iBotPeaches/Apktool/blob/master/LICENSE) It is a tool for reverse engineering 3rd party, closed, binary Android apps. It can decode resources to nearly original form and rebuild them after making some modifications; it makes possible to debug smali code step by step. Also it makes working with app easier because of project-like files structure and automation of some repetitive tasks like building apk, etc. It is NOT intended for piracy and other non-legal uses. It could be used for localizing, adding some features or support for custom platforms and other GOOD purposes. Just try to be fair with authors of an app, that you use and probably like. #### Support - [Project Page](https://ibotpeaches.github.io/Apktool/) - [#apktool on libera.chat](https://web.libera.chat/) #### Sponsored by * [Sourcetoad](https://www.sourcetoad.com/cool-tools/apktool/) - helping with a weekly sponsorship for continued improvement and maintenance of the project. #### IDE of Choice * [JetBrains IntelliJ](https://www.jetbrains.com/idea/) #### Security Vulnerabilities If you discover a security vulnerability within Apktool, please send an e-mail to Connor Tumbleson at connor.tumbleson(at)gmail.com. All security vulnerabilities will be promptly addressed. #### Links - [Downloads](https://bitbucket.org/iBotPeaches/apktool/downloads) - [Downloads Mirror](https://connortumbleson.com/apktool/) - [How to Build](https://ibotpeaches.github.io/Apktool/build/) - [Documentation](https://ibotpeaches.github.io/Apktool/documentation/) - [Bug Reports](https://github.com/iBotPeaches/Apktool/issues) - [Changelog/Information](https://ibotpeaches.github.io/Apktool/changes/) - [XDA Post](https://forum.xda-developers.com/t/util-dec-2-2020-apktool-tool-for-reverse-engineering-apk-files.1755243/) - [Source (Github)](https://github.com/iBotPeaches/Apktool) - [Source (Bitbucket)](https://bitbucket.org/iBotPeaches/apktool/)
Markdown
Apktool/ROADMAP.md
## Automatic Remapping of ResourceId We currently prevent resourceIds from changing, by utilizing the `public.xml` file which makes the resources public, but then prevents them to be used in some locations (`android:scheme`). The correct fix would be to record the resourceIds and use dexlib2 (no regular expressions) to rewrite them to the new resourceId after the `resources.arsc` is built. This would be a lookup table of old->new resourceIds leveraging the API of dexlib2 to do the replacement. Doing this properly would nullify the need to do [#191](https://github.com/iBotPeaches/Apktool/issues/191) Suggestions: [#244](https://github.com/iBotPeaches/Apktool/issues/244) Discussions: [#2062](https://github.com/iBotPeaches/Apktool/issues/2062) ## Implicit Qualifiers Cleanup Currently we have a mismatch between reading the folders and reading the qualifiers which leads to a mismatch between implicit qualifiers like version (-v4, v13, etc). This was first spotted in bug [#1272](https://github.com/iBotPeaches/Apktool/issues/1272). This was attempted to be fixed in [!1758](https://github.com/iBotPeaches/Apktool/pull/1758/files), but had to be reverted due to [this](https://github.com/iBotPeaches/Apktool/issues/1272#issuecomment-379345005). Suggestions: [#2237](https://github.com/iBotPeaches/Apktool/issues/2237) ## Qualifier Plugin System For some OEMs, past and present. They re-use qualifiers that AOSP ends up using. This with CTS is becoming very rare and pretty much a problem of the past, but now custom modifications and more "off the cuff" OEMs are doing it. Apktool can't do anything because it stays true to AOSP. It would need a plugin system that controls how to read the qualifiers. Or even an override file. Suggestions: [#1420](https://github.com/iBotPeaches/Apktool/issues/1420), [#2474](https://github.com/iBotPeaches/Apktool/issues/2474) ## Non-reference Resources Some applications may shove resources into the /res folder, but have no references to them. Apktool follows the resource table, so these files are effectively abandoned. Crawling the filesystem for non-checked files would be slow especially having to cross check with already parsed files. Suggestions: [#1366](https://github.com/iBotPeaches/Apktool/issues/1366) ## Multi-threaded Applications are getting larger as well as frameworks, but Apktool is getting slower. Suggestions: [#2685](https://github.com/iBotPeaches/Apktool/issues/2685) ## Android Support Folks have requested running Apktool on device itself. This has been a challenge due to the arch requirements that would be placed on the aapt2/aapt binaries. Suggestions: [#2811](https://github.com/iBotPeaches/Apktool/issues/2811) ## Split APK Support Applications are further getting split on qualifiers. Apktool has been built on the assumption of one apk. Suggestions: [#2283](https://github.com/iBotPeaches/Apktool/issues/2283), [#2218](https://github.com/iBotPeaches/Apktool/issues/2218), [#2880](https://github.com/iBotPeaches/Apktool/issues/2880) ## Dummy Resources Folks want the ability to stop the auto generation of dummy resources. Suggestions: [#2683](https://github.com/iBotPeaches/Apktool/issues/2683), [#2104](https://github.com/iBotPeaches/Apktool/issues/2104) Pull Request(s): [#2463](https://github.com/iBotPeaches/Apktool/pull/2463)
Markdown
Apktool/SECURITY.md
# Security Policy ## Reporting a Vulnerability If you discover a security vulnerability within Apktool, please send an e-mail to Connor Tumbleson at connor.tumbleson(at)gmail.com. All security vulnerabilities will be promptly addressed.
Apktool/settings.gradle.kts
rootProject.name = "apktool-cli" include("brut.j.common", "brut.j.util", "brut.j.dir", "brut.apktool:apktool-lib", "brut.apktool:apktool-cli")
Markdown
Apktool/.github/CONTRIBUTING.md
# Contributing A couple of quick tips to ease the submission process. * You may use [Github](https://github.com/iBotPeaches/Apktool) or [Bitbucket](https://bitbucket.org/iBotPeaches/apktool/) to submit a pull request. * Please reference the bug number from our [issue list](https://github.com/iBotPeaches/Apktool/issues) in any pull requests to help associate fixes with bugs. * If possible, add unit-tests for any bugs that you fix. * [Building](http://ibotpeaches.github.io/Apktool/build/) via Gradle will automatically run unit-tests. The build will end if any test fails. * [IntelliJ IDEA](http://www.jetbrains.com/idea/) is our IDE of choice. It has built in debugger support along with Gradle integration. * For changes to smali/baksmali please see their [page](https://github.com/google/smali) for more information. ## Code Styles * A rough guideline based on [AOSP Guidelines](https://source.android.com/source/code-style.html). * A tab counts as 4 spaces and we use 4 spaces. * Our right margin is 120 characters long.
YAML
Apktool/.github/dependabot.yml
version: 2 updates: - package-ecosystem: github-actions directory: / schedule: interval: weekly time: "04:00" timezone: "America/New_York" - package-ecosystem: gradle directory: / schedule: interval: weekly time: "04:00" timezone: "America/New_York"
Markdown
Apktool/.github/ISSUE_TEMPLATE/bug-report.md
--- name: Bug Report about: Report a bug in Apktool title: "[BUG]" labels: '' assignees: '' --- ### Information 1. **Apktool Version (`apktool -version`)** - 2. **Operating System (Mac, Linux, Windows)** - 3. **APK From? (Playstore, ROM, Other)** - 4. **Java Version (`java --version`)** - ### Stacktrace/Logcat ``` Include stacktrace here ``` ### Steps to Reproduce 1. `apktool ` ### Frameworks If this APK is from an OEM ROM (Samsung, HTC, LG). Please attach framework files (`.apks` that live in `/system/framework` or `/system/priv-app`) ### APK If this APK can be freely shared, please upload/attach a link to it. ### Questions to ask before submission 1. Have you tried `apktool d`, `apktool b` without changing anything? 2. If you are trying to install a modified apk, did you resign it? 3. Are you using the latest apktool version?
YAML
Apktool/.github/ISSUE_TEMPLATE/config.yml
blank_issues_enabled: true contact_links: - name: Feature request url: https://github.com/iBotPeaches/Apktool/discussions/categories/ideas about: 'For ideas or feature requests, start a new discussion'
YAML
Apktool/.github/workflows/analyze.yml
name: Analyze on: push: branches: [master] pull_request: branches: [master] concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: analyze: name: Analyze runs-on: ubuntu-latest steps: - name: Checkout repository uses: actions/checkout@v3 - name: Initialize CodeQL uses: github/codeql-action/init@v2 with: languages: java - name: Autobuild uses: github/codeql-action/autobuild@v2 - name: Perform CodeQL Analysis uses: github/codeql-action/analyze@v2
YAML
Apktool/.github/workflows/build.yml
name: CI on: push: branches: - master pull_request: paths: - '**.java' - '**.kts' - 'brut.apktool/apktool-lib/src/main/resources/**' - 'brut.apktool/apktool-lib/src/test/**' - '.github/workflows/**' - 'gradle/wrapper/**' - 'gradlew' - 'gradlew.bat' concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true env: BINARY_PATH: brut.apktool/apktool-lib/src/main/resources/prebuilt jobs: analyze-mac-aapt: runs-on: macos-latest strategy: matrix: file: [ aapt_64, aapt2_64 ] steps: - uses: actions/checkout@v3 - name: Verify Executable run: ${{ env.BINARY_PATH }}/macosx/${{ matrix.file }} version - name: Output Static run: otool -L ${{ env.BINARY_PATH }}/macosx/${{ matrix.file }} || true analyze-linux-aapt: runs-on: ubuntu-latest strategy: matrix: file: [ aapt, aapt_64, aapt2, aapt2_64 ] steps: - uses: actions/checkout@v3 - name: Verify Executable run: ${{ env.BINARY_PATH }}/linux/${{ matrix.file }} version - name: Output Static run: ldd ${{ env.BINARY_PATH }}/linux/${{ matrix.file }} || true analyze-windows-aapt: runs-on: windows-latest strategy: matrix: file: [ aapt.exe, aapt_64.exe, aapt2.exe, aapt2_64.exe ] steps: - uses: actions/checkout@v3 - name: Verify Executable run: ${{ env.BINARY_PATH }}/windows/${{ matrix.file }} version - name: Output Static run: ldd ${{ env.BINARY_PATH }}/windows/${{ matrix.file }} || true build-and-test-with-Java-8-and-later: runs-on: ${{ matrix.os }} needs: - analyze-mac-aapt - analyze-linux-aapt - analyze-windows-aapt name: Build/Test (JDK ${{ matrix.java }}, ${{ matrix.os }}) strategy: fail-fast: true matrix: os: [ ubuntu-latest, macOS-latest, windows-latest ] java: [ 8, 11, 17, 18, 19, 20 ] steps: - uses: actions/checkout@v3 - uses: actions/setup-java@v3 with: distribution: 'zulu' java-version: ${{ matrix.java }} - name: Build and test uses: gradle/[email protected] with: arguments: build shadowJar proguard upload-artifact: runs-on: ubuntu-latest name: Build apktool.jar if: github.repository == 'iBotPeaches/Apktool' && github.ref == 'refs/heads/master' needs: - build-and-test-with-Java-8-and-later steps: - uses: actions/checkout@v3 - uses: actions/setup-java@v3 with: distribution: 'zulu' java-version: 17 - name: Build uses: gradle/[email protected] with: arguments: build shadowJar proguard - name: Upload uses: actions/upload-artifact@v3 with: name: apktool.jar path: brut.apktool/apktool-cli/build/libs/apktool-*-small.jar
YAML
Apktool/.github/workflows/gradle.yml
name: Gradle Validate on: push: branches: - master paths: - 'gradle/wrapper/gradle-wrapper.jar' pull_request: paths: - 'gradle/wrapper/gradle-wrapper.jar' concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true jobs: validate-gradle-wrapper: runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: actions/setup-java@v3 with: distribution: 'zulu' java-version: 17 - uses: gradle/[email protected]
Apktool/brut.apktool/apktool-cli/build.gradle.kts
import proguard.gradle.ProGuardTask val commonsCliVersion: String by rootProject.extra val apktoolVersion: String by rootProject.extra plugins { id("com.github.johnrengelman.shadow") application } // Buildscript is deprecated, but the alternative approach does not support expanded properties // https://github.com/gradle/gradle/issues/9830 // So we must hard-code the version here. buildscript { dependencies { // Proguard doesn't support plugin DSL - https://github.com/Guardsquare/proguard/issues/225 classpath("com.guardsquare:proguard-gradle:7.3.2") } } dependencies { implementation("commons-cli:commons-cli:$commonsCliVersion") implementation(project(":brut.apktool:apktool-lib")) } application { mainClass.set("brut.apktool.Main") tasks.run.get().workingDir = file(System.getProperty("user.dir")) } tasks.withType<Jar> { manifest { attributes["Main-Class"] = "brut.apktool.Main" } } tasks.register<Delete>("cleanOutputDirectory") { delete(fileTree("build/libs") { exclude("apktool-cli-all.jar") }) } tasks.register<ProGuardTask>("proguard") { dependsOn("cleanOutputDirectory") dependsOn("shadowJar") injars(tasks.named("shadowJar").get().outputs.files) val javaHome = System.getProperty("java.home") if (JavaVersion.current() <= JavaVersion.VERSION_1_8) { libraryjars("$javaHome/lib/jce.jar") libraryjars("$javaHome/lib/rt.jar") } else { libraryjars(mapOf("jarfilter" to "!**.jar", "filter" to "!module-info.class"), { "$javaHome/jmods/" } ) } dontobfuscate() dontoptimize() keep("class brut.apktool.Main { public static void main(java.lang.String[]); }") keepclassmembers("enum * { public static **[] values(); public static ** valueOf(java.lang.String); }") dontwarn("com.google.common.base.**") dontwarn("com.google.common.collect.**") dontwarn("com.google.common.util.**") dontwarn("javax.xml.xpath.**") dontnote("**") val outPath = "build/libs/apktool-cli-$apktoolVersion.jar" outjars(outPath) }
Java
Apktool/brut.apktool/apktool-cli/src/main/java/brut/apktool/Main.java
/* * Copyright (C) 2010 Ryszard Wiśniewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.apktool; import brut.androlib.*; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.CantFindFrameworkResException; import brut.androlib.exceptions.InFileNotFoundException; import brut.androlib.exceptions.OutDirExistsException; import brut.androlib.res.Framework; import brut.common.BrutException; import brut.directory.DirectoryException; import brut.directory.ExtFile; import brut.util.AaptManager; import brut.util.OSDetection; import org.apache.commons.cli.*; import java.io.*; import java.util.logging.*; /** * Main entry point of the apktool. */ public class Main { public static void main(String[] args) throws BrutException { // headless System.setProperty("java.awt.headless", "true"); // Ignore stricter validation on zip files from java 11 onwards as this is a protection technique // that applications use to thwart disassembly tools. We have protections in place for directory traversal // and handling of bogus data in the zip header, so we can ignore this. System.setProperty("jdk.nio.zipfs.allowDotZipEntry", "true"); System.setProperty("jdk.util.zip.disableZip64ExtraFieldValidation", "true"); // set verbosity default Verbosity verbosity = Verbosity.NORMAL; // cli parser CommandLineParser parser = new DefaultParser(); CommandLine commandLine; // load options _Options(); try { commandLine = parser.parse(allOptions, args, false); if (! OSDetection.is64Bit()) { System.err.println("32 bit support is deprecated. Apktool will not support 32bit on v3.0.0."); } } catch (ParseException ex) { System.err.println(ex.getMessage()); usage(); System.exit(1); return; } // check for verbose / quiet if (commandLine.hasOption("-v") || commandLine.hasOption("--verbose")) { verbosity = Verbosity.VERBOSE; } else if (commandLine.hasOption("-q") || commandLine.hasOption("--quiet")) { verbosity = Verbosity.QUIET; } setupLogging(verbosity); // check for advance mode if (commandLine.hasOption("advance") || commandLine.hasOption("advanced")) { setAdvanceMode(); } Config config = Config.getDefaultConfig(); initConfig(commandLine, config); boolean cmdFound = false; for (String opt : commandLine.getArgs()) { if (opt.equalsIgnoreCase("d") || opt.equalsIgnoreCase("decode")) { cmdDecode(commandLine, config); cmdFound = true; } else if (opt.equalsIgnoreCase("b") || opt.equalsIgnoreCase("build")) { cmdBuild(commandLine, config); cmdFound = true; } else if (opt.equalsIgnoreCase("if") || opt.equalsIgnoreCase("install-framework")) { cmdInstallFramework(commandLine, config); cmdFound = true; } else if (opt.equalsIgnoreCase("empty-framework-dir")) { cmdEmptyFrameworkDirectory(commandLine, config); cmdFound = true; } else if (opt.equalsIgnoreCase("list-frameworks")) { cmdListFrameworks(commandLine, config); cmdFound = true; } else if (opt.equalsIgnoreCase("publicize-resources")) { cmdPublicizeResources(commandLine, config); cmdFound = true; } } // if no commands ran, run the version / usage check. if (!cmdFound) { if (commandLine.hasOption("version")) { _version(); System.exit(0); } else { usage(); } } } private static void initConfig(CommandLine cli, Config config) { if (cli.hasOption("p") || cli.hasOption("frame-path")) { config.frameworkDirectory = cli.getOptionValue("p"); } if (cli.hasOption("t") || cli.hasOption("tag")) { config.frameworkTag = cli.getOptionValue("t"); } if (cli.hasOption("api") || cli.hasOption("api-level")) { config.apiLevel = Integer.parseInt(cli.getOptionValue("api")); } } private static void cmdDecode(CommandLine cli, Config config) throws AndrolibException { String apkName = getLastArg(cli); // check decode options if (cli.hasOption("s") || cli.hasOption("no-src")) { config.setDecodeSources(Config.DECODE_SOURCES_NONE); } if (cli.hasOption("only-main-classes")) { config.setDecodeSources(Config.DECODE_SOURCES_SMALI_ONLY_MAIN_CLASSES); } if (cli.hasOption("d") || cli.hasOption("debug")) { System.err.println("SmaliDebugging has been removed in 2.1.0 onward. Please see: https://github.com/iBotPeaches/Apktool/issues/1061"); System.exit(1); } if (cli.hasOption("b") || cli.hasOption("no-debug-info")) { config.baksmaliDebugMode = false; } if (cli.hasOption("f") || cli.hasOption("force")) { config.forceDelete = true; } if (cli.hasOption("r") || cli.hasOption("no-res")) { config.setDecodeResources(Config.DECODE_RESOURCES_NONE); } if (cli.hasOption("force-manifest")) { config.setForceDecodeManifest(Config.FORCE_DECODE_MANIFEST_FULL); } if (cli.hasOption("no-assets")) { config.setDecodeAssets(Config.DECODE_ASSETS_NONE); } if (cli.hasOption("k") || cli.hasOption("keep-broken-res")) { config.keepBrokenResources = true; } if (cli.hasOption("m") || cli.hasOption("match-original")) { config.analysisMode = true; } File outDir; if (cli.hasOption("o") || cli.hasOption("output")) { outDir = new File(cli.getOptionValue("o")); } else { // make out folder manually using name of apk String outName = apkName; outName = outName.endsWith(".apk") ? outName.substring(0, outName.length() - 4).trim() : outName + ".out"; // make file from path outName = new File(outName).getName(); outDir = new File(outName); } ExtFile apkFile = new ExtFile(apkName); ApkDecoder decoder = new ApkDecoder(config, apkFile); try { decoder.decode(outDir); } catch (OutDirExistsException ex) { System.err .println("Destination directory (" + outDir.getAbsolutePath() + ") " + "already exists. Use -f switch if you want to overwrite it."); System.exit(1); } catch (InFileNotFoundException ex) { System.err.println("Input file (" + apkFile.getAbsolutePath() + ") " + "was not found or was not readable."); System.exit(1); } catch (CantFindFrameworkResException ex) { System.err .println("Can't find framework resources for package of id: " + ex.getPkgId() + ". You must install proper " + "framework files, see project website for more info."); System.exit(1); } catch (IOException ex) { System.err.println("Could not modify file. Please ensure you have permission."); System.exit(1); } catch (DirectoryException ex) { System.err.println("Could not modify internal dex files. Please ensure you have permission."); System.exit(1); } } private static void cmdBuild(CommandLine cli, Config config) { String[] args = cli.getArgs(); String appDirName = args.length < 2 ? "." : args[1]; // check for build options if (cli.hasOption("f") || cli.hasOption("force-all")) { config.forceBuildAll = true; } if (cli.hasOption("d") || cli.hasOption("debug")) { config.debugMode = true; } if (cli.hasOption("n") || cli.hasOption("net-sec-conf")) { config.netSecConf = true; } if (cli.hasOption("v") || cli.hasOption("verbose")) { config.verbose = true; } if (cli.hasOption("a") || cli.hasOption("aapt")) { config.aaptPath = cli.getOptionValue("a"); } if (cli.hasOption("c") || cli.hasOption("copy-original")) { config.copyOriginalFiles = true; } if (cli.hasOption("nc") || cli.hasOption("no-crunch")) { config.noCrunch = true; } // Temporary flag to enable the use of aapt2. This will transform in time to a use-aapt1 flag, which will be // legacy and eventually removed. if (cli.hasOption("use-aapt2")) { config.useAapt2 = true; } File outFile; if (cli.hasOption("o") || cli.hasOption("output")) { outFile = new File(cli.getOptionValue("o")); } else { outFile = null; } if (config.netSecConf && !config.useAapt2) { System.err.println("-n / --net-sec-conf is only supported with --use-aapt2."); System.exit(1); } // try and build apk try { if (cli.hasOption("a") || cli.hasOption("aapt")) { config.aaptVersion = AaptManager.getAaptVersion(cli.getOptionValue("a")); } new ApkBuilder(config, new ExtFile(appDirName)).build(outFile); } catch (BrutException ex) { System.err.println(ex.getMessage()); System.exit(1); } } private static void cmdInstallFramework(CommandLine cli, Config config) throws AndrolibException { String apkName = getLastArg(cli); new Framework(config).installFramework(new File(apkName)); } private static void cmdListFrameworks(CommandLine cli, Config config) throws AndrolibException { new Framework(config).listFrameworkDirectory(); } private static void cmdPublicizeResources(CommandLine cli, Config config) throws AndrolibException { String apkName = getLastArg(cli); new Framework(config).publicizeResources(new File(apkName)); } private static void cmdEmptyFrameworkDirectory(CommandLine cli, Config config) throws AndrolibException { if (cli.hasOption("f") || cli.hasOption("force")) { config.forceDeleteFramework = true; } new Framework(config).emptyFrameworkDirectory(); } private static String getLastArg(CommandLine cli) { int paraCount = cli.getArgList().size(); return cli.getArgList().get(paraCount - 1); } private static void _version() { System.out.println(ApktoolProperties.getVersion()); } private static void _Options() { // create options Option versionOption = Option.builder("version") .longOpt("version") .desc("Print the version.") .build(); Option advanceOption = Option.builder("advance") .longOpt("advanced") .desc("Print advanced information.") .build(); Option noSrcOption = Option.builder("s") .longOpt("no-src") .desc("Do not decode sources.") .build(); Option onlyMainClassesOption = Option.builder() .longOpt("only-main-classes") .desc("Only disassemble the main dex classes (classes[0-9]*.dex) in the root.") .build(); Option noResOption = Option.builder("r") .longOpt("no-res") .desc("Do not decode resources.") .build(); Option forceManOption = Option.builder() .longOpt("force-manifest") .desc("Decode the APK's compiled manifest, even if decoding of resources is set to \"false\".") .build(); Option noAssetOption = Option.builder() .longOpt("no-assets") .desc("Do not decode assets.") .build(); Option debugDecOption = Option.builder("d") .longOpt("debug") .desc("REMOVED (DOES NOT WORK): Decode in debug mode.") .build(); Option analysisOption = Option.builder("m") .longOpt("match-original") .desc("Keep files to closest to original as possible (prevents rebuild).") .build(); Option apiLevelOption = Option.builder("api") .longOpt("api-level") .desc("The numeric api-level of the file to generate, e.g. 14 for ICS.") .hasArg(true) .argName("API") .build(); Option debugBuiOption = Option.builder("d") .longOpt("debug") .desc("Set android:debuggable to \"true\" in the APK's compiled manifest.") .build(); Option netSecConfOption = Option.builder("n") .longOpt("net-sec-conf") .desc("Add a generic Network Security Configuration file in the output APK") .build(); Option noDbgOption = Option.builder("b") .longOpt("no-debug-info") .desc("Do not write out debug info (.local, .param, .line, etc.)") .build(); Option forceDecOption = Option.builder("f") .longOpt("force") .desc("Force delete destination directory.") .build(); Option frameTagOption = Option.builder("t") .longOpt("frame-tag") .desc("Use framework files tagged by <tag>.") .hasArg(true) .argName("tag") .build(); Option frameDirOption = Option.builder("p") .longOpt("frame-path") .desc("Use framework files located in <dir>.") .hasArg(true) .argName("dir") .build(); Option frameIfDirOption = Option.builder("p") .longOpt("frame-path") .desc("Store framework files into <dir>.") .hasArg(true) .argName("dir") .build(); Option keepResOption = Option.builder("k") .longOpt("keep-broken-res") .desc("Use if there was an error and some resources were dropped, e.g.\n" + " \"Invalid config flags detected. Dropping resources\", but you\n" + " want to decode them anyway, even with errors. You will have to\n" + " fix them manually before building.") .build(); Option forceBuiOption = Option.builder("f") .longOpt("force-all") .desc("Skip changes detection and build all files.") .build(); Option aaptOption = Option.builder("a") .longOpt("aapt") .hasArg(true) .argName("loc") .desc("Load aapt from specified location.") .build(); Option aapt2Option = Option.builder() .longOpt("use-aapt2") .desc("Use aapt2 binary instead of aapt1 during the build step.") .build(); Option originalOption = Option.builder("c") .longOpt("copy-original") .desc("Copy original AndroidManifest.xml and META-INF. See project page for more info.") .build(); Option noCrunchOption = Option.builder("nc") .longOpt("no-crunch") .desc("Disable crunching of resource files during the build step.") .build(); Option tagOption = Option.builder("t") .longOpt("tag") .desc("Tag frameworks using <tag>.") .hasArg(true) .argName("tag") .build(); Option outputBuiOption = Option.builder("o") .longOpt("output") .desc("The name of apk that gets written. (default: dist/name.apk)") .hasArg(true) .argName("dir") .build(); Option outputDecOption = Option.builder("o") .longOpt("output") .desc("The name of folder that gets written. (default: apk.out)") .hasArg(true) .argName("dir") .build(); Option quietOption = Option.builder("q") .longOpt("quiet") .build(); Option verboseOption = Option.builder("v") .longOpt("verbose") .build(); // check for advance mode if (isAdvanceMode()) { decodeOptions.addOption(noDbgOption); decodeOptions.addOption(keepResOption); decodeOptions.addOption(analysisOption); decodeOptions.addOption(onlyMainClassesOption); decodeOptions.addOption(apiLevelOption); decodeOptions.addOption(noAssetOption); decodeOptions.addOption(forceManOption); buildOptions.addOption(apiLevelOption); buildOptions.addOption(debugBuiOption); buildOptions.addOption(netSecConfOption); buildOptions.addOption(aaptOption); buildOptions.addOption(originalOption); buildOptions.addOption(aapt2Option); buildOptions.addOption(noCrunchOption); } // add global options normalOptions.addOption(versionOption); normalOptions.addOption(advanceOption); // add basic decode options decodeOptions.addOption(frameTagOption); decodeOptions.addOption(outputDecOption); decodeOptions.addOption(frameDirOption); decodeOptions.addOption(forceDecOption); decodeOptions.addOption(noSrcOption); decodeOptions.addOption(noResOption); // add basic build options buildOptions.addOption(outputBuiOption); buildOptions.addOption(frameDirOption); buildOptions.addOption(forceBuiOption); // add basic framework options frameOptions.addOption(tagOption); frameOptions.addOption(frameIfDirOption); // add empty framework options emptyFrameworkOptions.addOption(forceDecOption); emptyFrameworkOptions.addOption(frameIfDirOption); // add list framework options listFrameworkOptions.addOption(frameIfDirOption); // add all, loop existing cats then manually add advance for (Option op : normalOptions.getOptions()) { allOptions.addOption(op); } for (Option op : decodeOptions.getOptions()) { allOptions.addOption(op); } for (Option op : buildOptions.getOptions()) { allOptions.addOption(op); } for (Option op : frameOptions.getOptions()) { allOptions.addOption(op); } allOptions.addOption(apiLevelOption); allOptions.addOption(analysisOption); allOptions.addOption(debugDecOption); allOptions.addOption(noDbgOption); allOptions.addOption(forceManOption); allOptions.addOption(noAssetOption); allOptions.addOption(keepResOption); allOptions.addOption(debugBuiOption); allOptions.addOption(netSecConfOption); allOptions.addOption(aaptOption); allOptions.addOption(originalOption); allOptions.addOption(verboseOption); allOptions.addOption(quietOption); allOptions.addOption(aapt2Option); allOptions.addOption(noCrunchOption); allOptions.addOption(onlyMainClassesOption); } private static String verbosityHelp() { if (isAdvanceMode()) { return "[-q|--quiet OR -v|--verbose] "; } else { return ""; } } private static void usage() { _Options(); HelpFormatter formatter = new HelpFormatter(); formatter.setWidth(120); // print out license info prior to formatter. System.out.println( "Apktool " + ApktoolProperties.getVersion() + " - a tool for reengineering Android apk files\n" + "with smali v" + ApktoolProperties.get("smaliVersion") + " and baksmali v" + ApktoolProperties.get("baksmaliVersion") + "\n" + "Copyright 2010 Ryszard Wiśniewski <[email protected]>\n" + "Copyright 2010 Connor Tumbleson <[email protected]>" ); if (isAdvanceMode()) { System.out.println("Apache License 2.0 (https://www.apache.org/licenses/LICENSE-2.0)\n"); }else { System.out.println(); } // 4 usage outputs (general, frameworks, decode, build) formatter.printHelp("apktool " + verbosityHelp(), normalOptions); formatter.printHelp("apktool " + verbosityHelp() + "if|install-framework [options] <framework.apk>", frameOptions); formatter.printHelp("apktool " + verbosityHelp() + "d[ecode] [options] <file_apk>", decodeOptions); formatter.printHelp("apktool " + verbosityHelp() + "b[uild] [options] <app_path>", buildOptions); if (isAdvanceMode()) { formatter.printHelp("apktool " + verbosityHelp() + "publicize-resources <file_path>", emptyOptions); formatter.printHelp("apktool " + verbosityHelp() + "empty-framework-dir [options]", emptyFrameworkOptions); formatter.printHelp("apktool " + verbosityHelp() + "list-frameworks [options]", listFrameworkOptions); } System.out.println(); // print out more information System.out.println("For additional info, see: https://apktool.org \n" + "For smali/baksmali info, see: https://github.com/google/smali"); } private static void setupLogging(final Verbosity verbosity) { Logger logger = Logger.getLogger(""); for (Handler handler : logger.getHandlers()) { logger.removeHandler(handler); } LogManager.getLogManager().reset(); if (verbosity == Verbosity.QUIET) { return; } Handler handler = new Handler(){ @Override public void publish(LogRecord record) { if (getFormatter() == null) { setFormatter(new SimpleFormatter()); } try { String message = getFormatter().format(record); if (record.getLevel().intValue() >= Level.WARNING.intValue()) { System.err.write(message.getBytes()); } else { if (record.getLevel().intValue() >= Level.INFO.intValue()) { System.out.write(message.getBytes()); } else { if (verbosity == Verbosity.VERBOSE) { System.out.write(message.getBytes()); } } } } catch (Exception exception) { reportError(null, exception, ErrorManager.FORMAT_FAILURE); } } @Override public void close() throws SecurityException {} @Override public void flush(){} }; logger.addHandler(handler); if (verbosity == Verbosity.VERBOSE) { handler.setLevel(Level.ALL); logger.setLevel(Level.ALL); } else { handler.setFormatter(new Formatter() { @Override public String format(LogRecord record) { return record.getLevel().toString().charAt(0) + ": " + record.getMessage() + System.getProperty("line.separator"); } }); } } private static boolean isAdvanceMode() { return advanceMode; } private static void setAdvanceMode() { Main.advanceMode = true; } private enum Verbosity { NORMAL, VERBOSE, QUIET } private static boolean advanceMode = false; private final static Options normalOptions; private final static Options decodeOptions; private final static Options buildOptions; private final static Options frameOptions; private final static Options allOptions; private final static Options emptyOptions; private final static Options emptyFrameworkOptions; private final static Options listFrameworkOptions; static { //normal and advance usage output normalOptions = new Options(); buildOptions = new Options(); decodeOptions = new Options(); frameOptions = new Options(); allOptions = new Options(); emptyOptions = new Options(); emptyFrameworkOptions = new Options(); listFrameworkOptions = new Options(); } }
Apktool/brut.apktool/apktool-lib/build.gradle.kts
val baksmaliVersion: String by rootProject.extra val smaliVersion: String by rootProject.extra val xmlpullVersion: String by rootProject.extra val guavaVersion: String by rootProject.extra val commonsLangVersion: String by rootProject.extra val commonsIoVersion: String by rootProject.extra val commonsTextVersion: String by rootProject.extra val junitVersion: String by rootProject.extra val xmlunitVersion: String by rootProject.extra val gitRevision: String by rootProject.extra val apktoolVersion: String by rootProject.extra tasks { processResources { from("src/main/resources/properties") { include("**/*.properties") into("properties") expand("version" to apktoolVersion, "gitrev" to gitRevision) duplicatesStrategy = DuplicatesStrategy.INCLUDE } from("src/main/resources") { include("**/*.jar") duplicatesStrategy = DuplicatesStrategy.INCLUDE } includeEmptyDirs = false } test { // https://github.com/iBotPeaches/Apktool/issues/3174 - CVE-2023-22036 // Increases validation of extra field of zip header. Some older Android applications // used this field to store data violating the zip specification. systemProperty("jdk.util.zip.disableZip64ExtraFieldValidation", true) } } dependencies { api(project(":brut.j.dir")) api(project(":brut.j.util")) api(project(":brut.j.common")) implementation("com.android.tools.smali:smali-baksmali:$baksmaliVersion") implementation("com.android.tools.smali:smali:$smaliVersion") implementation("xpp3:xpp3:$xmlpullVersion") implementation("com.google.guava:guava:$guavaVersion") implementation("org.apache.commons:commons-lang3:$commonsLangVersion") implementation("commons-io:commons-io:$commonsIoVersion") implementation("org.apache.commons:commons-text:$commonsTextVersion") testImplementation("junit:junit:$junitVersion") testImplementation("org.xmlunit:xmlunit-legacy:$xmlunitVersion") }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/android/content/res/XmlResourceParser.java
/* * Copyright (C) 2006 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.content.res; import android.util.AttributeSet; import org.xmlpull.v1.XmlPullParser; /** * The XML parsing interface returned for an XML resource. This is a standard * XmlPullParser interface, as well as an extended AttributeSet interface and an * additional close() method on this interface for the client to indicate when * it is done reading the resource. */ public interface XmlResourceParser extends XmlPullParser, AttributeSet { /** * Close this interface to the resource. Calls on the interface are no * longer value after this call. */ void close(); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/android/util/AttributeSet.java
/* * Copyright 2008 Android4ME / Dmitry Skiba * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.util; public interface AttributeSet { int getAttributeCount(); String getAttributeName(int index); String getAttributeValue(int index); String getPositionDescription(); int getAttributeNameResource(int index); int getAttributeListValue(int index, String[] options, int defaultValue); boolean getAttributeBooleanValue(int index, boolean defaultValue); int getAttributeResourceValue(int index, int defaultValue); int getAttributeIntValue(int index, int defaultValue); int getAttributeUnsignedIntValue(int index, int defaultValue); float getAttributeFloatValue(int index, float defaultValue); String getIdAttribute(); String getClassAttribute(); int getIdAttributeResourceValue(int index); int getStyleAttribute(); String getAttributeValue(String namespace, String attribute); int getAttributeListValue(String namespace, String attribute, String[] options, int defaultValue); boolean getAttributeBooleanValue(String namespace, String attribute, boolean defaultValue); int getAttributeResourceValue(String namespace, String attribute, int defaultValue); int getAttributeIntValue(String namespace, String attribute, int defaultValue); int getAttributeUnsignedIntValue(String namespace, String attribute, int defaultValue); float getAttributeFloatValue(String namespace, String attribute, float defaultValue); // TODO: remove int getAttributeValueType(int index); int getAttributeValueData(int index); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/android/util/TypedValue.java
/* * Copyright (C) 2007 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package android.util; /** * Container for a dynamically typed data value. Primarily used with * Resources for holding resource values. */ public class TypedValue { /** The value contains no data. */ public static final int TYPE_NULL = 0x00; /** The <var>data</var> field holds a resource identifier. */ public static final int TYPE_REFERENCE = 0x01; /** * The <var>data</var> field holds an attribute resource identifier * (referencing an attribute in the current theme style, not a resource * entry). */ public static final int TYPE_ATTRIBUTE = 0x02; /** * The <var>string</var> field holds string data. In addition, if * <var>data</var> is non-zero then it is the string block index of the * string and <var>assetCookie</var> is the set of assets the string came * from. */ public static final int TYPE_STRING = 0x03; /** The <var>data</var> field holds an IEEE 754 floating point number. */ public static final int TYPE_FLOAT = 0x04; /** * The <var>data</var> field holds a complex number encoding a dimension * value. */ public static final int TYPE_DIMENSION = 0x05; /** * The <var>data</var> field holds a complex number encoding a fraction of a * container. */ public static final int TYPE_FRACTION = 0x06; /** * The <var>data</var> holds a dynamic res table reference, which needs to be * resolved before it can be used like TYPE_REFERENCE */ public static final int TYPE_DYNAMIC_REFERENCE = 0x07; /** * The <var>data</var> an attribute resource identifier, which needs to be resolved * before it can be used like a TYPE_ATTRIBUTE. */ public static final int TYPE_DYNAMIC_ATTRIBUTE = 0x08; /** * Identifies the start of plain integer values. Any type value from this to * {@link #TYPE_LAST_INT} means the <var>data</var> field holds a generic * integer value. */ public static final int TYPE_FIRST_INT = 0x10; /** * The <var>data</var> field holds a number that was originally specified in * decimal. */ public static final int TYPE_INT_DEC = 0x10; /** * The <var>data</var> field holds a number that was originally specified in * hexadecimal (0xn). */ public static final int TYPE_INT_HEX = 0x11; /** * The <var>data</var> field holds 0 or 1 that was originally specified as * "false" or "true". */ public static final int TYPE_INT_BOOLEAN = 0x12; /** * Identifies the start of integer values that were specified as color * constants (starting with '#'). */ public static final int TYPE_FIRST_COLOR_INT = 0x1c; /** * The <var>data</var> field holds a color that was originally specified as * #aarrggbb. */ public static final int TYPE_INT_COLOR_ARGB8 = 0x1c; /** * The <var>data</var> field holds a color that was originally specified as * #rrggbb. */ public static final int TYPE_INT_COLOR_RGB8 = 0x1d; /** * The <var>data</var> field holds a color that was originally specified as * #argb. */ public static final int TYPE_INT_COLOR_ARGB4 = 0x1e; /** * The <var>data</var> field holds a color that was originally specified as * #rgb. */ public static final int TYPE_INT_COLOR_RGB4 = 0x1f; /** * Identifies the end of integer values that were specified as color * constants. */ public static final int TYPE_LAST_COLOR_INT = 0x1f; /** Identifies the end of plain integer values. */ public static final int TYPE_LAST_INT = 0x1f; /* ------------------------------------------------------------ */ /** Complex data: bit location of unit information. */ public static final int COMPLEX_UNIT_SHIFT = 0; /** * Complex data: mask to extract unit information (after shifting by * {@link #COMPLEX_UNIT_SHIFT}). This gives us 16 possible types, as defined * below. */ public static final int COMPLEX_UNIT_MASK = 0xf; /** {@link #TYPE_DIMENSION} complex unit: Value is raw pixels. */ public static final int COMPLEX_UNIT_PX = 0; /** * {@link #TYPE_DIMENSION} complex unit: Value is Device Independent Pixels. */ public static final int COMPLEX_UNIT_DIP = 1; /** {@link #TYPE_DIMENSION} complex unit: Value is a scaled pixel. */ public static final int COMPLEX_UNIT_SP = 2; /** {@link #TYPE_DIMENSION} complex unit: Value is in points. */ public static final int COMPLEX_UNIT_PT = 3; /** {@link #TYPE_DIMENSION} complex unit: Value is in inches. */ public static final int COMPLEX_UNIT_IN = 4; /** {@link #TYPE_DIMENSION} complex unit: Value is in millimeters. */ public static final int COMPLEX_UNIT_MM = 5; /** * {@link #TYPE_FRACTION} complex unit: A basic fraction of the overall size. */ public static final int COMPLEX_UNIT_FRACTION = 0; /** {@link #TYPE_FRACTION} complex unit: A fraction of the parent size. */ public static final int COMPLEX_UNIT_FRACTION_PARENT = 1; /** * Complex data: where the radix information is, telling where the decimal * place appears in the mantissa. */ public static final int COMPLEX_RADIX_SHIFT = 4; /** * Complex data: mask to extract radix information (after shifting by * {@link #COMPLEX_RADIX_SHIFT}). This give us 4 possible fixed point * representations as defined below. */ public static final int COMPLEX_RADIX_MASK = 0x3; /** Complex data: the mantissa is an integral number -- i.e., 0xnnnnnn.0 */ public static final int COMPLEX_RADIX_23p0 = 0; /** Complex data: the mantissa magnitude is 16 bits -- i.e, 0xnnnn.nn */ public static final int COMPLEX_RADIX_16p7 = 1; /** Complex data: the mantissa magnitude is 8 bits -- i.e, 0xnn.nnnn */ public static final int COMPLEX_RADIX_8p15 = 2; /** Complex data: the mantissa magnitude is 0 bits -- i.e, 0x0.nnnnnn */ public static final int COMPLEX_RADIX_0p23 = 3; /** Complex data: bit location of mantissa information. */ public static final int COMPLEX_MANTISSA_SHIFT = 8; /** * Complex data: mask to extract mantissa information (after shifting by * {@link #COMPLEX_MANTISSA_SHIFT}). This gives us 23 bits of precision; the * top bit is the sign. */ public static final int COMPLEX_MANTISSA_MASK = 0xffffff; /* ------------------------------------------------------------ */ /** * {@link #TYPE_NULL} data indicating the value was not specified. */ public static final int DATA_NULL_UNDEFINED = 0; /** * {@link #TYPE_NULL} data indicating the value was explicitly set to null. */ public static final int DATA_NULL_EMPTY = 1; /* ------------------------------------------------------------ */ /** * If density is equal to this value, then the density should be * treated as the system's default density value: */ public static final int DENSITY_DEFAULT = 0; /** * If density is equal to this value, then there is no density * associated with the resource and it should not be scaled. */ public static final int DENSITY_NONE = 0xffff; /* ------------------------------------------------------------ */ /** * The type held by this value, as defined by the constants here. This tells * you how to interpret the other fields in the object. */ public int type; private static final float MANTISSA_MULT = 1.0f / (1 << TypedValue.COMPLEX_MANTISSA_SHIFT); private static final float[] RADIX_MULTS = new float[] { MANTISSA_MULT, 1.0f / (1 << 7) * MANTISSA_MULT, 1.0f / (1 << 15) * MANTISSA_MULT, 1.0f / (1 << 23) * MANTISSA_MULT }; /** * Retrieve the base value from a complex data integer. This uses the * {@link #COMPLEX_MANTISSA_MASK} and {@link #COMPLEX_RADIX_MASK} fields of * the data to compute a floating point representation of the number they * describe. The units are ignored. * * @param complex * A complex data value. * * @return A floating point value corresponding to the complex data. */ public static float complexToFloat(int complex) { return (complex & (TypedValue.COMPLEX_MANTISSA_MASK << TypedValue.COMPLEX_MANTISSA_SHIFT)) * RADIX_MULTS[(complex >> TypedValue.COMPLEX_RADIX_SHIFT) & TypedValue.COMPLEX_RADIX_MASK]; } private static final String[] DIMENSION_UNIT_STRS = new String[] { "px", "dip", "sp", "pt", "in", "mm" }; private static final String[] FRACTION_UNIT_STRS = new String[] { "%", "%p" }; /** * Perform type conversion as per coerceToString on an explicitly * supplied type and data. * * @param type The data type identifier. * @param data The data value. * * @return String The coerced string value. If the value is null or the type * is not known, null is returned. */ public static String coerceToString(int type, int data) { switch (type) { case TYPE_NULL: return null; case TYPE_REFERENCE: return "@" + data; case TYPE_ATTRIBUTE: return "?" + data; case TYPE_FLOAT: return Float.toString(Float.intBitsToFloat(data)); case TYPE_DIMENSION: return complexToFloat(data) + DIMENSION_UNIT_STRS[(data >> COMPLEX_UNIT_SHIFT) & COMPLEX_UNIT_MASK]; case TYPE_FRACTION: return complexToFloat(data) * 100 + FRACTION_UNIT_STRS[(data >> COMPLEX_UNIT_SHIFT) & COMPLEX_UNIT_MASK]; case TYPE_INT_HEX: return String.format("0x%08X", data); case TYPE_INT_BOOLEAN: return data != 0 ? "true" : "false"; } if (type >= TYPE_FIRST_COLOR_INT && type <= TYPE_LAST_COLOR_INT) { String res = String.format("%08x", data); char[] vals = res.toCharArray(); switch (type) { default: case TYPE_INT_COLOR_ARGB8:// #AaRrGgBb break; case TYPE_INT_COLOR_RGB8:// #FFRrGgBb->#RrGgBb res = res.substring(2); break; case TYPE_INT_COLOR_ARGB4:// #AARRGGBB->#ARGB res = String.valueOf(vals[0]) + vals[2] + vals[4] + vals[6]; break; case TYPE_INT_COLOR_RGB4:// #FFRRGGBB->#RGB res = String.valueOf(vals[2]) + vals[4] + vals[6]; break; } return "#" + res; } else if (type >= TYPE_FIRST_INT && type <= TYPE_LAST_INT) { String res = null; if (type == TYPE_INT_DEC) { res = Integer.toString(data); } return res; } return null; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/AaptInvoker.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib; import brut.androlib.exceptions.AndrolibException; import brut.androlib.apk.ApkInfo; import brut.common.BrutException; import brut.util.AaptManager; import brut.util.OS; import java.io.*; import java.util.*; import java.util.logging.Logger; public class AaptInvoker { private final Config mConfig; private final ApkInfo mApkInfo; private final static Logger LOGGER = Logger.getLogger(AaptInvoker.class.getName()); public AaptInvoker(Config config, ApkInfo apkInfo) { mConfig = config; mApkInfo = apkInfo; } private File getAaptBinaryFile() throws AndrolibException { try { if (getAaptVersion() == 2) { return AaptManager.getAapt2(); } return AaptManager.getAapt1(); } catch (BrutException ex) { throw new AndrolibException(ex); } } private int getAaptVersion() { return mConfig.isAapt2() ? 2 : 1; } private File createDoNotCompressExtensionsFile(ApkInfo apkInfo) throws AndrolibException { if (apkInfo.doNotCompress == null || apkInfo.doNotCompress.isEmpty()) { return null; } File doNotCompressFile; try { doNotCompressFile = File.createTempFile("APKTOOL", null); doNotCompressFile.deleteOnExit(); BufferedWriter fileWriter = new BufferedWriter(new FileWriter(doNotCompressFile)); for (String extension : apkInfo.doNotCompress) { fileWriter.write(extension); fileWriter.newLine(); } fileWriter.close(); return doNotCompressFile; } catch (IOException ex) { throw new AndrolibException(ex); } } private void invokeAapt2(File apkFile, File manifest, File resDir, File rawDir, File assetDir, File[] include, List<String> cmd, boolean customAapt) throws AndrolibException { List<String> compileCommand = new ArrayList<>(cmd); File resourcesZip = null; if (resDir != null) { File buildDir = new File(resDir.getParent(), "build"); resourcesZip = new File(buildDir, "resources.zip"); } if (resDir != null && !resourcesZip.exists()) { // Compile the files into flat arsc files cmd.add("compile"); cmd.add("--dir"); cmd.add(resDir.getAbsolutePath()); // Treats error that used to be valid in aapt1 as warnings in aapt2 cmd.add("--legacy"); File buildDir = new File(resDir.getParent(), "build"); resourcesZip = new File(buildDir, "resources.zip"); cmd.add("-o"); cmd.add(resourcesZip.getAbsolutePath()); if (mConfig.verbose) { cmd.add("-v"); } if (mConfig.noCrunch) { cmd.add("--no-crunch"); } try { OS.exec(cmd.toArray(new String[0])); LOGGER.fine("aapt2 compile command ran: "); LOGGER.fine(cmd.toString()); } catch (BrutException ex) { throw new AndrolibException(ex); } } if (manifest == null) { return; } // Link them into the final apk, reusing our old command after clearing for the aapt2 binary cmd = new ArrayList<>(compileCommand); cmd.add("link"); cmd.add("-o"); cmd.add(apkFile.getAbsolutePath()); if (mApkInfo.packageInfo.forcedPackageId != null && ! mApkInfo.sharedLibrary) { cmd.add("--package-id"); cmd.add(mApkInfo.packageInfo.forcedPackageId); } if (mApkInfo.sharedLibrary) { cmd.add("--shared-lib"); } if (mApkInfo.getMinSdkVersion() != null) { cmd.add("--min-sdk-version"); cmd.add(mApkInfo.getMinSdkVersion() ); } if (mApkInfo.getTargetSdkVersion() != null) { cmd.add("--target-sdk-version"); cmd.add(mApkInfo.checkTargetSdkVersionBounds()); } if (mApkInfo.packageInfo.renameManifestPackage != null) { cmd.add("--rename-manifest-package"); cmd.add(mApkInfo.packageInfo.renameManifestPackage); cmd.add("--rename-instrumentation-target-package"); cmd.add(mApkInfo.packageInfo.renameManifestPackage); } if (mApkInfo.versionInfo.versionCode != null) { cmd.add("--version-code"); cmd.add(mApkInfo.versionInfo.versionCode); } if (mApkInfo.versionInfo.versionName != null) { cmd.add("--version-name"); cmd.add(mApkInfo.versionInfo.versionName); } // Disable automatic changes cmd.add("--no-auto-version"); cmd.add("--no-version-vectors"); cmd.add("--no-version-transitions"); cmd.add("--no-resource-deduping"); cmd.add("--allow-reserved-package-id"); cmd.add("--no-compile-sdk-metadata"); if (mApkInfo.sparseResources) { cmd.add("--enable-sparse-encoding"); } if (mApkInfo.isFrameworkApk) { cmd.add("-x"); } if (mApkInfo.doNotCompress != null && !customAapt) { // Use custom -e option to avoid limits on commandline length. // Can only be used when custom aapt binary is not used. String extensionsFilePath = Objects.requireNonNull(createDoNotCompressExtensionsFile(mApkInfo)).getAbsolutePath(); cmd.add("-e"); cmd.add(extensionsFilePath); } else if (mApkInfo.doNotCompress != null) { for (String file : mApkInfo.doNotCompress) { cmd.add("-0"); cmd.add(file); } } if (!mApkInfo.resourcesAreCompressed) { cmd.add("-0"); cmd.add("arsc"); } if (include != null) { for (File file : include) { cmd.add("-I"); cmd.add(file.getPath()); } } cmd.add("--manifest"); cmd.add(manifest.getAbsolutePath()); if (assetDir != null) { cmd.add("-A"); cmd.add(assetDir.getAbsolutePath()); } if (rawDir != null) { cmd.add("-R"); cmd.add(rawDir.getAbsolutePath()); } if (mConfig.verbose) { cmd.add("-v"); } if (resourcesZip != null) { cmd.add(resourcesZip.getAbsolutePath()); } try { OS.exec(cmd.toArray(new String[0])); LOGGER.fine("aapt2 link command ran: "); LOGGER.fine(cmd.toString()); } catch (BrutException ex) { throw new AndrolibException(ex); } } private void invokeAapt1(File apkFile, File manifest, File resDir, File rawDir, File assetDir, File[] include, List<String> cmd, boolean customAapt) throws AndrolibException { cmd.add("p"); if (mConfig.verbose) { // output aapt verbose cmd.add("-v"); } if (mConfig.updateFiles) { cmd.add("-u"); } if (mConfig.debugMode) { // inject debuggable="true" into manifest cmd.add("--debug-mode"); } if (mConfig.noCrunch) { cmd.add("--no-crunch"); } // force package id so that some frameworks build with correct id // disable if user adds own aapt (can't know if they have this feature) if (mApkInfo.packageInfo.forcedPackageId != null && ! customAapt && ! mApkInfo.sharedLibrary) { cmd.add("--forced-package-id"); cmd.add(mApkInfo.packageInfo.forcedPackageId); } if (mApkInfo.sharedLibrary) { cmd.add("--shared-lib"); } if (mApkInfo.getMinSdkVersion() != null) { cmd.add("--min-sdk-version"); cmd.add(mApkInfo.getMinSdkVersion()); } if (mApkInfo.getTargetSdkVersion() != null) { cmd.add("--target-sdk-version"); // Ensure that targetSdkVersion is between minSdkVersion/maxSdkVersion if // they are specified. cmd.add(mApkInfo.checkTargetSdkVersionBounds()); } if (mApkInfo.getMaxSdkVersion() != null) { cmd.add("--max-sdk-version"); cmd.add(mApkInfo.getMaxSdkVersion()); // if we have max sdk version, set --max-res-version, // so we can ignore anything over that during build. cmd.add("--max-res-version"); cmd.add(mApkInfo.getMaxSdkVersion()); } if (mApkInfo.packageInfo.renameManifestPackage != null) { cmd.add("--rename-manifest-package"); cmd.add(mApkInfo.packageInfo.renameManifestPackage); } if (mApkInfo.versionInfo.versionCode != null) { cmd.add("--version-code"); cmd.add(mApkInfo.versionInfo.versionCode); } if (mApkInfo.versionInfo.versionName != null) { cmd.add("--version-name"); cmd.add(mApkInfo.versionInfo.versionName); } cmd.add("--no-version-vectors"); cmd.add("-F"); cmd.add(apkFile.getAbsolutePath()); if (mApkInfo.isFrameworkApk) { cmd.add("-x"); } if (mApkInfo.doNotCompress != null && !customAapt) { // Use custom -e option to avoid limits on commandline length. // Can only be used when custom aapt binary is not used. String extensionsFilePath = Objects.requireNonNull(createDoNotCompressExtensionsFile(mApkInfo)).getAbsolutePath(); cmd.add("-e"); cmd.add(extensionsFilePath); } else if (mApkInfo.doNotCompress != null) { for (String file : mApkInfo.doNotCompress) { cmd.add("-0"); cmd.add(file); } } if (!mApkInfo.resourcesAreCompressed) { cmd.add("-0"); cmd.add("arsc"); } if (include != null) { for (File file : include) { cmd.add("-I"); cmd.add(file.getPath()); } } if (resDir != null) { cmd.add("-S"); cmd.add(resDir.getAbsolutePath()); } if (manifest != null) { cmd.add("-M"); cmd.add(manifest.getAbsolutePath()); } if (assetDir != null) { cmd.add("-A"); cmd.add(assetDir.getAbsolutePath()); } if (rawDir != null) { cmd.add(rawDir.getAbsolutePath()); } try { OS.exec(cmd.toArray(new String[0])); LOGGER.fine("command ran: "); LOGGER.fine(cmd.toString()); } catch (BrutException ex) { throw new AndrolibException(ex); } } public void invokeAapt(File apkFile, File manifest, File resDir, File rawDir, File assetDir, File[] include) throws AndrolibException { String aaptPath = mConfig.aaptPath; boolean customAapt = !aaptPath.isEmpty(); List<String> cmd = new ArrayList<>(); try { String aaptCommand = AaptManager.getAaptExecutionCommand(aaptPath, getAaptBinaryFile()); cmd.add(aaptCommand); } catch (BrutException ex) { LOGGER.warning("aapt: " + ex.getMessage() + " (defaulting to $PATH binary)"); cmd.add(AaptManager.getAaptBinaryName(getAaptVersion())); } if (mConfig.isAapt2()) { invokeAapt2(apkFile, manifest, resDir, rawDir, assetDir, include, cmd, customAapt); return; } invokeAapt1(apkFile, manifest, resDir, rawDir, assetDir, include, cmd, customAapt); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/ApkBuilder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib; import brut.androlib.exceptions.AndrolibException; import brut.androlib.apk.ApkInfo; import brut.androlib.apk.UsesFramework; import brut.androlib.res.Framework; import brut.androlib.res.data.ResConfigFlags; import brut.androlib.res.xml.ResXmlPatcher; import brut.androlib.src.SmaliBuilder; import brut.common.BrutException; import brut.common.InvalidUnknownFileException; import brut.common.RootUnknownFileException; import brut.common.TraversalUnknownFileException; import brut.directory.Directory; import brut.directory.DirectoryException; import brut.directory.ExtFile; import brut.directory.ZipUtils; import brut.util.BrutIO; import brut.util.OS; import org.apache.commons.io.FileUtils; import org.apache.commons.io.IOUtils; import org.xml.sax.SAXException; import javax.xml.parsers.ParserConfigurationException; import javax.xml.transform.TransformerException; import java.io.*; import java.nio.file.Files; import java.util.*; import java.util.logging.Logger; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; public class ApkBuilder { private final static Logger LOGGER = Logger.getLogger(ApkBuilder.class.getName()); private final Config mConfig; private final ExtFile mApkDir; private ApkInfo mApkInfo; private int mMinSdkVersion = 0; private final static String APK_DIRNAME = "build/apk"; private final static String UNK_DIRNAME = "unknown"; private final static String[] APK_RESOURCES_FILENAMES = new String[] { "resources.arsc", "AndroidManifest.xml", "res", "r", "R" }; private final static String[] APK_RESOURCES_WITHOUT_RES_FILENAMES = new String[] { "resources.arsc", "AndroidManifest.xml" }; private final static String[] APP_RESOURCES_FILENAMES = new String[] { "AndroidManifest.xml", "res" }; private final static String[] APK_MANIFEST_FILENAMES = new String[] { "AndroidManifest.xml" }; public ApkBuilder(ExtFile apkDir) { this(Config.getDefaultConfig(), apkDir); } public ApkBuilder(Config config, ExtFile apkDir) { mConfig = config; mApkDir = apkDir; } public void build(File outFile) throws BrutException { LOGGER.info("Using Apktool " + ApktoolProperties.getVersion()); mApkInfo = ApkInfo.load(mApkDir); if (mApkInfo.getSdkInfo() != null && mApkInfo.getSdkInfo().get("minSdkVersion") != null) { String minSdkVersion = mApkInfo.getSdkInfo().get("minSdkVersion"); mMinSdkVersion = mApkInfo.getMinSdkVersionFromAndroidCodename(minSdkVersion); } if (outFile == null) { String outFileName = mApkInfo.apkFileName; outFile = new File(mApkDir, "dist" + File.separator + (outFileName == null ? "out.apk" : outFileName)); } //noinspection ResultOfMethodCallIgnored new File(mApkDir, APK_DIRNAME).mkdirs(); File manifest = new File(mApkDir, "AndroidManifest.xml"); File manifestOriginal = new File(mApkDir, "AndroidManifest.xml.orig"); buildSources(); buildNonDefaultSources(); buildManifestFile(manifest, manifestOriginal); buildResources(); buildLibs(); buildCopyOriginalFiles(); buildApk(outFile); // we must go after the Apk is built, and copy the files in via Zip // this is because Aapt won't add files it doesn't know (ex unknown files) buildUnknownFiles(outFile); // we copied the AndroidManifest.xml to AndroidManifest.xml.orig so we can edit it // lets restore the unedited one, to not change the original if (manifest.isFile() && manifest.exists() && manifestOriginal.isFile()) { try { if (new File(mApkDir, "AndroidManifest.xml").delete()) { FileUtils.moveFile(manifestOriginal, manifest); } } catch (IOException ex) { throw new AndrolibException(ex.getMessage()); } } LOGGER.info("Built apk into: " + outFile.getPath()); } private void buildManifestFile(File manifest, File manifestOriginal) throws AndrolibException { // If we decoded in "raw", we cannot patch AndroidManifest if (new File(mApkDir, "resources.arsc").exists()) { return; } if (manifest.isFile() && manifest.exists()) { try { if (manifestOriginal.exists()) { //noinspection ResultOfMethodCallIgnored manifestOriginal.delete(); } FileUtils.copyFile(manifest, manifestOriginal); ResXmlPatcher.fixingPublicAttrsInProviderAttributes(manifest); } catch (IOException ex) { throw new AndrolibException(ex.getMessage()); } } } private void buildSources() throws AndrolibException { if (!buildSourcesRaw("classes.dex") && !buildSourcesSmali("smali", "classes.dex")) { LOGGER.warning("Could not find sources"); } } private void buildNonDefaultSources() throws AndrolibException { try { // loop through any smali_ directories for multi-dex apks Map<String, Directory> dirs = mApkDir.getDirectory().getDirs(); for (Map.Entry<String, Directory> directory : dirs.entrySet()) { String name = directory.getKey(); if (name.startsWith("smali_")) { String filename = name.substring(name.indexOf("_") + 1) + ".dex"; if (!buildSourcesRaw(filename) && !buildSourcesSmali(name, filename)) { LOGGER.warning("Could not find sources"); } } } // loop through any classes#.dex files for multi-dex apks File[] dexFiles = mApkDir.listFiles(); if (dexFiles != null) { for (File dex : dexFiles) { // skip classes.dex because we have handled it in buildSources() if (dex.getName().endsWith(".dex") && !dex.getName().equalsIgnoreCase("classes.dex")) { buildSourcesRaw(dex.getName()); } } } } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private boolean buildSourcesRaw(String filename) throws AndrolibException { File working = new File(mApkDir, filename); if (!working.exists()) { return false; } File stored = new File(mApkDir, APK_DIRNAME + "/" + filename); if (mConfig.forceBuildAll || isModified(working, stored)) { LOGGER.info("Copying " + mApkDir.toString() + " " + filename + " file..."); try { BrutIO.copyAndClose(Files.newInputStream(working.toPath()), Files.newOutputStream(stored.toPath())); return true; } catch (IOException ex) { throw new AndrolibException(ex); } } return true; } private boolean buildSourcesSmali(String folder, String filename) throws AndrolibException { ExtFile smaliDir = new ExtFile(mApkDir, folder); if (!smaliDir.exists()) { return false; } File dex = new File(mApkDir, APK_DIRNAME + "/" + filename); if (!mConfig.forceBuildAll) { LOGGER.info("Checking whether sources has changed..."); } if (mConfig.forceBuildAll || isModified(smaliDir, dex)) { LOGGER.info("Smaling " + folder + " folder into " + filename + "..."); //noinspection ResultOfMethodCallIgnored dex.delete(); SmaliBuilder.build(smaliDir, dex, mConfig.forceApi > 0 ? mConfig.forceApi : mMinSdkVersion); } return true; } private void buildResources() throws BrutException { if (!buildResourcesRaw() && !buildResourcesFull() && !buildManifest()) { LOGGER.warning("Could not find resources"); } } private boolean buildResourcesRaw() throws AndrolibException { try { if (!new File(mApkDir, "resources.arsc").exists()) { return false; } File apkDir = new File(mApkDir, APK_DIRNAME); if (!mConfig.forceBuildAll) { LOGGER.info("Checking whether resources has changed..."); } if (mConfig.forceBuildAll || isModified(newFiles(APK_RESOURCES_FILENAMES, mApkDir), newFiles(APK_RESOURCES_FILENAMES, apkDir))) { LOGGER.info("Copying raw resources..."); mApkDir.getDirectory().copyToDir(apkDir, APK_RESOURCES_FILENAMES); } return true; } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private boolean buildResourcesFull() throws AndrolibException { try { if (!new File(mApkDir, "res").exists()) { return false; } if (!mConfig.forceBuildAll) { LOGGER.info("Checking whether resources has changed..."); } File apkDir = new File(mApkDir, APK_DIRNAME); File resourceFile = new File(apkDir.getParent(), "resources.zip"); if (mConfig.forceBuildAll || isModified(newFiles(APP_RESOURCES_FILENAMES, mApkDir), newFiles(APK_RESOURCES_FILENAMES, apkDir)) || (mConfig.isAapt2() && !isFile(resourceFile))) { LOGGER.info("Building resources..."); if (mConfig.debugMode) { if (mConfig.isAapt2()) { LOGGER.info("Using aapt2 - setting 'debuggable' attribute to 'true' in AndroidManifest.xml"); ResXmlPatcher.setApplicationDebugTagTrue(new File(mApkDir, "AndroidManifest.xml")); } else { ResXmlPatcher.removeApplicationDebugTag(new File(mApkDir, "AndroidManifest.xml")); } } if (mConfig.netSecConf) { ApkInfo meta = ApkInfo.load(new ExtFile(mApkDir)); if (meta.getSdkInfo() != null && meta.getSdkInfo().get("targetSdkVersion") != null) { if (Integer.parseInt(meta.getSdkInfo().get("targetSdkVersion")) < ResConfigFlags.SDK_NOUGAT) { LOGGER.warning("Target SDK version is lower than 24! Network Security Configuration might be ignored!"); } } File netSecConfOrig = new File(mApkDir, "res/xml/network_security_config.xml"); if (netSecConfOrig.exists()) { LOGGER.info("Replacing existing network_security_config.xml!"); //noinspection ResultOfMethodCallIgnored netSecConfOrig.delete(); } ResXmlPatcher.modNetworkSecurityConfig(netSecConfOrig); ResXmlPatcher.setNetworkSecurityConfig(new File(mApkDir, "AndroidManifest.xml")); LOGGER.info("Added permissive network security config in manifest"); } File apkFile = File.createTempFile("APKTOOL", null); //noinspection ResultOfMethodCallIgnored apkFile.delete(); //noinspection ResultOfMethodCallIgnored resourceFile.delete(); File ninePatch = new File(mApkDir, "9patch"); if (!ninePatch.exists()) { ninePatch = null; } AaptInvoker invoker = new AaptInvoker(mConfig, mApkInfo); invoker.invokeAapt(apkFile, new File(mApkDir, "AndroidManifest.xml"), new File(mApkDir, "res"), ninePatch, null, getIncludeFiles()); ExtFile tmpExtFile = new ExtFile(apkFile); Directory tmpDir = tmpExtFile.getDirectory(); // Sometimes an application is built with a resources.arsc file with no resources, // Apktool assumes it will have a rebuilt arsc file, when it doesn't. So if we // encounter a copy error, move to a warning and continue on. (#1730) try { tmpDir.copyToDir(apkDir, tmpDir.containsDir("res") ? APK_RESOURCES_FILENAMES : APK_RESOURCES_WITHOUT_RES_FILENAMES); } catch (DirectoryException ex) { LOGGER.warning(ex.getMessage()); } finally { tmpExtFile.close(); } // delete tmpDir //noinspection ResultOfMethodCallIgnored apkFile.delete(); } return true; } catch (IOException | BrutException | ParserConfigurationException | TransformerException | SAXException ex) { throw new AndrolibException(ex); } } private boolean buildManifestRaw() throws AndrolibException { try { File apkDir = new File(mApkDir, APK_DIRNAME); LOGGER.info("Copying raw AndroidManifest.xml..."); mApkDir.getDirectory().copyToDir(apkDir, APK_MANIFEST_FILENAMES); return true; } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private boolean buildManifest() throws BrutException { try { if (!new File(mApkDir, "AndroidManifest.xml").exists()) { return false; } if (!mConfig.forceBuildAll) { LOGGER.info("Checking whether resources has changed..."); } File apkDir = new File(mApkDir, APK_DIRNAME); if (mConfig.forceBuildAll || isModified(newFiles(APK_MANIFEST_FILENAMES, mApkDir), newFiles(APK_MANIFEST_FILENAMES, apkDir))) { LOGGER.info("Building AndroidManifest.xml..."); File apkFile = File.createTempFile("APKTOOL", null); //noinspection ResultOfMethodCallIgnored apkFile.delete(); File ninePatch = new File(mApkDir, "9patch"); if (!ninePatch.exists()) { ninePatch = null; } AaptInvoker invoker = new AaptInvoker(mConfig, mApkInfo); invoker.invokeAapt(apkFile, new File(mApkDir, "AndroidManifest.xml"), null, ninePatch, null, getIncludeFiles()); Directory tmpDir = new ExtFile(apkFile).getDirectory(); tmpDir.copyToDir(apkDir, APK_MANIFEST_FILENAMES); //noinspection ResultOfMethodCallIgnored apkFile.delete(); } return true; } catch (IOException | DirectoryException ex) { throw new AndrolibException(ex); } catch (AndrolibException ex) { LOGGER.warning("Parse AndroidManifest.xml failed, treat it as raw file."); return buildManifestRaw(); } } private void buildLibs() throws AndrolibException { buildLibrary("lib"); buildLibrary("libs"); buildLibrary("kotlin"); buildLibrary("META-INF/services"); } private void buildLibrary(String folder) throws AndrolibException { File working = new File(mApkDir, folder); if (!working.exists()) { return; } File stored = new File(mApkDir, APK_DIRNAME + "/" + folder); if (mConfig.forceBuildAll || isModified(working, stored)) { LOGGER.info("Copying libs... (/" + folder + ")"); try { OS.rmdir(stored); OS.cpdir(working, stored); } catch (BrutException ex) { throw new AndrolibException(ex); } } } private void buildCopyOriginalFiles() throws AndrolibException { if (mConfig.copyOriginalFiles) { File originalDir = new File(mApkDir, "original"); if (originalDir.exists()) { try { LOGGER.info("Copy original files..."); Directory in = (new ExtFile(originalDir)).getDirectory(); if (in.containsFile("AndroidManifest.xml")) { LOGGER.info("Copy AndroidManifest.xml..."); in.copyToDir(new File(mApkDir, APK_DIRNAME), "AndroidManifest.xml"); } if (in.containsFile("stamp-cert-sha256")) { LOGGER.info("Copy stamp-cert-sha256..."); in.copyToDir(new File(mApkDir, APK_DIRNAME), "stamp-cert-sha256"); } if (in.containsDir("META-INF")) { LOGGER.info("Copy META-INF..."); in.copyToDir(new File(mApkDir, APK_DIRNAME), "META-INF"); } } catch (DirectoryException ex) { throw new AndrolibException(ex); } } } } private void buildUnknownFiles(File outFile) throws AndrolibException { if (mApkInfo.unknownFiles != null) { LOGGER.info("Copying unknown files/dir..."); Map<String, String> files = mApkInfo.unknownFiles; File tempFile = new File(outFile.getParent(), outFile.getName() + ".apktool_temp"); boolean renamed = outFile.renameTo(tempFile); if (!renamed) { throw new AndrolibException("Unable to rename temporary file"); } try ( ZipFile inputFile = new ZipFile(tempFile); ZipOutputStream actualOutput = new ZipOutputStream(Files.newOutputStream(outFile.toPath())) ) { copyExistingFiles(inputFile, actualOutput); copyUnknownFiles(actualOutput, files); } catch (IOException | BrutException ex) { throw new AndrolibException(ex); } // Remove our temporary file. //noinspection ResultOfMethodCallIgnored tempFile.delete(); } } private void copyExistingFiles(ZipFile inputFile, ZipOutputStream outputFile) throws IOException { // First, copy the contents from the existing outFile: Enumeration<? extends ZipEntry> entries = inputFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = new ZipEntry(entries.nextElement()); // We can't reuse the compressed size because it depends on compression sizes. entry.setCompressedSize(-1); outputFile.putNextEntry(entry); // No need to create directory entries in the final apk if (!entry.isDirectory()) { BrutIO.copy(inputFile, outputFile, entry); } outputFile.closeEntry(); } } private void copyUnknownFiles(ZipOutputStream outputFile, Map<String, String> files) throws BrutException, IOException { File unknownFileDir = new File(mApkDir, UNK_DIRNAME); // loop through unknown files for (Map.Entry<String,String> unknownFileInfo : files.entrySet()) { File inputFile; try { inputFile = new File(unknownFileDir, BrutIO.sanitizeUnknownFile(unknownFileDir, unknownFileInfo.getKey())); } catch (RootUnknownFileException | InvalidUnknownFileException | TraversalUnknownFileException exception) { LOGGER.warning(String.format("Skipping file %s (%s)", unknownFileInfo.getKey(), exception.getMessage())); continue; } if (inputFile.isDirectory()) { continue; } ZipEntry newEntry = new ZipEntry(unknownFileInfo.getKey()); int method = Integer.parseInt(unknownFileInfo.getValue()); LOGGER.fine(String.format("Copying unknown file %s with method %d", unknownFileInfo.getKey(), method)); if (method == ZipEntry.STORED) { newEntry.setMethod(ZipEntry.STORED); newEntry.setSize(inputFile.length()); newEntry.setCompressedSize(-1); BufferedInputStream unknownFile = new BufferedInputStream(Files.newInputStream(inputFile.toPath())); CRC32 crc = BrutIO.calculateCrc(unknownFile); newEntry.setCrc(crc.getValue()); unknownFile.close(); } else { newEntry.setMethod(ZipEntry.DEFLATED); } outputFile.putNextEntry(newEntry); BrutIO.copy(inputFile, outputFile); outputFile.closeEntry(); } } private void buildApk(File outApk) throws AndrolibException { LOGGER.info("Building apk file..."); if (outApk.exists()) { //noinspection ResultOfMethodCallIgnored outApk.delete(); } else { File outDir = outApk.getParentFile(); if (outDir != null && !outDir.exists()) { //noinspection ResultOfMethodCallIgnored outDir.mkdirs(); } } File assetDir = new File(mApkDir, "assets"); if (!assetDir.exists()) { assetDir = null; } zipPackage(outApk, new File(mApkDir, APK_DIRNAME), assetDir); } private void zipPackage(File apkFile, File rawDir, File assetDir) throws AndrolibException { try { ZipUtils.zipFolders(rawDir, apkFile, assetDir, mApkInfo.doNotCompress); } catch (IOException | BrutException ex) { throw new AndrolibException(ex); } } private File[] getIncludeFiles() throws AndrolibException { UsesFramework usesFramework = mApkInfo.usesFramework; if (usesFramework == null) { return null; } List<Integer> ids = usesFramework.ids; if (ids == null || ids.isEmpty()) { return null; } Framework framework = new Framework(mConfig); String tag = usesFramework.tag; File[] files = new File[ids.size()]; int i = 0; for (int id : ids) { files[i++] = framework.getFrameworkApk(id, tag); } return files; } private boolean isModified(File working, File stored) { return !stored.exists() || BrutIO.recursiveModifiedTime(working) > BrutIO .recursiveModifiedTime(stored); } private boolean isFile(File working) { return working.exists(); } private boolean isModified(File[] working, File[] stored) { for (File file : stored) { if (!file.exists()) { return true; } } return BrutIO.recursiveModifiedTime(working) > BrutIO.recursiveModifiedTime(stored); } private File[] newFiles(String[] names, File dir) { File[] files = new File[names.length]; for (int i = 0; i < names.length; i++) { files[i] = new File(dir, names[i]); } return files; } public boolean detectWhetherAppIsFramework() throws AndrolibException { File publicXml = new File(mApkDir, "res/values/public.xml"); if (!publicXml.exists()) { return false; } Iterator<String> it; try { it = IOUtils.lineIterator(new FileReader(new File(mApkDir, "res/values/public.xml"))); } catch (FileNotFoundException ex) { throw new AndrolibException( "Could not detect whether app is framework one", ex); } it.next(); it.next(); return it.next().contains("0x01"); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/ApkDecoder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.InFileNotFoundException; import brut.androlib.exceptions.OutDirExistsException; import brut.androlib.apk.ApkInfo; import brut.androlib.res.ResourcesDecoder; import brut.androlib.src.SmaliDecoder; import brut.directory.Directory; import brut.directory.ExtFile; import brut.common.BrutException; import brut.directory.DirectoryException; import brut.util.OS; import com.android.tools.smali.dexlib2.iface.DexFile; import org.apache.commons.io.FilenameUtils; import java.io.*; import java.util.*; import java.util.logging.Logger; import java.util.regex.Pattern; public class ApkDecoder { private final static Logger LOGGER = Logger.getLogger(ApkDecoder.class.getName()); private final Config mConfig; private final ApkInfo mApkInfo; private int mMinSdkVersion = 0; private final static String SMALI_DIRNAME = "smali"; private final static String UNK_DIRNAME = "unknown"; private final static String[] APK_STANDARD_ALL_FILENAMES = new String[] { "classes.dex", "AndroidManifest.xml", "resources.arsc", "res", "r", "R", "lib", "libs", "assets", "META-INF", "kotlin" }; private final static String[] APK_RESOURCES_FILENAMES = new String[] { "resources.arsc", "res", "r", "R" }; private final static String[] APK_MANIFEST_FILENAMES = new String[] { "AndroidManifest.xml" }; private final static Pattern NO_COMPRESS_PATTERN = Pattern.compile("(" + "jpg|jpeg|png|gif|wav|mp2|mp3|ogg|aac|mpg|mpeg|mid|midi|smf|jet|rtttl|imy|xmf|mp4|" + "m4a|m4v|3gp|3gpp|3g2|3gpp2|amr|awb|wma|wmv|webm|webp|mkv)$"); public ApkDecoder(File apkFile) { this(Config.getDefaultConfig(), new ExtFile(apkFile)); } public ApkDecoder(ExtFile apkFile) { this(Config.getDefaultConfig(), apkFile); } public ApkDecoder(Config config, File apkFile) { this(config, new ExtFile(apkFile)); } public ApkDecoder(Config config, ExtFile apkFile) { mConfig = config; mApkInfo = new ApkInfo(apkFile); } public ApkInfo decode(File outDir) throws AndrolibException, IOException, DirectoryException { ExtFile apkFile = mApkInfo.getApkFile(); try { if (!mConfig.forceDelete && outDir.exists()) { throw new OutDirExistsException(); } if (!apkFile.isFile() || !apkFile.canRead()) { throw new InFileNotFoundException(); } try { OS.rmdir(outDir); } catch (BrutException ex) { throw new AndrolibException(ex); } outDir.mkdirs(); LOGGER.info("Using Apktool " + ApktoolProperties.getVersion() + " on " + mApkInfo.apkFileName); ResourcesDecoder resourcesDecoder = new ResourcesDecoder(mConfig, mApkInfo); if (mApkInfo.hasResources()) { switch (mConfig.decodeResources) { case Config.DECODE_RESOURCES_NONE: copyResourcesRaw(outDir); break; case Config.DECODE_RESOURCES_FULL: resourcesDecoder.decodeResources(outDir); break; } } if (mApkInfo.hasManifest()) { if (mConfig.decodeResources == Config.DECODE_RESOURCES_FULL || mConfig.forceDecodeManifest == Config.FORCE_DECODE_MANIFEST_FULL) { resourcesDecoder.decodeManifest(outDir); } else { copyManifestRaw(outDir); } } resourcesDecoder.updateApkInfo(outDir); if (mApkInfo.hasSources()) { switch (mConfig.decodeSources) { case Config.DECODE_SOURCES_NONE: copySourcesRaw(outDir, "classes.dex"); break; case Config.DECODE_SOURCES_SMALI: case Config.DECODE_SOURCES_SMALI_ONLY_MAIN_CLASSES: decodeSourcesSmali(outDir, "classes.dex"); break; } } if (mApkInfo.hasMultipleSources()) { // foreach unknown dex file in root, lets disassemble it Set<String> files = apkFile.getDirectory().getFiles(true); for (String file : files) { if (file.endsWith(".dex")) { if (!file.equalsIgnoreCase("classes.dex")) { switch(mConfig.decodeSources) { case Config.DECODE_SOURCES_NONE: copySourcesRaw(outDir, file); break; case Config.DECODE_SOURCES_SMALI: decodeSourcesSmali(outDir, file); break; case Config.DECODE_SOURCES_SMALI_ONLY_MAIN_CLASSES: if (file.startsWith("classes") && file.endsWith(".dex")) { decodeSourcesSmali(outDir, file); } else { copySourcesRaw(outDir, file); } break; } } } } } // In case we have no resources. We should store the minSdk we pulled from the source opcode api level if (!mApkInfo.hasResources() && mMinSdkVersion > 0) { mApkInfo.setSdkInfoField("minSdkVersion", Integer.toString(mMinSdkVersion)); } copyRawFiles(outDir); copyUnknownFiles(outDir); recordUncompressedFiles(resourcesDecoder.getResFileMapping()); copyOriginalFiles(outDir); writeApkInfo(outDir); return mApkInfo; } finally { try { apkFile.close(); } catch (IOException ignored) {} } } private void writeApkInfo(File outDir) throws AndrolibException { mApkInfo.save(new File(outDir, "apktool.yml")); } private void copyManifestRaw(File outDir) throws AndrolibException { try { LOGGER.info("Copying raw manifest..."); mApkInfo.getApkFile().getDirectory().copyToDir(outDir, APK_MANIFEST_FILENAMES); } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private void copyResourcesRaw(File outDir) throws AndrolibException { try { LOGGER.info("Copying raw resources..."); mApkInfo.getApkFile().getDirectory().copyToDir(outDir, APK_RESOURCES_FILENAMES); } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private void copySourcesRaw(File outDir, String filename) throws AndrolibException { try { LOGGER.info("Copying raw " + filename + " file..."); mApkInfo.getApkFile().getDirectory().copyToDir(outDir, filename); } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private void decodeSourcesSmali(File outDir, String filename) throws AndrolibException { try { File smaliDir; if (filename.equalsIgnoreCase("classes.dex")) { smaliDir = new File(outDir, SMALI_DIRNAME); } else { smaliDir = new File(outDir, SMALI_DIRNAME + "_" + filename.substring(0, filename.indexOf("."))); } OS.rmdir(smaliDir); //noinspection ResultOfMethodCallIgnored smaliDir.mkdirs(); LOGGER.info("Baksmaling " + filename + "..."); DexFile dexFile = SmaliDecoder.decode(mApkInfo.getApkFile(), smaliDir, filename, mConfig.baksmaliDebugMode, mConfig.apiLevel); int minSdkVersion = dexFile.getOpcodes().api; if (mMinSdkVersion == 0 || mMinSdkVersion > minSdkVersion) { mMinSdkVersion = minSdkVersion; } } catch (BrutException ex) { throw new AndrolibException(ex); } } private void copyRawFiles(File outDir) throws AndrolibException { LOGGER.info("Copying assets and libs..."); try { Directory in = mApkInfo.getApkFile().getDirectory(); if (mConfig.decodeAssets == Config.DECODE_ASSETS_FULL) { if (in.containsDir("assets")) { in.copyToDir(outDir, "assets"); } } if (in.containsDir("lib")) { in.copyToDir(outDir, "lib"); } if (in.containsDir("libs")) { in.copyToDir(outDir, "libs"); } if (in.containsDir("kotlin")) { in.copyToDir(outDir, "kotlin"); } } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private boolean isAPKFileNames(String file) { for (String apkFile : APK_STANDARD_ALL_FILENAMES) { if (apkFile.equals(file) || file.startsWith(apkFile + "/")) { return true; } } return false; } private void copyUnknownFiles(File outDir) throws AndrolibException { LOGGER.info("Copying unknown files..."); File unknownOut = new File(outDir, UNK_DIRNAME); try { Directory unk = mApkInfo.getApkFile().getDirectory(); // loop all items in container recursively, ignoring any that are pre-defined by aapt Set<String> files = unk.getFiles(true); for (String file : files) { if (!isAPKFileNames(file) && !file.endsWith(".dex")) { // copy file out of archive into special "unknown" folder unk.copyToDir(unknownOut, file); // let's record the name of the file, and its compression type // so that we may re-include it the same way mApkInfo.addUnknownFileInfo(file, String.valueOf(unk.getCompressionLevel(file))); } } } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private void copyOriginalFiles(File outDir) throws AndrolibException { LOGGER.info("Copying original files..."); File originalDir = new File(outDir, "original"); if (!originalDir.exists()) { //noinspection ResultOfMethodCallIgnored originalDir.mkdirs(); } try { Directory in = mApkInfo.getApkFile().getDirectory(); if (in.containsFile("AndroidManifest.xml")) { in.copyToDir(originalDir, "AndroidManifest.xml"); } if (in.containsFile("stamp-cert-sha256")) { in.copyToDir(originalDir, "stamp-cert-sha256"); } if (in.containsDir("META-INF")) { in.copyToDir(originalDir, "META-INF"); if (in.containsDir("META-INF/services")) { // If the original APK contains the folder META-INF/services folder // that is used for service locators (like coroutines on android), // copy it to the destination folder, so it does not get dropped. LOGGER.info("Copying META-INF/services directory"); in.copyToDir(outDir, "META-INF/services"); } } } catch (DirectoryException ex) { throw new AndrolibException(ex); } } private void recordUncompressedFiles(Map<String, String> resFileMapping) throws AndrolibException { try { List<String> uncompressedFilesOrExts = new ArrayList<>(); Directory unk = mApkInfo.getApkFile().getDirectory(); Set<String> files = unk.getFiles(true); for (String file : files) { if (isAPKFileNames(file) && unk.getCompressionLevel(file) == 0) { String extOrFile = ""; if (unk.getSize(file) != 0) { extOrFile = FilenameUtils.getExtension(file); } if (extOrFile.isEmpty() || !NO_COMPRESS_PATTERN.matcher(extOrFile).find()) { extOrFile = file; if (resFileMapping.containsKey(extOrFile)) { extOrFile = resFileMapping.get(extOrFile); } } if (!uncompressedFilesOrExts.contains(extOrFile)) { uncompressedFilesOrExts.add(extOrFile); } } } // update apk info if (!uncompressedFilesOrExts.isEmpty()) { mApkInfo.doNotCompress = uncompressedFilesOrExts; } } catch (DirectoryException ex) { throw new AndrolibException(ex); } } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/ApktoolProperties.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import java.util.logging.Logger; public class ApktoolProperties { private static final Logger LOGGER = Logger.getLogger(ApktoolProperties.class.getName()); private static Properties sProps; public static String get(String key) { return get().getProperty(key); } public static Properties get() { if (sProps == null) { loadProps(); } return sProps; } public static String getVersion() { return get("application.version"); } private static void loadProps() { InputStream in = ApktoolProperties.class.getResourceAsStream("/properties/apktool.properties"); sProps = new Properties(); try { sProps.load(in); in.close(); } catch (IOException ex) { LOGGER.warning("Can't load properties."); } InputStream templateStream = null; try { templateStream = com.android.tools.smali.baksmali.Main.class.getClassLoader().getResourceAsStream("baksmali.properties"); } catch(NoClassDefFoundError ex) { LOGGER.warning("Can't load baksmali properties."); } Properties properties = new Properties(); String version = "(unknown)"; if (templateStream != null) { try { properties.load(templateStream); version = properties.getProperty("application.version"); templateStream.close(); } catch (IOException ignored) { } } sProps.put("baksmaliVersion", version); templateStream = null; try { templateStream = com.android.tools.smali.smali.Main.class.getClassLoader().getResourceAsStream("smali.properties"); } catch(NoClassDefFoundError ex) { LOGGER.warning("Can't load smali properties."); } properties = new Properties(); version = "(unknown)"; if (templateStream != null) { try { properties.load(templateStream); version = properties.getProperty("application.version"); templateStream.close(); } catch (IOException ignored) { } } sProps.put("smaliVersion", version); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/Config.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib; import brut.androlib.exceptions.AndrolibException; import brut.util.OSDetection; import java.io.File; import java.util.logging.Logger; public class Config { private final static Logger LOGGER = Logger.getLogger(Config.class.getName()); public final static short DECODE_SOURCES_NONE = 0x0000; public final static short DECODE_SOURCES_SMALI = 0x0001; public final static short DECODE_SOURCES_SMALI_ONLY_MAIN_CLASSES = 0x0010; public final static short DECODE_RESOURCES_NONE = 0x0100; public final static short DECODE_RESOURCES_FULL = 0x0101; public final static short FORCE_DECODE_MANIFEST_NONE = 0x0000; public final static short FORCE_DECODE_MANIFEST_FULL = 0x0001; public final static short DECODE_ASSETS_NONE = 0x0000; public final static short DECODE_ASSETS_FULL = 0x0001; // Build options public boolean forceBuildAll = false; public boolean forceDeleteFramework = false; public boolean debugMode = false; public boolean netSecConf = false; public boolean verbose = false; public boolean copyOriginalFiles = false; public boolean updateFiles = false; public boolean useAapt2 = false; public boolean noCrunch = false; public int forceApi = 0; // Decode options public short decodeSources = DECODE_SOURCES_SMALI; public short decodeResources = DECODE_RESOURCES_FULL; public short forceDecodeManifest = FORCE_DECODE_MANIFEST_NONE; public short decodeAssets = DECODE_ASSETS_FULL; public int apiLevel = 0; public boolean analysisMode = false; public boolean forceDelete = false; public boolean keepBrokenResources = false; public boolean baksmaliDebugMode = true; // Common options public String frameworkDirectory = null; public String frameworkTag = null; public String aaptPath = ""; public int aaptVersion = 1; // default to v1 // Utility functions public boolean isAapt2() { return this.useAapt2 || this.aaptVersion == 2; } private Config() { } private void setDefaultFrameworkDirectory() { File parentPath = new File(System.getProperty("user.home")); String path; if (OSDetection.isMacOSX()) { path = parentPath.getAbsolutePath() + String.format("%1$sLibrary%1$sapktool%1$sframework", File.separatorChar); } else if (OSDetection.isWindows()) { path = parentPath.getAbsolutePath() + String.format("%1$sAppData%1$sLocal%1$sapktool%1$sframework", File.separatorChar); } else { String xdgDataFolder = System.getenv("XDG_DATA_HOME"); if (xdgDataFolder != null) { path = xdgDataFolder + String.format("%1$sapktool%1$sframework", File.separatorChar); } else { path = parentPath.getAbsolutePath() + String.format("%1$s.local%1$sshare%1$sapktool%1$sframework", File.separatorChar); } } frameworkDirectory = path; } public void setDecodeSources(short mode) throws AndrolibException { if (mode != DECODE_SOURCES_NONE && mode != DECODE_SOURCES_SMALI && mode != DECODE_SOURCES_SMALI_ONLY_MAIN_CLASSES) { throw new AndrolibException("Invalid decode sources mode: " + mode); } if (decodeSources == DECODE_SOURCES_NONE && mode == DECODE_SOURCES_SMALI_ONLY_MAIN_CLASSES) { LOGGER.info("--only-main-classes cannot be paired with -s/--no-src. Ignoring."); return; } decodeSources = mode; } public void setDecodeResources(short mode) throws AndrolibException { if (mode != DECODE_RESOURCES_NONE && mode != DECODE_RESOURCES_FULL) { throw new AndrolibException("Invalid decode resources mode"); } decodeResources = mode; } public void setForceDecodeManifest(short mode) throws AndrolibException { if (mode != FORCE_DECODE_MANIFEST_NONE && mode != FORCE_DECODE_MANIFEST_FULL) { throw new AndrolibException("Invalid force decode manifest mode"); } forceDecodeManifest = mode; } public void setDecodeAssets(short mode) throws AndrolibException { if (mode != DECODE_ASSETS_NONE && mode != DECODE_ASSETS_FULL) { throw new AndrolibException("Invalid decode asset mode"); } decodeAssets = mode; } public static Config getDefaultConfig() { Config config = new Config(); config.setDefaultFrameworkDirectory(); return config; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/apk/ApkInfo.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.apk; import brut.androlib.ApktoolProperties; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResConfigFlags; import brut.directory.DirectoryException; import brut.directory.ExtFile; import brut.directory.FileDirectory; import java.io.*; import java.util.*; public class ApkInfo implements YamlSerializable { private transient ExtFile mApkFile; public String version; public String apkFileName; public boolean isFrameworkApk; public UsesFramework usesFramework; private Map<String, String> sdkInfo = new LinkedHashMap<>(); public PackageInfo packageInfo = new PackageInfo(); public VersionInfo versionInfo = new VersionInfo(); public boolean resourcesAreCompressed; public boolean sharedLibrary; public boolean sparseResources; public Map<String, String> unknownFiles = new LinkedHashMap<>(); public List<String> doNotCompress; /** @Deprecated use {@link #resourcesAreCompressed} */ public boolean compressionType; public ApkInfo() { this(null); } public ApkInfo(ExtFile apkFile) { this.version = ApktoolProperties.getVersion(); if (apkFile != null) { setApkFile(apkFile); } } public ExtFile getApkFile() { return mApkFile; } public void setApkFile(ExtFile apkFile) { mApkFile = apkFile; if (this.apkFileName == null) { this.apkFileName = apkFile.getName(); } } public boolean hasManifest() throws AndrolibException { if (mApkFile == null) { return false; } try { return mApkFile.getDirectory().containsFile("AndroidManifest.xml"); } catch (DirectoryException ex) { throw new AndrolibException(ex); } } public boolean hasResources() throws AndrolibException { if (mApkFile == null) { return false; } try { return mApkFile.getDirectory().containsFile("resources.arsc"); } catch (DirectoryException ex) { throw new AndrolibException(ex); } } public boolean hasSources() throws AndrolibException { if (mApkFile == null) { return false; } try { return mApkFile.getDirectory().containsFile("classes.dex"); } catch (DirectoryException ex) { throw new AndrolibException(ex); } } public boolean hasMultipleSources() throws AndrolibException { if (mApkFile == null) { return false; } try { Set<String> files = mApkFile.getDirectory().getFiles(false); for (String file : files) { if (file.endsWith(".dex")) { if (!file.equalsIgnoreCase("classes.dex")) { return true; } } } return false; } catch (DirectoryException ex) { throw new AndrolibException(ex); } } public void addUnknownFileInfo(String file, String value) { unknownFiles.put(file, value); } public String checkTargetSdkVersionBounds() { int target = mapSdkShorthandToVersion(getTargetSdkVersion()); int min = (getMinSdkVersion() != null) ? mapSdkShorthandToVersion(getMinSdkVersion()) : 0; int max = (getMaxSdkVersion() != null) ? mapSdkShorthandToVersion(getMaxSdkVersion()) : target; target = Math.min(max, target); target = Math.max(min, target); return Integer.toString(target); } public Map<String, String> getSdkInfo() { return sdkInfo; } public void setSdkInfo(Map<String, String> sdkInfo) { this.sdkInfo = sdkInfo; } public void setSdkInfoField(String key, String value) { sdkInfo.put(key, value); } public String getMinSdkVersion() { return sdkInfo.get("minSdkVersion"); } public String getMaxSdkVersion() { return sdkInfo.get("maxSdkVersion"); } public String getTargetSdkVersion() { return sdkInfo.get("targetSdkVersion"); } public int getMinSdkVersionFromAndroidCodename(String sdkVersion) { int sdkNumber = mapSdkShorthandToVersion(sdkVersion); if (sdkNumber == ResConfigFlags.SDK_BASE) { return Integer.parseInt(sdkInfo.get("minSdkVersion")); } return sdkNumber; } private int mapSdkShorthandToVersion(String sdkVersion) { switch (sdkVersion.toUpperCase()) { case "M": return ResConfigFlags.SDK_MNC; case "N": return ResConfigFlags.SDK_NOUGAT; case "O": return ResConfigFlags.SDK_OREO; case "P": return ResConfigFlags.SDK_P; case "Q": return ResConfigFlags.SDK_Q; case "R": return ResConfigFlags.SDK_R; case "S": return ResConfigFlags.SDK_S; case "SV2": return ResConfigFlags.SDK_S_V2; case "T": case "TIRAMISU": return ResConfigFlags.SDK_TIRAMISU; case "UPSIDEDOWNCAKE": case "UPSIDE_DOWN_CAKE": case "VANILLAICECREAM": case "VANILLA_ICE_CREAM": return ResConfigFlags.SDK_DEVELOPMENT; default: return Integer.parseInt(sdkVersion); } } public void save(File file) throws AndrolibException { try (YamlWriter writer = new YamlWriter(new FileOutputStream(file))) { write(writer); } catch (FileNotFoundException e) { throw new AndrolibException("File not found"); } catch (Exception e) { throw new AndrolibException(e); } } public static ApkInfo load(InputStream is) throws AndrolibException { YamlReader reader = new YamlReader(is); ApkInfo apkInfo = new ApkInfo(); reader.readRoot(apkInfo); return apkInfo; } public static ApkInfo load(File appDir) throws AndrolibException { try (InputStream in = new FileDirectory(appDir).getFileInput("apktool.yml")) { ApkInfo apkInfo = ApkInfo.load(in); apkInfo.setApkFile(new ExtFile(appDir)); return apkInfo; } catch (DirectoryException | IOException ex) { throw new AndrolibException(ex); } } @Override public void readItem(YamlReader reader) throws AndrolibException { YamlLine line = reader.getLine(); switch (line.getKey()) { case "version": { this.version = line.getValue(); break; } case "apkFileName": { this.apkFileName = line.getValue(); break; } case "isFrameworkApk": { this.isFrameworkApk = line.getValueBool(); break; } case "usesFramework": { this.usesFramework = new UsesFramework(); reader.readObject(usesFramework); break; } case "sdkInfo": { reader.readMap(sdkInfo); break; } case "packageInfo": { this.packageInfo = new PackageInfo(); reader.readObject(packageInfo); break; } case "versionInfo": { this.versionInfo = new VersionInfo(); reader.readObject(versionInfo); break; } case "compressionType": case "resourcesAreCompressed": { this.resourcesAreCompressed = line.getValueBool(); break; } case "sharedLibrary": { this.sharedLibrary = line.getValueBool(); break; } case "sparseResources": { this.sparseResources = line.getValueBool(); break; } case "unknownFiles": { this.unknownFiles = new LinkedHashMap<>(); reader.readMap(unknownFiles); break; } case "doNotCompress": { this.doNotCompress = new ArrayList<>(); reader.readStringList(doNotCompress); break; } } } @Override public void write(YamlWriter writer) { writer.writeString("version", version); writer.writeString("apkFileName", apkFileName); writer.writeBool("isFrameworkApk", isFrameworkApk); writer.writeObject("usesFramework", usesFramework); writer.writeStringMap("sdkInfo", sdkInfo); writer.writeObject("packageInfo", packageInfo); writer.writeObject("versionInfo", versionInfo); writer.writeBool("resourcesAreCompressed", resourcesAreCompressed); writer.writeBool("sharedLibrary", sharedLibrary); writer.writeBool("sparseResources", sparseResources); if (unknownFiles.size() > 0) { writer.writeStringMap("unknownFiles", unknownFiles); } writer.writeList("doNotCompress", doNotCompress); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/apk/PackageInfo.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.apk; public class PackageInfo implements YamlSerializable { public String forcedPackageId; public String renameManifestPackage; @Override public void readItem(YamlReader reader) { YamlLine line = reader.getLine(); switch (line.getKey()) { case "forcedPackageId": { forcedPackageId = line.getValue(); break; } case "renameManifestPackage": { renameManifestPackage = line.getValue(); break; } } } @Override public void write(YamlWriter writer) { writer.writeString("forcedPackageId", forcedPackageId); writer.writeString("renameManifestPackage", renameManifestPackage); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/apk/UsesFramework.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.apk; import brut.androlib.exceptions.AndrolibException; import java.util.ArrayList; import java.util.List; public class UsesFramework implements YamlSerializable { public List<Integer> ids; public String tag; @Override public void readItem(YamlReader reader) throws AndrolibException { YamlLine line = reader.getLine(); switch (line.getKey()) { case "ids": { ids = new ArrayList<>(); reader.readIntList(ids); break; } case "tag": { tag = line.getValue(); break; } } } @Override public void write(YamlWriter writer) { writer.writeList("ids", ids); writer.writeString("tag", tag); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/apk/VersionInfo.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.apk; public class VersionInfo implements YamlSerializable { public String versionCode; public String versionName; @Override public void readItem(YamlReader reader) { YamlLine line = reader.getLine(); switch (line.getKey()) { case "versionCode": { versionCode = line.getValue(); break; } case "versionName": { versionName = line.getValue(); break; } } } @Override public void write(YamlWriter writer) { writer.writeString("versionCode", versionCode); writer.writeString("versionName", versionName); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/apk/YamlLine.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.apk; import java.util.Objects; public class YamlLine { public int indent = 0; private String key = ""; private String value = ""; public boolean isComment; public boolean isEmpty; public boolean hasColon; public boolean isNull; public boolean isItem; public YamlLine(String line) { // special end line marker isNull = Objects.isNull(line); if (isNull) { return; } isEmpty = line.trim().isEmpty(); if (isEmpty) { return; } // count indent - space only for (int i = 0; i < line.length(); i++) { if (line.charAt(i) == ' ') { indent++; } else { break; } } // remove whitespace line = line.trim(); char first = line.charAt(0); isComment = first == '#' || first == '!'; isItem = first == '-'; if (isComment) { // for comment fill value value = line.substring(1).trim(); } else { // value line hasColon = line.contains(":"); if (isItem) { // array item line has only the value value = line.substring(1).trim(); } else { // split line to key - value String[] parts = line.split(":"); if (parts.length > 0) { key = parts[0].trim(); if (parts.length > 1) { value = parts[1].trim(); } } } } } public static String unescape(String value) { return YamlStringEscapeUtils.unescapeString(value); } public String getValue() { if (value.equals("null")) { return null; } String res = unescape(value); // remove quotation marks res = res.replaceAll("^\"|\"$", ""); res = res.replaceAll("^'|'$", ""); return res; } public String getKey() { String res = unescape(key); // remove quotation marks res = res.replaceAll("^\"|\"$", ""); res = res.replaceAll("^'|'$", ""); return res; } public boolean getValueBool() { return Objects.equals(value, "true"); } public int getValueInt() { return Integer.parseInt(value); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/apk/YamlReader.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.apk; import brut.androlib.exceptions.AndrolibException; import java.io.InputStream; import java.util.*; public class YamlReader { private ArrayList<YamlLine> mLines; private int mCurrent = 0; public YamlReader(InputStream in) { mLines = new ArrayList<>(); mLines.add(new YamlLine(null)); read(in); } public void pushLine() { if (mCurrent > 0) { mCurrent--; } } public void read(InputStream in) { Scanner scanner = new Scanner(in); mLines = new ArrayList<>(); while (scanner.hasNextLine()) { mLines.add(new YamlLine(scanner.nextLine())); } mLines.add(new YamlLine(null)); } public YamlLine getLine() { return mLines.get(mCurrent); } public int getIndent() { return getLine().indent; } public boolean isEnd() { return getLine().isNull; } public boolean isCommentOrEmpty() { YamlLine line = getLine(); return line.isEmpty || line.isComment; } public void skipInsignificant() { if (isEnd()) { return; } while (isCommentOrEmpty()) { mCurrent++; if (isEnd()) { break; } } } public boolean nextLine() { if (isEnd()) { return false; } while (true) { mCurrent++; if (isCommentOrEmpty()) { continue; } return !isEnd(); } } interface Checker { boolean check(YamlLine line); } interface Updater<T> { void update(T items, YamlReader reader) throws AndrolibException; } /** * Read root object from start to end */ public <T extends YamlSerializable> void readRoot(T obj) throws AndrolibException { if (isEnd()) { return; } int objIndent = 0; skipInsignificant(); while (true) { if (isEnd()) { return; } YamlLine line = getLine(); // skip don't checked line or lines with other indent if (objIndent != line.indent || !line.hasColon) { nextLine(); continue; } obj.readItem(this); nextLine(); } } /** * Read object. Reader stand on the object name. * The object data should be placed on the next line * and have indent. */ public <T> void readObject(T obj, Checker check, Updater<T> updater) throws AndrolibException { if (isEnd()) { return; } int prevIndent = getIndent(); // detect indent for the object data nextLine(); YamlLine line = getLine(); int objIndent = line.indent; // object data must have indent // otherwise stop reading if (objIndent <= prevIndent || !check.check(line)) { pushLine(); return; } updater.update(obj, this); while (nextLine()) { if (isEnd()) { return; } line = getLine(); if (objIndent != line.indent || !check.check(line)) { pushLine(); return; } updater.update(obj, this); } } <T extends YamlSerializable> void readObject(T obj) throws AndrolibException { readObject(obj, line -> line.hasColon, YamlSerializable::readItem); } /** * Read list. Reader stand on the object name. * The list data should be placed on the next line. * Data should have same indent. May by same with name. */ public <T> void readList(List<T> list, Updater<List<T>> updater) throws AndrolibException { if (isEnd()) { return; } int listIndent = getIndent(); nextLine(); int dataIndent = getIndent(); while (true) { if (isEnd()) { return; } // check incorrect data indent if (dataIndent < listIndent) { pushLine(); return; } YamlLine line = getLine(); if (dataIndent != line.indent || !line.isItem) { pushLine(); return; } updater.update(list, this); nextLine(); } } public void readStringList(List<String> list) throws AndrolibException { readList(list, (items, reader) -> items.add(reader.getLine().getValue())); } public void readIntList(List<Integer> list) throws AndrolibException { readList(list, (items, reader) -> items.add(reader.getLine().getValueInt())); } public void readMap(Map<String, String> map) throws AndrolibException { readObject(map, line -> line.hasColon, (items, reader) -> { YamlLine line = reader.getLine(); items.put(line.getKey(), line.getValue()); }); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/apk/YamlSerializable.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.apk; import brut.androlib.exceptions.AndrolibException; public interface YamlSerializable { void readItem(YamlReader reader) throws AndrolibException; void write(YamlWriter writer); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/apk/YamlStringEscapeUtils.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.apk; import org.apache.commons.text.StringEscapeUtils; import org.apache.commons.text.translate.CharSequenceTranslator; import java.io.IOException; import java.io.StringWriter; import java.io.Writer; public class YamlStringEscapeUtils { public static String escapeString(String str) { return escapeJavaStyleString(str); } /** * @param str String to escape values in, may be null * @return the escaped string */ private static String escapeJavaStyleString(String str) { if (str == null) { return null; } try { StringWriter writer = new StringWriter(str.length() * 2); escapeJavaStyleString(writer, str); return writer.toString(); } catch (IOException ioe) { // this should never ever happen while writing to a StringWriter throw new RuntimeException(ioe); } } /** * @param out write to receive the escaped string * @param str String to escape values in, may be null * @throws IOException if an IOException occurs */ private static void escapeJavaStyleString(Writer out, String str) throws IOException { if (out == null) { throw new IllegalArgumentException("The Writer must not be null"); } if (str == null) { return; } int sz; sz = str.length(); for (int i = 0; i < sz; i++) { char ch = str.charAt(i); // "[^\t\n\r\u0020-\u007E\u0085\u00A0-\uD7FF\uE000-\uFFFD]" // handle unicode if (ch > 0xFFFD) { out.write("\\u" + CharSequenceTranslator.hex(ch)); } else if (ch > 0xD7FF && ch < 0xE000) { out.write("\\u" + CharSequenceTranslator.hex(ch)); } else if (ch > 0x7E && ch != 0x85 && ch < 0xA0) { out.write("\\u00" + CharSequenceTranslator.hex(ch)); } else if (ch < 32) { switch (ch) { case '\t' : out.write('\\'); out.write('t'); break; case '\n' : out.write('\\'); out.write('n'); break; case '\r' : out.write('\\'); out.write('r'); break; default : if (ch > 0xf) { out.write("\\u00" + CharSequenceTranslator.hex(ch)); } else { out.write("\\u000" + CharSequenceTranslator.hex(ch)); } break; } } else { switch (ch) { case '\'' : if (false) { out.write('\\'); } out.write('\''); break; case '"' : out.write('\\'); out.write('"'); break; case '\\' : out.write('\\'); out.write('\\'); break; case '/' : if (false) { out.write('\\'); } out.write('/'); break; default : out.write(ch); break; } } } } /** * <p>Unescapes any Java literals found in the <code>String</code>. * For example, it will turn a sequence of <code>'\'</code> and * <code>'n'</code> into a newline character, unless the <code>'\'</code> * is preceded by another <code>'\'</code>.</p> * * @param str the <code>String</code> to unescape, may be null * @return a new unescaped <code>String</code>, <code>null</code> if null string input */ public static String unescapeString(String str) { return StringEscapeUtils.unescapeJava(str); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/apk/YamlWriter.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.apk; import java.io.*; import java.nio.charset.StandardCharsets; import java.util.*; public class YamlWriter implements Closeable { private int mIndent = 0; private final PrintWriter mWriter; private final String QUOTE = "'"; public YamlWriter(OutputStream out) { mWriter = new PrintWriter(new BufferedWriter( new OutputStreamWriter(out, StandardCharsets.UTF_8))); } @Override public void close() throws IOException { mWriter.close(); } public String getIndentString() { // for java 11 // return " ".repeat(mIndent); // for java 8 return String.join("", Collections.nCopies(mIndent, " ")); } public static String escape(String value) { return YamlStringEscapeUtils.escapeString(value); } public void nextIndent() { mIndent += 2; } public void prevIndent() { if (mIndent != 0) { mIndent -= 2; } } public void writeIndent() { mWriter.print(getIndentString()); } public void writeBool(String key, boolean value) { writeIndent(); String val = value ? "true": "false"; mWriter.println(escape(key) + ": " + val); } public void writeString(String key, String value, boolean quoted) { writeIndent(); if (Objects.isNull(value)) { mWriter.println(escape(key) + ": null"); } else { if (quoted) { value = QUOTE + value + QUOTE; } mWriter.println(escape(key) + ": " + escape(value)); } } public void writeString(String key, String value) { writeString(key, value, false); } public <T> void writeList(String key, List<T> list) { if (Objects.isNull(list)) { return; } writeIndent(); mWriter.println(escape(key) + ":"); for (T item: list) { writeIndent(); mWriter.println("- " + item); } } public void writeStringMap(String key, Map<String, String> map) { if (Objects.isNull(map)) { return; } writeIndent(); mWriter.println(escape(key) + ":"); nextIndent(); for (String mapKey: map.keySet()) { writeString(mapKey, map.get(mapKey)); } prevIndent(); } public <T extends YamlSerializable> void writeObject(String key, T obj) { if (Objects.isNull(obj)) { return; } writeIndent(); mWriter.println(escape(key) + ":"); nextIndent(); obj.write(this); prevIndent(); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/exceptions/AndrolibException.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.exceptions; import brut.common.BrutException; public class AndrolibException extends BrutException { public AndrolibException() { } public AndrolibException(String message) { super(message); } public AndrolibException(String message, Throwable cause) { super(message, cause); } public AndrolibException(Throwable cause) { super(cause); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/exceptions/AXmlDecodingException.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.exceptions; public class AXmlDecodingException extends AndrolibException { public AXmlDecodingException(String message, Throwable cause) { super(message, cause); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/exceptions/CantFind9PatchChunkException.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.exceptions; public class CantFind9PatchChunkException extends AndrolibException { public CantFind9PatchChunkException(String message, Throwable cause) { super(message, cause); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/exceptions/CantFindFrameworkResException.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.exceptions; public class CantFindFrameworkResException extends AndrolibException { public CantFindFrameworkResException(int id) { mPkgId = id; } public int getPkgId() { return mPkgId; } @Override public String getMessage() { return String.format("Can't find framework resources for package of id: %d", this.getPkgId()); } private final int mPkgId; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/exceptions/InFileNotFoundException.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.exceptions; public class InFileNotFoundException extends AndrolibException { public InFileNotFoundException() { } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/exceptions/OutDirExistsException.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.exceptions; public class OutDirExistsException extends AndrolibException { public OutDirExistsException() { } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/exceptions/RawXmlEncounteredException.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.exceptions; public class RawXmlEncounteredException extends AndrolibException { public RawXmlEncounteredException(String message, Throwable cause) { super(message, cause); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/exceptions/UndefinedResObjectException.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.exceptions; public class UndefinedResObjectException extends AndrolibException { public UndefinedResObjectException(String message) { super(message); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/mod/SmaliMod.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.mod; import org.antlr.runtime.CommonTokenStream; import org.antlr.runtime.RecognitionException; import org.antlr.runtime.Token; import org.antlr.runtime.tree.CommonTree; import org.antlr.runtime.tree.CommonTreeNodeStream; import com.android.tools.smali.dexlib2.writer.builder.DexBuilder; import com.android.tools.smali.smali.smaliFlexLexer; import com.android.tools.smali.smali.smaliParser; import com.android.tools.smali.smali.smaliTreeWalker; import java.io.*; import java.nio.charset.StandardCharsets; import java.nio.file.Files; public class SmaliMod { public static boolean assembleSmaliFile(File smaliFile, DexBuilder dexBuilder, int apiLevel, boolean verboseErrors, boolean printTokens) throws IOException, RecognitionException { CommonTokenStream tokens; smaliFlexLexer lexer; InputStream is = Files.newInputStream(smaliFile.toPath()); InputStreamReader reader = new InputStreamReader(is, StandardCharsets.UTF_8); lexer = new smaliFlexLexer(reader, apiLevel); (lexer).setSourceFile(smaliFile); tokens = new CommonTokenStream(lexer); if (printTokens) { tokens.getTokens(); for (int i=0; i<tokens.size(); i++) { Token token = tokens.get(i); if (token.getChannel() == smaliParser.HIDDEN) { continue; } System.out.println(smaliParser.tokenNames[token.getType()] + ": " + token.getText()); } } smaliParser parser = new smaliParser(tokens); parser.setApiLevel(apiLevel); parser.setVerboseErrors(verboseErrors); smaliParser.smali_file_return result = parser.smali_file(); if (parser.getNumberOfSyntaxErrors() > 0 || lexer.getNumberOfSyntaxErrors() > 0) { is.close(); reader.close(); return false; } CommonTree t = result.getTree(); CommonTreeNodeStream treeStream = new CommonTreeNodeStream(t); treeStream.setTokenStream(tokens); smaliTreeWalker dexGen = new smaliTreeWalker(treeStream); dexGen.setApiLevel(apiLevel); dexGen.setVerboseErrors(verboseErrors); dexGen.setDexBuilder(dexBuilder); dexGen.smali_file(); is.close(); reader.close(); return dexGen.getNumberOfSyntaxErrors() == 0; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/Framework.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res; import brut.androlib.Config; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.CantFindFrameworkResException; import brut.androlib.res.decoder.ARSCDecoder; import brut.androlib.res.data.arsc.ARSCData; import brut.androlib.res.data.arsc.FlagsOffset; import brut.util.Jar; import org.apache.commons.io.IOUtils; import java.io.*; import java.nio.file.Files; import java.util.Objects; import java.util.logging.Logger; import java.util.zip.CRC32; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import java.util.zip.ZipOutputStream; public class Framework { private final Config config; private File mFrameworkDirectory = null; private final static Logger LOGGER = Logger.getLogger(Framework.class.getName()); public Framework(Config config) { this.config = config; } public void installFramework(File frameFile) throws AndrolibException { installFramework(frameFile, config.frameworkTag); } public void installFramework(File frameFile, String tag) throws AndrolibException { InputStream in = null; ZipOutputStream out = null; try { ZipFile zip = new ZipFile(frameFile); ZipEntry entry = zip.getEntry("resources.arsc"); if (entry == null) { throw new AndrolibException("Can't find resources.arsc file"); } in = zip.getInputStream(entry); byte[] data = IOUtils.toByteArray(in); ARSCData arsc = ARSCDecoder.decode(new ByteArrayInputStream(data), true, true); publicizeResources(data, arsc.getFlagsOffsets()); File outFile = new File(getFrameworkDirectory(), arsc .getOnePackage().getId() + (tag == null ? "" : '-' + tag) + ".apk"); out = new ZipOutputStream(Files.newOutputStream(outFile.toPath())); out.setMethod(ZipOutputStream.STORED); CRC32 crc = new CRC32(); crc.update(data); entry = new ZipEntry("resources.arsc"); entry.setSize(data.length); entry.setMethod(ZipOutputStream.STORED); entry.setCrc(crc.getValue()); out.putNextEntry(entry); out.write(data); out.closeEntry(); //Write fake AndroidManifest.xml file to support original aapt entry = zip.getEntry("AndroidManifest.xml"); if (entry != null) { in = zip.getInputStream(entry); byte[] manifest = IOUtils.toByteArray(in); CRC32 manifestCrc = new CRC32(); manifestCrc.update(manifest); entry.setSize(manifest.length); entry.setCompressedSize(-1); entry.setCrc(manifestCrc.getValue()); out.putNextEntry(entry); out.write(manifest); out.closeEntry(); } zip.close(); LOGGER.info("Framework installed to: " + outFile); } catch (IOException ex) { throw new AndrolibException(ex); } finally { IOUtils.closeQuietly(in); IOUtils.closeQuietly(out); } } public void listFrameworkDirectory() throws AndrolibException { File dir = getFrameworkDirectory(); if (dir == null) { LOGGER.severe("No framework directory found. Nothing to list."); return; } for (File file : Objects.requireNonNull(dir.listFiles())) { if (file.isFile() && file.getName().endsWith(".apk")) { LOGGER.info(file.getName()); } } } public void publicizeResources(File arscFile) throws AndrolibException { byte[] data = new byte[(int) arscFile.length()]; try(InputStream in = Files.newInputStream(arscFile.toPath()); OutputStream out = Files.newOutputStream(arscFile.toPath())) { //noinspection ResultOfMethodCallIgnored in.read(data); publicizeResources(data); out.write(data); } catch (IOException ex){ throw new AndrolibException(ex); } } private void publicizeResources(byte[] arsc) throws AndrolibException { publicizeResources(arsc, ARSCDecoder.decode(new ByteArrayInputStream(arsc), true, true).getFlagsOffsets()); } public void publicizeResources(byte[] arsc, FlagsOffset[] flagsOffsets) { for (FlagsOffset flags : flagsOffsets) { int offset = flags.offset + 3; int end = offset + 4 * flags.count; while (offset < end) { arsc[offset] |= (byte) 0x40; offset += 4; } } } public File getFrameworkDirectory() throws AndrolibException { if (mFrameworkDirectory != null) { return mFrameworkDirectory; } String path; // use default framework path or specified on the command line path = config.frameworkDirectory; File dir = new File(path); if (!dir.isDirectory() && dir.isFile()) { throw new AndrolibException("--frame-path is set to a file, not a directory."); } if (dir.getParentFile() != null && dir.getParentFile().isFile()) { throw new AndrolibException("Please remove file at " + dir.getParentFile()); } if (! dir.exists()) { if (! dir.mkdirs()) { if (config.frameworkDirectory != null) { LOGGER.severe("Can't create Framework directory: " + dir); } throw new AndrolibException(String.format( "Can't create directory: (%s). Pass a writable path with --frame-path {DIR}. ", dir )); } } if (config.frameworkDirectory == null) { if (! dir.canWrite()) { LOGGER.severe(String.format("WARNING: Could not write to (%1$s), using %2$s instead...", dir.getAbsolutePath(), System.getProperty("java.io.tmpdir"))); LOGGER.severe("Please be aware this is a volatile directory and frameworks could go missing, " + "please utilize --frame-path if the default storage directory is unavailable"); dir = new File(System.getProperty("java.io.tmpdir")); } } mFrameworkDirectory = dir; return dir; } public File getFrameworkApk(int id, String frameTag) throws AndrolibException { File dir = getFrameworkDirectory(); File apk; if (frameTag != null) { apk = new File(dir, String.valueOf(id) + '-' + frameTag + ".apk"); if (apk.exists()) { return apk; } } apk = new File(dir, id + ".apk"); if (apk.exists()) { return apk; } if (id == 1) { try ( InputStream in = getAndroidFrameworkResourcesAsStream(); OutputStream out = Files.newOutputStream(apk.toPath()) ) { IOUtils.copy(in, out); return apk; } catch (IOException ex) { throw new AndrolibException(ex); } } throw new CantFindFrameworkResException(id); } public void emptyFrameworkDirectory() throws AndrolibException { File dir = getFrameworkDirectory(); File apk; apk = new File(dir, "1.apk"); if (! apk.exists()) { LOGGER.warning("Can't empty framework directory, no file found at: " + apk.getAbsolutePath()); } else { try { if (apk.exists() && Objects.requireNonNull(dir.listFiles()).length > 1 && ! config.forceDeleteFramework) { LOGGER.warning("More than default framework detected. Please run command with `--force` parameter to wipe framework directory."); } else { for (File file : Objects.requireNonNull(dir.listFiles())) { if (file.isFile() && file.getName().endsWith(".apk")) { LOGGER.info("Removing " + file.getName() + " framework file..."); //noinspection ResultOfMethodCallIgnored file.delete(); } } } } catch (NullPointerException e) { throw new AndrolibException(e); } } } private InputStream getAndroidFrameworkResourcesAsStream() { return Jar.class.getResourceAsStream("/brut/androlib/android-framework.jar"); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/ResourcesDecoder.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res; import brut.androlib.Config; import brut.androlib.apk.ApkInfo; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.*; import brut.androlib.res.decoder.*; import brut.androlib.res.util.ExtMXSerializer; import brut.androlib.res.util.ExtXmlSerializer; import brut.androlib.res.xml.ResValuesXmlSerializable; import brut.androlib.res.xml.ResXmlPatcher; import brut.directory.Directory; import brut.directory.DirectoryException; import brut.directory.FileDirectory; import org.xmlpull.v1.XmlSerializer; import java.io.*; import java.util.*; import java.util.logging.Logger; public class ResourcesDecoder { private final static Logger LOGGER = Logger.getLogger(ResourcesDecoder.class.getName()); private final Config mConfig; private final ApkInfo mApkInfo; private final ResTable mResTable; private final Map<String, String> mResFileMapping = new HashMap<>(); private final static String[] IGNORED_PACKAGES = new String[] { "android", "com.htc", "com.lge", "com.lge.internal", "yi", "flyme", "air.com.adobe.appentry", "FFFFFFFFFFFFFFFFFFFFFF" }; public ResourcesDecoder(Config config, ApkInfo apkInfo) { mConfig = config; mApkInfo = apkInfo; mResTable = new ResTable(mConfig, mApkInfo); } public ResTable getResTable() throws AndrolibException { if (!mApkInfo.hasManifest() && !mApkInfo.hasResources()) { throw new AndrolibException( "Apk doesn't contain either AndroidManifest.xml file or resources.arsc file"); } return mResTable; } public Map<String, String> getResFileMapping() { return mResFileMapping; } public void loadMainPkg() throws AndrolibException { mResTable.loadMainPkg(mApkInfo.getApkFile()); } public void decodeManifest(File outDir) throws AndrolibException { if (!mApkInfo.hasManifest()) { return; } AXmlResourceParser axmlParser = new AndroidManifestResourceParser(mResTable); XmlPullStreamDecoder fileDecoder = new XmlPullStreamDecoder(axmlParser, getResXmlSerializer()); Directory inApk, out; try { inApk = mApkInfo.getApkFile().getDirectory(); out = new FileDirectory(outDir); if (mApkInfo.hasResources()) { LOGGER.info("Decoding AndroidManifest.xml with resources..."); } else { LOGGER.info("Decoding AndroidManifest.xml with only framework resources..."); } InputStream inputStream = inApk.getFileInput("AndroidManifest.xml"); OutputStream outputStream = out.getFileOutput("AndroidManifest.xml"); fileDecoder.decodeManifest(inputStream, outputStream); } catch (DirectoryException ex) { throw new AndrolibException(ex); } if (mApkInfo.hasResources()) { if (!mConfig.analysisMode) { // Remove versionName / versionCode (aapt API 16) // // check for a mismatch between resources.arsc package and the package listed in AndroidManifest // also remove the android::versionCode / versionName from manifest for rebuild // this is a required change to prevent aapt warning about conflicting versions // it will be passed as a parameter to aapt like "--min-sdk-version" via apktool.yml adjustPackageManifest(outDir.getAbsolutePath() + File.separator + "AndroidManifest.xml"); ResXmlPatcher.removeManifestVersions(new File( outDir.getAbsolutePath() + File.separator + "AndroidManifest.xml")); // update apk info mApkInfo.packageInfo.forcedPackageId = String.valueOf(mResTable.getPackageId()); } } } public void updateApkInfo(File outDir) throws AndrolibException { mResTable.initApkInfo(mApkInfo, outDir); } private void adjustPackageManifest(String filePath) throws AndrolibException { // compare resources.arsc package name to the one present in AndroidManifest ResPackage resPackage = mResTable.getCurrentResPackage(); String pkgOriginal = resPackage.getName(); String pkgRenamed = mResTable.getPackageRenamed(); mResTable.setPackageId(resPackage.getId()); mResTable.setPackageOriginal(pkgOriginal); // 1) Check if pkgOriginal is null (empty resources.arsc) // 2) Check if pkgRenamed is null // 3) Check if pkgOriginal === mPackageRenamed // 4) Check if pkgOriginal is ignored via IGNORED_PACKAGES if (pkgOriginal == null || pkgRenamed == null || pkgOriginal.equalsIgnoreCase(pkgRenamed) || (Arrays.asList(IGNORED_PACKAGES).contains(pkgOriginal))) { LOGGER.info("Regular manifest package..."); } else { LOGGER.info("Renamed manifest package found! Replacing " + pkgRenamed + " with " + pkgOriginal); ResXmlPatcher.renameManifestPackage(new File(filePath), pkgOriginal); } } public void decodeResources(File outDir) throws AndrolibException { if (!mApkInfo.hasResources()) { return; } mResTable.loadMainPkg(mApkInfo.getApkFile()); ResStreamDecoderContainer decoders = new ResStreamDecoderContainer(); decoders.setDecoder("raw", new ResRawStreamDecoder()); decoders.setDecoder("9patch", new Res9patchStreamDecoder()); AXmlResourceParser axmlParser = new AXmlResourceParser(mResTable); decoders.setDecoder("xml", new XmlPullStreamDecoder(axmlParser, getResXmlSerializer())); ResFileDecoder fileDecoder = new ResFileDecoder(decoders); Directory in, out; try { out = new FileDirectory(outDir); in = mApkInfo.getApkFile().getDirectory(); out = out.createDir("res"); } catch (DirectoryException ex) { throw new AndrolibException(ex); } ExtMXSerializer xmlSerializer = getResXmlSerializer(); for (ResPackage pkg : mResTable.listMainPackages()) { LOGGER.info("Decoding file-resources..."); for (ResResource res : pkg.listFiles()) { fileDecoder.decode(res, in, out, mResFileMapping); } LOGGER.info("Decoding values */* XMLs..."); for (ResValuesFile valuesFile : pkg.listValuesFiles()) { generateValuesFile(valuesFile, out, xmlSerializer); } generatePublicXml(pkg, out, xmlSerializer); } AndrolibException decodeError = axmlParser.getFirstError(); if (decodeError != null) { throw decodeError; } } private ExtMXSerializer getResXmlSerializer() { ExtMXSerializer serial = new ExtMXSerializer(); serial.setProperty(ExtXmlSerializer.PROPERTY_SERIALIZER_INDENTATION, " "); serial.setProperty(ExtXmlSerializer.PROPERTY_SERIALIZER_LINE_SEPARATOR, System.getProperty("line.separator")); serial.setProperty(ExtXmlSerializer.PROPERTY_DEFAULT_ENCODING, "utf-8"); serial.setDisabledAttrEscape(true); return serial; } private void generateValuesFile(ResValuesFile valuesFile, Directory out, ExtXmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput(valuesFile.getPath()); serial.setOutput((outStream), null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResource res : valuesFile.listResources()) { if (valuesFile.isSynthesized(res)) { continue; } ((ResValuesXmlSerializable) res.getValue()).serializeToResValuesXml(serial, res); } serial.endTag(null, "resources"); serial.newLine(); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException | DirectoryException ex) { throw new AndrolibException("Could not generate: " + valuesFile.getPath(), ex); } } private void generatePublicXml(ResPackage pkg, Directory out, XmlSerializer serial) throws AndrolibException { try { OutputStream outStream = out.getFileOutput("values/public.xml"); serial.setOutput(outStream, null); serial.startDocument(null, null); serial.startTag(null, "resources"); for (ResResSpec spec : pkg.listResSpecs()) { serial.startTag(null, "public"); serial.attribute(null, "type", spec.getType().getName()); serial.attribute(null, "name", spec.getName()); serial.attribute(null, "id", String.format("0x%08x", spec.getId().id)); serial.endTag(null, "public"); } serial.endTag(null, "resources"); serial.endDocument(); serial.flush(); outStream.close(); } catch (IOException | DirectoryException ex) { throw new AndrolibException("Could not generate public.xml file", ex); } } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResConfigFlags.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data; import java.util.logging.Logger; public class ResConfigFlags { public final short mcc; public final short mnc; public final char[] language; public final char[] region; public final byte orientation; public final byte touchscreen; public final int density; public final byte keyboard; public final byte navigation; public final byte inputFlags; public final short screenWidth; public final short screenHeight; public final short sdkVersion; public final byte screenLayout; public final byte uiMode; public final short smallestScreenWidthDp; public final short screenWidthDp; public final short screenHeightDp; private final char[] localeScript; private final char[] localeVariant; private final byte screenLayout2; private final byte colorMode; private final char[] localeNumberingSystem; public final boolean isInvalid; private final String mQualifiers; private final int size; public ResConfigFlags() { mcc = 0; mnc = 0; language = new char[] { '\00', '\00' }; region = new char[] { '\00', '\00' }; orientation = ORIENTATION_ANY; touchscreen = TOUCHSCREEN_ANY; density = DENSITY_DEFAULT; keyboard = KEYBOARD_ANY; navigation = NAVIGATION_ANY; inputFlags = KEYSHIDDEN_ANY | NAVHIDDEN_ANY; screenWidth = 0; screenHeight = 0; sdkVersion = 0; screenLayout = SCREENLONG_ANY | SCREENSIZE_ANY; uiMode = UI_MODE_TYPE_ANY | UI_MODE_NIGHT_ANY; smallestScreenWidthDp = 0; screenWidthDp = 0; screenHeightDp = 0; localeScript = null; localeVariant = null; screenLayout2 = 0; colorMode = COLOR_WIDE_UNDEFINED; localeNumberingSystem = null; isInvalid = false; mQualifiers = ""; size = 0; } public ResConfigFlags(short mcc, short mnc, char[] language, char[] region, byte orientation, byte touchscreen, int density, byte keyboard, byte navigation, byte inputFlags, short screenWidth, short screenHeight, short sdkVersion, byte screenLayout, byte uiMode, short smallestScreenWidthDp, short screenWidthDp, short screenHeightDp, char[] localeScript, char[] localeVariant, byte screenLayout2, byte colorMode, char[] localeNumberingSystem, boolean isInvalid, int size) { if (orientation < 0 || orientation > 3) { LOGGER.warning("Invalid orientation value: " + orientation); orientation = 0; isInvalid = true; } if (touchscreen < 0 || touchscreen > 3) { LOGGER.warning("Invalid touchscreen value: " + touchscreen); touchscreen = 0; isInvalid = true; } if (density < -1) { LOGGER.warning("Invalid density value: " + density); density = 0; isInvalid = true; } if (keyboard < 0 || keyboard > 3) { LOGGER.warning("Invalid keyboard value: " + keyboard); keyboard = 0; isInvalid = true; } if (navigation < 0 || navigation > 4) { LOGGER.warning("Invalid navigation value: " + navigation); navigation = 0; isInvalid = true; } if (localeScript != null && localeScript.length != 0) { if (localeScript[0] == '\00') { localeScript = null; } } else { localeScript = null; } if (localeVariant != null && localeVariant.length != 0) { if (localeVariant[0] == '\00') { localeVariant = null; } } else { localeVariant = null; } this.mcc = mcc; this.mnc = mnc; this.language = language; this.region = region; this.orientation = orientation; this.touchscreen = touchscreen; this.density = density; this.keyboard = keyboard; this.navigation = navigation; this.inputFlags = inputFlags; this.screenWidth = screenWidth; this.screenHeight = screenHeight; this.sdkVersion = sdkVersion; this.screenLayout = screenLayout; this.uiMode = uiMode; this.smallestScreenWidthDp = smallestScreenWidthDp; this.screenWidthDp = screenWidthDp; this.screenHeightDp = screenHeightDp; this.localeScript = localeScript; this.localeVariant = localeVariant; this.screenLayout2 = screenLayout2; this.colorMode = colorMode; this.localeNumberingSystem = localeNumberingSystem; this.isInvalid = isInvalid; this.size = size; mQualifiers = generateQualifiers(); } public String getQualifiers() { return mQualifiers; } private String generateQualifiers() { StringBuilder ret = new StringBuilder(); if (mcc != 0) { ret.append("-mcc").append(String.format("%03d", mcc)); if (mnc != MNC_ZERO) { if (mnc != 0) { ret.append("-mnc"); if (size <= 32) { if (mnc > 0 && mnc < 10) { ret.append(String.format("%02d", mnc)); } else { ret.append(String.format("%03d", mnc)); } } else { ret.append(mnc); } } } else { ret.append("-mnc00"); } } else { if (mnc != 0) { ret.append("-mnc").append(mnc); } } ret.append(getLocaleString()); switch (screenLayout & MASK_LAYOUTDIR) { case SCREENLAYOUT_LAYOUTDIR_RTL: ret.append("-ldrtl"); break; case SCREENLAYOUT_LAYOUTDIR_LTR: ret.append("-ldltr"); break; } if (smallestScreenWidthDp != 0) { ret.append("-sw").append(smallestScreenWidthDp).append("dp"); } if (screenWidthDp != 0) { ret.append("-w").append(screenWidthDp).append("dp"); } if (screenHeightDp != 0) { ret.append("-h").append(screenHeightDp).append("dp"); } switch (screenLayout & MASK_SCREENSIZE) { case SCREENSIZE_SMALL: ret.append("-small"); break; case SCREENSIZE_NORMAL: ret.append("-normal"); break; case SCREENSIZE_LARGE: ret.append("-large"); break; case SCREENSIZE_XLARGE: ret.append("-xlarge"); break; } switch (screenLayout & MASK_SCREENLONG) { case SCREENLONG_YES: ret.append("-long"); break; case SCREENLONG_NO: ret.append("-notlong"); break; } switch (screenLayout2 & MASK_SCREENROUND) { case SCREENLAYOUT_ROUND_NO: ret.append("-notround"); break; case SCREENLAYOUT_ROUND_YES: ret.append("-round"); break; } switch (colorMode & COLOR_HDR_MASK) { case COLOR_HDR_YES: ret.append("-highdr"); break; case COLOR_HDR_NO: ret.append("-lowdr"); break; } switch (colorMode & COLOR_WIDE_MASK) { case COLOR_WIDE_YES: ret.append("-widecg"); break; case COLOR_WIDE_NO: ret.append("-nowidecg"); break; } switch (orientation) { case ORIENTATION_PORT: ret.append("-port"); break; case ORIENTATION_LAND: ret.append("-land"); break; case ORIENTATION_SQUARE: ret.append("-square"); break; } switch (uiMode & MASK_UI_MODE_TYPE) { case UI_MODE_TYPE_CAR: ret.append("-car"); break; case UI_MODE_TYPE_DESK: ret.append("-desk"); break; case UI_MODE_TYPE_TELEVISION: ret.append("-television"); break; case UI_MODE_TYPE_SMALLUI: ret.append("-smallui"); break; case UI_MODE_TYPE_MEDIUMUI: ret.append("-mediumui"); break; case UI_MODE_TYPE_LARGEUI: ret.append("-largeui"); break; case UI_MODE_TYPE_GODZILLAUI: ret.append("-godzillaui"); break; case UI_MODE_TYPE_HUGEUI: ret.append("-hugeui"); break; case UI_MODE_TYPE_APPLIANCE: ret.append("-appliance"); break; case UI_MODE_TYPE_WATCH: ret.append("-watch"); break; case UI_MODE_TYPE_VR_HEADSET: ret.append("-vrheadset"); break; } switch (uiMode & MASK_UI_MODE_NIGHT) { case UI_MODE_NIGHT_YES: ret.append("-night"); break; case UI_MODE_NIGHT_NO: ret.append("-notnight"); break; } switch (density) { case DENSITY_DEFAULT: break; case DENSITY_LOW: ret.append("-ldpi"); break; case DENSITY_MEDIUM: ret.append("-mdpi"); break; case DENSITY_HIGH: ret.append("-hdpi"); break; case DENSITY_TV: ret.append("-tvdpi"); break; case DENSITY_XHIGH: ret.append("-xhdpi"); break; case DENSITY_XXHIGH: ret.append("-xxhdpi"); break; case DENSITY_XXXHIGH: ret.append("-xxxhdpi"); break; case DENSITY_ANY: ret.append("-anydpi"); break; case DENSITY_NONE: ret.append("-nodpi"); break; default: ret.append('-').append(density).append("dpi"); } switch (touchscreen) { case TOUCHSCREEN_NOTOUCH: ret.append("-notouch"); break; case TOUCHSCREEN_STYLUS: ret.append("-stylus"); break; case TOUCHSCREEN_FINGER: ret.append("-finger"); break; } switch (inputFlags & MASK_KEYSHIDDEN) { case KEYSHIDDEN_NO: ret.append("-keysexposed"); break; case KEYSHIDDEN_YES: ret.append("-keyshidden"); break; case KEYSHIDDEN_SOFT: ret.append("-keyssoft"); break; } switch (keyboard) { case KEYBOARD_NOKEYS: ret.append("-nokeys"); break; case KEYBOARD_QWERTY: ret.append("-qwerty"); break; case KEYBOARD_12KEY: ret.append("-12key"); break; } switch (inputFlags & MASK_NAVHIDDEN) { case NAVHIDDEN_NO: ret.append("-navexposed"); break; case NAVHIDDEN_YES: ret.append("-navhidden"); break; } switch (navigation) { case NAVIGATION_NONAV: ret.append("-nonav"); break; case NAVIGATION_DPAD: ret.append("-dpad"); break; case NAVIGATION_TRACKBALL: ret.append("-trackball"); break; case NAVIGATION_WHEEL: ret.append("-wheel"); break; } if (screenWidth != 0 && screenHeight != 0) { if (screenWidth > screenHeight) { ret.append(String.format("-%dx%d", screenWidth, screenHeight)); } else { ret.append(String.format("-%dx%d", screenHeight, screenWidth)); } } if (sdkVersion > 0 && sdkVersion >= getNaturalSdkVersionRequirement()) { ret.append("-v").append(sdkVersion); } if (isInvalid) { ret.append("-ERR").append(sErrCounter++); } return ret.toString(); } private short getNaturalSdkVersionRequirement() { if ((uiMode & MASK_UI_MODE_TYPE) == UI_MODE_TYPE_VR_HEADSET || (colorMode & COLOR_WIDE_MASK) != 0 || ((colorMode & COLOR_HDR_MASK) != 0)) { return SDK_OREO; } if ((screenLayout2 & MASK_SCREENROUND) != 0) { return SDK_MNC; } if (density == DENSITY_ANY) { return SDK_LOLLIPOP; } if (smallestScreenWidthDp != 0 || screenWidthDp != 0 || screenHeightDp != 0) { return SDK_HONEYCOMB_MR2; } if ((uiMode & (MASK_UI_MODE_TYPE | MASK_UI_MODE_NIGHT)) != UI_MODE_NIGHT_ANY) { return SDK_FROYO; } if ((screenLayout & (MASK_SCREENSIZE | MASK_SCREENLONG)) != SCREENSIZE_ANY || density != DENSITY_DEFAULT) { return SDK_DONUT; } return 0; } private String getLocaleString() { StringBuilder sb = new StringBuilder(); // check for old style non BCP47 tags // allows values-xx-rXX, values-xx, values-xxx-rXX // denies values-xxx, anything else if (localeVariant == null && localeScript == null && (region[0] != '\00' || language[0] != '\00') && region.length != 3) { sb.append("-").append(language); if (region[0] != '\00') { sb.append("-r").append(region); } } else { // BCP47 if (language[0] == '\00' && region[0] == '\00') { return sb.toString(); // early return, no language or region } sb.append("-b+"); if (language[0] != '\00') { sb.append(language); } if (localeScript != null && localeScript.length == 4) { sb.append("+").append(localeScript); } if ((region.length == 2 || region.length == 3) && region[0] != '\00') { sb.append("+").append(region); } if (localeVariant != null && localeVariant.length >= 5) { sb.append("+").append(toUpper(localeVariant)); } // If we have a numbering system - it isn't used in qualifiers for build tools, but AOSP understands it // So chances are - this may be valid, but aapt 1/2 will not like it. if (localeNumberingSystem != null && localeNumberingSystem.length > 0) { sb.append("+u+nu+").append(localeNumberingSystem); } } return sb.toString(); } private String toUpper(char[] character) { StringBuilder sb = new StringBuilder(); for (char ch: character) { sb.append(Character.toUpperCase(ch)); } return sb.toString(); } @Override public String toString() { return !getQualifiers().equals("") ? getQualifiers() : "[DEFAULT]"; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ResConfigFlags other = (ResConfigFlags) obj; return this.mQualifiers.equals(other.mQualifiers); } @Override public int hashCode() { int hash = 17; hash = 31 * hash + this.mQualifiers.hashCode(); return hash; } // TODO: Dirty static hack. This counter should be a part of ResPackage, // but it would be hard right now and this feature is very rarely used. private static int sErrCounter = 0; public final static byte SDK_BASE = 1; public final static byte SDK_BASE_1_1 = 2; public final static byte SDK_CUPCAKE = 3; public final static byte SDK_DONUT = 4; public final static byte SDK_ECLAIR = 5; public final static byte SDK_ECLAIR_0_1 = 6; public final static byte SDK_ECLAIR_MR1 = 7; public final static byte SDK_FROYO = 8; public final static byte SDK_GINGERBREAD = 9; public final static byte SDK_GINGERBREAD_MR1 = 10; public final static byte SDK_HONEYCOMB = 11; public final static byte SDK_HONEYCOMB_MR1 = 12; public final static byte SDK_HONEYCOMB_MR2 = 13; public final static byte SDK_ICE_CREAM_SANDWICH = 14; public final static byte SDK_ICE_CREAM_SANDWICH_MR1 = 15; public final static byte SDK_JELLY_BEAN = 16; public final static byte SDK_JELLY_BEAN_MR1 = 17; public final static byte SDK_JELLY_BEAN_MR2 = 18; public final static byte SDK_KITKAT = 19; public final static byte SDK_LOLLIPOP = 21; public final static byte SDK_LOLLIPOP_MR1 = 22; public final static byte SDK_MNC = 23; public final static byte SDK_NOUGAT = 24; public final static byte SDK_NOUGAT_MR1 = 25; public final static byte SDK_OREO = 26; public final static byte SDK_OREO_MR1 = 27; public final static byte SDK_P = 28; public final static byte SDK_Q = 29; public final static byte SDK_R = 30; public final static byte SDK_S = 31; public final static byte SDK_S_V2 = 32; public final static byte SDK_TIRAMISU = 33; // AOSP has this as 10,000 for dev purposes. // platform_frameworks_base/commit/c7a1109a1fe0771d4c9b572dcf178e2779fc4f2d public final static int SDK_DEVELOPMENT = 10000; public final static byte ORIENTATION_ANY = 0; public final static byte ORIENTATION_PORT = 1; public final static byte ORIENTATION_LAND = 2; public final static byte ORIENTATION_SQUARE = 3; public final static byte TOUCHSCREEN_ANY = 0; public final static byte TOUCHSCREEN_NOTOUCH = 1; public final static byte TOUCHSCREEN_STYLUS = 2; public final static byte TOUCHSCREEN_FINGER = 3; public final static int DENSITY_DEFAULT = 0; public final static int DENSITY_LOW = 120; public final static int DENSITY_MEDIUM = 160; public final static int DENSITY_400 = 190; public final static int DENSITY_TV = 213; public final static int DENSITY_HIGH = 240; public final static int DENSITY_XHIGH = 320; public final static int DENSITY_XXHIGH = 480; public final static int DENSITY_XXXHIGH = 640; public final static int DENSITY_ANY = 0xFFFE; public final static int DENSITY_NONE = 0xFFFF; public final static int MNC_ZERO = -1; public final static short MASK_LAYOUTDIR = 0xc0; public final static short SCREENLAYOUT_LAYOUTDIR_ANY = 0x00; public final static short SCREENLAYOUT_LAYOUTDIR_LTR = 0x40; public final static short SCREENLAYOUT_LAYOUTDIR_RTL = 0x80; public final static short SCREENLAYOUT_LAYOUTDIR_SHIFT = 0x06; public final static short MASK_SCREENROUND = 0x03; public final static short SCREENLAYOUT_ROUND_ANY = 0; public final static short SCREENLAYOUT_ROUND_NO = 0x1; public final static short SCREENLAYOUT_ROUND_YES = 0x2; public final static byte KEYBOARD_ANY = 0; public final static byte KEYBOARD_NOKEYS = 1; public final static byte KEYBOARD_QWERTY = 2; public final static byte KEYBOARD_12KEY = 3; public final static byte NAVIGATION_ANY = 0; public final static byte NAVIGATION_NONAV = 1; public final static byte NAVIGATION_DPAD = 2; public final static byte NAVIGATION_TRACKBALL = 3; public final static byte NAVIGATION_WHEEL = 4; public final static byte MASK_KEYSHIDDEN = 0x3; public final static byte KEYSHIDDEN_ANY = 0x0; public final static byte KEYSHIDDEN_NO = 0x1; public final static byte KEYSHIDDEN_YES = 0x2; public final static byte KEYSHIDDEN_SOFT = 0x3; public final static byte MASK_NAVHIDDEN = 0xc; public final static byte NAVHIDDEN_ANY = 0x0; public final static byte NAVHIDDEN_NO = 0x4; public final static byte NAVHIDDEN_YES = 0x8; public final static byte MASK_SCREENSIZE = 0x0f; public final static byte SCREENSIZE_ANY = 0x00; public final static byte SCREENSIZE_SMALL = 0x01; public final static byte SCREENSIZE_NORMAL = 0x02; public final static byte SCREENSIZE_LARGE = 0x03; public final static byte SCREENSIZE_XLARGE = 0x04; public final static byte MASK_SCREENLONG = 0x30; public final static byte SCREENLONG_ANY = 0x00; public final static byte SCREENLONG_NO = 0x10; public final static byte SCREENLONG_YES = 0x20; public final static byte MASK_UI_MODE_TYPE = 0x0f; public final static byte UI_MODE_TYPE_ANY = 0x00; public final static byte UI_MODE_TYPE_NORMAL = 0x01; public final static byte UI_MODE_TYPE_DESK = 0x02; public final static byte UI_MODE_TYPE_CAR = 0x03; public final static byte UI_MODE_TYPE_TELEVISION = 0x04; public final static byte UI_MODE_TYPE_APPLIANCE = 0x05; public final static byte UI_MODE_TYPE_WATCH = 0x06; public final static byte UI_MODE_TYPE_VR_HEADSET = 0x07; // start - miui public final static byte UI_MODE_TYPE_GODZILLAUI = 0x0b; public final static byte UI_MODE_TYPE_SMALLUI = 0x0c; public final static byte UI_MODE_TYPE_MEDIUMUI = 0x0d; public final static byte UI_MODE_TYPE_LARGEUI = 0x0e; public final static byte UI_MODE_TYPE_HUGEUI = 0x0f; // end - miui public final static byte MASK_UI_MODE_NIGHT = 0x30; public final static byte UI_MODE_NIGHT_ANY = 0x00; public final static byte UI_MODE_NIGHT_NO = 0x10; public final static byte UI_MODE_NIGHT_YES = 0x20; public final static byte COLOR_HDR_MASK = 0xC; public final static byte COLOR_HDR_NO = 0x4; public final static byte COLOR_HDR_SHIFT = 0x2; public final static byte COLOR_HDR_UNDEFINED = 0x0; public final static byte COLOR_HDR_YES = 0x8; public final static byte COLOR_UNDEFINED = 0x0; public final static byte COLOR_WIDE_UNDEFINED = 0x0; public final static byte COLOR_WIDE_NO = 0x1; public final static byte COLOR_WIDE_YES = 0x2; public final static byte COLOR_WIDE_MASK = 0x3; private static final Logger LOGGER = Logger.getLogger(ResConfigFlags.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResID.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data; public class ResID { public final int pkgId; public final int type; public final int entry; public final int id; public ResID(int pkgId, int type, int entry) { this(pkgId, type, entry, (pkgId << 24) + (type << 16) + entry); } public ResID(int id) { this((id >> 24) & 0xff, (id >> 16) & 0x000000ff, id & 0x0000ffff, id); } public ResID(int pkgId, int type, int entry, int id) { this.pkgId = (pkgId == 0) ? 2 : pkgId; this.type = type; this.entry = entry; this.id = id; } @Override public String toString() { return String.format("0x%08x", id); } @Override public int hashCode() { int hash = 17; hash = 31 * hash + this.id; return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ResID other = (ResID) obj; return this.id == other.id; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResPackage.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.UndefinedResObjectException; import brut.androlib.res.data.value.ResFileValue; import brut.androlib.res.data.value.ResValueFactory; import brut.androlib.res.xml.ResValuesXmlSerializable; import brut.util.Duo; import java.util.*; import java.util.logging.Logger; public class ResPackage { private final ResTable mResTable; private final int mId; private final String mName; private final Map<ResID, ResResSpec> mResSpecs = new LinkedHashMap<>(); private final Map<ResConfigFlags, ResType> mConfigs = new LinkedHashMap<>(); private final Map<String, ResTypeSpec> mTypes = new LinkedHashMap<>(); private final Set<ResID> mSynthesizedRes = new HashSet<>(); private ResValueFactory mValueFactory; public ResPackage(ResTable resTable, int id, String name) { this.mResTable = resTable; this.mId = id; this.mName = name; } public List<ResResSpec> listResSpecs() { return new ArrayList<>(mResSpecs.values()); } public boolean hasResSpec(ResID resID) { return mResSpecs.containsKey(resID); } public ResResSpec getResSpec(ResID resID) throws UndefinedResObjectException { ResResSpec spec = mResSpecs.get(resID); if (spec == null) { throw new UndefinedResObjectException("resource spec: " + resID.toString()); } return spec; } public int getResSpecCount() { return mResSpecs.size(); } public ResType getOrCreateConfig(ResConfigFlags flags) { ResType config = mConfigs.get(flags); if (config == null) { config = new ResType(flags); mConfigs.put(flags, config); } return config; } public ResTypeSpec getType(String typeName) throws AndrolibException { ResTypeSpec type = mTypes.get(typeName); if (type == null) { throw new UndefinedResObjectException("type: " + typeName); } return type; } public Set<ResResource> listFiles() { Set<ResResource> ret = new HashSet<>(); for (ResResSpec spec : mResSpecs.values()) { for (ResResource res : spec.listResources()) { if (res.getValue() instanceof ResFileValue) { ret.add(res); } } } return ret; } public Collection<ResValuesFile> listValuesFiles() { Map<Duo<ResTypeSpec, ResType>, ResValuesFile> ret = new HashMap<>(); for (ResResSpec spec : mResSpecs.values()) { for (ResResource res : spec.listResources()) { if (res.getValue() instanceof ResValuesXmlSerializable) { ResTypeSpec type = res.getResSpec().getType(); ResType config = res.getConfig(); Duo<ResTypeSpec, ResType> key = new Duo<>(type, config); ResValuesFile values = ret.get(key); if (values == null) { values = new ResValuesFile(this, type, config); ret.put(key, values); } values.addResource(res); } } } return ret.values(); } public ResTable getResTable() { return mResTable; } public int getId() { return mId; } public String getName() { return mName; } boolean isSynthesized(ResID resId) { return mSynthesizedRes.contains(resId); } public void addResSpec(ResResSpec spec) throws AndrolibException { if (mResSpecs.put(spec.getId(), spec) != null) { throw new AndrolibException("Multiple resource specs: " + spec); } } public void addType(ResTypeSpec type) { if (mTypes.containsKey(type.getName())) { LOGGER.warning("Multiple types detected! " + type + " ignored!"); } else { mTypes.put(type.getName(), type); } } public void addSynthesizedRes(int resId) { mSynthesizedRes.add(new ResID(resId)); } @Override public String toString() { return mName; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ResPackage other = (ResPackage) obj; if (!Objects.equals(this.mResTable, other.mResTable)) { return false; } return this.mId == other.mId; } @Override public int hashCode() { int hash = 17; hash = 31 * hash + (this.mResTable != null ? this.mResTable.hashCode() : 0); hash = 31 * hash + this.mId; return hash; } public ResValueFactory getValueFactory() { if (mValueFactory == null) { mValueFactory = new ResValueFactory(this); } return mValueFactory; } private final static Logger LOGGER = Logger.getLogger(ResPackage.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResResource.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.value.ResValue; public class ResResource { private final ResType mConfig; private final ResResSpec mResSpec; private final ResValue mValue; public ResResource(ResType config, ResResSpec spec, ResValue value) { this.mConfig = config; this.mResSpec = spec; this.mValue = value; } public String getFilePath() { return mResSpec.getType().getName() + mConfig.getFlags().getQualifiers() + "/" + mResSpec.getName(); } public ResType getConfig() { return mConfig; } public ResResSpec getResSpec() { return mResSpec; } public ResValue getValue() { return mValue; } public void replace(ResValue value) throws AndrolibException { ResResource res = new ResResource(mConfig, mResSpec, value); mConfig.addResource(res, true); mResSpec.addResource(res, true); } @Override public String toString() { return getFilePath(); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResResSpec.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.UndefinedResObjectException; import org.apache.commons.lang3.StringUtils; import java.util.Arrays; import java.util.Collections; import java.util.HashSet; import java.util.LinkedHashMap; import java.util.LinkedHashSet; import java.util.Map; import java.util.Set; public class ResResSpec { private final ResID mId; private final String mName; private final ResPackage mPackage; private final ResTypeSpec mType; private final Map<ResConfigFlags, ResResource> mResources = new LinkedHashMap<>(); private static final Set<String> EMPTY_RESOURCE_NAMES = Collections.unmodifiableSet(new HashSet<>(Arrays.asList( "0_resource_name_obfuscated", "(name removed)" ))); public ResResSpec(ResID id, String name, ResPackage pkg, ResTypeSpec type) { this.mId = id; String cleanName; name = EMPTY_RESOURCE_NAMES.contains(name) ? null : name; ResResSpec resResSpec = type.getResSpecUnsafe(name); if (resResSpec != null) { cleanName = String.format("APKTOOL_DUPLICATE_%s_%s", type, id.toString()); } else { cleanName = ((name == null || name.isEmpty()) ? ("APKTOOL_DUMMYVAL_" + id.toString()) : name); } this.mName = cleanName; this.mPackage = pkg; this.mType = type; } public Set<ResResource> listResources() { return new LinkedHashSet<>(mResources.values()); } public ResResource getResource(ResType config) throws AndrolibException { return getResource(config.getFlags()); } public ResResource getResource(ResConfigFlags config) throws AndrolibException { ResResource res = mResources.get(config); if (res == null) { throw new UndefinedResObjectException(String.format("resource: spec=%s, config=%s", this, config)); } return res; } public ResResource getDefaultResource() throws AndrolibException { return getResource(new ResConfigFlags()); } public boolean hasDefaultResource() { return mResources.containsKey(new ResConfigFlags()); } public String getFullName(ResPackage relativeToPackage, boolean excludeType) { return getFullName(getPackage().equals(relativeToPackage), excludeType); } public String getFullName(boolean excludePackage, boolean excludeType) { return (excludePackage ? "" : getPackage().getName() + ":") + (excludeType ? "" : getType().getName() + "/") + getName(); } public ResID getId() { return mId; } public String getName() { return StringUtils.replace(mName, "\"", "q"); } public ResPackage getPackage() { return mPackage; } public ResTypeSpec getType() { return mType; } public void addResource(ResResource res) throws AndrolibException { addResource(res, false); } public void addResource(ResResource res, boolean overwrite) throws AndrolibException { ResConfigFlags flags = res.getConfig().getFlags(); if (mResources.put(flags, res) != null && !overwrite) { throw new AndrolibException(String.format("Multiple resources: spec=%s, config=%s", this, flags)); } } @Override public String toString() { return mId.toString() + " " + mType.toString() + "/" + mName; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResTable.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data; import brut.androlib.ApkDecoder; import brut.androlib.Config; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.UndefinedResObjectException; import brut.androlib.apk.ApkInfo; import brut.androlib.apk.UsesFramework; import brut.androlib.res.Framework; import brut.androlib.res.data.value.ResValue; import brut.androlib.res.decoder.ARSCDecoder; import brut.androlib.res.xml.ResXmlPatcher; import brut.directory.Directory; import brut.directory.DirectoryException; import brut.directory.ExtFile; import com.google.common.base.Strings; import java.io.BufferedInputStream; import java.io.File; import java.io.IOException; import java.util.*; import java.util.logging.Logger; public class ResTable { private final static Logger LOGGER = Logger.getLogger(ApkDecoder.class.getName()); private final Config mConfig; private final ApkInfo mApkInfo; private final Map<Integer, ResPackage> mPackagesById = new HashMap<>(); private final Map<String, ResPackage> mPackagesByName = new HashMap<>(); private final Set<ResPackage> mMainPackages = new LinkedHashSet<>(); private final Set<ResPackage> mFramePackages = new LinkedHashSet<>(); private String mPackageRenamed; private String mPackageOriginal; private int mPackageId; private boolean mMainPkgLoaded = false; public ResTable() { this(Config.getDefaultConfig(), new ApkInfo()); } public ResTable(ExtFile apkFile) { this(Config.getDefaultConfig(), new ApkInfo(apkFile)); } public ResTable(Config config, ApkInfo apkInfo) { mConfig = config; mApkInfo = apkInfo; } public boolean getAnalysisMode() { return mConfig.analysisMode; } public boolean isMainPkgLoaded() { return mMainPkgLoaded; } public ResResSpec getResSpec(int resID) throws AndrolibException { // The pkgId is 0x00. That means a shared library is using its // own resource, so lie to the caller replacing with its own // packageId if (resID >> 24 == 0) { int pkgId = (mPackageId == 0 ? 2 : mPackageId); resID = (0xFF000000 & (pkgId << 24)) | resID; } return getResSpec(new ResID(resID)); } public ResResSpec getResSpec(ResID resID) throws AndrolibException { return getPackage(resID.pkgId).getResSpec(resID); } public Set<ResPackage> listMainPackages() { return mMainPackages; } public Set<ResPackage> listFramePackages() { return mFramePackages; } public ResPackage getPackage(int id) throws AndrolibException { ResPackage pkg = mPackagesById.get(id); if (pkg != null) { return pkg; } pkg = loadFrameworkPkg(id); addPackage(pkg, false); return pkg; } private ResPackage selectPkgWithMostResSpecs(ResPackage[] pkgs) { int id = 0; int value = 0; int index = 0; for (int i = 0; i < pkgs.length; i++) { ResPackage resPackage = pkgs[i]; if (resPackage.getResSpecCount() > value && ! resPackage.getName().equalsIgnoreCase("android")) { value = resPackage.getResSpecCount(); id = resPackage.getId(); index = i; } } // if id is still 0, we only have one pkgId which is "android" -> 1 return (id == 0) ? pkgs[0] : pkgs[index]; } public void loadMainPkg(ExtFile apkFile) throws AndrolibException { LOGGER.info("Loading resource table..."); ResPackage[] pkgs = loadResPackagesFromApk(apkFile, mConfig.keepBrokenResources); ResPackage pkg; switch (pkgs.length) { case 0: pkg = new ResPackage(this, 0, null); break; case 1: pkg = pkgs[0]; break; case 2: LOGGER.warning("Skipping package group: " + pkgs[0].getName()); pkg = pkgs[1]; break; default: pkg = selectPkgWithMostResSpecs(pkgs); break; } addPackage(pkg, true); mMainPkgLoaded = true; } private ResPackage loadFrameworkPkg(int id) throws AndrolibException { Framework framework = new Framework(mConfig); File frameworkApk = framework.getFrameworkApk(id, mConfig.frameworkTag); LOGGER.info("Loading resource table from file: " + frameworkApk); ResPackage[] pkgs = loadResPackagesFromApk(new ExtFile(frameworkApk), true); ResPackage pkg; if (pkgs.length > 1) { pkg = selectPkgWithMostResSpecs(pkgs); } else if (pkgs.length == 0) { throw new AndrolibException("Arsc files with zero or multiple packages"); } else { pkg = pkgs[0]; } if (pkg.getId() != id) { throw new AndrolibException("Expected pkg of id: " + id + ", got: " + pkg.getId()); } return pkg; } private ResPackage[] loadResPackagesFromApk(ExtFile apkFile, boolean keepBrokenResources) throws AndrolibException { try { Directory dir = apkFile.getDirectory(); try (BufferedInputStream bfi = new BufferedInputStream(dir.getFileInput("resources.arsc"))) { return ARSCDecoder.decode(bfi, false, keepBrokenResources, this).getPackages(); } } catch (DirectoryException | IOException ex) { throw new AndrolibException("Could not load resources.arsc from file: " + apkFile, ex); } } public ResPackage getHighestSpecPackage() throws AndrolibException { int id = 0; int value = 0; for (ResPackage resPackage : mPackagesById.values()) { if (resPackage.getResSpecCount() > value && !resPackage.getName().equalsIgnoreCase("android")) { value = resPackage.getResSpecCount(); id = resPackage.getId(); } } // if id is still 0, we only have one pkgId which is "android" -> 1 return (id == 0) ? getPackage(1) : getPackage(id); } public ResPackage getCurrentResPackage() throws AndrolibException { ResPackage pkg = mPackagesById.get(mPackageId); if (pkg != null) { return pkg; } else { if (mMainPackages.size() == 1) { return mMainPackages.iterator().next(); } return getHighestSpecPackage(); } } public ResPackage getPackage(String name) throws AndrolibException { ResPackage pkg = mPackagesByName.get(name); if (pkg == null) { throw new UndefinedResObjectException("package: name=" + name); } return pkg; } public ResValue getValue(String package_, String type, String name) throws AndrolibException { return getPackage(package_).getType(type).getResSpec(name).getDefaultResource().getValue(); } public void addPackage(ResPackage pkg, boolean main) throws AndrolibException { Integer id = pkg.getId(); if (mPackagesById.containsKey(id)) { throw new AndrolibException("Multiple packages: id=" + id); } String name = pkg.getName(); if (mPackagesByName.containsKey(name)) { throw new AndrolibException("Multiple packages: name=" + name); } mPackagesById.put(id, pkg); mPackagesByName.put(name, pkg); if (main) { mMainPackages.add(pkg); } else { mFramePackages.add(pkg); } } public void setPackageRenamed(String pkg) { mPackageRenamed = pkg; } public void setPackageOriginal(String pkg) { mPackageOriginal = pkg; } public void setPackageId(int id) { mPackageId = id; } public void setSharedLibrary(boolean flag) { mApkInfo.sharedLibrary = flag; } public void setSparseResources(boolean flag) { if (mApkInfo.sparseResources != flag) { LOGGER.info("Sparsely packed resources detected."); } mApkInfo.sparseResources = flag; } public void clearSdkInfo() { mApkInfo.getSdkInfo().clear(); } public void addSdkInfo(String key, String value) { mApkInfo.getSdkInfo().put(key, value); } public void setVersionName(String versionName) { mApkInfo.versionInfo.versionName = versionName; } public void setVersionCode(String versionCode) { mApkInfo.versionInfo.versionCode = versionCode; } public String getPackageRenamed() { return mPackageRenamed; } public String getPackageOriginal() { return mPackageOriginal; } public int getPackageId() { return mPackageId; } public boolean getSparseResources() { return mApkInfo.sparseResources; } private boolean isFrameworkApk() { for (ResPackage pkg : mMainPackages) { if (pkg.getId() > 0 && pkg.getId() < 64) { return true; } } return false; } public void initApkInfo(ApkInfo apkInfo, File outDir) throws AndrolibException { apkInfo.isFrameworkApk = isFrameworkApk(); apkInfo.usesFramework = getUsesFramework(); if (!mApkInfo.getSdkInfo().isEmpty()) { updateSdkInfoFromResources(outDir); } initPackageInfo(); loadVersionName(outDir); } private UsesFramework getUsesFramework() { UsesFramework info = new UsesFramework(); Integer[] ids = new Integer[mFramePackages.size()]; int i = 0; for (ResPackage pkg : mFramePackages) { ids[i++] = pkg.getId(); } Arrays.sort(ids); info.ids = Arrays.asList(ids); info.tag = mConfig.frameworkTag; return info; } private void updateSdkInfoFromResources(File outDir) { String refValue; Map<String, String> sdkInfo = mApkInfo.getSdkInfo(); if (sdkInfo.get("minSdkVersion") != null) { refValue = ResXmlPatcher.pullValueFromIntegers(outDir, sdkInfo.get("minSdkVersion")); if (refValue != null) { sdkInfo.put("minSdkVersion", refValue); } } if (sdkInfo.get("targetSdkVersion") != null) { refValue = ResXmlPatcher.pullValueFromIntegers(outDir, sdkInfo.get("targetSdkVersion")); if (refValue != null) { sdkInfo.put("targetSdkVersion", refValue); } } if (sdkInfo.get("maxSdkVersion") != null) { refValue = ResXmlPatcher.pullValueFromIntegers(outDir, sdkInfo.get("maxSdkVersion")); if (refValue != null) { sdkInfo.put("maxSdkVersion", refValue); } } } private void initPackageInfo() throws AndrolibException { String renamed = getPackageRenamed(); String original = getPackageOriginal(); int id = getPackageId(); try { id = getPackage(renamed).getId(); } catch (UndefinedResObjectException ignored) {} if (Strings.isNullOrEmpty(original)) { return; } // only put rename-manifest-package into apktool.yml, if the change will be required if (renamed != null && !renamed.equalsIgnoreCase(original)) { mApkInfo.packageInfo.renameManifestPackage = renamed; } mApkInfo.packageInfo.forcedPackageId = String.valueOf(id); } private void loadVersionName(File outDir) { String versionName = mApkInfo.versionInfo.versionName; String refValue = ResXmlPatcher.pullValueFromStrings(outDir, versionName); if (refValue != null) { mApkInfo.versionInfo.versionName = refValue; } } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResType.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.UndefinedResObjectException; import java.util.*; public class ResType { private final ResConfigFlags mFlags; private final Map<ResResSpec, ResResource> mResources = new LinkedHashMap<>(); public ResType(ResConfigFlags flags) { this.mFlags = flags; } public ResResource getResource(ResResSpec spec) throws AndrolibException { ResResource res = mResources.get(spec); if (res == null) { throw new UndefinedResObjectException(String.format("resource: spec=%s, config=%s", spec, this)); } return res; } public ResConfigFlags getFlags() { return mFlags; } public void addResource(ResResource res) throws AndrolibException { addResource(res, false); } public void addResource(ResResource res, boolean overwrite) throws AndrolibException { ResResSpec spec = res.getResSpec(); if (mResources.put(spec, res) != null && !overwrite) { throw new AndrolibException(String.format("Multiple resources: spec=%s, config=%s", spec, this)); } } @Override public String toString() { return mFlags.toString(); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResTypeSpec.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data; import brut.androlib.exceptions.AndrolibException; import brut.androlib.exceptions.UndefinedResObjectException; import java.util.*; public final class ResTypeSpec { public static final String RES_TYPE_NAME_ARRAY = "array"; public static final String RES_TYPE_NAME_PLURALS = "plurals"; public static final String RES_TYPE_NAME_STYLES = "style"; public static final String RES_TYPE_NAME_ATTR = "attr"; private final String mName; private final Map<String, ResResSpec> mResSpecs = new LinkedHashMap<>(); private final int mId; public ResTypeSpec(String name, int id) { this.mName = name; this.mId = id; } public String getName() { return mName; } public int getId() { return mId; } public boolean isString() { return mName.equalsIgnoreCase("string"); } public ResResSpec getResSpec(String name) throws AndrolibException { ResResSpec spec = getResSpecUnsafe(name); if (spec == null) { throw new UndefinedResObjectException(String.format("resource spec: %s/%s", getName(), name)); } return spec; } public ResResSpec getResSpecUnsafe(String name) { return mResSpecs.get(name); } public void addResSpec(ResResSpec spec) throws AndrolibException { if (mResSpecs.put(spec.getName(), spec) != null) { throw new AndrolibException(String.format("Multiple res specs: %s/%s", getName(), spec.getName())); } } @Override public String toString() { return mName; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ResValuesFile.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data; import java.util.LinkedHashSet; import java.util.Objects; import java.util.Set; public class ResValuesFile { private final ResPackage mPackage; private final ResTypeSpec mType; private final ResType mConfig; private final Set<ResResource> mResources = new LinkedHashSet<>(); public ResValuesFile(ResPackage pkg, ResTypeSpec type, ResType config) { this.mPackage = pkg; this.mType = type; this.mConfig = config; } public String getPath() { return "values" + mConfig.getFlags().getQualifiers() + "/" + mType.getName() + (mType.getName().endsWith("s") ? "" : "s") + ".xml"; } public Set<ResResource> listResources() { return mResources; } public ResTypeSpec getType() { return mType; } public boolean isSynthesized(ResResource res) { return mPackage.isSynthesized(res.getResSpec().getId()); } public void addResource(ResResource res) { mResources.add(res); } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final ResValuesFile other = (ResValuesFile) obj; if (!Objects.equals(this.mType, other.mType)) { return false; } return Objects.equals(this.mConfig, other.mConfig); } @Override public int hashCode() { int hash = 17; hash = 31 * hash + (this.mType != null ? this.mType.hashCode() : 0); hash = 31 * hash + (this.mConfig != null ? this.mConfig.hashCode() : 0); return hash; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/arsc/ARSCData.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data.arsc; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResPackage; import java.util.logging.Logger; public class ARSCData { private final ResPackage[] mPackages; private final FlagsOffset[] mFlagsOffsets; public ARSCData(ResPackage[] packages, FlagsOffset[] flagsOffsets) { mPackages = packages; mFlagsOffsets = flagsOffsets; } public FlagsOffset[] getFlagsOffsets() { return mFlagsOffsets; } public ResPackage[] getPackages() { return mPackages; } public ResPackage getOnePackage() throws AndrolibException { if (mPackages.length == 0) { throw new AndrolibException("Arsc file contains zero packages"); } else if (mPackages.length != 1) { int id = findPackageWithMostResSpecs(); LOGGER.info("Arsc file contains multiple packages. Using package " + mPackages[id].getName() + " as default."); return mPackages[id]; } return mPackages[0]; } public int findPackageWithMostResSpecs() { int count = mPackages[0].getResSpecCount(); int id = 0; for (int i = 0; i < mPackages.length; i++) { if (mPackages[i].getResSpecCount() >= count) { count = mPackages[i].getResSpecCount(); id = i; } } return id; } private static final Logger LOGGER = Logger.getLogger(ARSCData.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/arsc/ARSCHeader.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data.arsc; import brut.util.ExtCountingDataInput; import brut.util.ExtDataInput; import java.io.EOFException; import java.io.IOException; import java.math.BigInteger; import java.util.logging.Logger; public class ARSCHeader { public final short type; public final int headerSize; public final int chunkSize; public final int startPosition; public final int endPosition; public ARSCHeader(short type, int headerSize, int chunkSize, int headerStart) { this.type = type; this.headerSize = headerSize; this.chunkSize = chunkSize; this.startPosition = headerStart; this.endPosition = headerStart + chunkSize; } public static ARSCHeader read(ExtCountingDataInput in) throws IOException { short type; int start = in.position(); try { type = in.readShort(); } catch (EOFException ex) { return new ARSCHeader(RES_NONE_TYPE, 0, 0, in.position()); } return new ARSCHeader(type, in.readShort(), in.readInt(), start); } public void checkForUnreadHeader(ExtCountingDataInput in) throws IOException { // Some applications lie about the reported size of their chunk header. Trusting the chunkSize is misleading // So compare to what we actually read in the header vs reported and skip the rest. // However, this runs after each chunk and not every chunk reading has a specific distinction between the // header and the body. int actualHeaderSize = in.position() - this.startPosition; int exceedingSize = this.headerSize - actualHeaderSize; if (exceedingSize > 0) { byte[] buf = new byte[exceedingSize]; in.readFully(buf); BigInteger exceedingBI = new BigInteger(1, buf); if (exceedingBI.equals(BigInteger.ZERO)) { LOGGER.fine(String.format("Chunk header size (%d), read (%d), but exceeding bytes are all zero.", this.headerSize, actualHeaderSize )); } else { LOGGER.warning(String.format("Chunk header size (%d), read (%d). Exceeding bytes: 0x%X.", this.headerSize, actualHeaderSize, exceedingBI )); } } } public void skipChunk(ExtDataInput in) throws IOException { in.skipBytes(chunkSize - headerSize); } public final static short RES_NONE_TYPE = -1; public final static short RES_NULL_TYPE = 0x0000; public final static short RES_STRING_POOL_TYPE = 0x0001; public final static short RES_TABLE_TYPE = 0x0002; public final static short RES_XML_TYPE = 0x0003; // RES_TABLE_TYPE Chunks public final static short XML_TYPE_PACKAGE = 0x0200; public final static short XML_TYPE_TYPE = 0x0201; public final static short XML_TYPE_SPEC_TYPE = 0x0202; public final static short XML_TYPE_LIBRARY = 0x0203; public final static short XML_TYPE_OVERLAY = 0x0204; public final static short XML_TYPE_OVERLAY_POLICY = 0x0205; public final static short XML_TYPE_STAGED_ALIAS = 0x0206; // RES_XML_TYPE Chunks public final static short RES_XML_FIRST_CHUNK_TYPE = 0x0100; public final static short RES_XML_START_NAMESPACE_TYPE = 0x0100; public final static short RES_XML_END_NAMESPACE_TYPE = 0x0101; public final static short RES_XML_START_ELEMENT_TYPE = 0x0102; public final static short RES_XML_END_ELEMENT_TYPE = 0x0103; public final static short RES_XML_CDATA_TYPE = 0x0104; public final static short RES_XML_LAST_CHUNK_TYPE = 0x017f; public final static short RES_XML_RESOURCE_MAP_TYPE = 0x0180; private static final Logger LOGGER = Logger.getLogger(ARSCHeader.class.getName()); }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/arsc/EntryData.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data.arsc; import brut.androlib.res.data.value.ResValue; public class EntryData { public short mFlags; public int mSpecNamesId; public ResValue mValue; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/arsc/FlagsOffset.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data.arsc; public class FlagsOffset { public final int offset; public final int count; public FlagsOffset(int offset, int count) { this.offset = offset; this.count = count; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/axml/NamespaceStack.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data.axml; /** * Namespace stack, holds prefix+uri pairs, as well as depth information. * All information is stored in one int[] array. Array consists of depth * frames: Data=DepthFrame*; DepthFrame=Count+[Prefix+Uri]*+Count; * Count='count of Prefix+Uri pairs'; Yes, count is stored twice, to enable * bottom-up traversal. increaseDepth adds depth frame, decreaseDepth * removes it. push/pop operations operate only in current depth frame. * decreaseDepth removes any remaining (not pop'ed) namespace pairs. findXXX * methods search all depth frames starting from the last namespace pair of * current depth frame. All functions that operate with int, use -1 as * 'invalid value'. * <p> * !! functions expect 'prefix'+'uri' pairs, not 'uri'+'prefix' !! */ public final class NamespaceStack { private int[] m_data; private int m_dataLength; private int m_depth; public NamespaceStack() { m_data = new int[32]; } public void reset() { m_dataLength = 0; m_depth = 0; } public int getCurrentCount() { if (m_dataLength == 0) { return 0; } int offset = m_dataLength - 1; return m_data[offset]; } public int getAccumulatedCount(int depth) { if (m_dataLength == 0 || depth < 0) { return 0; } if (depth > m_depth) { depth = m_depth; } int accumulatedCount = 0; int offset = 0; for (; depth != 0; --depth) { int count = m_data[offset]; accumulatedCount += count; offset += (2 + count * 2); } return accumulatedCount; } public void push(int prefix, int uri) { if (m_depth == 0) { increaseDepth(); } ensureDataCapacity(2); int offset = m_dataLength - 1; int count = m_data[offset]; m_data[offset - 1 - count * 2] = count + 1; m_data[offset] = prefix; m_data[offset + 1] = uri; m_data[offset + 2] = count + 1; m_dataLength += 2; } public boolean pop() { if (m_dataLength == 0) { return false; } int offset = m_dataLength - 1; int count = m_data[offset]; if (count == 0) { return false; } count -= 1; offset -= 2; m_data[offset] = count; offset -= (1 + count * 2); m_data[offset] = count; m_dataLength -= 2; return true; } public int getPrefix(int index) { return get(index, true); } public int getUri(int index) { return get(index, false); } public int findPrefix(int uri) { return find(uri, false); } public int getDepth() { return m_depth; } public void increaseDepth() { ensureDataCapacity(2); int offset = m_dataLength; m_data[offset] = 0; m_data[offset + 1] = 0; m_dataLength += 2; m_depth += 1; } public void decreaseDepth() { if (m_dataLength == 0) { return; } int offset = m_dataLength - 1; int count = m_data[offset]; if ((offset - 1 - count * 2) == 0) { return; } m_dataLength -= 2 + count * 2; m_depth -= 1; } private void ensureDataCapacity(int capacity) { int available = (m_data.length - m_dataLength); if (available > capacity) { return; } int newLength = (m_data.length + available) * 2; int[] newData = new int[newLength]; System.arraycopy(m_data, 0, newData, 0, m_dataLength); m_data = newData; } private int find(int prefixOrUri, boolean prefix) { if (m_dataLength == 0) { return -1; } int offset = m_dataLength - 1; for (int i = m_depth; i != 0; --i) { int count = m_data[offset]; offset -= 2; for (; count != 0; --count) { if (prefix) { if (m_data[offset] == prefixOrUri) { return m_data[offset + 1]; } } else { if (m_data[offset + 1] == prefixOrUri) { return m_data[offset]; } } offset -= 2; } } return -1; } private int get(int index, boolean prefix) { if (m_dataLength == 0 || index < 0) { return -1; } int offset = 0; for (int i = m_depth; i != 0; --i) { int count = m_data[offset]; if (index >= count) { index -= count; offset += (2 + count * 2); continue; } offset += (1 + index * 2); if (!prefix) { offset += 1; } return m_data[offset]; } return -1; } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ninepatch/NinePatchData.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data.ninepatch; import brut.util.ExtDataInput; import java.io.IOException; public class NinePatchData { public final int padLeft, padRight, padTop, padBottom; public final int[] xDivs, yDivs; public NinePatchData(int padLeft, int padRight, int padTop, int padBottom, int[] xDivs, int[] yDivs) { this.padLeft = padLeft; this.padRight = padRight; this.padTop = padTop; this.padBottom = padBottom; this.xDivs = xDivs; this.yDivs = yDivs; } public static NinePatchData decode(ExtDataInput di) throws IOException { di.skipBytes(1); // wasDeserialized byte numXDivs = di.readByte(); byte numYDivs = di.readByte(); di.skipBytes(1); // numColors di.skipBytes(8); // xDivs/yDivs offset int padLeft = di.readInt(); int padRight = di.readInt(); int padTop = di.readInt(); int padBottom = di.readInt(); di.skipBytes(4); // colorsOffset int[] xDivs = di.readIntArray(numXDivs); int[] yDivs = di.readIntArray(numYDivs); return new NinePatchData(padLeft, padRight, padTop, padBottom, xDivs, yDivs); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/ninepatch/OpticalInset.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data.ninepatch; import brut.util.ExtDataInput; import java.io.IOException; public class OpticalInset { public final int layoutBoundsLeft, layoutBoundsTop, layoutBoundsRight, layoutBoundsBottom; public OpticalInset(int layoutBoundsLeft, int layoutBoundsTop, int layoutBoundsRight, int layoutBoundsBottom) { this.layoutBoundsLeft = layoutBoundsLeft; this.layoutBoundsTop = layoutBoundsTop; this.layoutBoundsRight = layoutBoundsRight; this.layoutBoundsBottom = layoutBoundsBottom; } public static OpticalInset decode(ExtDataInput di) throws IOException { int layoutBoundsLeft = Integer.reverseBytes(di.readInt()); int layoutBoundsTop = Integer.reverseBytes(di.readInt()); int layoutBoundsRight = Integer.reverseBytes(di.readInt()); int layoutBoundsBottom = Integer.reverseBytes(di.readInt()); return new OpticalInset(layoutBoundsLeft, layoutBoundsTop, layoutBoundsRight, layoutBoundsBottom); } }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResArrayValue.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResResource; import brut.androlib.res.xml.ResValuesXmlSerializable; import brut.util.Duo; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; import java.util.Arrays; public class ResArrayValue extends ResBagValue implements ResValuesXmlSerializable { ResArrayValue(ResReferenceValue parent, Duo<Integer, ResScalarValue>[] items) { super(parent); mItems = new ResScalarValue[items.length]; for (int i = 0; i < items.length; i++) { mItems[i] = items[i].m2; } } public ResArrayValue(ResReferenceValue parent, ResScalarValue[] items) { super(parent); mItems = items; } @Override public void serializeToResValuesXml(XmlSerializer serializer, ResResource res) throws IOException, AndrolibException { String type = getType(); type = (type == null ? "" : type + "-") + "array"; serializer.startTag(null, type); serializer.attribute(null, "name", res.getResSpec().getName()); // lets check if we need to add formatted="false" to this array for (ResScalarValue item : mItems) { if (item.hasMultipleNonPositionalSubstitutions()) { serializer.attribute(null, "formatted", "false"); break; } } // add <item>'s for (ResScalarValue mItem : mItems) { serializer.startTag(null, "item"); serializer.text(mItem.encodeAsResXmlNonEscapedItemValue()); serializer.endTag(null, "item"); } serializer.endTag(null, type); } public String getType() throws AndrolibException { if (mItems.length == 0) { return null; } String type = mItems[0].getType(); for (ResScalarValue mItem : mItems) { if (mItem.encodeAsResXmlItemValue().startsWith("@string")) { return "string"; } else if (mItem.encodeAsResXmlItemValue().startsWith("@drawable")) { return null; } else if (mItem.encodeAsResXmlItemValue().startsWith("@integer")) { return "integer"; } else if (!"string".equals(type) && !"integer".equals(type)) { return null; } else if (!type.equals(mItem.getType())) { return null; } } if (!Arrays.asList(AllowedArrayTypes).contains(type)) { return "string"; } return type; } private final ResScalarValue[] mItems; private final String[] AllowedArrayTypes = {"string", "integer"}; public static final int BAG_KEY_ARRAY_START = 0x02000000; }
Java
Apktool/brut.apktool/apktool-lib/src/main/java/brut/androlib/res/data/value/ResAttr.java
/* * Copyright (C) 2010 Ryszard WiÅ›niewski <[email protected]> * Copyright (C) 2010 Connor Tumbleson <[email protected]> * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package brut.androlib.res.data.value; import brut.androlib.exceptions.AndrolibException; import brut.androlib.res.data.ResPackage; import brut.androlib.res.data.ResResource; import brut.androlib.res.xml.ResValuesXmlSerializable; import brut.util.Duo; import org.xmlpull.v1.XmlSerializer; import java.io.IOException; public class ResAttr extends ResBagValue implements ResValuesXmlSerializable { ResAttr(ResReferenceValue parentVal, int type, Integer min, Integer max, Boolean l10n) { super(parentVal); mType = type; mMin = min; mMax = max; mL10n = l10n; } public String convertToResXmlFormat(ResScalarValue value) throws AndrolibException { return null; } @Override public void serializeToResValuesXml(XmlSerializer serializer, ResResource res) throws IOException, AndrolibException { String type = getTypeAsString(); serializer.startTag(null, "attr"); serializer.attribute(null, "name", res.getResSpec().getName()); if (type != null) { serializer.attribute(null, "format", type); } if (mMin != null) { serializer.attribute(null, "min", mMin.toString()); } if (mMax != null) { serializer.attribute(null, "max", mMax.toString()); } if (mL10n != null && mL10n) { serializer.attribute(null, "localization", "suggested"); } serializeBody(serializer, res); serializer.endTag(null, "attr"); } public static ResAttr factory(ResReferenceValue parent, Duo<Integer, ResScalarValue>[] items, ResValueFactory factory, ResPackage pkg) throws AndrolibException { int type = ((ResIntValue) items[0].m2).getValue(); int scalarType = type & 0xffff; Integer min = null, max = null; Boolean l10n = null; int i; for (i = 1; i < items.length; i++) { switch (items[i].m1) { case BAG_KEY_ATTR_MIN: min = ((ResIntValue) items[i].m2).getValue(); continue; case BAG_KEY_ATTR_MAX: max = ((ResIntValue) items[i].m2).getValue(); continue; case BAG_KEY_ATTR_L10N: l10n = ((ResIntValue) items[i].m2).getValue() != 0; continue; } break; } if (i == items.length) { return new ResAttr(parent, scalarType, min, max, l10n); } Duo<ResReferenceValue, ResIntValue>[] attrItems = new Duo[items.length - i]; int j = 0; for (; i < items.length; i++) { int resId = items[i].m1; pkg.addSynthesizedRes(resId); attrItems[j++] = new Duo<>(factory.newReference(resId, null), (ResIntValue) items[i].m2); } switch (type & 0xff0000) { case TYPE_ENUM: return new ResEnumAttr(parent, scalarType, min, max, l10n, attrItems); case TYPE_FLAGS: return new ResFlagsAttr(parent, scalarType, min, max, l10n, attrItems); } throw new AndrolibException("Could not decode attr value"); } protected void serializeBody(XmlSerializer serializer, ResResource res) throws IOException, AndrolibException { } protected String getTypeAsString() { String s = ""; if ((mType & TYPE_REFERENCE) != 0) { s += "|reference"; } if ((mType & TYPE_STRING) != 0) { s += "|string"; } if ((mType & TYPE_INT) != 0) { s += "|integer"; } if ((mType & TYPE_BOOL) != 0) { s += "|boolean"; } if ((mType & TYPE_COLOR) != 0) { s += "|color"; } if ((mType & TYPE_FLOAT) != 0) { s += "|float"; } if ((mType & TYPE_DIMEN) != 0) { s += "|dimension"; } if ((mType & TYPE_FRACTION) != 0) { s += "|fraction"; } if (s.isEmpty()) { return null; } return s.substring(1); } private final int mType; private final Integer mMin; private final Integer mMax; private final Boolean mL10n; public static final int BAG_KEY_ATTR_TYPE = 0x01000000; private static final int BAG_KEY_ATTR_MIN = 0x01000001; private static final int BAG_KEY_ATTR_MAX = 0x01000002; private static final int BAG_KEY_ATTR_L10N = 0x01000003; private final static int TYPE_REFERENCE = 0x01; private final static int TYPE_STRING = 0x02; private final static int TYPE_INT = 0x04; private final static int TYPE_BOOL = 0x08; private final static int TYPE_COLOR = 0x10; private final static int TYPE_FLOAT = 0x20; private final static int TYPE_DIMEN = 0x40; private final static int TYPE_FRACTION = 0x80; private final static int TYPE_ANY_STRING = 0xee; private static final int TYPE_ENUM = 0x00010000; private static final int TYPE_FLAGS = 0x00020000; }