Related
Hi geeks,
of course native ARM code compiling could be done with the full blown SDK+NDK, but honestly i found it way too much in some cases.
So i started investigating about a more simple cross environment.
There are many solutions out there, but IMHO the easiest way is to use the agcc wrapper written by Andrew Ross.
To make it comfortable, one of the prebuilt toolchains from the android source repository is used (gcc-4.4.0).
The environemnt will create dynamically linked executables, so we will link against the bionic libs here.
If you don't know what i'm talking about, follow the links at the bottom or step over to use your phone as a phone.
In fact this solution is not re-inventing the wheel, but more a walk on a practical trail for native development.
Everything could be easily put together and equipped with the essential source packages, you get a very handy solution to compile simple c-code for your Android platform.
Only minor tweaks had been done to the agcc wrapper, and you might do as well to fit it to your needs.
Grab the complete package here:
http://dl.dropbox.com/u/8815400/android-agcc-4.4.0.tar.gz
Everything was choosen to work nicely for the Milestone platform.
To make it the most compatible i decided to use the includes and libs from the eclair branches.
It might also work for other devices, but some tweaks could be required then.
To start development for your platform you'll need a more or less up-to-date linux OS on your host.
Minimum should be:
Debian 5.0
Ubuntu 10
...
Simply extract the archive to a directory of your choice, user rights should be O.K. (the default directory of the package would be /opt).
To make everything work properly, it is required to modify the $DROID variable insdide agcc wrapper to point at your working directory (e.g. /opt/android).
It is also required to add the path to the android toolchain to the PATH variable of your system. There are different attempts to do so.
E.g. on Debian 5.0 add the following line at the end of your .bashrc:
Code:
export PATH=$PATH:/opt/android/prebuilt/linux-x86/toolchain/arm-eabi-4.4.0/bin
To check, if the toolchain is working, create a simple hello.c like this:
Code:
#include <stdio.h>
main()
{
printf ("Hello World!\n");
}
Compile the code on your host:
./agcc hello.c -o hello
The result is a 32-bit ELF executable for ARM. Transfer the binary to your platform and make it executable.
You might use adb to do so (usb debugging needs to be activated on your device).
Attach the Milestone to your host and type:
./adb start-server
./adb push hello /data/local
./adb shell
Now in the shell on your device type:
$ cd /data/local
$ chmod +x hello
$ ./hello
There you go!
It is also possible to compile even more complex tools using MAKEFILE.
Some details might be discussed here, if there's some interest.
Useful links:
The essential packages had been taken from source packages over here:
http://android.git.kernel.org/
Also some libs had been grabbed from this project:
http://gitorious.org/rowboat
Original agcc wrapper could be found here:
http://plausible.org/andy/agcc
Further information:
http://labs.embinux.org/index.php/Toolchain_For_Android
http://android-dls.com/wiki/index.php?title=Compiling_for_Android
http://elinux.org/Android_Tools
Happy hacking!
scholbert
Examples ...
You'll find some simple c-code examples for console here.
Most of them would require root access.
A good location to store them locally on your device is /data/local.
omapinfo v.1.0.0 (reads out some very special registers )
Code:
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
int main() {
printf("omapinfo v.1.0.0\n");
int fd = open("/dev/mem", O_RDWR | O_SYNC);
if (fd < 0) {
printf("Could not open memory\n");
return 1;
}
// map L4 core registers @ 0x4800 0000 to memory
volatile unsigned long *L4_core_base;
L4_core_base = (unsigned long*) mmap(NULL, 0x10000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x48000000);
if (L4_core_base == MAP_FAILED) {
printf("Mapping L4 core base failed\n");
close(fd);
return 1;
}
// read some register values
printf("STATE : %8x \n",L4_core_base[0x22f0/4]); // check HS bit, boot mode
printf("PKEY0 : %8x \n",L4_core_base[0x2300/4]); // read out RPUB_KEY_H_0
printf("PKEY1 : %8x \n",L4_core_base[0x2304/4]); // read out RPUB_KEY_H_1
printf("PKEY2 : %8x \n",L4_core_base[0x2308/4]); // read out RPUB_KEY_H_2
printf("PKEY3 : %8x \n",L4_core_base[0x230c/4]); // read out RPUB_KEY_H_3
printf("PKEY4 : %8x \n",L4_core_base[0x2310/4]); // read out RPUB_KEY_H_4
// map L4 wakeup registers @ 0x4830 00000 to memory
volatile unsigned long *L4_wakeup_base;
L4_wakeup_base = (unsigned long*) mmap(NULL, 0x10000, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0x48300000);
if (L4_wakeup_base == MAP_FAILED) {
printf("Mapping L4 wakeup base failed\n");
close(fd);
return 1;
}
//read CONTROL_ID
printf("CPU-ID: %8x \n",L4_wakeup_base[0xa204/4]);
close(fd);
}
Cheers,
scholbert
I'm sorry but I don't understand what the end result is.
My brain ain't big enough to figure out which problem this is solving.
Hi zeppelinrox!
zeppelinrox said:
I'm sorry but I don't understand what the end result is.
Click to expand...
Click to collapse
The end result is a very lightweight cross environment to write simple progs for your android device (c-code based).
The package could easily be installed and run on a netbook with linux OS.
Nothing more nothing less..
zeppelinrox said:
My brain ain't big enough to figure out which problem this is solving.
Click to expand...
Click to collapse
You don't need a big brain and there's also no specific problem to solve.
As i tried to point out, i needed this kind of tool to compile some very basic command line tools.
Pushing the whole Android SDK+NDK was way too much for this.
I did not find any package like this, so i thought i put it together myself and share it.
Of course this is mostly for fun, but could be used for hardware-oriented programming and similar stuff.
By using the memory mapped register access, some kernel settings could easily be overridden and this maybe useful for testing new drivers and stuff.
E.g. i'll try to compile i2c-tools next... let's see if it works .
Have fun!
scholbert
This is only practical for small native utility.
YongkiCA said:
This is only practical for small native utility.
Click to expand...
Click to collapse
That's what i said....
BTW here's another small native utility!
Look at the project page for info.
http://www.lm-sensors.org/wiki/I2CTools
Regards,
scholbert
Thanks for this thread scholbert! Thanks for taking the time I haven't tried this yet, but I may later, but right know acknowledging your efforts! Wonderful job
Phone:motorola charm
Kernel:2.6.29-omap1
# omapinfo
Code:
omapinfo v.1.0.0
STATE : 21b
PKEY0 : 62b63f1d
PKEY1 : 708c4d79
PKEY2 : cbb457fb
PKEY3 : f6272e49
PKEY4 : 4f2e156f
CPU-ID: 4b7ae02f
Hi all,
this thread would like to be a shortly introduction about root user permission on general android platform!
As we all know the root user in Unix-based OS is the user with UID equal to 0.
Many threads talks about gain root on android by means of magic oneclick tool or by way of flashing custom recovery on device then copy the fantastic ChainsDD's su binary and install superuser or another apk to manage privileged action request .
Do we really need? Probably! But we maybe only want a root prompt, root privilege through adb shell or on the terminal emulator, this is certainly possible.
Deafult android shell is /system/bin/sh, if we could run it through, for example, an executable owned by user with UID 0, and if there was a Unix access rights flags that allow users to run an executable with the permissions of the executable's owner, we probably would get a root shell only by running that executable! Easy!
Only one thing, we should know a method for push our unsecure setuidded executable owned by root under the /system/xbin directory, which is also owned by root!
For example, might be possible to dump our /system, mount the filesystem data on a Linux box (which we know the root password), copy the unsecure elf under the correct path, and then flash back the modified /system image to our device, all with the original bootloader, without any custom recovery.
Once done, if we run the executable, ta daaan....
If someone wants to get his hands dirty:
Code:
void main()
{
setuid(0);
system("/system/bin/sh");
}
this can be enough!
Anyone...?
Well, I was going to hold off until all of the vendors had new releases posted, but now that the cat is out of the bag and the evildoers have sufficient information to figure out what got fixed:
[size=+1]Current Superuser/SuperSU releases have security holes that allow any application to execute commands as root without the user's permission (even apps with no permissions). Please upgrade immediately to SuperSU >= v1.69 or another patched release.[/size]
This is expected to impact the vast majority of rooted devices and custom ROMs.
Details follow:
[size=+2]Superuser unsanitized environment vulnerability on Android <= 4.2.x[/size]
Vulnerable releases of several common Android Superuser packages may allow malicious Android applications to execute arbitrary commands as root without notifying the device owner:
ChainsDD Superuser (current releases, including v3.1.3)
CyanogenMod/ClockWorkMod/Koush Superuser (current releases, including v1.0.2.1)
Chainfire SuperSU prior to v1.69
The majority of third-party ROMs include one of these packages.
On a rooted Android <= 4.2.x device, /system/xbin/su is a setuid root binary which performs a number of privilege checks in order to determine whether the operation requested by the caller should be allowed. In the course of its normal duties, and prior to making the allow/deny decision, /system/xbin/su invokes external programs under a privileged UID, typically root (0) or system (1000):
/system/bin/log, to record activity to logcat
/system/bin/am, to send intents to the Superuser Java app
/system/bin/sh, to execute the /system/bin/am wrapper script
/system/bin/app_process, the Dalvik VM
The user who invokes /system/xbin/su may have the ability to manipulate the environment variables, file descriptors, signals, rlimits, tty/stdin/stdout/stderr, and possibly other items belonging to any of these subprocesses. At least two vulnerabilities are readily apparent:
- On ClockWorkMod Superuser, /system/xbin/su does not set PATH to a known-good value, so a malicious user could trick /system/bin/am into using a trojaned app_process binary:
Code:
echo -e '#!/system/bin/sh\nexport PATH=/system/bin:$PATH\ntouch /data/trojan.out\nexec $0 "[email protected]"' > app_process ; chmod 755 app_process
PATH=`pwd`:$PATH su -c 'true'
The PATH vulnerability is being tracked under CVE-2013-6768.
- Other environment variables could be used to affect the behavior of the (moderately complex) subprocesses. For instance, manipulation of BOOTCLASSPATH could cause a malicious .jar file to be loaded into the privileged Dalvik VM instance. All three Superuser implementations allowed Dalvik's BOOTCLASSPATH to be supplied by the attacker.
The BOOTCLASSPATH vulnerability is being tracked under CVE-2013-6774.
[size=+2]Android Superuser shell character escape vulnerability[/size]
Vulnerable releases of two common Android Superuser packages may allow malicious Android applications to execute arbitrary commands as root, either without prompting the user or after the user has denied the request:
CyanogenMod/ClockWorkMod/Koush Superuser (current releases, including v1.0.2.1)
Chainfire SuperSU prior to v1.69
The majority of recent third-party ROMs include one of these packages. Older ROMs may use the ChainsDD Superuser package, which is not affected but is no longer maintained.
On a rooted Android <= 4.2.x device, /system/xbin/su is a setuid root binary which performs a number of privilege checks in order to determine whether the operation requested by the caller should be allowed. If any of these checks fail, the denial is recorded by broadcasting an intent to the Superuser app through the Android Activity Manager binary, /system/bin/am. /system/bin/am is invoked as root, and user-supplied arguments to the "su" command can be included on the "am" command line.
On a rooted Android >= 4.3 device, due to changes in Android's security model, /system/xbin/su functions as an unprivileged client which connects to a "su daemon" started early in the boot process. The client passes the request over a UNIX socket, and the daemon reads the caller's credentials using SO_PEERCRED. As described above, /system/bin/am is called (now from the daemon) to communicate with the app that implements the user interface.
If the user invokes "su -c 'COMMAND'" and the request is denied (or approved), ClockWorkMod Superuser constructs a command line to pass to a root shell:
Code:
snprintf(user_result_command, sizeof(user_result_command), "exec /system/bin/am " ACTION_RESULT " --ei binary_version %d --es from_name '%s' --es desired_name '%s' --ei uid %d --ei desired_uid %d --es command '%s' --es action %s --user %d",
VERSION_CODE,
ctx->from.name, ctx->to.name,
ctx->from.uid, ctx->to.uid, get_command(&ctx->to),
policy == ALLOW ? "allow" : "deny", ctx->user.android_user_id);
get_command() would return "COMMAND", unescaped, through "/system/bin/sh -c". By adding shell metacharacters to the command, the root subshell can be tricked into running arbitrary command lines as root:
Code:
su -c "'&touch /data/abc;'"
Upon denial by the operator, "touch /data/abc" will be executed with root privileges. The Superuser variant of this problem is being tracked under CVE-2013-6769.
SuperSU prior to v1.69 removes quote and backslash characters from the string passed to /system/bin/sh, but backticks or $() can be used instead for the same effect:
Code:
su -c '`touch /data/abc`'
su -c '$(touch /data/abc)'
The SuperSU variant of this problem is being tracked under CVE-2013-6775.
ChainsDD Superuser v3.1.3 does not appear to pass the user-supplied input on the /system/bin/am command line.
[size=+2]Superuser "su --daemon" vulnerability on Android >= 4.3[/size]
Current releases of the CyanogenMod/ClockWorkMod/Koush Superuser package may allow restricted local users to execute arbitrary commands as root in certain, non-default device configurations.
Android 4.3 introduced the concept of "restricted profiles," created through the Settings -> Users menu. A restricted profile can be configured to allow access to only a minimal set of applications, and has extremely limited abilities to change settings on the device. This is often used to enforce parental controls, or to protect shared devices set up in public places. The OS requires an unlock code to be entered in order to access the owner's profile to administer the system.
/system/xbin/su is a setuid root executable, and any user may invoke it in client mode ("su -c 'foo'" or just "su"), or in daemon mode ("su --daemon"). In either mode of operation, the user who invokes this program has the ability to manipulate its environment variables, file descriptors, signals, rlimits, tty/stdin/stdout/stderr, and possibly other items. By adding new entries at the front of the PATH for commonly-executed root commands, then re-invoking "su --daemon", an attacker may be able to hijack legitimate root sessions subsequently started by other applications on the device.
"su --daemon" is normally started up very early in the boot process, as root, from /init.superuser.rc (CM) or from /system/etc/install-recovery.sh (other ROMs). The fact that unprivileged users are allowed to restart the daemon later, under EUID 0, appears to be an oversight.
Successful exploitation requires a number of conditions to be met:
- The attacker must have ADB shell access, e.g. over USB. This is disabled by default, and normally restricted to trusted ADB clients whose RSA key fingerprints have been accepted by the device administrator. Root access via ADB (i.e. Settings -> Developer Options -> Root access -> Apps and ADB) is not required. Note that ADB shell access is typically considered a security risk, even in the absence of this problem.
- The attacker must have a way to assume a non-shell (non-2000), suid-capable Linux UID in order to prevent /system/xbin/su from creating infinitely recursive connections to itself through the daemon client UID check in main(). One way to do this would involve uploading an app with the "debuggable" flag and using /system/bin/run-as to assume this UID. "adb install" can probably used for this purpose. However, due to a bug in Android 4.3's "run-as" implementation[1], this does not currently work. This bug was fixed in Android 4.4, so CM11 will probably be able to satisfy this requirement.
- The device owner must have granted root permissions to one or more applications via Superuser. The restricted profile does not need to be able to run this app from the launcher.
Sample exploit:
The restricted local user can reboot the tablet, run "adb shell" when the boot animation shows up, then invoke the following commands:
Code:
echo -e '#!/system/bin/sh\nexport PATH=/system/bin:$PATH\ntouch /data/trojan.out\nexec $0 "[email protected]"' > /data/local/tmp/trojan
chmod 755 /data/local/tmp/trojan
for x in id ls cp cat touch chmod chown iptables dmesg; do ln -s trojan /data/local/tmp/$x ; done
PATH=/data/local/tmp:$PATH setsid run-as.422 my.debuggable.package /system/xbin/su --daemon &
(Note the use of "run-as.422" as a proxy for a working Android 4.3 run-as binary, and the installation of "my.debuggable.package" with the debuggable flag set.)
At this point the USB cable may be disconnected.
The next time a root application successfully passes the Superuser check and invokes one of the trojaned shell commands, /data/local/tmp/trojan will be executed under UID 0.
An ideal candidate for exploitation is a package which runs privileged commands on boot, e.g. AdBlock Plus or AFWall+, as this allows for instant access. Another possibility is to hijack an app which the device's operator runs frequently, such as Titanium Backup.
Note that this can NOT be exploited by malicious applications, as zygote-spawned processes (apps) always access /system in nosuid mode[2] on Android 4.3+. The ADB shell was used as the attack vector as it is not subject to this restriction.
ChainsDD Superuser v3.1.3 does not have an Android 4.3+ client/server mode at all, and SuperSU aborts if an existing "daemonsu" instance is already bound to the abstract @"eu.chainfire.supersu" socket.
Proposed resolution: on Android 4.3 and higher, install all Superuser-related binaries with mode 0755 (setuid bit unset).
This problem is being tracked under CVE-2013-6770.
[1] https://code.google.com/p/android/issues/detail?id=58373
[2] http://source.android.com/devices/tech/security/enhancements43.html
Did you report that to @Chainfire?
SecUpwN said:
Did you report that to @Chainfire?
Click to expand...
Click to collapse
Yes, he's been very responsive.
I contacted all three developers last Saturday, and posted the advisory after there was enough public information available to deduce what the problems were.
In case you're curious, there's been some additional discussion about exploiting ChainsDD Superuser on BUGTRAQ.
Is there a way we can patch this maybe using xposed framework
milojoseph said:
Is there a way we can patch this
Click to expand...
Click to collapse
There are new releases of SuperSU and CWM Superuser posted:
https://play.google.com/store/apps/details?id=eu.chainfire.supersu&hl=en
http://forum.xda-developers.com/showthread.php?t=1538053
https://play.google.com/store/apps/details?id=com.koushikdutta.superuser&hl=en
I haven't seen any updates to ChainsDD Superuser, and AFAICT the project is no longer maintained.
maybe using xposed framework
Click to expand...
Click to collapse
Xposed is useful for patching Java programs, but /system/xbin/su is compiled C code. So the techniques used by Xposed would not apply to this case.
cernekee said:
Xposed is useful for patching Java programs, but /system/xbin/su is compiled C code. So the techniques used by Xposed would not apply to this case.
Click to expand...
Click to collapse
There's always Substrate, that can be used even for patching native code, but still in this case not applicable I guess.
Where you able to find any patch to fix them?
thank you for sharing ...
I am getting this message in lollipop "zygote has been granted superuser permission" i accidentally allowed it root access thinking it was link2sd. Could it be malware? There is a nameless app in my supersu under name "zygote". i didn't installed anything outside from playstore. My supersu version is 2.78
diabolicalprophecy said:
I am getting this message in lollipop "zygote has been granted superuser permission" i accidentally allowed it root access thinking it was link2sd. Could it be malware? There is a nameless app in my supersu under name "zygote". i didn't installed anything outside from playstore. My supersu version is 2.78
Click to expand...
Click to collapse
Did you get an answer for this? I have the same issue on 4.4.4
Vankog said:
Did you get an answer for this? I have the same issue on 4.4.4
Click to expand...
Click to collapse
No I didn't, I reflashed the rom and it solved the problem.
Author: Apriorit (Device Team)
Permanent link: www(dot)apriorit(dot)com/dev-blog/255-android-rooting
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 - the adb exhaustion attack, which is simpler to understand than a previous udev exploit. It is suitable for all Android-powered devices with the version 2.2 and lower.
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 the ADB command 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 the AID_SHELL rights, 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 the ADB daemon has the ADT_SHELL user 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, ueventd service 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 the init service 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, is adb_main. I skipped non significant pieces of code to focus your attention on the daemon security.
Code:
int adb_main(int is_daemon, int server_port)
{
...
int secure = 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);
...
return 0;
}
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 set secure flag 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 emulator
ro.secure – “1” // secure mode
After properties are checked, the secure flag is set to true, and we hit to such code section:
Code:
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 the AID_SHELL user id as it drops root privileges. All processes, started by the ADB daemon, like sh, will inherit its rights and will work in very limited environment. It is really sad, isn’t it?
Exhaustion attack
The main rooting principle of the exploit described in this article is the setuid exhaustion attack. The setuid function 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 the RLIMIT_NPROC resource. 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. The setuid function doesn’t create processes, but it follows this rule. Once, the NPROC limit for the AID_SHELL user is reached, setuid fails and the process continues its execution with the user id set before the setuid call. It means, when the ADB daemon starts with the AID_ROOT user id and tries to change it for AID_SHELL, for which NPROC is reached, setuid fails and the daemon user id remains AID_ROOT.
It is easy enough, isn’t it?
In files attached to the article, you can find the binary file and sources. They implement the adb exhaustion 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 the root() function in the impl.cpp file. It implements the main logic of the exploit.
...
Code:
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 the NPROC limits, 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:
Code:
pid_t pid( -1 );
for( int i( 0 ); ; ++i )
{
pid = fork();
if( pid == 0 )
{
return ret;
}
...
The code above represents an infinite loop. It forks calling process and exits from a child. That is enough because PID, 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 the NPROC limit. Let’s look at the next code piece. The PID is negative, but we have to remember that there is one more shell user process that will be terminated soon. This process is the ADB daemon 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 is AID_SHELL or AID_ROOT (because we could reach the condition from the second or third iteration).If it is AID_SHELL, the program just sends SIGKILL to it and continues the loop (soon, we will reach it again). Once the daemon is killed, one more PID for this user is freed. We have to allocate this PID for the AID_SHELL user as soon as possible to prevent the daemon setting its user id as AID_SHELL. Ideally, there will be two additional loops: the first one forks and allocates a new PID for the AID_SHELL user and, as the result, the second one reaches the limit again, checks the daemon PID that should be AID_ROOT and exits. However, because of lack of resources or lots of delays, there could be rather more iterations.
...
Code:
else if( 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 the ADB daemon 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 big NPROC limit. 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.
...
Code:
else
{
static int theRespounGuard( 10 );
if( --theRespounGuard )
{
sleep( 1 );
}
else
{
break;
}
}
...
Configuration & Build
The exploit was configured to be built with the NDK toolset both on Linux, and on the Windows platform. If you are working on Linux, it will be enough for you to download NDK only; however, on the Windows platform, you have to download and install the Cygwin environment 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.
You can add a path to platform-tools into your PATH variable 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 the Cygwin environment. Install them in the same location with SDK and add a path to your NDK package into the PATH variable or into your Cygwin .bash_profile. Then unpack a project archive attached to this article into your working directory available for Cygwin.
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.
Code:
/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 the Cygwin environment, change a directory to the project/jni directory, and execute ndk-build. The Compiler output should look like this:
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 the PATH variable. 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 the adb shell command, 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 type adb push exploit /data/local/tmp. This command will upload the exploit in the device temporary directory available for the user. Then, type adb shell and change the directory to /data/local/tmp. The ls –l command will show you its content and permissions on recently uploaded files. Make the file executable by executing chmod exploit 776 and run it by ./exploit root.
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 type adb shell again. As a result, you should see root # shell. Type id to make sure you are a root.
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.
Say I have a vector variable with a list of .apks, would
Code:
for (int i = 0; i < apps.size(); i++) {
string arg = "adb install -r "+apps[i];
system(arg.c_str());
}
be a viable method of installing those .apks, or would the device reject all installs besides the first (or at least until the first is done, if any code left to be executed by that time)?
Thanks.
unignostik said:
Say I have a vector variable with a list of .apks, would
Code:
for (int i = 0; i < apps.size(); i++) {
string arg = "adb install -r "+apps[i];
system(arg.c_str());
}
be a viable method of installing those .apks, or would the device reject all installs besides the first (or at least until the first is done, if any code left to be executed by that time)?
Thanks.
Click to expand...
Click to collapse
Nope. I wish. There really is no good way to batch (safely) uninstall, and Package Manager checks manifest and apk perms and signature for every install so installing is rate limited too
Sent from my [device_name] using XDA-Developers Legacy app
Surge1223 said:
Nope. I wish. There really is no good way to batch (safely) uninstall, and Package Manager checks manifest and apk perms and signature for every install so installing is rate limited too
Sent from my [device_name] using XDA-Developers Legacy app
Click to expand...
Click to collapse
Got cha. Just getting to know Android, coming from MacOS/iOS development...
I'm assuming the Package Manager process is always running, do you happen to know if that "checker" is ran only at the time of installation, either as a separate process or a thread of Package Manager? If so, maybe blocking next install command until the process/thread is done will work.?.
edit: I've found that there's a service called "InstallAppProgress.java", available in the PackageInstaller source code. Maybe on to something.. via an app rather than adb tho.
unignostik said:
Got cha. Just getting to know Android, coming from MacOS/iOS development...
I'm assuming the Package Manager process is always running, do you happen to know if that "checker" is ran only at the time of installation, either as a separate process or a thread of Package Manager? If so, maybe blocking next install command until the process/thread is done will work.?.
edit: I've found that there's a service called "InstallAppProgress.java", available in the PackageInstaller source code. Maybe on to something.. via an app rather than adb tho.
Click to expand...
Click to collapse
Please, keep in mind that different manufacturers may use customized or completely different package installers.
If you want to wait until a package is installed, you may poll package manager for package info until it becomes available.