pwned.c 1.5 KB

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