• Stars
    star
    183
  • Rank 205,693 (Top 5 %)
  • Language
    Java
  • License
    Other
  • Created over 2 years ago
  • Updated 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

ADB library for Android

LibADB Android

ADB library for Android. It enables an app to connect to the ADB daemon (adbd process) belonging to the same or a different device and execute arbitrary services or commands (via shell: service).

Disclaimer: This library has never gone through a security audit. Please, proceed with caution if security is crucial for your app. Avoid using the APIs for reasons other than connecting or using ADB. For the safety of your app and its users, open a remote service instead of using ADB and ask the user to disconnect Wireless debugging.

Getting Started

Adding Dependencies

LibADB Android is available via JitPack.

// Top level build file
repositories {
    mavenCentral()
    maven { url "https://jitpack.io" }
}

// Add to dependencies section
dependencies {
    // Add this library
    implementation 'com.github.MuntashirAkon:libadb-android:1.0.1'
    
    // Library to generate X509Certificate. You can also use BouncyCastle for
    // this. See example for use-case.
    // implementation 'com.github.MuntashirAkon:sun-security-android:1.1'

    // Bypass hidden API if you want to use the Android default Conscrypt in
    // Android 9 (Pie) or later. It also requires additional steps. See
    // https://github.com/LSPosed/AndroidHiddenApiBypass to find out more about
    // this.
    // implementation 'org.lsposed.hiddenapibypass:hiddenapibypass:2.0'

    // Use custom Conscrypt library. If you want to connect to a remote ADB
    // daemon instead of the device the app is currently running or do not want
    // to bypass hidden API, this is the recommended choice.
    implementation 'org.conscrypt:conscrypt-android:2.5.2'
}

If you're using the custom Conscrypt library in order to connect to a remote ADB daemon and the app targets Android version below 4.4, you have to extend android.app.Application to apply fixes for the random number generation:

public class MyAwesomeApp extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
        // Fix random number generation in Android versions below 4.4.
        PRNGFixes.apply();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        // Uncomment the following line if you want to bypass hidden API as
        // described above.
        // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
        //     HiddenApiBypass.addHiddenApiExemptions("L");
        // }
    }
}

Notice: Conscrypt supports only API 9 (Gingerbread) or later, meaning you cannot use ADB pairing or any TLSv1.3 features in API less than 9. The corresponding methods are already annotated properly. So, you don't have to worry about compatibility issues that may arise when your app's minimum SDK is set to one of the unsupported versions.

Configuring ADB

Instead of doing everything manually, you can create a concrete implementation of the AbsAdbConnectionManager class. Example:

public class AdbConnectionManager extends AbsAdbConnectionManager {
    private static AbsAdbConnectionManager INSTANCE;

    public static AbsAdbConnectionManager getInstance() throws Exception {
        if (INSTANCE == null) {
            INSTANCE = new AdbConnectionManager();
        }
        return INSTANCE;
    }

    private PrivateKey mPrivateKey;
    private Certificate mCertificate;

    private AdbConnectionManager() throws Exception {
        // Set the API version whose `adbd` is running
        setApi(Build.VERSION.SDK_INT);
        // TODO: Load private key and certificate (along with public key) from
        //  some place such as KeyStore or file system.
        mPrivateKey = ...;
        mCertificate = ...;
        if (mPrivateKey == null) {
            // Generate a new key pair
            int keySize = 2048;
            KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
            keyPairGenerator.initialize(keySize, SecureRandom.getInstance("SHA1PRNG"));
            KeyPair generateKeyPair = keyPairGenerator.generateKeyPair();
            PublicKey publicKey = generateKeyPair.getPublic();
            mPrivateKey = generateKeyPair.getPrivate();
            // Generate a certificate
            // On Android, it requires sun.security-android library as mentioned
            // above.
            String subject = "CN=My Awesome App";
            String algorithmName = "SHA512withRSA";
            long expiryDate = System.currentTimeMillis() + 86400000;
            CertificateExtensions certificateExtensions = new CertificateExtensions();
            certificateExtensions.set("SubjectKeyIdentifier", new SubjectKeyIdentifierExtension(
                    new KeyIdentifier(publicKey).getIdentifier()));
            X500Name x500Name = new X500Name(subject);
            Date notBefore = new Date();
            Date notAfter = new Date(expiryDate);
            certificateExtensions.set("PrivateKeyUsage", new PrivateKeyUsageExtension(notBefore, notAfter));
            CertificateValidity certificateValidity = new CertificateValidity(notBefore, notAfter);
            X509CertInfo x509CertInfo = new X509CertInfo();
            x509CertInfo.set("version", new CertificateVersion(2));
            x509CertInfo.set("serialNumber", new CertificateSerialNumber(new Random().nextInt() & Integer.MAX_VALUE));
            x509CertInfo.set("algorithmID", new CertificateAlgorithmId(AlgorithmId.get(algorithmName)));
            x509CertInfo.set("subject", new CertificateSubjectName(x500Name));
            x509CertInfo.set("key", new CertificateX509Key(publicKey));
            x509CertInfo.set("validity", certificateValidity);
            x509CertInfo.set("issuer", new CertificateIssuerName(x500Name));
            x509CertInfo.set("extensions", certificateExtensions);
            X509CertImpl x509CertImpl = new X509CertImpl(x509CertInfo);
            x509CertImpl.sign(mPrivateKey, algorithmName);
            mCertificate = x509CertImpl;
            // TODO: Store the key pair to some place else.
        }
    }

    @NonNull
    @Override
    protected PrivateKey getPrivateKey() {
        return mPrivateKey;
    }

    @NonNull
    @Override
    protected Certificate getCertificate() {
        return mCertificate;
    }

    @NonNull
    @Override
    protected String getDeviceName() {
        return "MyAwesomeApp";
    }
}

Connecting to ADB

You can connect to ADB in several ways from the AbsAdbConnectionManager:

Method Description
connect(host, port) Connect using a host address and a port number
connect(port) Connect using a host address set by setHostAddress() and a port number
connectTcp(Context, timeout) (SDK 16+) Discover host address and port number automatically for ADB over TCP and connect to it
connectTls(Context, timeout) (SDK 16+) Discover host address and port number automatically for TLS (from Android 9) and connect to it
autoConnect(Context, timeout) (SDK 16+) Discover host address and port number automatically for both ADB over TCP and TLS and connect to it

Wireless Debugging

Internally, ADB over TCP and Wireless Debugging are very similar except Wireless Debugging requires an extra step of pairing the device. In order to pair a new device, you can simply invoke AdbConnectionManager.getInstance().pair(host, port, pairingCode). After the pairing, you can connect to ADB via the usual connect() methods without any additional steps.

Opening ADB Shell for Executing Arbitrary Commands

Simply use AdbConnectionManager.getInstance().openStream("shell:"). This will return an AdbStream which can be used to read/write to the ADB shell via AdbStream#openInputStream() and AdbStream#openOutputStream() methods respectively like a normal Java Process. While it is possible to read/write in the same thread (first write and then read), this is not recommended because the shell might be stuck indefinitely for commands such as top.

NOTE: If you want to create a full-featured terminal emulator, this approach isn't recommended. Instead, you should create a remote service via app_process or start an SSH server and connect to it.

Other services

You can also use other services via the AdbConnectionManager#openStream() methods. See SERVICES.md for more information.

For Java (non-Android) Projects

It is possible to modify this library to work on non-Android project. But it isn't supported because Spake2-Java only provides stable releases for Android. However, you can incorporate this library in your project by manually compiling Spake2 library for your platforms.

Contributing

By contributing to this project, you permit your work to be released under the terms of GNU General Public License, Version 3 or later or Apache License, Version 2.0.

Donating

Bitcoin: 3FHTxPoYa92dNJK6pkhwyVkMG8Vv3VpGpg

Ethereum: 0xa048a882301d9503d8c27Da8044c4E72dF14C817

Open Collective: https://opencollective.com/muntashir

License

Copyright 2021 Muntashir Al-Islam

Dual licensed under the terms of GPL-3.0-or-later or Apache-2.0 license. Use whatever license you need for your project.

Note regarding the Apache-2.0 license, this library has an LGPL dependency which may go against the policy of some organizations such as ASF.

More Repositories

1

AppManager

A full-featured package manager and viewer for Android
Java
4,271
star
2

SetEdit

Open source version of the original Settings Database Editor
Java
252
star
3

android-debloat-list

[WIP] A comprehensive list of apps for debloating Android with suggestions and vulnerabilities, based on but independent of UAD project.
PHP
170
star
4

DPCIManager

Simple OS X app for viewing PCI hardware info
Objective-C
131
star
5

CaptivePortalController

Control the captive portal in your Android device, stop phoning home.
Java
88
star
6

