pwned.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <ctype.h>
  2. #include "curl.h"
  3. #include "sha.h"
  4. // https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange
  5. #define HASH_PREFIX_LENGTH 5
  6. #define HASH_SUFFIX_LENGTH 35
  7. #define BASEURL "https://api.pwnedpasswords.com/range/"
  8. #define BASEURL_SIZE (sizeof BASEURL)
  9. #define URL_SIZE (BASEURL_SIZE + HASH_PREFIX_LENGTH)
  10. #define NUMBER_SIZE 20
  11. char *getURL(const char* hash) {
  12. char *url = malloc(URL_SIZE);
  13. if (url == NULL) return NULL;
  14. snprintf(url, URL_SIZE, "%s%s", BASEURL, hash);
  15. return url;
  16. }
  17. char *getNumber(char *text) {
  18. char *part = strchr(text, ':');
  19. if (part == NULL) return NULL;
  20. char *number = malloc(NUMBER_SIZE);
  21. snprintf(number, NUMBER_SIZE, "%s", part+1);
  22. return number;
  23. }
  24. char *findSuffix(const char *suffix, char *data) {
  25. char *token = strtok(data, "\n");
  26. while (token != NULL) {
  27. if (strncmp(token, suffix, HASH_SUFFIX_LENGTH) == 0) {
  28. return token;
  29. }
  30. token = strtok(NULL, "\n");
  31. }
  32. return NULL;
  33. }
  34. void usage(const char *app) {
  35. printf("Usage:\n%s <password>\n", app);
  36. }
  37. int main(int argc, char **argv) {
  38. if (argc < 2) {
  39. usage(argv[0]);
  40. return 1;
  41. }
  42. char *hash = getHash(argv[1]);
  43. if (hash == NULL) {
  44. puts("Couldn't get hash!");
  45. return 1;
  46. }
  47. char *url = getURL(hash);
  48. if (url == NULL) {
  49. puts("Couldn't get URL!");
  50. return 1;
  51. }
  52. char *data = getData(url);
  53. if (data == NULL) {
  54. puts("Couldn't get data from the API!");
  55. return 1;
  56. }
  57. free(url);
  58. char *suffix = findSuffix(hash+HASH_PREFIX_LENGTH, data);
  59. if (suffix == NULL) {
  60. puts("Password not pwned!");
  61. return 1;
  62. }
  63. char *number = getNumber(suffix);
  64. if (number == NULL) {
  65. puts("Hash found, but can't obtain the number!");
  66. return 1;
  67. }
  68. printf("This is how many times your password was pwned: %s\n", number);
  69. free(hash);
  70. free(data);
  71. free(number);
  72. }