Search code examples
node.jsjsontypescriptbuffer

TypeScript Decode Buffer to JSON Object with NodeJS/memoryjs


I am trying to get a json object from a buffer with mermoryjs.readBuffer() and I've been at it for a while now I am not sure what else to do. Here is what I have tried:

import { readBuffer } from 'memoryjs';

let buffer: Buffer = readBuffer(process, address, bufferLength);
console.log(buffer);

// (correctly) OUTPUTS -> <Buffer 88 77 b3 10 00 00 00 00 00 00 00 00 60 d5 69 1b 06 00 00 00 16 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 40 c2 52 16 01 00 00 00 00 9a 8f 07 00 00 ... 6 more bytes>
console.log(buffer.toJson());

// OUTPUS: 
{
  type: 'Buffer',
  data: [
    136, 119, 179, 16, 0, 0, 0, 0,  0,   0,   0, 0,
     96, 213, 105, 27, 6, 0, 0, 0, 22,   0,   0, 0,
      0,   0,   0,  0, 0, 0, 0, 0,  0,   0,   0, 0,
     64, 194,  82, 22, 1, 0, 0, 0,  0, 154, 143, 7,
      0,   0,   0,  0, 0, 0, 0, 0
  ]
}
console.log(JSON.parse(JSON.stringify(buffer)));

// OUTPUS: 
{
  type: 'Buffer',
  data: [
    136, 119, 179, 16, 0, 0, 0, 0,  0,   0,   0, 0,
     96, 213, 105, 27, 6, 0, 0, 0, 22,   0,   0, 0,
      0,   0,   0,  0, 0, 0, 0, 0,  0,   0,   0, 0,
     64, 194,  82, 22, 1, 0, 0, 0,  0, 154, 143, 7,
      0,   0,   0,  0, 0, 0, 0, 0
  ]
}
console.log(buffer.toString());

// OUTPUTS: �w�►`�i♠▬�R▬☺��

And subsequently when it try this:

console.log(JSON.parse(buffer.toString()));

// OUTPUTS: 
    SyntaxError: Unexpected token � in JSON at position 0
         at JSON.parse (<anonymous>)

Using structron's read() function (npm package https://www.npmjs.com/package/structron)

import Struct = require('structron'); // doing " import Struct from 'structron' " gives an import error

let struct = new Struct();
console.log(this.struct.read(buffer, address));

// OUPUTS: {}

I am reading an application's memory in real time and when I check a checkbox within the application I can see the buffer var having a 00 change to 01 and viscera so I don't think the issue comes from getting the buffer data the wrong way (with wrong address or process).

I am thinking maybe I can decode/deserialize the int array from buffer.data into a json object but I am not sure if there is a way to do it.

Any input will help me greatly. Thanks in advance.


Solution

  • The best way to serialize a buffer in plaintext is probably to convert it to base64:

    const buf = Buffer.from("asdf");
    // this is a string you can store in a JSON object somewhere
    const serialized = x.toString("base64");
    console.log(serialized); // YXNkZg==
    // you can get the serialized base64 from a JSON object
    const deserialized = Buffer.from(serialized, "base64");
    console.log(deserialized); // <Buffer 61 73 64 66>
    console.log(deserialized.toString("utf8")); // asdf
    

    Note that if you can, you should write the buffer directly to a file, as base64 is more space-consuming than raw binary data.