Securing Telegram Bot Webhooks on Linux Servers

Securing Telegram Bot Webhooks on Linux Servers

What You’ll Need

  • A Linux VPS such as a Hetzner VPS or Contabo VPS running Ubuntu 22.04 or Ubuntu 24.04 LTS (a DigitalOcean droplet works equally well).
  • A domain name registered via Namecheap with an A record pointing directly to your server IPv4 address.
  • Sudo root permissions on your Linux server.
  • Python 3.10 or newer installed on the server.
  • An official Bot Token provided by Telegram’s @BotFather.

Table of Contents

Understanding Telegram Webhook Security Threats

When building Telegram bots, developers choose between long polling and webhooks. Long polling pulls updates from Telegram servers on a continuous loop, while webhooks allow Telegram to push updates to your server HTTP endpoint instantly. Webhooks offer better execution latency and consume fewer network resources, but they expose a public port on your server.

Exposing an unauthenticated API endpoint on the open internet introduces distinct security vectors:

  1. Request Spoofing: Malicious bots scanning IPv4 address space can send forged JSON payloads to your endpoint, triggering unauthorized bot actions or database writes.
  2. Man In The Middle Interception: Transmitting bot updates over HTTP without SSL/TLS encrypting allows network intermediaries to intercept sensitive chat metadata.
  3. Resource Exhaustion: Attacking your application with arbitrary POST requests can exhaust your application execution pool and bring down your server.

Securing your Telegram webhook requires a defense in depth strategy. You must enforce TLS encryption, restrict inbound traffic exclusively to official Telegram IP subnets at the web server layer, validate secret payload headers inside your application code, and run your application process under an isolated Linux service wrapper. Similar to when we discussed Deploying Self-Hosted PocketBase Backend on Ubuntu, isolating application runtimes behind a hardened Nginx reverse proxy ensures your backend service is protected against direct internet exposure.

Configuring Nginx Reverse Proxy with SSL and IP Whitelisting

The first line of defense is your web server. We will use Nginx to terminate TLS encryption and filter incoming traffic. Telegram publishes its public IP ranges specifically so server administrators can drop non-Telegram traffic prior to hitting backend application servers.

Telegram uses two primary IPv4 ranges for webhook delivery:

  • 149.154.160.0/20
  • 91.108.4.0/22

First, spin up an instance on a Hetzner VPS or Contabo VPS and install Nginx alongside Certbot to obtain valid SSL certificates.

sudo apt update
sudo apt install -y nginx certbot python3-certbot-nginx

Next, acquire your TLS certificate using Certbot. Replace bot.yourdomain.com with the domain name registered through Namecheap.

sudo certbot certonly --nginx -d bot.yourdomain.com --non-interactive --agree-tos -m admin@yourdomain.com

Now create a customized Nginx virtual host configuration file at /etc/nginx/sites-available/telegram-bot.conf. This configuration block restricts incoming access exclusively to Telegram IP ranges and forwards the secret token header to our backend service running locally on port 8000.

server {
    listen 80;
    listen [::]:80;
    server_name bot.yourdomain.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    server_name bot.yourdomain.com;

    ssl_certificate /etc/letsencrypt/live/bot.yourdomain.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/bot.yourdomain.com/privkey.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers HIGH:!aNULL:!MD5;
    ssl_prefer_server_ciphers on;

    # Telegram API Subnet Restrictions
    allow 149.154.160.0/20;
    allow 91.108.4.0/22;
    deny all;

    client_max_body_size 2M;

    location /telegram-webhook {
        proxy_pass http://127.0.0.1:8000/webhook;
        proxy_http_version 1.1;
        
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;
        proxy_set_header X-Telegram-Bot-Api-Secret-Token $http_x_telegram_bot_api_secret_token;

        proxy_connect_timeout 5s;
        proxy_read_timeout 10s;
        proxy_send_timeout 10s;
    }
}

Enable the site configuration and remove the default Nginx configuration link:

sudo ln -s /etc/nginx/sites-available/telegram-bot.conf /etc/nginx/sites-enabled/
sudo rm -f /etc/nginx/sites-enabled/default
sudo nginx -t
sudo systemctl restart nginx

