4

Recently I started using Frida and playing with some native methods. But i have a problem with reading value of basic_string

Here is method which I'm hooking:

Here is JavaScript code which I'm using to hook method:

Interceptor.attach(Module.getExportByName('libsigning.so', '_ZN8Security4signEP7_JNIEnvP6rsa_stRKNSt6__ndk112basic_stringIcNS4_11char_traitsIcEENS4_9allocatorIcEEEE'), {
    onEnter: function (args) {
        console.log("RSA.sign()")
        console.log(Memory.readCString(args[2]))
    },
    onLeave: function (retval) {
        // simply replace the value to be returned with 0
        return retval
    }
});

In output I'm getting ! character instead of real value

What is a proper way of doing this?

Robert
  • 39,162
  • 17
  • 99
  • 152
Kaspek
  • 159
  • 1
  • 11
  • 2
    Seems like `basic_string` is not a pointer to a `char[]` but to a C++ object. Therefore when directly using that pointer you interpret the c++ instance data as string which does not work. See https://en.cppreference.com/w/cpp/string/basic_string and https://stek29.rocks/2017/08/07/frida-stdstring.html and https://codeshare.frida.re/@oleavr/read-std-string/ – Robert Jul 04 '21 at 10:59
  • Robert thanks for your answer, you solved my problem <3 – Kaspek Jul 04 '21 at 11:37

1 Answers1

3

Problem was resolved using this frida code:

function readStdString (str) {
  const isTiny = (str.readU8() & 1) === 0;
  if (isTiny) {
    return str.add(1).readUtf8String();
  }

  return str.add(2 * Process.pointerSize).readPointer().readUtf8String();
}

source: https://codeshare.frida.re/@oleavr/read-std-string/

final working code:

Interceptor.attach(Module.getExportByName('libsigning.so', '_ZN8Security4signEP7_JNIEnvP6rsa_stRKNSt6__ndk112basic_stringIcNS4_11char_traitsIcEENS4_9allocatorIcEEEE'), {
    onEnter: function (args) {
        console.log("RSA.sign()")
        console.log(readStdString(args[2]))
    },
    onLeave: function (retval) {
        // simply replace the value to be returned with 0
        return retval
    }
});
Kaspek
  • 159
  • 1
  • 11