Skip to content

Instantly share code, notes, and snippets.

@yarienkiva
Created February 26, 2024 17:31
Show Gist options
  • Select an option

  • Save yarienkiva/017d29ec3c060f07415ee1607bfef1e4 to your computer and use it in GitHub Desktop.

Select an option

Save yarienkiva/017d29ec3c060f07415ee1607bfef1e4 to your computer and use it in GitHub Desktop.
Extract telegram chad_id and bot_token from web requests using MitM (with Fiddler). Future version will probably use Drakvuf instead of VBox.
from tqdm import tqdm
import subprocess
import logging
import email
import time
logging.basicConfig(level=logging.INFO)
VM_USERNAME = "..."
VM_PASSWORD = "..."
VM_NAME = "..."
TIMEOUT = 30 # seconds
"""
import System;
import System.IO;
import System.Windows.Forms;
import Fiddler;
import Fiddler.WebFormats
var filePath = "C:\\Temp\\rizz-{0}.log";
class Handlers {
static function OnBeforeRequest(oSession: Session) {
if ((oSession.fullUrl.StartsWith("https://api.telegram.org/bot")
|| oSession.fullUrl.StartsWith("https://discord.com/api/webhooks/"))
&& oSession.RequestMethod == "POST") {
try {
oSession.SaveSession(String.Format(filePath, Guid.NewGuid()), false);
oSession.oRequest.FailSession(404, "Blocked", "Woops, can't leak that ;)");
} catch (ex) {
FiddlerApplication.Log.LogString("Error logging request: " + ex.Message);
}
}
}
}
"""
def VM_guestcontrol(command: list) -> bytes:
"""
Executes `vboxmanager guestcontrol $VM_NAME --username $VM_USERNAME --password $VM_PASSWORD $command`
"""
return subprocess.check_output(
[
"vboxmanage",
"guestcontrol",
VM_NAME,
"--username",
VM_USERNAME,
"--password",
VM_PASSWORD,
]
+ command,
)
def VM_exec(command: str) -> bytes:
"""
Executes `vboxmanager guestcontrol $VM_NAME --username $VM_USERNAME --password $VM_PASSWORD \
run -- $exe $command`
"""
return VM_guestcontrol(["run", "--", "cmd.exe", "/c", command])
def get_chat_id(raw_req: bytes) -> str:
"""
Extract chat id from the raw http request's form
"""
for part in email.message_from_bytes(
raw_req.split(b"\r\n", maxsplit=1)[1]
).get_payload():
if part.get_param("name", header="content-disposition") == "chat_id":
return part.get_payload()
def get_bot_token(raw_req: bytes) -> str:
"""
Extract bot token from the raw http request's url
"""
return raw_req.split(b"\r\n", maxsplit=1)[0].split(b"/")[3].decode()
def extract(file: str) -> dict:
logging.debug(f"Starting {VM_NAME}")
subprocess.run(["vboxmanage", "startvm", VM_NAME])
# copy sample to vm
logging.debug(f"Copying {file} to C:\\Users\\{VM_USERNAME}\\AppData\\Roaming\\sample.exe")
VM_guestcontrol(["copyto", file, f"C:\\Users\\{VM_USERNAME}\\AppData\\Roaming\\sample.exe"])
logging.debug(f"Starting sample.exe")
VM_exec(f"start C:\\Users\\{VM_USERNAME}\\AppData\\Roaming\\sample.exe")
for _ in tqdm(range(TIMEOUT)):
time.sleep(1)
# read log files to extract `chat_id`s and `bot_token`s
configs = []
try:
log_files = VM_exec("dir /B C:\\Temp\\rizz*.log")
for log in log_files.decode().splitlines():
raw_req = VM_exec("type C:\\Temp\\" + log)
config = (get_chat_id(raw_req), get_bot_token(raw_req))
if not all(config):
continue
configs.append(config)
if len(set(configs)) > 1:
logging.warning(f"Multiple configs extracted: {set(configs)}")
except:
pass
logging.debug(f"Resetting VM state")
subprocess.run(["vboxmanage", "controlvm", VM_NAME, "poweroff"])
subprocess.run(["vboxmanage", "snapshot", VM_NAME, "restorecurrent"])
if configs:
config = max(set(configs), key=configs.count)
return {"chat_id": config[0], "bot_token": config[1]}
if __name__ == "__main__":
import sys, os, json
files = sys.argv[1:]
if not sys.stdin.isatty():
files += [f.strip() for f in sys.stdin]
if not files:
print("Usage:\n Files : ARGV + STDIN\n Config: STDOUT")
exit(1)
for file in files:
file = os.path.abspath(os.path.expanduser(os.path.expandvars(file)))
try:
print("Processing,", file, file=sys.stderr)
if not (c := extract(file)):
raise Exception("it's likely not an interesting sample")
print(json.dumps(c))
except Exception as e:
print("Failed to extract from", file, "because", e, file=sys.stderr)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment