Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Extracting data from objects using Unsafe (bypassing the Security Manager0

I am fully aware that I am doing is:
1) Unsafe, that I have no more guarantees, type safety, and that the JVM could therefore crash
2) That I could do similar operations using ByteBuffers or JNI
3) That Unsafe is an internal class and could well disappear.

I am doing this for experimentation purposes only and am aware of the consequences.

With this in mind, I am trying to extract the data from an array using Unsafe and reflection:

I first find the field offset of the array:

public long findFieldOffset(Event event) {
    try {
        Class cl = event.getClass();            
        Field data_field = cl.getDeclaredField("data");            
        data_field.setAccessible(true);
        long offset = unsafe.objectFieldOffset(data_field);            
        return offset;            
    } catch (NoSuchFieldException e) {
        e.printStackTrace();
    }
    return 0;        
}

I also extract the base location of the array:

       int base = unsafe.arrayBaseOffset(byte[].class);

I subsequently try to extract the array from the class Event, and copy it to a buffer (byte_offset is the result of findFieldOffset).
In the code below, the first part is just a test function and prints out the correct string, whilst the second part extracts what should be the array, but when testing returns garbage unicode values:

                  /* Testing  */
                    active_buffer.getBuffer().position(1); 
                    active_buffer.getBuffer().put(event.getData()); 
                    active_buffer.getBuffer().position(1); 
                    active_buffer.getBuffer().get(tuple, 0, (int)tuple_size);
                    System.out.println("Test1: " + new String(tuple)) ;
                   /* Test1 prints out the correct string */

                    unsafe.copyMemory( (Object) event,  byte_offset  +  base, (Object) null, active_buffer.getAddress() + 1, tuple_size);
                    active_buffer.getBuffer().position(1); 
                    active_buffer.getBuffer().get(tuple, 0, (int)tuple_size);
                    System.out.println("Test2: " + new String(tuple)); 
                    /* Garbage unicode values gets printed*/ 

Can anyone see anything wrong with this code?

like image 950
user1018513 Avatar asked Dec 04 '25 23:12

user1018513


1 Answers

As data is a field, it is either a primitive or a reference, in either case you cannot copy it somewhere and treat it as a byte[]

If data is a byte[] you need to treat this as the true object, not the Event.

like image 152
Peter Lawrey Avatar answered Dec 07 '25 12:12

Peter Lawrey



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!