binary.c 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. /*
  2. * binary.c -- handles:
  3. * misc update functions
  4. * md5 hash verifying
  5. *
  6. */
  7. #include "common.h"
  8. #include "binary.h"
  9. #include "crypt.h"
  10. #include "shell.h"
  11. #include "main.h"
  12. #include "salt.h"
  13. #include "misc_file.h"
  14. encdata_t encdata = {
  15. "AAAAAAAAAAAAAAAA",
  16. ""
  17. };
  18. char *
  19. bin_md5(const char *fname, int todo)
  20. {
  21. static char hash[MD5_HASH_LENGTH + 1] = "";
  22. unsigned char md5out[MD5_HASH_LENGTH + 1] = "";
  23. char *buf = NULL, *p = NULL, *fname_bak = NULL;
  24. FILE *f = NULL;
  25. size_t size = 0, size_p = 0;
  26. MD5_CTX ctx;
  27. if (!(f = fopen(fname, "rb")))
  28. werr(ERR_BINSTAT);
  29. MD5_Init(&ctx);
  30. size = strlen(fname) + 2;
  31. fname_bak = calloc(1, size);
  32. egg_snprintf(fname_bak, size, "%s~", fname);
  33. size = 0;
  34. fseek(f, 0, SEEK_END);
  35. size = ftell(f);
  36. fseek(f, 0, SEEK_SET);
  37. buf = calloc(1, size + 1);
  38. if (fread(buf, 1, size, f) != size)
  39. fatal("Can't read binary", 0);
  40. p = buf;
  41. while (p < (buf + size - 4)) {
  42. if (!strncmp(p, STR("AAAAAAAA"), 8)) /* this STR() is *REQUIRED* */
  43. break;
  44. p += 4;
  45. size_p += 4;
  46. }
  47. if (p >= (buf + size - 4))
  48. fatal("Shit out of luck brotha", 0);
  49. p += 16;
  50. size_p += 16;
  51. /* now we have 512 for data :D */
  52. MD5_Update(&ctx, buf, size_p);
  53. MD5_Final(md5out, &ctx);
  54. strncpyz(hash, btoh(md5out, MD5_DIGEST_LENGTH), sizeof(hash));
  55. OPENSSL_cleanse(&ctx, sizeof(ctx));
  56. if (todo == WRITE_MD5) {
  57. char *enc_hash = NULL;
  58. enc_hash = encrypt_string(SALT1, hash);
  59. strncpyz(p, enc_hash, strlen(enc_hash) + 1);
  60. size += strlen(enc_hash);
  61. free(enc_hash);
  62. fclose(f);
  63. movefile(fname, fname_bak);
  64. if (!(f = fopen(fname, "wb"))) {
  65. movefile(fname_bak, fname);
  66. werr(ERR_BINSTAT);
  67. }
  68. if (fwrite(buf, 1, size, f) != size) {
  69. movefile(fname_bak, fname);
  70. fatal("Failed to re-write binary", 0);
  71. }
  72. fclose(f);
  73. fixmod(fname);
  74. unlink(fname_bak);
  75. }
  76. free(buf);
  77. return hash;
  78. }