JerryCoder commited on
Commit
fe1d6aa
·
verified ·
1 Parent(s): 599ff3c

Update bot.py

Browse files
Files changed (1) hide show
  1. bot.py +33 -60
bot.py CHANGED
@@ -5,7 +5,6 @@ import base64
5
  import uuid
6
  import tempfile
7
  import shutil
8
- import subprocess
9
  from pathlib import Path
10
  from fastapi import FastAPI, UploadFile, File
11
  import aiohttp
@@ -13,85 +12,59 @@ import uvicorn
13
 
14
  app = FastAPI()
15
 
 
 
16
  # -------------------------------
17
- # 🔐 Custom C-Based Python File Encoder
18
  # -------------------------------
19
 
20
- C_TEMPLATE = """/*KEY_BYTES*/""" # Replace with your actual C template
21
- SETUP_PY = """# Your setup.py content""" # Replace with actual setup.py
22
-
23
  def make_zip_bytes(filename: str, content: bytes) -> bytes:
24
  bio = io.BytesIO()
25
  with zipfile.ZipFile(bio, "w", compression=zipfile.ZIP_DEFLATED) as zf:
26
  zf.writestr(filename, content)
27
  return bio.getvalue()
28
 
29
- def rand_bytes(n):
30
  return os.urandom(n)
31
 
32
- def compile_c_extension(build_dir: Path):
33
- (build_dir/"setup.py").write_text(SETUP_PY)
34
- proc = subprocess.run([os.sys.executable,"setup.py","build_ext","--inplace"],
35
- cwd=str(build_dir), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=30)
36
- candidates = list(build_dir.glob("aes_helper*.so")) + list(build_dir.glob("build/lib.*/*.so"))
37
- if not candidates:
38
- raise RuntimeError("Compile fail:\n"+proc.stdout.decode())
39
- return candidates[0]
40
-
41
- def build_wrapper(cipher_b64, so_b64, so_filename):
42
- wrapper = f"""# Auto Encrypted by JerryCoder C Encryptor
43
- import base64,zipfile,io,tempfile,os,runpy
44
- O = base64.b64decode('{cipher_b64}')
45
- M = base64.b64decode('{so_b64}')
 
46
  tmpdir = tempfile.mkdtemp()
47
- so_path = os.path.join(tmpdir,'{so_filename}')
48
- with open(so_path,'wb') as f: f.write(M)
49
- import importlib.machinery as L, importlib.util as U
50
- loader = L.ExtensionFileLoader('aes_helper',so_path)
51
- spec = U.spec_from_loader(loader.name,loader)
52
- mod = U.module_from_spec(spec)
53
- loader.exec_module(mod)
54
- try:
55
- z = mod.decrypt(O)
56
- extract_dir = tempfile.mkdtemp()
57
- zipfile.ZipFile(io.BytesIO(z)).extractall(extract_dir)
58
- py_file = [f for f in os.listdir(extract_dir) if f.endswith('.py')][0]
59
- runpy.run_path(os.path.join(extract_dir, py_file))
60
- except Exception as e:
61
- print('decrypt_error', e)
62
- finally:
63
- os.remove(so_path)
64
  """
65
  return wrapper.encode()
66
 
67
  def encode_bytes(file_bytes: bytes, filename: str):
68
- tmpdir = Path(tempfile.mkdtemp())
69
- try:
70
- # Save original .py
71
- input_path = tmpdir/filename
72
- input_path.write_bytes(file_bytes)
73
- zipped = make_zip_bytes(filename, file_bytes)
74
- key = rand_bytes(32)
75
- iv = rand_bytes(16)
76
- (tmpdir/"aes_helper.c").write_text(C_TEMPLATE.replace("/*KEY_BYTES*/", ",".join(str(x) for x in key)))
77
- so_path = compile_c_extension(tmpdir)
78
- so_b64 = base64.b64encode(so_path.read_bytes()).decode()
79
- cipher_b64 = base64.b64encode(zipped).decode() # Optionally replace with mod.encrypt(zipped)
80
- wrapper_name = f"{os.path.splitext(filename)[0]}_{uuid.uuid4().hex}_enc.py"
81
- wrapper_bytes = build_wrapper(cipher_b64, so_b64, so_path.name)
82
- return wrapper_bytes, wrapper_name
83
- finally:
84
- shutil.rmtree(tmpdir, ignore_errors=True)
85
-
86
- MAX_FILE_SIZE = 5*1024*1024 # 5 MB limit
87
 
88
  # -------------------------------
89
  # POST /api/encode
90
  # -------------------------------
91
  @app.post("/api/encode")
92
  async def encode_post(file: UploadFile = File(...)):
93
- filename = file.filename
94
- if not filename.endswith(".py"):
95
  return {"ok": False, "error": "Only Python (.py) files are allowed"}
96
 
97
  try:
@@ -99,8 +72,7 @@ async def encode_post(file: UploadFile = File(...)):
99
  if len(file_bytes) > MAX_FILE_SIZE:
