Writing raw data to the Android Serial Port (USB) - android

I need to write some "raw" data to the usb port for a project of mine (no prob if root should be required).
I found a port of libusb for Android and managed to compile it with NDK. I linked the library to an executable of mine (executed as root), but the function "libusb_init" always returns an error (LIBUSB_ERROR_OTHER).
I found that the problem (by now...) is in the file "linux_usbfs.c", more precisely in this function:
static const char *find_usbfs_path(void)
{
const char *path = "/dev/bus/usb";
const char *ret = NULL;
if (check_usb_vfs(path)) {
ret = path;
} else {
path = "/proc/bus/usb";
if (check_usb_vfs(path))
ret = path;
}
usbi_dbg("found usbfs at %s", ret);
return ret;
}
/dev/bus/usb obviously doesn't exist on my N1.

Why not try pyserial? python seems simpler for me. You need either a kernel with usb host mode or your phone supports serial over a ttyMSM0 natively, which you need to find out. Once you are sure you have a serial port on your phone, look at this link which is meant for huawei ideos U8150, but the pyserial stuff done using python for android is the alternative I am suggesting.

Related

C++: Executing command and returning output results in assertion failure

I am working on a project that requires me to programmatically install an Android .apk using adb install. I also need to get the result output to use later on. I have the following generic function to execute a command and return the output as a string:
std::string exec(const char* command) {
std::string output = "";
const int bufferSize = 100;
FILE *pipe;
char buffer[bufferSize];
pipe = _popen(command, "r");
if (pipe == NULL) {
exit(1);
}
while (fgets(buffer, bufferSize, pipe) != NULL) {
output += buffer;
}
_pclose(pipe);
return output;
}
While the command executes and returns the output properly, I get the following error when executing adb install using this function:
Debug Assertion Failed!
Program: ...(My .exe) File:
minkernel\crts\ucrt\src\appcrt\lowio\read.cpp Line: 258
Expression: static_cast(source_buffer) ==
static_cast(result_buffer)
I searched for this error online and turned up nothing. The following is the line that causes the assertion failure:
while (fgets(buffer, bufferSize, pipe) != NULL) {
Can anyone tell me what's going on here, and I can do to fix this?
Got the same issue, and fixed by set mode to binary(add 'b'):
_popen(myBuffer, "rb");
Note that only "r" is enough for Linux and MacOS, and even MSVC 2010.
Hence, seems to be yet another MSVC 2015 bug, and may be fixed in future MSVC versions.
Perhaps the following is relevant (from the microsoft docs)
If used in a Windows program, the _popen function returns an invalid
file pointer that causes the program to stop responding indefinitely.
_popen works properly in a console application. To create a Windows application that redirects input and output, see Creating a Child
Process with Redirected Input and Output in the Windows SDK.
Try the following https://msdn.microsoft.com/library/windows/desktop/ms682499

Cross-compiling of C code for Android

I cross-compiled my C application for Android ARM with arm-linux-gnueabi tool under Ubuntu 16.04 LTS. I compiled it with static linking flag. This C application is big and it has complicated makefile. It compiled successfully without any errors. But it behaves differently on Android phone and Ubuntu PC. More precisely i have two problems:
popen() and system() functions don't work on Android. They are carried out but do nothing and don't give any errors. This problem i solved with dirty hack.
fgets() functions works strange on Android.
1. About first problem.
I did small research and found that Android doesn't use ordinary libc library (glibc or another library which implements POSIX standard properly). It uses Bionic library instead of it (sorry, Android is new OS for me). I looked into popen() and system() functions code and noticed that these functions use _PATH_BSHELL macros. _PATH_BSHELL is path to the actual system shell. This path is "/system/bin/sh" on Android and "/bin/sh" on Ubuntu.
When i understood it i tried to hook popen() and system() functions. I copied code of these functions from the Bionic source, than i defined macros #define _MY_PATH_BSHELL "/system/bin/sh" and replaced calls like execve(_MY_PATH_BSHELL, argp, environ); by execve(_MY_PATH_BSHELL, argp, environ); calls. So it started work properly.
2. About second problem.
On Ubuntu this code works properly:
is_received = false;
while(!is_received) {
FILE *cmd = popen(command, "r");
is_received = fgets(buf, sizeof(buf), cmd) == NULL ? false : true;
}
But on Android fgets() always returns NULL and this loop works infinitely long. I tried to use read() function instead of fgets() and it worked.
On Android this code with read() works properly:
is_received = false;
while(!is_received) {
FILE *cmd = hooked_popen(command, "r");
int fd = fileno(cmd);
is_received = read(fd, buf, sizeof(buf)) == 0 ? false : true;
}
My questions.
How to solve my problems with popen() and system() neatly and correctly? I think i have to link statically with Bionic library. Is it right? How can i do it in console without Android Studio? I read that it is necessary to use NDK but it is not clear to me how.
Why fgets() behavior isn't similar on Android and Ubuntu?

File exchange PC <--> Android via USB MTP issues

In my android app, I create a file and write some test text into it:
File externalPath = getExternalFilesDir(null);
File importPath = new File(externalPath, "pd-import");
if(!importPath.exists()) {
Log.d(this.getClass().getSimpleName(), "Create import dir: " + importPath.getAbsolutePath());
importPath.mkdirs();
}
File readme = new File(importPath, "README.txt");
try {
FileWriter fw = new FileWriter(readme);
fw.write("This is a test");
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
This writes the file, which can be approved with an android file browser like B1 File Manager. It's written to HOME/Android/data/JAVA_PACKAGE_NAME/files/pd-import/README.txt
The logcat shows me:
D/MainActivity﹕ Create import dir: /storage/emulated/0/Android/data/JAVA_PACKAGE_NAME/files/pd-import
When I connect my Nexus, where I tested the code, to my Ubuntu Laptop via USB, I see all the other applications data directories like NEXUS 5/Interner Speicher/Android/data/ALL_THE_OTHER_JAVA_PACKAGE_NAMEs ("Interner Speicher" stands for: internal memory). But the folder is not listed for my app is not listed.
Do I need to set some additional medatdata/information/whatever, to have the folder listed over the MTP connection? Anny suggestions?
Does the directory appear when the device is rebooted ? If yes, I think this bug is the cause : https://code.google.com/p/android/issues/detail?id=38282
All phones using MTP instead of USB Mass storage do not properly show
the list of files when that phone is connected to a computer using a
USB cable. Android apps running on the device also cannot see these
files.
This affects files written using Java APIs, but does not appear to
affect files written using the C API.
The solution is to reboot the device.
It does not seem to be resolved.

Unable to access sys_call_table

I managed to find address of the sys_call_table by looking into /proc/kallsyms. I have the following code:
void **sys_call_table;
#include <linux/kernel.h>
#include <asm/unistd.h>
void Java_com_example_testlib_LibLoader_test() {
sys_call_table = (void *) 0xc023cd28;
LOGD("backup original sys_open %p", sys_call_table[__NR_open]);
}
The problem is that the code causes Fatal Signal Exeption why trying to get the sys_call_table entry sys_call_table[__NR_open]
I tried to get entry 0, 1, 2, ... as well.
Ok so the answer is like Crhis said "You cannot modify the kernel from a user mode program!"
I compiled it as a LKM and loaded it using insmod command and it worked
PS: I have also found that only LKM modules can read /proc/kallsyms. User space programs are no longer to do so due to a kernel patch in Android 4.1. /proc/sys/kernel/kptr_restrict is introduced to avoid leaking kernel addresses.
So now in order for userspace programs to see the kallsym address, we can either set kptr_restrict to either 0 or 1.
echo 1 > /proc/sys/kernel/kptr_restrict
Info can be found here:
https://blog.duosecurity.com/2012/07/exploit-mitigations-in-android-jelly-bean-4-1/
And here: http://insitusec.blogspot.sg/2013/01/kallsyms-on-android.html

Run python Script in android application

I want to get list of installed software on remote computer.For that I want to use python script in my android application.Now,I have a python script which is getting the list of installed software on remote computer.But,I don't know how to make it supported in android.
For this, I found SL4A android Scripting here . So, I tried to run my python script in android device using SL4A.But,It's not working and giving me error because some packages like win32.client is missing.I don't know more about SL4A so I don't know how to convert my python script in Android supported form.So,anyone have any idea or code please suggest me.....
Also If anyone have another way to get installed software list from remote Pc then please suggest...
Below is my python script
import wmi
from winreg import (HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS, OpenKey, EnumValue, QueryValueEx)
c = wmi.WMI(computer="PC02",user="admin",password="a#1",namespace="root/default").StdRegProv
result, names = c.EnumKey (hDefKey=HKEY_LOCAL_MACHINE, sSubKeyName=r"Software\Microsoft\Windows\CurrentVersion\Uninstall")
print('These subkeys are found under "HKEY_LOCAL_MACHINE\\Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall"\n\n')
separator = "*" * 80
keyPath = r"Software\Microsoft\Windows\CurrentVersion\Uninstall"
count = 0
while count < len(names):
try:
print(separator+'\n')
path = keyPath + "\\" + names[count]
key = OpenKey(HKEY_LOCAL_MACHINE, path, 0, KEY_ALL_ACCESS)
temp = QueryValueEx(key, 'DisplayName')
display = str(temp[0])
print (" Name: "+display+'\n',"key:",names[count])
count += 1
except:
print ("Key:",names[count])
count += 1
continue
Run the script on your remote computer, and expose the list of installed software on HTTP, a good way to write this simple web app is to use flask and its development server to serve the list of installed software, then write a python script which uses the native android web interface to fetch the list and display it.
You are having problems with missing libraries because you are importing windows specific ones. At any rate, this isn't the correct script to be running. This script seems to be for a computer, not an android phone.
You're trying to use a Python script that uses Windows Management Instrumentation (WMI), on a device that doesn't have that library.
Sadly, WMI on Python requires the win32 library, which is only available on Windows. I don't think you're going to have much success on checking the installed programs on remote Windows computer from an Android device in this way.
Since WMI is based on WBEM, you may be able to use wbem to access it; you might want to try using pywbem, a pure python wbem library.
Running python scripts is now achievable in gradle system using Tasks
task pythonFile(type:Exec) {
workingDir 'src_path'
commandLine 'python', 'my_script.py'
}

Categories

Resources