pwned.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
  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. void printNumber(const char *data) {
  36. for (int i = 0; data[i] != '\n' && data[i] != 0; i++)
  37. putchar(data[i]);
  38. putchar('\n');
  39. }
  40. int findSuffix(const char *suffix, const char *data) {
  41. for (int i = 0; data[i] != 0; i++) {
  42. int j;
  43. for (j = 0; suffix[j] != 0; j++)
  44. if (data[i+j] != suffix[j])
  45. break;
  46. if (suffix[j] == 0 && data[i+j] == ':') {
  47. printf("This is how many times your password was pwned: ");
  48. printNumber(data+i+j+1);
  49. return 1;
  50. }
  51. }
  52. return 0;
  53. }
  54. void usage(const char *app) {
  55. printf("Usage:\n%s <password>\n", app);
  56. }
  57. int main(int argc, char **argv) {
  58. if (argc < 2) {
  59. usage(argv[0]);
  60. return 1;
  61. }
  62. char *hash = getHash(argv[1]);
  63. if (hash == NULL) {
  64. puts("Couldn't get hash!");
  65. return 1;
  66. }
  67. char *url = getURL(hash);
  68. if (url == NULL) {
  69. puts("Couldn't get URL!");
  70. return 1;
  71. }
  72. char *suffix = getSuffixUppercase(hash);
  73. if (suffix == NULL) {
  74. puts("Couldn't make suffix uppercase!");
  75. return 1;
  76. }
  77. free(hash);
  78. char *data = getData(url);
  79. if (data == NULL) {
  80. puts("Couldn't get data from the API!");
  81. return 1;
  82. }
  83. free(url);
  84. if (!findSuffix(suffix, data)) puts("Password not pwned!");
  85. free(data);
  86. free(suffix);
  87. }