pwned.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. #include <ctype.h>
  2. #include "curl.h"
  3. #include "sha.h"
  4. // https://haveibeenpwned.com/API/v2#SearchingPwnedPasswordsByRange
  5. #define HASH_PREFIX_SIZE 5
  6. #define HASH_SUFFIX_SIZE 35
  7. #define URL_SIZE 43
  8. char *getURL(const char* hash) {
  9. const char *baseURL = "https://api.pwnedpasswords.com/range/";
  10. char *url = malloc(URL_SIZE);
  11. if (url == NULL) return NULL;
  12. strncpy(url, baseURL, strlen(baseURL)+1);
  13. strncat(url, hash, HASH_PREFIX_SIZE);
  14. return url;
  15. }
  16. char *getSuffixUppercase(const char *hash) {
  17. char hashSuffix[HASH_SUFFIX_SIZE + 1];
  18. strncpy(hashSuffix, hash+HASH_PREFIX_SIZE, HASH_SUFFIX_SIZE);
  19. char *suffixUpper = malloc(HASH_SUFFIX_SIZE + 1);
  20. if (suffixUpper == NULL) {
  21. puts("Couldn't allocate memory for suffix!");
  22. return NULL;
  23. }
  24. for (int i = 0; i < HASH_SUFFIX_SIZE; i++) {
  25. int c = hashSuffix[i];
  26. c = toupper(c);
  27. sprintf(suffixUpper+i, "%c", c);
  28. }
  29. return suffixUpper;
  30. }
  31. void printNumber(const char *data) {
  32. for (int i = 0; data[i] != '\n' && data[i] != 0; i++)
  33. putchar(data[i]);
  34. putchar('\n');
  35. }
  36. int findSuffix(const char *suffix, const char *data) {
  37. for (int i = 0; data[i] != 0; i++) {
  38. int j;
  39. for (j = 0; suffix[j] != 0; j++)
  40. if (data[i+j] != suffix[j])
  41. break;
  42. if (suffix[j] == 0 && data[i+j] == ':') {
  43. printf("This is how many times your password was pwned: ");
  44. printNumber(data+i+j+1);
  45. return 1;
  46. }
  47. }
  48. return 0;
  49. }
  50. void usage(const char *app) {
  51. printf("Usage:\n%s <password>\n", app);
  52. }
  53. int main(int argc, char **argv) {
  54. if (argc < 2) {
  55. usage(argv[0]);
  56. return 1;
  57. }
  58. char *hash = getHash(argv[1]);
  59. if (hash == NULL) {
  60. puts("Couldn't get hash!");
  61. return 1;
  62. }
  63. char *url = getURL(hash);
  64. if (url == NULL) {
  65. puts("Couldn't get URL!");
  66. return 1;
  67. }
  68. char *suffix = getSuffixUppercase(hash);
  69. if (suffix == NULL) {
  70. puts("Couldn't make suffix uppercase!");
  71. return 1;
  72. }
  73. free(hash);
  74. char *data = getData(url);
  75. if (data == NULL) {
  76. puts("Couldn't get data from the API!");
  77. return 1;
  78. }
  79. free(url);
  80. if (!findSuffix(suffix, data)) puts("Password not pwned!");
  81. free(data);
  82. free(suffix);
  83. }