3

I'm trying to build a C program that will bruteforce a hash given in argument. Here is the code:

#include <unistd.h>
#include <stdio.h>
#include <crypt.h>
#include <string.h>

const char setting[] = "$6$QSX8hjVa$";
const char values[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

int main(int argc, char *argv[])
{
    char *hashToCrack = crypt(argv[1], setting);

    printf("%s\n", hashToCrack);

    for (int i = 0; i < strlen(values); i++)
    {
        printf("trying %c ...\n", values[i]);
        char *try = crypt(&values[i], setting);

        if (strcmp(hashToCrack, try) == 0)
        {
            printf("calc: %s\n", try);
            printf("init: %s\n", hashToCrack);
            printf("Found!\n");
        } 
    }
    
    return 0;
}

For convenience, I just give in argument a string that will be the one to crack. It is encrypted at the beginning of the main function (stored in hashToCrack). For now, I just work with one char. I compile the program this way: gcc main.c -o main -lcrypt -Wall.

The problem - When I launch this program, I have "Found!" in every iteration in the for loop. It seems that hashToCrack and try are the same. However, I never overwrite hashToCrack, so it should never change.

There is probably something I don't understand with pointers, but I can't find it.

Any idea ? :D

hacb
  • 175
  • 2
  • 10

1 Answers1

4

The crypt function returns a pointer to a static data buffer. So when you call it again, the string pointed to by hashToCrack changes.

You need to copy the results of the first call to crypt into a separate buffer.

char *hashToCrack = strdup(crypt(argv[1], setting));

Don't forget to call free on this buffer when you're done with it.

dbush
  • 205,898
  • 23
  • 218
  • 273