💡 Fast-Track Your Project: Don’t want to configure this yourself? I build custom n8n pipelines and bots. Message me with code SYS3-HUGO.

Implementing Secret Token Verification in Python FastAPI

Even with IP whitelisting in place, spoofed requests could originate from compromised shared infrastructure within those IP ranges. Telegram provides an additional authentication mechanism: the secret token parameter (secret_token). When registering your webhook, you define an arbitrary string. Telegram sends this string in the X-Telegram-Bot-Api-Secret-Token HTTP header with every update payload.

We will build an asynchronous FastAPI web application that validates this header before parsing the request payload.

First, create a dedicated directory and virtual environment:

sudo mkdir -p /opt/telegram-bot
sudo chown -R $USER:$USER /opt/telegram-bot
cd /opt/telegram-bot
python3 -m venv venv
source venv/bin/activate
pip install fastapi uvicorn pydantic

Create the full Python script at /opt/telegram-bot/main.py:

import os
import sys
import uvicorn
from fastapi import FastAPI, Request, HTTPException, Header, status

app = FastAPI(title="Production Telegram Webhook Handler")

EXPECTED_SECRET_TOKEN = os.getenv("TELEGRAM_SECRET_TOKEN", "7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c")

@app.post("/webhook")
async def handle_telegram_webhook(
    request: Request,
    x_telegram_bot_api_secret_token: str | None = Header(default=None)
):
    if x_telegram_bot_api_secret_token != EXPECTED_SECRET_TOKEN:
        raise HTTPException(
            status_code=status.HTTP_403_FORBIDDEN,
            detail="Forbidden: Invalid or missing secret token header."
        )

    try:
        payload = await request.json()
    except Exception:
        raise HTTPException(
            status_code=status.HTTP_400_BAD_REQUEST,
            detail="Bad Request: Invalid JSON body."
        )

    if "message" in payload:
        chat_id = payload["message"]["chat"]["id"]
        text = payload["message"].get("text", "")
        sender = payload["message"].get("from", {}).get("username", "Unknown")
        print(f"Verified webhook processed for Chat ID {chat_id} from @{sender}: {text}", flush=True)

    return {"status": "success", "detail": "Update processed"}

if __name__ == "__main__":
    uvicorn.run("main:app", host="127.0.0.1", port=8000, workers=1)

This application explicitly requires the incoming HTTP header to match our server secret token. If an attacker bypasses the web server layer, the application immediately drops the payload returning an HTTP 403 status code.

Managing Systemd Services and Firewall Rules

To ensure your webhook endpoint stays online after server reboots, run your application as a managed Systemd daemon under a non-root system account.

Create a restricted system user for your bot service:

sudo useradd -r -s /bin/false www-bot
sudo chown -R www-bot:www-bot /opt/telegram-bot

Next, create the systemd unit file at /etc/systemd/system/telegram-bot.service:

[Unit]
Description=Telegram Webhook Application Service
After=network.target nginx.service

[Service]
Type=simple
User=www-bot
Group=www-bot
WorkingDirectory=/opt/telegram-bot
Environment="TELEGRAM_SECRET_TOKEN=7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c"
ExecStart=/opt/telegram-bot/venv/bin/python3 /opt/telegram-bot/main.py
Restart=always
RestartSec=3
StandardOutput=journal
StandardError=journal
SyslogIdentifier=telegram-bot

# Security Sandbox Directives
NoNewPrivileges=true
ProtectSystem=full
ProtectHome=true
PrivateTmp=true

[Install]
WantedBy=multi-user.target

Reload the systemd daemon, enable, and start your service:

sudo systemctl daemon-reload
sudo systemctl enable telegram-bot
sudo systemctl start telegram-bot

Check the active service state using systemctl:

sudo systemctl status telegram-bot

To view real-time logs generated by your Python backend, use journalctl:

sudo journalctl -u telegram-bot -f

If you are monitoring multiple Linux background daemons across your infrastructure, consider Aggregating Linux Systemd Logs With Vector to automatically collect, structure, and forward these webhook logs to a central security operations center.

