Android root detection not working with mentioned code - java

I'm using following code for root detection in Android device. But still my security expert saying it can be installed and run in rooted device. Could someone detect what the issue with my code
public static boolean isDeviceRooted() {
// get from build info
String buildTags = android.os.Build.TAGS;
if (buildTags != null && buildTags.contains("test-keys")) {
return true;
}
return checkFiles() || checkLocations();
}
private static boolean checkFiles(){
String[] files = {
"/system/app/Superuser.apk",
"/system/etc/init.d/99SuperSUDaemon",
"/dev/com.koushikdutta.superuser.daemon/",
"/system/xbin/daemonsu"
};
for (String fileData : files) {
try {
File file = new File(fileData);
if (file.exists()) {
return true;
}
} catch (Exception e1) {
// ignore
}
}
return false;
}
private static boolean checkLocations(){
String su = "su";
String[] locations = {
"/system/bin/",
"/system/xbin/",
"/sbin/",
"/system/sd/xbin/",
"/system/bin/failsafe/",
"/data/local/xbin/",
"/data/local/bin/",
"/data/local/",
"/system/sbin/",
"/usr/bin/",
"/vendor/bin/"
};
for (String location : locations) {
if (new File(location + su).exists()) {
return true;
}
}
return false;
}

Related

The root deduction code has been Bypassed by frida and Object Bypassing how to save apps from those bypass method?

My application is Under VAPT report certification. in my application i wrote a code for detecting weather the device is root or not. the method is returning boolean values. but they Bypassed the code with Magisk or some other root application. How to disable the bypassing???? How????
public class DeviceUtils {
public static boolean isDeviceRooted() {
return checkRootMethod1() || checkRootMethod2() || checkRootMethod3() || checkRootMethod4() || checkRootMethod5();
}
private static boolean checkRootMethod1() {
String buildTags = android.os.Build.TAGS;
return buildTags != null && buildTags.contains("test-keys");
}
private static boolean checkRootMethod2() {
String[] paths = { "/system/app/Superuser.apk", "/sbin/su", "/system/bin/su", "/system/xbin/su", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su",
"/system/bin/failsafe/su", "/data/local/su", "/su/bin/su"};
for (String path : paths) {
if (new File(path).exists()) return true;
}
return false;
}
private static boolean checkRootMethod3() {
Process process = null;
try {
process = Runtime.getRuntime().exec(new String[] { "/system/xbin/which", "su" });
BufferedReader in = new BufferedReader(new InputStreamReader(process.getInputStream()));
if (in.readLine() != null) return true;
return false;
} catch (Throwable t) {
return false;
} finally {
if (process != null) process.destroy();
}
}
private static boolean checkRootMethod4() {
File file = new File("/system/app/Superuser.apk");
if (file.exists()) {
return true;
}
return false;
}
public static boolean findBinary(String binaryName)
{ boolean found = false;
if (!found) { String[] places = { "/sbin/", "/system/bin/", "/system/xbin/", "/data/local/xbin/", "/data/local/bin/", "/system/sd/xbin/", "/system/bin/failsafe/", "/data/local/", "/system/app/Superuser.apk", "/sbin/su", "/sbin/su/", "/system/bin/su","/system/bin/su/", "/system/xbin/su", "/system/xbin/su/", "/data/local/xbin/su", "/data/local/bin/su", "/system/sd/xbin/su", "/system/bin/failsafe/su", "/data/local/su", "/su/bin/su", "/su/", "/data/local/xbin/", "/system/bin/.ext/", "/system/bin/failsafe/", "/system/sd/xbin/", "/su/xbin/", "/su/bin/", "/magisk/.core/bin/", "/system/usr/we-need-root/", "/system/xbin/", "/system/su","/system/bin/.ext/.su","/system/usr/we-need-root/su-backup", "/system/xbin/mu", "/system/su/","/system/bin/.ext/.su/","/system/usr/we-need-root/su-backup/", "/system/xbin/mu/"};
for (String where : places)
{
if (new File(where + binaryName).exists())
{
found = true;
break;
}
}
}
return found;
}
private static boolean checkRootMethod5()
{
return findBinary("su");
}
}

How to search entire hard drive for a specific file (Java Eclipse)?

public static void fileSearcher() throws IOException {
File dire = new File ("C:/");
String[] allFile = dire.list();
for (int i = 0;i<10;i++) {
String FilIn = allFile[i]; // here is where I need to scan entire pc for file
if(FilIn.equals("eclipse.exe")){
System.out.println("Found Eclipse!");
break;
}
else {
System.out.println("Eclipse not found on local drive.");
}
Is there a simple way to scan an entire HHD/SSD for a specific file ?
This will do the job for you and it works too when there are multiple drives or partitions. It will also search for additional files with that same name.
import java.io.File;
import javax.swing.filechooser.FileSystemView;
public class HardDiskSearcher {
private static boolean fileFound = false;
private static String searchTerm = "eclipse.exe";
public static void main(String[] args) {
fileFound = false;
File[] systemRoots = File.listRoots();
FileSystemView fsv = FileSystemView.getFileSystemView();
for (File root: systemRoots) {
if (fsv.getSystemTypeDescription(root).equals("Local Disk")) {
File[] filesFromRoot = root.listFiles();
recursiveSearch(searchTerm, filesFromRoot);
}
}
System.out.println("File you searched for was found? : " + fileFound);
}
private static void recursiveSearch(String searchTerm, File... files) {
for (File file: files) {
if (file.isDirectory()) {
File[] filesInFolder = file.listFiles();
if (filesInFolder != null) {
for (File f : filesInFolder) {
if (f.isFile()) {
if (isTheSearchedFile(f, searchTerm)) {
fileFound = true;
}
}
}
for (File f : filesInFolder) {
if (f.isDirectory()) {
recursiveSearch(searchTerm, f);
}
}
}
}
else if (isTheSearchedFile(file, searchTerm)) {
fileFound = true;
}
}
}
private static boolean isTheSearchedFile(File file, String searchTerm) {
if (file.isFile() && (searchTerm.equals(file.getName())) ) {
System.out.println("The file you searched for has been found! " +
"It was found at: " + file.getAbsolutePath());
return true;
}
return false;
}
}
I am not 100% sure about why the if-statement (filesInFolder != null) is necessary here but i suspect Windows returns null when trying to list files from specific system folder or something.

Enumeration<URL> configs.hasMoreElements() gives false

I am developing a voice-based app in android and facing some problems please see below code,
Java File 1
file = .wav file
public static AudioInputStream getAudioInputStream(File file) throws UnsupportedAudioFileException, IOException {
return getAudioInputStreamImpl(file);
}
private static AudioInputStream getAudioInputStreamImpl(Object source) throws UnsupportedAudioFileException, IOException {
GetAudioInputStreamAudioFileReaderAction action = new GetAudioInputStreamAudioFileReaderAction(source);
doAudioFileReaderIteration(action);
AudioInputStream audioInputStream = action.getAudioInputStream();
if (audioInputStream != null) {
return audioInputStream;
}
throw new UnsupportedAudioFileException("format not supported");
}
private static void doAudioFileReaderIteration(AudioFileReaderAction action) throws IOException {
Iterator audioFileReaders = TAudioConfig.getAudioFileReaders();
boolean bCompleted = false;
while (audioFileReaders.hasNext() && !bCompleted) {
AudioFileReader audioFileReader = (AudioFileReader) audioFileReaders.next();
bCompleted = action.handleAudioFileReader(audioFileReader);
}
}
Java file 2 (TAudioConfig)
public static synchronized Iterator<AudioFileReader> getAudioFileReaders() {
Iterator<AudioFileReader> it;
synchronized (TAudioConfig.class) {
it = getAudioFileReadersImpl().iterator();
}
return it;
}
private static synchronized Set<AudioFileReader> getAudioFileReadersImpl() {
Set<AudioFileReader> set;
synchronized (TAudioConfig.class) {
if (sm_audioFileReaders == null) {
sm_audioFileReaders = new ArraySet();
registerAudioFileReaders();
}
set = sm_audioFileReaders;
}
return set;
}
private static void registerAudioFileReaders() {
TInit.registerClasses(AudioFileReader.class, new C00001());
}
Java File 3 (TInit)
public static void registerClasses(Class providerClass, ProviderRegistrationAction action) {
Iterator providers = Service.providers(providerClass);
if (providers != null) {
while (providers.hasNext()) {
try {
action.register(providers.next());
} catch (Throwable e) {
}
}
}
}
Java File 4 (Service)
public static Iterator<?> providers(Class<?> cls) {
String strFullName = "com/example/voiceautomator/AudioFileReader.class";
Iterator<?> iterator = createInstancesList(strFullName).iterator();
return iterator;
}
private static List<Object> createInstancesList(String strFullName) {
List<Object> providers = new ArrayList<Object>();
Iterator<?> classNames = createClassNames(strFullName);
if (classNames != null) {
while (classNames.hasNext()) {
String strClassName = (String) classNames.next();
try {
Class<?> cls = Class.forName(strClassName, REVERSE_ORDER, ClassLoader.getSystemClassLoader());
providers.add(0, cls.newInstance());
} catch (Throwable e) {
}
}
}
return providers;
}
private static Iterator<String> createClassNames(String strFullName) {
Set<String> providers = new ArraySet<String>();
Enumeration<?> configs = null;
try {
configs = Service.class.getClassLoader().getSystemResources(strFullName);
} catch (Throwable e) {
}
if (configs != null) {
while (configs.hasMoreElements()) {
URL configFileUrl = (URL) configs.nextElement();
InputStream input = null;
try {
input = configFileUrl.openStream();
} catch (Throwable e2) {
}
if (input != null) {
BufferedReader reader = new BufferedReader(new InputStreamReader(input));
try {
for (String strLine = reader.readLine(); strLine != null; strLine = reader.readLine()) {
strLine = strLine.trim();
int nPos = strLine.indexOf(35);
if (nPos >= 0) {
strLine = strLine.substring(0, nPos);
}
if (strLine.length() > 0) {
providers.add(strLine);
}
}
} catch (Throwable e22) {
}
}
}
}
Iterator<String> iterator = providers.iterator();
return iterator;
}
getClassLoader().getSystemResources in the Java File 4 (Service) gives me TwoEnumerationsInOne and configs.hasMoreElements() gives false so not able to go into while loop.
AudioFileReader.java is included in the package
Please guide me to resolve this issue?
Please don't forget I am working on this code in an android project
Please see the value of configs here
http://capsicumtech.in/Screenshot_1.png
Thanks in advance.

How to change boolean in fucntion ussing mockito

So here is my class:
public class FileDeleter implements Deleter {
public void deleteDirectories(List<GroupOfCountries> organizedCountries, String path) {
List<String> listOfThreeLettersGroups = new ArrayList<String>();
for (GroupOfCountries groupedCountries : organizedCountries) {
listOfThreeLettersGroups.add(groupedCountries.getName()); //Here it's adding "ABC" and "PQR" to ArrayList because my countries are Albania, Belgium and Portugal.
}
for (String directoryToDelete : listOfThreeLettersGroups) {
String pathOfGorupDirectory = (path + File.separator + directoryToDelete); //Here it's creating paths to ABC and PQR directories, for example /home/test/ABC
File tempfile = createFile(pathOfGorupDirectory);
deleteDirectory(tempfile);
}
}
protected File createFile(String pathOfGorupDirectory) {
return new File(pathOfGorupDirectory);
}
private boolean deleteDirectory(File dir) {
if (dir.isDirectory()) {
File[] children = dir.listFiles();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDirectory(children[i]);
if (!success) {
return false;
}
}
}
return dir.delete();
}
}
I want to have 100% missed branches. If I comment these lines:
if (!success) {
return false;
}
I have 100% missed branches. But somebody have idea what can I do using mockito/junits to change success into false? Because success always returns true so this if will never happend.
Maybe this will help.
FileDeleter deleter = Mockito.mock(FileDeleter.class);
Mockito.when(deleter.deleteDirectory(Mockito.any())).thenReturn(false);

How to serialize object to CSV file?

I want to write a Object into CSV file.
For XML we have XStream like this
So if i want to convert object to CSV do we have any such library ?
EDIT:
I want to pass my list of Bean to a method which should write all the fields of bean to CSV.
First, serialization is writing the object to a file 'as it is'. AFAIK, you cannot choose file formats and all. The serialized object (in a file) has its own 'file format'
If you want to write the contents of an object (or a list of objects) to a CSV file, you can do it yourself, it should not be complex.
Looks like Java CSV Library can do this, but I have not tried this myself.
EDIT: See following sample. This is by no way foolproof, but you can build on this.
//European countries use ";" as
//CSV separator because "," is their digit separator
private static final String CSV_SEPARATOR = ",";
private static void writeToCSV(ArrayList<Product> productList)
{
try
{
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("products.csv"), "UTF-8"));
for (Product product : productList)
{
StringBuffer oneLine = new StringBuffer();
oneLine.append(product.getId() <=0 ? "" : product.getId());
oneLine.append(CSV_SEPARATOR);
oneLine.append(product.getName().trim().length() == 0? "" : product.getName());
oneLine.append(CSV_SEPARATOR);
oneLine.append(product.getCostPrice() < 0 ? "" : product.getCostPrice());
oneLine.append(CSV_SEPARATOR);
oneLine.append(product.isVatApplicable() ? "Yes" : "No");
bw.write(oneLine.toString());
bw.newLine();
}
bw.flush();
bw.close();
}
catch (UnsupportedEncodingException e) {}
catch (FileNotFoundException e){}
catch (IOException e){}
}
This is product (getters and setters hidden for readability):
class Product
{
private long id;
private String name;
private double costPrice;
private boolean vatApplicable;
}
And this is how I tested:
public static void main(String[] args)
{
ArrayList<Product> productList = new ArrayList<Product>();
productList.add(new Product(1, "Pen", 2.00, false));
productList.add(new Product(2, "TV", 300, true));
productList.add(new Product(3, "iPhone", 500, true));
writeToCSV(productList);
}
Hope this helps.
Cheers.
For easy CSV access, there is a library called OpenCSV. It really ease access to CSV file content.
EDIT
According to your update, I consider all previous replies as incorrect (due to their low-levelness). You can then go a completely diffferent way, the hibernate way, in fact !
By using the CsvJdbc driver, you can load your CSV files as JDBC data source, and then directly map your beans to this datasource.
I would have talked to you about CSVObjects, but as the site seems broken, I fear the lib is unavailable nowadays.
Two options I just ran into:
http://sojo.sourceforge.net/
http://supercsv.sourceforge.net/
It would be interesting to have a csv serializer as it would take up the minimal space compared to other serializing method.
The closest support for java object to csv is stringutils provided by spring utils project
arrayToCommaDelimitedString(Object[] arr) but it is far from being a serializer.
Here is a simple utility which uses reflection to serialize value objects
public class CSVWriter
{
private static String produceCsvData(Object[] data) throws IllegalArgumentException, IllegalAccessException, InvocationTargetException
{
if(data.length==0)
{
return "";
}
Class classType = data[0].getClass();
StringBuilder builder = new StringBuilder();
Method[] methods = classType.getDeclaredMethods();
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get"))
{
builder.append(m.getName().substring(3)).append(',');
}
else if(m.getName().startsWith("is"))
{
builder.append(m.getName().substring(2)).append(',');
}
}
}
builder.deleteCharAt(builder.length()-1);
builder.append('\n');
for(Object d : data)
{
for(Method m : methods)
{
if(m.getParameterTypes().length==0)
{
if(m.getName().startsWith("get") || m.getName().startsWith("is"))
{
System.out.println(m.invoke(d).toString());
builder.append(m.invoke(d).toString()).append(',');
}
}
}
builder.append('\n');
}
builder.deleteCharAt(builder.length()-1);
return builder.toString();
}
public static boolean generateCSV(File csvFileName,Object[] data)
{
FileWriter fw = null;
try
{
fw = new FileWriter(csvFileName);
if(!csvFileName.exists())
csvFileName.createNewFile();
fw.write(produceCsvData(data));
fw.flush();
}
catch(Exception e)
{
System.out.println("Error while generating csv from data. Error message : " + e.getMessage());
e.printStackTrace();
return false;
}
finally
{
if(fw!=null)
{
try
{
fw.close();
}
catch(Exception e)
{
}
fw=null;
}
}
return true;
}
}
Here is an example value object
public class Product {
private String name;
private double price;
private int identifier;
private boolean isVatApplicable;
public Product(String name, double price, int identifier,
boolean isVatApplicable) {
super();
this.name = name;
this.price = price;
this.identifier = identifier;
this.isVatApplicable = isVatApplicable;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getPrice() {
return price;
}
public void setPrice(long price) {
this.price = price;
}
public int getIdentifier() {
return identifier;
}
public void setIdentifier(int identifier) {
this.identifier = identifier;
}
public boolean isVatApplicable() {
return isVatApplicable;
}
public void setVatApplicable(boolean isVatApplicable) {
this.isVatApplicable = isVatApplicable;
}
}
and the code to run the util
public class TestCSV
{
public static void main(String... a)
{
Product[] list = new Product[5];
list[0] = new Product("dvd", 24.99, 967, true);
list[1] = new Product("pen", 4.99, 162, false);
list[2] = new Product("ipad", 624.99, 234, true);
list[3] = new Product("crayons", 4.99,127, false);
list[4] = new Product("laptop", 1444.99, 997, true);
CSVWriter.generateCSV(new File("C:\\products.csv"),list);
}
}
Output:
Name VatApplicable Price Identifier
dvd true 24.99 967
pen false 4.99 162
ipad true 624.99 234
crayons false 4.99 127
laptop true 1444.99 997
I wrote a simple class that uses OpenCSV and has two static public methods.
static public File toCSVFile(Object object, String path, String name) {
File pathFile = new File(path);
pathFile.mkdirs();
File returnFile = new File(path + name);
try {
CSVWriter writer = new CSVWriter(new FileWriter(returnFile));
writer.writeNext(new String[]{"Member Name in Code", "Stored Value", "Type of Value"});
for (Field field : object.getClass().getDeclaredFields()) {
writer.writeNext(new String[]{field.getName(), field.get(object).toString(), field.getType().getName()});
}
writer.flush();
writer.close();
return returnFile;
} catch (IOException e) {
Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
return null;
} catch (IllegalAccessException e) {
Log.e("EasyStorage", "Easy Storage toCSVFile failed.", e);
return null;
}
}
static public void fromCSVFile(Object object, File file) {
try {
CSVReader reader = new CSVReader(new FileReader(file));
String[] nextLine = reader.readNext(); // Ignore the first line.
while ((nextLine = reader.readNext()) != null) {
if (nextLine.length >= 2) {
try {
Field field = object.getClass().getDeclaredField(nextLine[0]);
Class<?> rClass = field.getType();
if (rClass == String.class) {
field.set(object, nextLine[1]);
} else if (rClass == int.class) {
field.set(object, Integer.parseInt(nextLine[1]));
} else if (rClass == boolean.class) {
field.set(object, Boolean.parseBoolean(nextLine[1]));
} else if (rClass == float.class) {
field.set(object, Float.parseFloat(nextLine[1]));
} else if (rClass == long.class) {
field.set(object, Long.parseLong(nextLine[1]));
} else if (rClass == short.class) {
field.set(object, Short.parseShort(nextLine[1]));
} else if (rClass == double.class) {
field.set(object, Double.parseDouble(nextLine[1]));
} else if (rClass == byte.class) {
field.set(object, Byte.parseByte(nextLine[1]));
} else if (rClass == char.class) {
field.set(object, nextLine[1].charAt(0));
} else {
Log.e("EasyStorage", "Easy Storage doesn't yet support extracting " + rClass.getSimpleName() + " from CSV files.");
}
} catch (NoSuchFieldException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
} catch (IllegalAccessException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
}
} // Close if (nextLine.length >= 2)
} // Close while ((nextLine = reader.readNext()) != null)
} catch (FileNotFoundException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
} catch (IOException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
} catch (IllegalArgumentException e) {
Log.e("EasyStorage", "Easy Storage fromCSVFile failed.", e);
}
}
I think with some simple recursion these methods could be modified to handle any Java object, but for me this was adequate.
Though its very late reply, I have faced this problem of exporting java entites to CSV, EXCEL etc in various projects, Where we need to provide export feature on UI.
I have created my own light weight framework. It works with any Java Beans, You just need to add annotations on fields you want to export to CSV, Excel etc.
Link: https://github.com/abhisoni96/dev-tools
Worth mentioning that the handlebar library https://github.com/jknack/handlebars.java can trivialize many transformation tasks include toCSV.
You can use gererics to work for any class
public class FileUtils<T> {
public String createReport(String filePath, List<T> t) {
if (t.isEmpty()) {
return null;
}
List<String> reportData = new ArrayList<String>();
addDataToReport(t.get(0), reportData, 0);
for (T k : t) {
addDataToReport(k, reportData, 1);
}
return !dumpReport(filePath, reportData) ? null : filePath;
}
public static Boolean dumpReport(String filePath, List<String> lines) {
Boolean isFileCreated = false;
String[] dirs = filePath.split(File.separator);
String baseDir = "";
for (int i = 0; i < dirs.length - 1; i++) {
baseDir += " " + dirs[i];
}
baseDir = baseDir.replace(" ", "/");
File base = new File(baseDir);
base.mkdirs();
File file = new File(filePath);
try {
if (!file.exists())
file.createNewFile();
} catch (Exception e) {
e.printStackTrace();
return isFileCreated;
}
try (BufferedWriter writer = new BufferedWriter(
new OutputStreamWriter(new FileOutputStream(file), System.getProperty("file.encoding")))) {
for (String line : lines) {
writer.write(line + System.lineSeparator());
}
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
void addDataToReport(T t, List<String> reportData, int index) {
String[] jsonObjectAsArray = new Gson().toJson(t).replace("{", "").replace("}", "").split(",\"");
StringBuilder row = new StringBuilder();
for (int i = 0; i < jsonObjectAsArray.length; i++) {
String str = jsonObjectAsArray[i];
str = str.replaceFirst(":", "_").split("_")[index];
if (i == 0) {
if (str != null) {
row.append(str.replace("\"", ""));
} else {
row.append("N/A");
}
} else {
if (str != null) {
row.append(", " + str.replace("\"", ""));
} else {
row.append(", N/A");
}
}
}
reportData.add(row.toString());
}

Categories