What techniques can I use to determine the number generated by srand() in C?

98 Views Asked by At

How to know the secret number from srand((uint32_t)timer) where time_t timer = time(NULL)

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>

void printTerminalTime(time_t t) {
  char buffer[32];
  struct tm* tm_info = localtime(&t);
  strftime(buffer, 32, "%H:%M:%S > ", tm_info);
  printf("%s", buffer);
}

int main() {
  setbuf(stdout, NULL);
  time_t timer = time(NULL);
  srand((uint32_t)timer);
  printTerminalTime(timer);
  printf("%s", "Please enter your password: ");

  uint32_t input = 0;
  scanf("%u", &input);

  if (input == rand()) {
    puts(getenv("FLAG"));
  } else {
    printTerminalTime(time(NULL));
    puts("Access denied!");
  }

  return 0;
}

I can't perceive any pattern in rand(). How can I utilize a method to make input == rand()?

1

There are 1 best solutions below

1
nielsen On

Providing a given seed with srand(), the sequence of pseudo-random numbers generated by subsequent calls to rand() is fixed in a given environment (system+compiler).

Thus, knowing the seed makes it possible to predict the result of rand(). Not knowing the seed makes it very hard.

I am not quite sure what your goal is, put printing/storing the value of the seed will provide the necessary information:

...
#include <inttypes.h>
...
  uint32_t seed = (uint32_t)timer;
  srand(seed);
  printf("seed=%" PRIu32 "\n", seed);
...

Having a second program will then allow you to calculate the corresponding rand() result:

#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <inttypes.h>


int main() {
  uint32_t input = 0;
  printf("Enter seed: ");
  scanf("%" SCNu32, &input);
  srand(input);
  printf("Password: %" PRIu32 "\n", (uint32_t)rand());

  return 0;
}

If you choose to use a fixed seed, instead of one based on time(NULL), then that seed can be entered into the second program to get the corresponding "password".