Search code examples
cstringinthexstack-smash

Convert int to string in hex format


While I was trying to do a smash-stacking exploit just like this article: http://www.cs.wright.edu/people/faculty/tkprasad/courses/cs781/alephOne.html, I ran across a problem of needing to convert the stack pointer into a string.

I know how to print out an int in a hex format (using printf), but not how to store it as an internal string representation. I need to store it internally as a string so I can pass it into the memcpy function.

The theoretical function I need is "convertFromIntToHexCharStar" below.

unsigned long NOPSledPointer = get_sp() + 150;
char * address = convertFromIntToHexCharStar(NOPSledPointer);

It is intended to work with this function as the argument. It gives the stack pointer.

unsigned long get_sp(void) {
    __asm__("movl %esp,%eax");
}

I want to convert the stack pointer into a hex char* so I can do memcpy like this:

char buffer[517];   

/* Initialize buffer with 0x90 (NOP instruction) */
memset(&buffer, 0x90, 517);

/* Fill the buffer with appropriate contents here */ 
 memcpy((void*) buffer, (void*) address, 4);

I need to fill in the memory with the address represented in hex, because I know that it has worked in the past.

So, what I'm asking is for help with either converting it to a string, or another easier way to do this NOP sled (that is my real problem I'm trying to solve). I was going to fill in the address multiple times so it increases the odds of overwriting the return address on the stack, but for brevity I only gave one line of code writing "address" into "buffer."

I have already searched stackoverflow & google and couldn't find anything. Thanks in advance for your help!


Solution

  • snprintf solved my problem, since I know the size of the stack pointer in advance to be 4 bytes.

    This site helped me: http://www.cplusplus.com/reference/cstdio/snprintf/

    And here is the code solution below, with some print statements that I used to make sure it worked correctly.

    #include <stdio.h>
    
    unsigned long get_sp(void) 
    {
       __asm__("movl %esp,%eax");
    }
    
    
    int main()
    {
        unsigned long numberToConvert = get_sp();
        char address[9];
        snprintf(address, 9, "%08lX", numberToConvert);
    
        printf("Number To Convert: %lu \n", numberToConvert);
        printf("Expected hex number: %08lX \n", numberToConvert);
        printf("Actual hex number: %s \n", address);
    
        return 0;
    }