Skip to content

Instantly share code, notes, and snippets.

@frafra
Last active May 11, 2018 20:12
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save frafra/a8f7b8162f068f93ddc193d8317e35da to your computer and use it in GitHub Desktop.
Save frafra/a8f7b8162f068f93ddc193d8317e35da to your computer and use it in GitHub Desktop.
Detect fake USB drives
#!/usr/bin/env python3
#
# WARNING: This program will OVERWRITE the entire device and
# you may LOSE DATA. Use it carefully.
# How to create a test block device:
# $ dd if=/dev/zero of=fake bs=1M count=100
# # mknod fake b 7 200
# # losetup /dev/fake fake
import tqdm
import argparse
import os
import random
parser = argparse.ArgumentParser(description="Detect fake USB drives")
parser.add_argument("device",
help="Path to the device (like /dev/fake)")
parser.add_argument("size", default=8, type=int, nargs='?',
help="Block size (in MB)")
args = parser.parse_args()
block_size = args.size*1024**2
def new_chunk(size):
return bytearray(random.getrandbits(8) for _ in range(size))
# Get device size
fd = os.open(args.device, os.O_RDONLY)
size = os.lseek(fd, 0, os.SEEK_END)
os.close(fd)
def chunk_iterator(**kwargs):
return tqdm.trange(int(size/block_size),
unit='block',
**kwargs)
state = random.getstate()
with open(args.device, 'wb') as device:
for test in chunk_iterator(desc='Writing'):
device.write(new_chunk(block_size))
random.setstate(state)
with open(args.device, 'rb') as device:
for test in chunk_iterator(desc='Reading'):
if new_chunk(block_size) != device.read(block_size):
print("Fake device found!")
break
else:
print("Device seems legit.")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment