Skip to content

Instantly share code, notes, and snippets.

@Sasszem
Created May 15, 2021 15:14
Show Gist options
  • Save Sasszem/7a721c27771e1bf46a8cf10493919019 to your computer and use it in GitHub Desktop.
Save Sasszem/7a721c27771e1bf46a8cf10493919019 to your computer and use it in GitHub Desktop.
Like strings, but also searches (and bruteforces) single-byte XOR. Might be useful for CTFs. Uses click!
#!/bin/env python3
"""
import subprocess
def strings(data):
process = subprocess.Popen(["strings"], stdin=subprocess.PIPE,stdout=subprocess.PIPE)
print("Created process")
process.stdin.write(data)
process.stdin.close()
process.wait()
out = process.stdout.read().decode()
return [x for x in out.split("\n") if x]
"""
import string
PRINTABLE_CODES = [ord(s) for s in string.printable]
def strings(data, min_len, progress = False, require_termination = False):
results = []
current = ""
for ofset in (tqdm.tqdm if progress else lambda x: x)(range(len(data))):
b = data[ofset]
if not b in PRINTABLE_CODES:
if not require_termination or b==0:
if len(current)>=min_len:
results.append([ofset-len(current), current])
current = ""
else:
current += chr(b)
return results
def xor_decode(data, key):
return bytes(d^key for d in data)
import click
import tqdm
@click.group()
def app():
pass
@app.command()
@click.argument("filename")
def normal(**kwargs):
with open(kwargs["filename"], "rb") as f:
for l in strings(f.read()):
print(l)
@app.command()
@click.argument("filename")
@click.argument("XORKEY")
@click.option("--progress", is_flag = True)
@click.option("--min-len", type=int, default = 2)
def xor_known(filename, xorkey, min_len, progress = False):
xorkey = int(xorkey[2:], 16) if xorkey[:2].lower()=="0x" else int(xorkey)
with open(filename, "rb") as f:
data = xor_decode(f.read(), xorkey)
for l in strings(data, min_len, progress):
print(l)
@app.command()
@click.argument("filename")
@click.argument("pattern")
def xor_unknown(filename, pattern):
print("Starting")
with open(filename, "rb") as f:
data_raw = f.read()
print(f"Read {len(data_raw)} bytes!")
results = []
for xorkey in tqdm.tqdm(range(256)):
data = xor_decode(data_raw, xorkey)
if pattern.encode() in data:
results.append(xorkey)
print(results)
if __name__=="__main__":
app()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment