Secure USB debugging in Android 4.2.2

It seems we somehow managed to let two months slip by without a single post. Time to get back on track, and the recently unveiled Android maintenance release provides a nice opportunity to jump start things. Official release notes for Android 4.2.2 don't seem to be available at this time, but it made its way into AOSP quite promptly, so you can easily compile your own changelog based on git log messages. Or, you can simply check the now traditional one over at Funky Android. As you can see, there are quite a few changes, and if you want a higher level overview your time would probably be better spent reading some of the related posts by the usual suspects. Deviating from our usually somewhat obscure topics, we will focus on a new security feature that is quite visible and has received a fair bit of attention already. It was even introduced on the official Android Developers Blog, fortunately for us only in brief. As usual, we like to dig a little deeper, so if you are interested in more details about the shiny new secure debugging feature, read on.

Why bother securing debugging?

If you have done development in any programming environment, you know that 'debugging' is usually the exact opposite of 'secure'. Debugging typically involves inspecting (and sometimes even changing) internal program state, dumping encrypted communication data to log files, universal root access and other scary, but necessary activities. It is hard enough without having to bother with security, so why further complicate things by making developers jump through security hoops? As it turns out, Android debugging, as provided by the Android Debug Bridge (ADB), is quite versatile and gives you almost complete control over a device when enabled. This is, of course, is very welcome if you are developing or testing an application (or the OS itself), but can also be used for other purposes. Before we give an overview of those, here is a (non-exhaustive) list of things ADB lets you do:
  • debug apps running on the device (using JWDP)
  • install and remove apps
  • copy files to and from the device
  • execute shell commands on the device
  • get the system and apps logs
