LIVE PORTAL Telegram v11.8 API Synchronized Free Animated Stickers
translate Translated
admin_panel_settings ADMIN CONTROLS Guide #18469 • Beginner Basics

Bot Security & Scraper Defense: Rate Limiting, DDoS & Token Vaults

[Telegram 96] Bot Security & Scraper Defense: Rate Limiting, DDoS & Token Vaults
school TELEGRAM MASTERCLASS • STEP 096 / 100

Step 096: Bot Security & Scraper Defense: Rate Limiting, DDoS & Token Vaults

Step 096 of 100 (96%)

Executive Overview: Public Telegram bots and Mini Apps operate on an adversarial internet surface. Without zero-trust defensive engineering, bots are vulnerable to webhook spoofing, automated database scraping, API token leakage, and malicious command flooding that triggers severe Telegram FLOOD_WAIT penalties. In Telegram 196, we architect an enterprise-grade security perimeter: configuring Telegram CIDR subnet firewalls (149.154.160.0/20 and 91.108.4.0/22), enforcing X-Telegram-Bot-Api-Secret-Token cryptographic authentication, implementing high-concurrency Redis token-bucket sliding-window rate limiters, and establishing zero-plaintext token vault lifecycles with HashiCorp Vault.

CIDR Gate
149.154.160.0/20 & 91.108.4.0/22
X-Secret-Token
Zero-Trust Webhook Auth
30 req/min
Redis Token Bucket
0 FLOOD_WAIT
Exponential Backoff

security 1. Webhook Perimeter Defense: CIDR Whitelisting & Secret Tokens

When running Telegram bots in Webhook mode, your server exposes a public HTTPS endpoint. If an attacker discovers this URL, they can forge JSON payloads (such as fake payments, spoofed admin IDs, or malicious spam messages) directly into your processing queue. You must establish a zero-trust dual-gate perimeter at your reverse proxy (Nginx, Caddy, or Cloudflare):

Gate 1: Network Layer

Telegram CIDR Whitelisting

Telegram webhook servers only originate from two subnet ranges: 149.154.160.0/20 and 91.108.4.0/22. All other inbound traffic to your webhook route must be dropped at layer 4/7 with HTTP 403.

Gate 2: Application Layer

Secret Token Verification

When calling setWebhook, pass a 128-bit random secret_token. Telegram delivers this in the X-Telegram-Bot-Api-Secret-Token header, verified with constant-time string comparison.

nginx_webhook_defense.conf Reverse Proxy Layer
# 1. Telegram Webhook Subnets
geo $is_telegram_ip {
    default 0;
    149.154.160.0/20 1;
    91.108.4.0/22    1;
}

server {
    server_name bot.example.com;

    location /webhook/v1/tg_dispatch {
        # Drop all non-Telegram IPs immediately
        if ($is_telegram_ip = 0) {
            return 403 '{"error": "Forbidden: Non-Telegram Origin"}';
        }

        # Verify X-Telegram-Bot-Api-Secret-Token header
        if ($http_x_telegram_bot_api_secret_token != "e8b49c71a93e8201fba45c67d10e") {
            return 401 '{"error": "Unauthorized: Invalid Secret Token"}';
        }

        proxy_pass http://127.0.0.1:8000;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
    }
}

speed 2. Redis Sliding-Window Token-Bucket Rate Limiter

Telegram enforces global limits per bot (typically 30 messages/sec globally and 1 message/sec per private user). To protect your infrastructure from command floods and scrapers, execute an atomic Lua script inside Redis before processing any command:

rate_limiter.lua Atomic Redis Script
-- KEYS[1]: User rate limit key (e.g. rate:user:123456)
-- ARGV[1]: Max tokens capacity (e.g. 5)
-- ARGV[2]: Refill rate per millisecond (e.g. 0.0005 = 30 tokens/min)
-- ARGV[3]: Current timestamp in milliseconds

local key = KEYS[1]
local capacity = tonumber(ARGV[1])
local refill_rate = tonumber(ARGV[2])
local now = tonumber(ARGV[3])

local data = redis.call('HMGET', key, 'tokens', 'last_updated')
local tokens = tonumber(data[1])
local last_updated = tonumber(data[2])

if not tokens then
    tokens = capacity
    last_updated = now
else
    local delta = math.max(0, now - last_updated)
    tokens = math.min(capacity, tokens + delta * refill_rate)
    last_updated = now
end

if tokens >= 1.0 then
    tokens = tokens - 1.0
    redis.call('HMSET', key, 'tokens', tokens, 'last_updated', last_updated)
    redis.call('PEXPIRE', key, 60000)
    return 1 -- Request Allowed
else
    redis.call('HMSET', key, 'tokens', tokens, 'last_updated', last_updated)
    redis.call('PEXPIRE', key, 60000)
    return 0 -- Rate Limit Exceeded (Drop / 429)
end
Interactive Lab

Bot Security Gate & Token Bucket Simulator

QUARANTINED: 0
Active Token Bucket (User 381014) 5.0 / 5.0 Tokens
[SECURITY GATE] Ready. Select client type and dispatch payload.

help 4. Production Security FAQs & Hardening Tenets

Q1: What should I do if my bot token is accidentally committed to GitHub?

Immediately revoke it via @BotFather using /revoke. GitHub active secret scanning automatically pings Telegram, which often invalidates compromised tokens within minutes. Update your production HashiCorp Vault or AWS Secrets Manager secret, restart the daemon, and rotate your webhook secret token.

Q2: How do I handle Telegram FLOOD_WAIT exceptions gracefully?

When sending messages exceeds Telegram limits, the API responds with HTTP 429 and a parameter retry_after: N. Your task worker (Celery, BullMQ) must catch this exception, pause outbound worker threads for N + 1 seconds, and re-enqueue messages with exponential jitter to avoid herd collisions.

Q3: Are self-signed SSL certificates acceptable for enterprise webhooks?

While Telegram supports uploading custom public key certificates in setWebhook, production systems should always use valid CA-signed TLS 1.3 certificates (Let's Encrypt, Cloudflare) with modern cipher suites to ensure zero-trust integrity and automatic renewal.

Q4: How do honeypot commands mitigate automated bot scrapers?

Automated scrapers systematically iterate through standard admin commands (e.g. /admin, /export_db, /backup). By registering dummy honeypot endpoints that are never linked in public menus, any client invoking them can be automatically fingerprinted and quarantined in Redis for 24 hours.

Q5: Can rate limiting cause dropped payment confirmations?

Never apply rate limits to pre_checkout_query or successful_payment updates. Payments must be processed through an isolated high-priority queue with zero rate limiting to ensure users are never charged without prompt confirmation.

insights Master Summary Blueprint

Step 096 Visual Recap: Bot Security & Defense Perimeter Blueprint

Four-tier zero-trust bot defense: Token Vault dynamic secrets injection, X-Secret-Token cryptographic gateway, atomic Redis sliding-window token-bucket limiter, and edge Telegram CIDR subnet firewall.

Bot Security & Defense Perimeter Visual Blueprint
Continue Curriculum
Next: Step 097 • Enterprise Customer Support Ticketing Bot
Route 1-on-1 private customer inquiries directly into supergroup forum topics with bi-directional media mirroring and SLA tracking.
admin_panel_settings ADMIN Guide #18469 Actions
Enlarged Preview
Click anywhere outside or press ESC to close viewer
smart_display Telegram Video Short
1080p HD
Official Source: @TelegramTips Post #44 Press ESC or click outside to close