Advertisement
Gfy

bitflip.py WIP, old and not tested

Gfy
Jan 3rd, 2016
141
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.26 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # -*- coding: utf-8 -*-
  3.  
  4. # This program is free software: you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation, either version 3 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program. If not, see <http://www.gnu.org/licenses/>
  16.  
  17. """Flip a single bit of a file and check the CRC of the file
  18. until a match is found."""
  19.  
  20. import sys
  21. import optparse
  22. import zlib
  23.  
  24. def main(options, args):
  25. file_name = args[0]
  26. crc32 = int(args[1], 16)
  27.  
  28. # read complete file into memory
  29. with open(file_name, 'rb') as volume:
  30. data = volume.read()
  31. start = 0
  32. end = len(data)
  33. print("File size: %d" % end)
  34. print("CRC32: %0.X" % crc32)
  35.  
  36. # naive way and flipping it all
  37. for cur_byte in range(start, end + 1):
  38. if cur_byte % 10 == 0:
  39. print(cur_byte)
  40.  
  41. # calculate crc32
  42. first_crc = zlib.crc32(data[start:cur_byte])
  43. # 8 bit flips for each byte
  44. cur_byte_data = ord(data[cur_byte])
  45. for i in range(8):
  46. flip = chr(cur_byte_data ^ (0x80 >> i))
  47. test_crc = zlib.crc32(flip + data[cur_byte+1:end], first_crc)
  48.  
  49. if test_crc == crc32:
  50. print("Found in %d!" % cur_byte)
  51. print("Bit %d" % i)
  52.  
  53. # write out good file
  54. with open(file_name + ".bin", 'wb') as result:
  55. result.write(data[start:cur_byte])
  56. result.write(flip)
  57. result.write(data[cur_byte+1:end])
  58. break
  59. else:
  60. continue # executed if the loop ended normally (no break)
  61. break # executed if 'continue' was skipped (break)
  62.  
  63. if __name__ == '__main__':
  64. parser = optparse.OptionParser(
  65. usage="Usage: %prog file_name CRC32\n"
  66. "This tool will flip each bit and stops when a CRC match is found.\n",
  67. version="%prog 0.1 (2014-10-07)") # --help, --version
  68.  
  69. # no arguments given
  70. if len(sys.argv) < 2:
  71. print(parser.format_help())
  72. else:
  73. (options, args) = parser.parse_args()
  74. main(options, args)
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement