Abhimanyu Khanna Abhimanyu Khanna - 1 month ago 12
C Question

Memcmp for two pointers with different data

This question is a bit hard to explain as the code snippet is part of a larger project. I will try to explain the problem to the best I can.

I have two files

FILE *f,*m;
f=fopen("/home/machine/decoder.txt","a+");
m=fopen("/home/machine/offset.txt","a+");


In a function I run the following code,

char *c;
int i=0;
c = malloc(sizeof(SslDecoder));

//Pick a value from "decoder" file and compare it to a variable in the function

while (fgets(c, sizeof(SslDecoder), f) != NULL) {

//Print its value to offset file
fprintf(m,"%s\n",c);

// Print value of another variable to offset file.

for(i=0;i<32;i++){
fprintf(m,"%02x",ssl->client_random.data[i]);
}
fprintf(m,"\n");

//Compare the memory in the pointers.
int check = memcmp(c,ssl->client_random.data,32);
fprintf(m,"MEMCMP value: %d\n",check);
}


The values printed in offset.txt are as follows

625b70a9659b2fe9ba76ea26d3cfb6126bae4a48b4997548b26d9a101e682bc3

625b70a9659b2fe9ba76ea26d3cfb6126bae4a48b4997548b26d9a101e682bc3
MEMCMP value: -44


Definition of client_random and ssl is as follows -

typedef struct _StringInfo {
guchar *data; /* Backing storage which may be larger than data_len */
guint data_len; /* Length of the meaningful part of data */
} StringInfo;


typedef struct _SslDecryptSession {
StringInfo server_random;
StringInfo client_random;
StringInfo master_secret;
guchar _client_data_for_iv[24];
StringInfo client_data_for_iv;
gint state;
SslCipherSuite cipher_suite;
SslDecoder *server;
SslDecoder *client;
SslSession session;

} SslDecryptSession;


I do not understand why the values of memcmp is not zero. I suspect that the data stored in the pointers are encoded differently, but how do I compare the values in that case. I do not know if the data is of hex type or raw/ascii data in either of the pointers.

Answer

The data that you're reading in /home/machine/decoder.txt is an ASCII string.

You're printing it as ASCII (using %s).

The data you're comparing with is binary data (you're printing is using %02x, printing it using %s will print garbage depending on data being ASCII or not)

So of course they're not equal.

To compare them, you have to convert the binary values to ASCII or ASCII to binary. Make your pick. To compare both strings:

char sslstr[65];
for(i=0;i<32;i++){
  sprintf(sslstr+i*2,"%02x",ssl->client_random.data[i]);
}

int check = memcmp(c,sslstr,64);

Aside: you're reading your text file on a buffer which is too small, and you should zero-terminate it or you'll have garbage at the end of the string when you print it.