unapkm-android

A utility app to convert apkm files to apks on Android.
Java
59
star
7

Chrome-OS-Multiboot

My approach to multiboot Chrome/Chromium OS on regular PCs
Shell
42
star
8

apksig-android

Android port of apksig library.
Java
35
star
9

chrome_os_updater

Update Chrome OS on regular PCs
Python
25
star
10

Messages

SMS app based on QKSMS. DISCLAIMER: This project is intended for my own use. No issues are accepted
Java
18
star
11

DeleteYourAccountFromWebsite

A list of websites and how you can delete account from them
17
star
12

spake2-java

SPAKE2 implementation in Java
Java
15
star
13

android-libraries

Android libraries and/or signatures with classification (type, tags, anti-features)
PHP
14
star
14

sun-security-android

Use the Android-private sun.security library
Java
12
star
15

HackintoshDellInspiron5567

My efforts on installing macOS on Dell Inspiron 15-5567 (i3-7100u, IHD620)
ASL
11
star
16

AdvanceKextUpdater

Keep your kexts up-to-date all the time starting from macOS 10.7
Objective-C
11
star
17

termoneplus

Forked from https://gitlab.com/termapps/termoneplus
Java
11
star
18

zipalign-android

zipalign library for Android projects. Use ARSCLib instead: https://github.com/REAndroid/ARSCLib
C++
10
star
19

UnifiedAppStoreExt

If everything goes correctly, this will be an extension for App Manager which would let people install/update apps from F-Droid and Google Play Store.
7
star
20

AppManagerSDK

Easy-integration of App Manager to third-party apps
Java
7
star
21

hostap_realtek_osx

wpa_supplicant for many Realtek RTL8188 devices
C
6
star
22

rapidfuzz-android

Rapid fuzzy string matching using the Levenshtein Distance. JNI wrapper around RapidFuzz-CPP.
Java
6
star
23

TextWarrior

DISCONTINUED in favour of Sora-Editor (https://github.com/Rosemoe/sora-editor)
Java
5
star
24

BanglaDictionary

A Bangla to Bangla and English to Bangla Dictionary
Java
5
star
25

Apkpurer

Simple client for https://apkpure.com
Kotlin
4
star
26

AppOpsX

Forked from https://github.com/8enet/AppOpsX
Java
4
star
27

svg-android

SVG parsing and rendering for Android. Imported from http://code.google.com/p/svg-android/
Java
3
star
28

FiniteAutomataLabExperiments

Lab experiments of Finite Automata Theory course (CSE 2206 at RUET)
C++
2
star
29

magic-mime-db

A database of magic (used by the unix file command) and MIME types (not necessarily approved by IANA)
Roff
2
star
30

ugc-config

Configurations that I use with UnGoogled Chromium
Shell
2
star
31

blog

SCSS
2
star
32

GooglePasswordManager

DISCONTINUED. Use a sane password manager such as BitWarden or Keepass.
Swift
2
star
33

hackupdater

A startup script for OSx86 (Hackintosh) user to install kexts or run scripts on update or upgrade
PHP
2
star
34

AudioCodecDB

Audio Codec Database
1
star
35

BanglaHadith

Bangla Hadith written in JavaScript for website
JavaScript
1
star
36

KextStatViewer

kextstat viewer for nerds
Objective-C
1
star
37

BanglaAcademyDictionary

Bangla Academy Dictionary - English to Bangla
JavaScript
1
star
38

PHPBitBucketDownloader

A simple PHP library to download the latest binary file from a BitBucket Repo
PHP
1
star
39

GoogleChromeDarkTheme

Dark Mode for Dark Reader
1
star
40

WordGrid

WordGrid Game
PHP
1
star
41

TuitionManagement

Tuition Management System
Python
1
star
42

Mac-OS-Installation-Helper

Mac OS Installation Helper is a tool to that can help you install Mac OS to any supported laptops.
Shell
1
star
43

HackintoshLenovoIdeapad310-15ISK

My attempts to install macOS on Lenovo Ideapad 310 15ISK (i5-6200U, Intel HD520)
1
star
44

machelper

A command line tool for Macintosh as well as Hackintosh to help OSx86 users.
PHP
1
star
45

PHPPListEditor

A PHP Library for creating or editing Apple's plist files
PHP
1
star
46

test-arabic-text-android

An application to demonstrate rendering issues with Arabic texts in an Android TextView.
Java
1
star