100
  return {"ok": False, "error": "File too large (max 5MB)"}
101
 
102
- wrapper_bytes, wrapper_name = encode_bytes(file_bytes, filename)
103
-
104
  tmp_path = os.path.join(tempfile.gettempdir(), wrapper_name)
105
  with open(tmp_path, "wb") as f:
106
  f.write(wrapper_bytes)
@@ -132,6 +104,7 @@ async def encode_get(url: str, filename: str = "file.py"):
132
  if resp.status != 200:
133
  return {"ok": False, "error": f"Failed to fetch file ({resp.status})"}
134
  file_bytes = await resp.read()
 
135
  wrapper_bytes, wrapper_name = encode_bytes(file_bytes, filename)
136
  tmp_path = os.path.join(tempfile.gettempdir(), wrapper_name)
137
  with open(tmp_path, "wb") as f:
 
5
  import uuid
6
  import tempfile
7
  import shutil
 
8
  from pathlib import Path
9
  from fastapi import FastAPI, UploadFile, File
10
  import aiohttp
 
12
 
13
  app = FastAPI()
14
 
15
+ MAX_FILE_SIZE = 5*1024*1024 # 5 MB
16
+
17
  # -------------------------------
18
+ # 🔐 Pure Python Encryptor
19
  # -------------------------------
20
 
 
 
 
21
  def make_zip_bytes(filename: str, content: bytes) -> bytes:
22
  bio = io.BytesIO()
23
  with zipfile.ZipFile(bio, "w", compression=zipfile.ZIP_DEFLATED) as zf:
24
  zf.writestr(filename, content)
25
  return bio.getvalue()
26
 
27
+ def rand_bytes(n: int) -> bytes:
28
  return os.urandom(n)
29
 
30
+ def xor_bytes(data: bytes, key: bytes) -> bytes:
31
+ return bytes([b ^ key[i % len(key)] for i, b in enumerate(data)])
32
+
33
+ def generate_junk_data(min_kb=50, max_kb=70):
34
+ junk_size = int.from_bytes(rand_bytes(2), 'big') % ((max_kb-min_kb)*1024) + min_kb*1024
35
+ chars = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_()-./,;:!?"
36
+ return bytes([chars[b % len(chars)] for b in rand_bytes(junk_size)])
37
+
38
+ def build_wrapper(enc_b64: str, key_b64: str):
39
+ junk = generate_junk_data()
40
+ wrapper = f"""# Auto Encrypted by JerryCoder Python Encryptor
41
+ import base64, zipfile, io, tempfile, os, runpy
42
+ D = base64.b64decode('{enc_b64}')
43
+ K = base64.b64decode('{key_b64}')
44
+ O = bytes([b ^ K[i % len(K)] for i, b in enumerate(D)])
45
  tmpdir = tempfile.mkdtemp()
46
+ zipfile.ZipFile(io.BytesIO(O)).extractall(tmpdir)
47
+ py_file = [f for f in os.listdir(tmpdir) if f.endswith('.py')][0]
48
+ runpy.run_path(os.path.join(tmpdir, py_file))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  """
50
  return wrapper.encode()
51
 
52
  def encode_bytes(file_bytes: bytes, filename: str):
53
+ zipped = make_zip_bytes(filename, file_bytes)
54
+ key = rand_bytes(16)
55
+ enc = xor_bytes(zipped, key)
56
+ enc_b64 = base64.b64encode(enc).decode()
57
+ key_b64 = base64.b64encode(key).decode()
58
+ wrapper_bytes = build_wrapper(enc_b64, key_b64)
59
+ wrapper_name = f"{os.path.splitext(filename)[0]}_{uuid.uuid4().hex}_enc.py"
60
+ return wrapper_bytes, wrapper_name
 
 
 
 
 
 
 
 
 
 
 
61
 
62
  # -------------------------------
63
  # POST /api/encode
64
  # -------------------------------
65
  @app.post("/api/encode")
66
  async def encode_post(file: UploadFile = File(...)):
67
+ if not file.filename.endswith(".py"):
 
68
  return {"ok": False, "error": "Only Python (.py) files are allowed"}
69
 
70
  try:
 
72
  if len(file_bytes) > MAX_FILE_SIZE:
73
  return {"ok": False, "error": "File too large (max 5MB)"}
74
 
75
+ wrapper_bytes, wrapper_name = encode_bytes(file_bytes, file.filename)
 
76
  tmp_path = os.path.join(tempfile.gettempdir(), wrapper_name)
77
  with open(tmp_path, "wb") as f:
78
  f.write(wrapper_bytes)
 
104
  if resp.status != 200:
105
  return {"ok": False, "error": f"Failed to fetch file ({resp.status})"}
106
  file_bytes = await resp.read()
107
+
108
  wrapper_bytes, wrapper_name = encode_bytes(file_bytes, filename)
109
  tmp_path = os.path.join(tempfile.gettempdir(), wrapper_name)
110
  with open(tmp_path, "wb") as f: