Accessing .so native library methods in Python

281 Views Asked by At

I am trying to use a native library using Python, In IDA I have seen the function I want to access getting 6 parameters but in java, the same function is accessible with 4 parameters.

Along with that one of its parameters is Map (seen in java) and this parameter is typecasted to Object type while calling that method. I am not getting how can I call this method in python stuck because of that map as a parameter also that function returns byte[] in Java, so how can I do the same in python.

#1. below is the code used in Java.

public class NativeLibHelper{
    public static final String TAG = "NativeLibHelper";

    static {
        try {
            System.loadLibrary("nativelib");
        } catch (UnsatisfiedLinkError e) {
            Log.e(TAG, e.toString());
        }
    }

private native byte[] nSign(Context context, Object obj, byte[] bArr, int i);
}

#2. below is the code from IDA. [1]: https://i.stack.imgur.com/opH2u.png

#3. Below is the python code which is written to access the same method. Also expecting a byte array as output of the method.

from ctypes import *
libc = cdll.LoadLibrary("./nativelib.so")

bArr = [-11, -28, -45, -42]
bArr = "".join([chr(256 + i if i < 0 else i) for i in bArr])
byte_array = c_byte * len(bArr)

bArr = byte_array.from_buffer(bytearray(bArr))
apiLevel = c_int(24)

Tmp = [["name","abc"], ["age", "18"]]
# print Tmp
class CA(Structure):
   _fields_ = [("key", c_char_p), ("value", c_char_p)]

ca_list = []
for k,v in Tmp:
    ca = CA()
    ca.key = c_char_p(k)
    ca.value = c_char_p(v)
    ca_list.append(ca)
map = (CA * len(ca_list))(*ca_list)

libc.nSign.restype = POINTER(c_byte * 96)
libc.nSign.argtypes = [py_object, type(map), type(bArr), type(apiLevel)]
sign= libc._nSign(None, map, bArr, apiLevel)
0

There are 0 best solutions below