Now lock down your host network interface using Uncomplicated Firewall (UFW). You only need to open SSH, HTTP, and HTTPS ports to the public internet:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable

If your server runtime encounters authorization failures or network timeouts, configuring automated incident reporting using Setting Up Alertmanager Webhook Alerts for Linux will immediately notify your engineering team before your bot availability drops.

Registering the Secure Webhook Endpoint

Now that your server architecture is fully hardened, you must register your URL endpoint with Telegram’s Bot API. You must include your official bot token, your domain name, and the secret token matching your application code environment variable.

Run the following cURL request from your terminal:

curl -X POST "https://api.telegram.org/bot123456789:AAEFmXexampleBotTokenValueHere/setWebhook" \
     -H "Content-Type: application/json" \
     -d '{
           "url": "https://bot.yourdomain.com/telegram-webhook",
           "secret_token": "7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c",
           "max_connections": 40,
           "allowed_updates": ["message", "callback_query"]
         }'

If registered successfully, Telegram will return the following response payload:

{
  "ok": true,
  "result": true,
  "description": "Webhook was set"
}

To verify the operational status of your registered webhook and inspect connection diagnostics from Telegram’s servers, invoke getWebhookInfo:

curl -s "https://api.telegram.org/bot123456789:AAEFmXexampleBotTokenValueHere/getWebhookInfo"

The returned object confirms your active webhook state:

{
  "ok": true,
  "result": {
    "url": "https://bot.yourdomain.com/telegram-webhook",
    "has_custom_certificate": false,
    "pending_update_count": 0,
    "max_connections": 40,
    "allowed_updates": [
      "message",
      "callback_query"
    ]
  }
}

Test your setup by sending a manual HTTP request without the secret token to verify your application layer security drops unauthorized requests:

curl -i -X POST "https://bot.yourdomain.com/telegram-webhook" \
     -H "Content-Type: application/json" \
     -d '{"update_id": 10000, "message": {"message_id": 1, "date": 1441645532, "chat": {"id": 1111, "type": "private"}, "text": "Test message"}}'

Because your cURL request lacks the X-Telegram-Bot-Api-Secret-Token header, Nginx will pass it to FastAPI, which instantly rejects the unauthorized request with an HTTP 403 response:

HTTP/2 403 
date: Mon, 24 Feb 2025 12:00:00 GMT
content-type: application/json
content-length: 53

{"detail":"Forbidden: Invalid or missing secret token header."}

Now execute a request supplying the valid secret token matching your running process:

curl -i -X POST "https://bot.yourdomain.com/telegram-webhook" \
     -H "X-Telegram-Bot-Api-Secret-Token: 7f8a9b0c1d2e3f4a5b6c7d8e9f0a1b2c" \
     -H "Content-Type: application/json" \
     -d '{"update_id": 10000, "message": {"message_id": 1, "date": 1441645532, "chat": {"id": 1111, "type": "private"}, "text": "Valid secret test"}}'

You will receive an HTTP 200 response confirming your multi-layer defense strategy is fully operational:

HTTP/2 200 
date: Mon, 24 Feb 2025 12:00:05 GMT
content-type: application/json
content-length: 44

{"status":"success","detail":"Update processed"}

By enforcing strict Nginx IP range limitations, TLS encryption, header token authentication, and Systemd process isolation on your server hosting instance, your Telegram bot backend is protected against malicious scanning, request spoofing, and unauthorized access.

Getting Started

Securing your infrastructure requires choosing reliable cloud providers and automated tools. Get started by provisioning high performance infrastructure tailored for your automation stack:

Outsource Your Automation

Don’t have time? I build production n8n workflows, WhatsApp bots, and fully automated YouTube Shorts pipelines. Hire me on Fiverr, mention SYS3-HUGO for priority. Or DM at chasebot.online.

Want to automate this yourself?

Start with n8n Cloud (free tier available) or self-host on a Hetzner VPS for full control.

Want this engine running on your own VPS?

This blog publishes itself — daily, unattended, on free API tiers. The full engine, Hugo theme, and setup guide are available as System 3.

Get System 3
system online