If debugging is enabled on a device, you can do all of the above and more simply by connecting the device to a computer with an USB cable. If you think that's not much of a problem because the device is locked, here's some bad news: you don't have to unlock the device in order to execute ADB commands. And it gets worse -- if the device is rooted (as are many developer devices), you can access and change every single file, including system files and password databases. Of course, that is not the end of it: you don't actually need a computer with development tools in order to do this: another Android device and an OTG USB cable are sufficient. Security researchers, most notably Kyle Osborn, have build tools (there's even a GUI) that automate this and try very hard to extract as much data as possible from the device in a very short time. As we mentioned, if the device is rooted all bets are off -- it is trivial to lift all of your credentials, disable or crack the device lock and even log into your Google account(s). But even without root, anything on external storage (SD card) is accessible (for example your precious photos), as are your contacts and text messages. See Kyle's presentations for details and other attack vectors.

By now you should be at least concerned about leaving ADB access wide open, so let's see what are some ways to secure it.

Securing ADB

Despite some innovative attacks, none of the above is particularly new, but it has remained mostly unaddressed, probably because debugging is a developer feature regular users don't even know about. There have been some third-party solutions though, so let's briefly review those before introducing the one implemented in the core OS. Two of the more popular apps that allow you to control USB debugging are ADB Toggle and AdbdSecure. They automatically disable ADB debugging when the device is locked or unplugged, and enable it again when you unlock it or plug in the USB cable. This is generally sufficient protection, but has one major drawback -- starting and stopping the adbd daemon requires root access. If you want to develop and test apps on a device with stock firmware, you still have to disable debugging manually. Root access typically goes hand-in-hand with running custom firmware -- you usually need root access to flash a new ROM version (or at least it makes it much easier) and some of the apps shipping with those ROMs take advantage of root access to give you extra features not available in the stock OS (full backup, tethering, firewalls, etc.). As a result of this, custom ROMs have traditionally shipped with root access enabled (typically in the form of a SUID su binary and an accompanying 'Superuser' app). Thus, once you installed your favourite custom ROM you were automatically 'rooted'. CyanogenMod (which has over a million users and growing) changed this almost a year ago by disabling root access in their ROMs and giving you the option to enable it for apps only, for ADB of for both. This is not a bad compromise -- you can both run root apps and have ADB enabled without exposing your device too much, and it can be used in combination with an app that automates toggling ADB for even more control. Of course, these solutions don't apply to the majority of Android users -- those running stock OS versions.

The first step in making ADB access harder to reach was taken in Android 4.2 which hid the 'Developer options' settings screen, requiring you to use a secret knock in order to enable it. While this is mildly annoying for developers, it makes sure that most users cannot enable ADB access by accident. This is, of course, only a stop-gap measure, and once you manage to turn USB debugging on, your device is once again vulnerable. A proper solution was introduced in the 4.2.2 maintenance release with the so called 'secure USB debugging' (it was actually commited almost a year ago, but for some reason didn't make it into the original JB release). 'Secure' here refers to the fact that only hosts explicitly authorized by the user can now connect to the adbd daemon on the device and execute debugging commands. Thus if someone tries to connect a device to another one via USB in order to access ADB, they need to first unlock the target device and authorize access from the debug host by clicking 'OK' in the confirmation dialog shown below. You can make your decision persistent by checking the 'Always allow from this computer' and debugging will work just as before, as long as you are on the same machine. One thing to note is that on tablets with multi-user support the confirmation dialog is only shown to the primary (administrator) user, so you will need to switch to it in order to enable debugging. Naturally this 'secure debugging' is only effective if you have a reasonably secure lock screen password in place, but everyone has on of those, right? That's pretty much all you need to know in order to secure your developer device, but if you are interested in how all of this is implemented under the hood, proceed to the next sections. We will first a give a very brief overview of the ADB architecture and then show how it has been extended in order to support authenticated debugging.

ADB overview

The Android Debug Bridge serves two main purposes: it keeps track of all devices (or emulators) connected to a host, and it offers various services to its clients (command line clients, IDEs, etc.). It consists of three main components: the ADB server, the ADB daemon (adbd) and the default command line client (adb). The ADB server runs on the host machine as a background process and decouples clients from the actual devices or emulators. It monitors device connectivity and sets their state appropriately (CONNECTED, OFFLINE, RECOVERY, etc.). The ADB daemon runs on an Android device (or emulator) and provides the actual services client use. It connects to the ADB server through USB or TCP/IP, and receives and process commands from it. Finally, adb is the command line client that lets you send commands to a particular device. In practice it is implemented in the same binary as the ADB server and thus shares much of its code.

The client talks to the local ADB server via TCP (typically via localhost:5037) using text based commands, and receives OK or FAIL responses in return. Some commands, like enumerating devices, port forwarding or daemon restart are handled by the local daemon, and some (e.g., shell or log access) naturally require a connection to the target Android device. Device access is generally accomplished by forwarding input and output streams to/from the host. The transport layer that implements this uses simple messages with a 24 byte header and an optional payload to exchange commands and responses. We will not go into further details about those, but will only note the newly added authentication commands in the next section. For more details refer to the protocol description in system/core/adb/protocol.txt and this presentation which features quite a few helpful diagrams and examples.

Secure ADB implementation

The ADB host authentication functionality is enabled by default when the system property is set to 1, and there is no way to disable it via the system settings interface (which is a good thing). The device is initially in the OFFLINE state and only goes into the ONLINE state once the host has authenticated. As you may already know, hosts use RSA keys in order to authenticate to the ADB daemon on the device. Authentication is typically a three step process:
  1. After a host tries to connect, the device sends and AUTH message of type TOKEN that includes a 20 byte random value (read from /dev/urandom).
  2. The host responds with a SIGNATURE packet that includes a SHA1withRSA signature of the random token with one of its private keys.
  3. The device tries to verify the received signature, and if signature verification succeeds, it responds with a CONNECT message and goes into the ONLINE state. If verification fails, either because the signature value doesn't match or because there is no corresponding public key to verify with, the device sends another AUTH TOKEN with a new random value, so that the host can try authenticating again (slowing down if the number of failures goes over a certain threshold).
Signature verification typically fails the first time you connect the device to a new host because it doesn't yet have the host key. In that case the host sends its public key in an AUTH RSAPUBLICKEY message. The device takes the MD5 hash of that key and displays it in the 'Allow USB debugging' confirmation dialog. Since adbd is a native daemon, the key needs to be passed to the main Android OS. This is accomplished by simply writing the key to a local socket (aptly named, 'adbd'). When you enable ADB debugging from the developer settings screen, a thread that listens to the 'adbd' socket is started. When it receives a message starting with "PK" it treats it as a public key, parses it, calculates the MD5 hash and displays the confirmation dialog (an activity actually, part of the SystemUI package). If you tap 'OK', it sends a simple simple "OK" response and adbd uses the key to verify the authentication message (otherwise it just stays offline). In case you check the 'Always allow from this computer' checkbox, the public key is written to disk and automatically used for signature verification the next time you connect to the same host. The allow/deny debugging functionality, along with starting/stopping the adbd daemon, is exposed as public methods of the UsbDeviceManager system service.

We've described the ADB authentication protocol in some detail, but haven't said much about the actual keys used in the process. Those are 2048-bit RSA keys and are generated by the local ADB server. They are typically stored in $HOME/.android as adbkey and On Windows that usually translates to %USERPOFILE%\.android, but keys might end up in C:\Windows\System32\config\systemprofile\.android in some cases (see issue 49465). The default key directory can be overridden by setting the ANDROID_SDK_HOME environment variable. If the ADB_VENDOR_KEYS environment variable is set, the directory it points to is also searched for keys. If no keys are found in any of the above locations, a new key pair is generated and saved. On the device, keys are stored in the /data/misc/adb/adb_keys file, and new authorized keys are appended to the same file as you accept them. Read-only 'vendor keys' are stored in the /adb_keys file, but it doesn't seem to exist on current Nexus devices. The private key is in standard OpenSSL PEM format, while the public one consists of the Base 64 encoded key followed by a `user@host` user identifier, separated by space. The user identifier doesn't seem to be used at the moment and is only meaningful on Unix-based OS'es, on Windows it is always 'unknown@unknown'. 

While the USB debugging confirmation dialog helpfully displays a key fingerprint to let you verify you are connected to the expected host, the adb client doesn't have a handy command to print the fingerprint of the host key. You might think that there is little room for confusion: after all there is only one cable plugged to a single machine, but if you are running a couple of VMs, thing can get a little fuzzy. Here's one of way of displaying the host key's fingerprint in the same format the confirmation dialog uses (run in $HOME/.android or specify the full path to the public key file):

awk '{print $1}' <|openssl base64 -A -d -a \
|openssl md5 -c|awk '{print $2}'|tr '[:lower:]' '[:upper:]'

We've reviewed how secure ADB debugging is implemented and have shown why it is needed, but just to show that all of this solves a real problem, we'll finish off with a screenshot of what a failed ADB attack against an 4.2.2 device from another Android device looks like:


Android 4.2.2 finally adds a means to control  USB access to the ADB daemon by requiring debug hosts to be explicitly authorized by the user and added to a whitelist. This helps prevent information extraction via USB which requires only brief physical access and has been demonstrated to be quite effective. While secure debugging is not a feature most users will ever use directly, along with full disk encryption and a good screen lock password, it goes a long way towards making developer devices more secure. 


Sean Ryan said…
Nice article.

RSA security for ADB is fine and dandy but if you want to connect to the ADB daemon running on the android device from a process running on the android device via tcp as localhost then the connection is successful but the Authorisation prompt is not displayed and the device is shown as Offline. How can you generate an RSA key for localhost ? and would it be used if it existed ?
Nikolay Elenkov said…
Thanks. It seems this not supported (never was officially, AFAIK).

Peter Hultqvist said…
Good idea, I always feel a bit paranoid when debugging over the wireless.

Though it appears that you must connect the device over USB to add the fingerprint.

You showed how to get the fingerprint but not how to add it.
Is there any manual process to add the fingerprint of a remote(virtual) machine where USB is not an option?
Nikolay Elenkov said…
The whole idea of this is that the device needs to be unlocked and you need to explicitly add the fingerprint. Thus no 'manual' process. If you have root access and something running on the device you can modify the relevant files directly, but that kind of defeats the purpose.
Nikolay Elenkov said…
It seems it is actually doable:
BiDOrD said…
Thanks for the article.

Simple question: how to remove a previously authorized computer from the whitelist ?
Nikolay Elenkov said…
You have to manually remove it from the adb_keys files (requires root access).
Tony said…
Just noticed that with Android 4.3 they added an option to "Revoke USB debugging authorizations" to the Developer options menu. Horray! Course this removes all previously authorized computers; can't pick and choose.
Pyrouni said…
How can one bypass this whitelist security?.
Have nexus 4 with broken digitizer the LCD still works. Was able to unlock the boot loader and flash CWM recovery as well as custom ROM with USB debugging on by default but I cannot accept the RSA finger print without the touch input. Want to use the device as a media center using xbmc but can't set it up without ADB working.
Nikolay Elenkov said…
I sometimes wonder if people read anything besides the title...
Set in your custom ROM. Cf. first sentence in the 'Secure ADB implementation' section.
Atul Raj said…
Is there anyway possible to restrict the authorization to a single host.
Nikolay Elenkov said…
Not without modifying the platform (i.e., custom ROM, etc.).
Kinoma Mike said…
Is there a way to force the RSA authorization dialog to pop up manually, if it doesn't right when you plug in the device after enabling USB debugging?

We've got a tablet (HP Slate 10 HD) that won't cause the secure debugging authorization message to pop up. I've seen this before on our other JB4.2.2 tabs but eventually it would show up. Now I've got a bunch of developers scratching their heads about how to debug this thing, we've tried several times, disabled and re-enabled USB debugging, restarted components etc. to no avail.
Nikolay Elenkov said…
Killing the local adb server should do it. Try `adb kill-server` followed by `adb devices` on your development machine.
Caspar Kuo said…
Is there a way to copy adbkey from one PC to another PC so it will not pop up dialog agin?
Nikolay Elenkov said…
Well, that kinds of defeats the purpose of this... Still, if you copy `adbkey` and `` from .android/, that should do it.
Jack Patreas said…
I'm trying to understand the risks that existed before the secure ADB feature was added. You mention that previously device didn't have to be unlocked for running adb commands (I'm leaving out rooted devices, like developer devices, and focusing on normal users). If I'm correct, unless a user plugs in the device using USB to a computer, no one can run adb commands on it, right ? There is of course the risk of device theft, but what other scenarios were risky for a normal user when there was no secure USB debugging ?

Jack Patreas said…
I have a question about the authentication protocol. If I connect a device the first time, from your explanation, I understand that:
Device -> auth token -> Host
Device <- Signature <- Host
Device -> auth token -> Host
Device <- RSA public <- Host
Pop up alert
** Now will the device send the token again and ask the host to sign the random value, or just connect (because the user just approved the Host) ?

Nikolay Elenkov said…
Follow the links in the post -- it doesn't have to be a computer, it could be another Android device, or even a charger (Google 'juice jacking'). No need to steal the device -- a couple of minutes is enough to download all of your embarrassing photos and WhatsApp chat history.
Nikolay Elenkov said…
Signature is always verified, read the source for details.
BobCov said…
On a phone with a dead screen, but a working digitizer, how can I blindly okay the adb authorization dialog? Will it pop up over anything or does the phone have to be at the desktop or what?
Nikolay Elenkov said…
Please enter a new comment, don't just reply to a random, unrelated one. It will pop up on top of everything, OK button should be on the right side.
Jeff said…
This did not work for me either. After months of seeing "offline" for my devices I came across this article with enough clues to fix the problem. I had $ANDROID_SDK_HOME="D:\Program Files\Android_SDK\sdk-r21" and I guess because of the space, adb could not create the .android directory and the key files and quietly left the devices offline while never prompting on the device. When set to D:\temp everything works OK. Would this have been logged somewhere
Jeremy Viterbo said…
my android 4.4.2 was bricked by an application called 3d chainfire..i think if i could uninstall this apps using adb fix the problem..but my only problem is i cant confirm the authorization because my phone was on boot loop.

could someone help

Nikolay Elenkov said…
Boot your device in save mode and install the offending app.
Jeremy Viterbo said…
But how to boot my device in save mode while its on a stock logo after power switch press on?

ill appreciate your help sir...thanks
Jeremy Viterbo said…
This comment has been removed by the author.
Jeremy Viterbo said…
what is the minimum requirement of android kitkat 4.5 and 4.6 OS?was it compatible to 512mb ram,4g rom and 1.2Ghz quad core?
i think changing OS may fix my bootloop problem.
Thomas said…
I am accidentally revoked USB debugging on my Samsung I can't access the phone on computer with USB do I undo my mistake

Popular posts from this blog

Password storage in Android M

Decrypting Android M adopted storage

Unpacking Android backups