pwned.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  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_PREFIX_SIZE 6
  7. #define HASH_SUFFIX_LENGTH 35
  8. #define HASH_SUFFIX_SIZE 36
  9. #define URL_SIZE 43
  10. #define BASEURL_SIZE 38
  11. char *getURL(const char* hash) {
  12. const char *baseURL = "https://api.pwnedpasswords.com/range/";
  13. char *url = malloc(URL_SIZE);
  14. if (url == NULL) return NULL;
  15. strncpy(url, baseURL, BASEURL_SIZE);
  16. strncat(url, hash, HASH_PREFIX_LENGTH);
  17. return url;
  18. }
  19. char *getSuffixUppercase(const char *hash) {
  20. char hashSuffix[HASH_SUFFIX_SIZE];
  21. strcpy(hashSuffix, hash+HASH_PREFIX_LENGTH);
  22. char *suffixUpper = malloc(HASH_SUFFIX_SIZE);
  23. if (suffixUpper == NULL) {
  24. puts("Couldn't allocate memory for suffix!");
  25. return NULL;
  26. }
  27. for (int i = 0; i < HASH_SUFFIX_LENGTH; i++) {
  28. int c = hashSuffix[i];
  29. c = toupper(c);
  30. sprintf(suffixUpper+i, "%c", c);
  31. }
  32. suffixUpper[HASH_SUFFIX_LENGTH] = 0;
  33. return suffixUpper;
  34. }
  35. int printNumber(char *text) {
  36. char *part = strtok(text, ":");
  37. if (part == NULL) return 0;
  38. part = strtok(NULL, ":");
  39. if (part != NULL) {
  40. printf("This is how many times your password was pwned: %s\n", part);
  41. return 1;
  42. }
  43. return 0;
  44. }
  45. int findSuffix(const char *suffix, char *data) {
  46. char *token = strtok(data, "\n");
  47. while (token != NULL) {
  48. if (strncmp(token, suffix, HASH_SUFFIX_LENGTH) == 0) {
  49. if (!printNumber(token)) {
  50. puts("Hash found, but can't obtain the number!");
  51. return 0;
  52. }
  53. return 1;
  54. }
  55. token = strtok(NULL, "\n");
  56. }
  57. return 0;
  58. }
  59. void usage(const char *app) {
  60. printf("Usage:\n%s <password>\n", app);
  61. }
  62. int main(int argc, char **argv) {
  63. if (argc < 2) {
  64. usage(argv[0]);
  65. return 1;
  66. }
  67. char *hash = getHash(argv[1]);
  68. if (hash == NULL) {
  69. puts("Couldn't get hash!");
  70. return 1;
  71. }
  72. char *url = getURL(hash);
  73. if (url == NULL) {
  74. puts("Couldn't get URL!");
  75. return 1;
  76. }
  77. char *suffix = getSuffixUppercase(hash);
  78. if (suffix == NULL) {
  79. puts("Couldn't make suffix uppercase!");
  80. return 1;
  81. }
  82. free(hash);
  83. char *data = getData(url);
  84. if (data == NULL) {
  85. puts("Couldn't get data from the API!");
  86. return 1;
  87. }
  88. free(url);
  89. if (!findSuffix(suffix, data)) puts("Password not pwned!");
  90. free(data);
  91. free(suffix);
  92. }