Receber por email
← Voltar para o catálogo

telegram-bot-security-analysis

Reverse engineer and security-test Telegram bots — API analysis, callback interception, exploit discovery, and vulnerability documentation

10estrelas
Atualizado há 5 meses

Ver no GitHub ↗ Licença: MIT

Como adicionar

/plugin marketplace add kevinnft/ai-agent-skills

O comando exato pode variar conforme o repositório. Confira o README no GitHub.

Para o autor da skill

Cole no README do seu repo

Mostra que sua skill está catalogada na Skillteca, gera backlink e tráfego rastreável.

[![Skillteca](https://www.skillteca.com.br/api/badge/telegram-bot-security-analysis/svg)](https://www.skillteca.com.br/skills/telegram-bot-security-analysis)

Skills relacionadas

Ver todas de Segurança →

Alerta por categoria

Receba novas skills de Segurança toda segunda

1 email curto, só com as skills novas de Segurança. 4 minutos de leitura, sem spam, cancela com 1 clique.

Você confirma o email no primeiro envio. Sem spam. Cancela com 1 clique.

Ler descrição completa

Telegram Bot Security Analysis

Comprehensive methodology for analyzing Telegram bots to discover security vulnerabilities, reverse engineer backend systems, and document exploits.

Core Workflow

1. Initial Reconnaissance

Login and Access:

from telethon import TelegramClient

API_ID = 94575  # Public Telegram API credentials
API_HASH = 'a3406de8d171bb422bb6ddf3bbd800e2'

client = TelegramClient('session_name', API_ID, API_HASH)
await client.start()

Bot Information Gathering:

  • Bot ID and access hash
  • Available commands
  • Button callback data
  • Web app URLs
  • Inline query support

Command Discovery:

commands = [
    '/help', '/menu', '/balance', '/wallet', '/deposit', 
    '/withdraw', '/profile', '/settings', '/admin', '/debug'
]

for cmd in commands:
    await client.send_message(bot, cmd)
    await asyncio.sleep(1)

Conversation Dump:

all_msgs = await client.get_messages(bot, limit=200)

conversation = []
for msg in reversed(all_msgs):
    if msg.text:
        sender = "BOT" if msg.from_id == bot.id else "USER"
        conversation.append({
            "sender": sender,
            "time": msg.date.strftime('%Y-%m-%d %H:%M:%S'),
            "text": msg.text,
            "buttons": [[btn.text for btn in row] for row in msg.buttons] if msg.buttons else None
        })

2. Deep API Analysis

Intercept Callback Data:

from telethon.tl.functions.messages import GetBotCallbackAnswerRequest

# Get button callback data
for button in msg.reply_markup.rows:
    if hasattr(button, 'data'):
        callback_data = button.data.decode('utf-8', errors='ignore')
        print(f"Callback: {callback_data}")

Extract Web App URLs:

# Check for magic links, payment URLs, admin panels
for button in msg.buttons:
    if hasattr(button, 'button') and hasattr(button.button, 'url'):
        url = button.button.url
        if 'magic' in url or 'admin' in url or 'api' in url:
            print(f"Suspicious URL: {url}")

3. Backend Discovery

Common Patterns:

  • Magic links: /magic/go/{timestamp}/{user_id}
  • API endpoints: /api/v1/..., /webhook/...
  • Admin panels: /admin, /debug, /dashboard

Server Fingerprinting:

curl -I http://target-ip:port/
# Look for: Server header, framework version, error messages

Endpoint Fuzzing:

# Common API paths
/api /api/v1 /api/wallet /api/balance /api/deposit
/admin /debug /magic /webhook /callback

4. Exploit Discovery

Common Vulnerability Classes:

  1. Premature Reward Distribution
  2. Reward given before full verification
  3. No rollback mechanism
  4. Missing state validation
  1. 2FA/Authentication Bypass
  2. Temporary 2FA setup → get reward → disable 2FA
  3. No continuous verification
  4. App password validation gaps
  1. Race Conditions
  2. Rapid button clicking
  3. Concurrent requests
  4. State synchronization issues
  1. Payment Approval Manipulation
  2. Webhook triggers on payment approval
  3. No completion verification
  4. Abandoned registration still rewards
  1. Referral/Reward Gaming
  2. Self-referral loops
  3. Multiple account exploitation
  4. Reward duplication

5. Exploit Documentation

Structure:

## Vulnerability Summary
- Type: [Premature Reward / Auth Bypass / Race Condition]
- Severity: [Low / Medium / High / Critical]
- Impact: [Financial loss / Data breach / Account takeover]

## Exploit Steps
1. Step-by-step reproduction
2. Required prerequisites
3. Expected outcome

## Technical Details
- Root cause analysis
- Code snippets (if available)
- Attack flow diagram

## Mitigation
- Recommended fixes
- Code patches
- Security best practices

Tools and Techniques

Telethon API Methods

Message Inspection:

# Get conversation history
msgs = await client.get_messages(bot, limit=100)

# Filter for specific content
for msg in msgs:
    if msg.buttons:
        # Analyze button structure
    if msg.text and 'reward' in msg.text.lower():
        # Flag reward-related messages

Callback Testing:

# Test crafted callback data
test_payloads = [
    b'admin', b'debug', b'wallet', b'claim',
    b'{"action":"deposit","amount":9999}',
]

for payload in test_payloads:
    try:
        result = await client(GetBotCallbackAnswerRequest(
            peer=bot, msg_id=msg.id, data=payload
        ))
        if result.message:
            print(f"Payload {payload} → {result.message}")
    except Exception as e:
        print(f"Payload {payload} → Error: {e}")

Web API Security Testing

For testing backend APIs discovered during bot analysis:

Validation Testing

Test cases:

TEST_CASES = [
    # Negative values
    {"amount": -1, "price": 10},
    
    # Zero values
    {"amount": 0, "price": 10},
    
    # Float where integer expected
    {"amount": 0.1, "price": 10},
    
    # Very large numbers (integer overflow)
    {"amount": 2**63, "price": 10},
    
    # SQL injection
    {"amount": "1 OR 1=1", "price": 10},
    {"amount": "1'; DROP TABLE users--", "price": 10},
    
    # XSS injection
    {"amount": "<script>alert(1)</script>", "price": 10},
    
    # Null/undefined
    {"amount": None, "price": 10},
    
    # Type confusion
    {"amount": "1", "price": "10"},  # String instead of number
    {"amount": [1], "price": 10},    # Array instead of number
]

Race Condition Testing

import concurrent.futures

def send_request():
    return requests.post(
        "https://target.com/api/endpoint",
        headers=headers,
        json={"amount": 1, "price": 10},
        timeout=30
    )

# Send 5 simultaneous requests
with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    futures = [executor.submit(send_request) for _ in range(5)]
    results = [f.result() for f in concurrent.futures.as_completed(futures)]

success_count = sum(1 for r in results if r.status_code in (200, 201))

if success_count > 1:
    print(f"🚨 RACE CONDITION! {success_count} requests succeeded")

Authentication Testing

# Test 1: Expired token
headers = {"Authorization": "Bearer EXPIRED_TOKEN"}
resp = requests.get("https://target.com/api/me", headers=headers)
# Expected: 401 Unauthorized

# Test 2: Invalid token
headers = {"Authorization": "Bearer INVALID_TOKEN"}
resp = requests.get("https://target.com/api/me", headers=headers)
# Expected: 401 Unauthorized

# Test 3: Token from different user
headers = {"Authorization": "Bearer USER_A_TOKEN"}
resp = requests.get("https://target.com/api/users/USER_B_ID", headers=headers)
# Expected: 403 Forbidden

Common Vulnerabilities

  1. Insufficient Input Validation — API accepts invalid data (negative numbers, SQL injection)
  2. Race Conditions — Multiple requests succeed when only one should
  3. Broken Authentication — Can access resources without valid token
  4. Broken Authorization — Can access other users' resources
  5. Business Logic Flaws — Can perform actions that violate business rules

See references/web-api-security-patterns.md for comprehensive testing methodology.

Backend Server Analysis

Flask/Werkzeug Detection:

# Check for debug mode
curl http://target/console
curl http://target/_debug_toolbar

# Common Flask paths
curl http://target/static/
curl http://target/admin/

API Endpoint Discovery:

import requests

base_url = "http://target:port"
endpoints = [
    "/api/status", "/api/health", "/api/version",
    "/api/users", "/api/balance", "/api/transactions"
]

for endpoint in endpoints:
    r = requests.get(f"{base_url}{endpoint}")
    if r.status_code != 404:
        print(f"Found: {endpoint} → {r.status_code}")

Real-World Example: GmailMiner Bot

Vulnerability: 2FA Temporary Setup Exploit

Flow:

  1. Submit existing Gmail with wrong password
  2. Bot requests 2FA verification
  3. User enables 2FA on Google account
Compartilhar X LinkedIn