Skip to content

ironmist45/tg-vps-bot

Folders and files

NameName
Last commit message
Last commit date

Latest commit

Β 

History

1,395 Commits
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 
Β 

Repository files navigation

πŸš€ Telegram Server Bot Build Status

Production-ready Telegram bot for server monitoring and management, written in pure C.


✨ Features

πŸ–₯ System Monitoring

  • CPU load (1 / 5 / 15 min)
  • Memory usage (MB + %)
  • Disk usage (GB + %)
  • Uptime
  • Active users

βš™οΈ Service Management

  • Check system services status via systemctl
  • Start, stop, restart individual services via /service <alias> <action>

Supported actions: status, start, stop, restart

Supports the following services:

  • Clean formatted output with status indicators:

    • 🟒 UP
    • πŸ”΄ DOWN
    • 🟑 FAIL / STARTING
    • βšͺ UNKNOWN

πŸ“œ Logs & Users

  • View service logs via journalctl (/logs)
  • Semantic log filtering: error, auth, brute, ip, session, pam
  • Multi-keyword AND filtering (e.g. /logs ssh error)
  • Inspect active user sessions
  • Configurable line count (default 30, max 200)

πŸ“Š Metrics & Health Monitoring

Built-in metrics collected since last bot start:

Commands:

  • Total commands processed
  • Per-command counters (/start, /help, /logs, /fail2ban, /reboot, /restart, /services, /users, /health)

Errors:

  • Unauthorized access attempts
  • Polling timeouts
  • Exec failures (sudo, systemctl, journalctl)

Performance:

  • Average / max response time (ms)
  • Poll cycles count
  • Telegram API calls (total / failed)

How to check: /health β€” compact view with system status + bot metrics

On shutdown, full metrics summary is written to the log:

[SYS] Commands: 42 (start=1 help=2 logs=15 ...) | Errors: unauthorized=0 timeout=0 exec=0 | Response: avg=142ms max=570ms

πŸ›‘ Security

  • πŸ” Single allowed chat_id β€” only one Telegram user can control the bot
  • 🚫 All unauthorized access attempts are logged:
    poll=01a3 req=2212 ACCESS CHECK: chat_id=123456789 cmd=/start result=DENIED
    
  • πŸ”‘ Two-step confirmation for dangerous commands (/reboot, /restart, /service start|stop|restart)
    • TOTP mode (when TOTP_SECRET is configured): time-based one-time code from Google Authenticator, Aegis, Authy or any RFC 6238 app
    • Token mode (fallback): stateless time-based token with configurable TTL
    • Bruteforce protection (blocks after 5 failed attempts)
    • Replay protection (single-use)
  • πŸ§ͺ Input validation:
    • Message length limit
    • IP address validation (Fail2Ban)
    • Character whitelist for command arguments

πŸ”₯ Fail2Ban Integration

  • Check jail status (/fail2ban status, /fail2ban status sshd)
  • Ban / unban IP addresses
  • Secure wrapper execution via f2b-wrapper
  • Full audit logging via syslog (LOG_AUTH facility)

πŸ”„ Process Control

  • /restart β€” restart the bot process (systemctl restart tg-bot)
  • /reboot β€” reboot the server
  • Both require two-step confirmation (TOTP or token)
  • Tracks who requested the operation

⚑ Telegram Engine

  • Long polling (no webhooks)
  • Fork isolation for libcurl β€” network hangs cannot block the main process
  • Dynamic pipe buffer β€” handles large Telegram responses (100+ updates) without truncation
  • Offset persistence with atomic write (crash recovery, no duplicate messages)
  • Runtime duplicate detection
  • MarkdownV2 formatting with automatic escaping
  • Automatic message truncation (4096 char limit)

🧠 Reliability & Stability

  • Safe JSON parsing β€” no crashes on malformed Telegram responses
  • NULL checks everywhere
  • Deadline-based curl timeouts (no busy-wait)
  • Zero zombie processes β€” blocking waitpid after pipe EOF
  • Early log buffer β€” startup messages are captured before log file opens
  • Graceful shutdown on SIGTERM and on consecutive polling errors:
    • Saves update offset to disk
    • Flushes logs
    • Syncs filesystem
  • systemd watchdog support (Type=notify, WatchdogSec=60)
  • Log rotation support via SIGUSR1
  • Main loop iteration timing β€” warns if iteration exceeds 35s

πŸ“Š Logging System

  • Levels: DEBUG / INFO / WARN / ERROR
  • Millisecond-precision timestamps (single clock_gettime call β€” no race condition)
  • Complete log from process start β€” early messages buffered and flushed to file on open
  • Mirror to stderr when running interactively (isatty detection)
  • No stderr duplication when running as systemd service
  • Thread-safe writes via mutex
  • Safe formatting β€” no crashes on bad input

πŸ” TOTP Two-Factor Authentication

Dangerous commands (/reboot, /restart, /service start|stop|restart) support TOTP 2FA compatible with Google Authenticator, Aegis, Authy and any RFC 6238 application.

Setup

1. Generate a secret:

python3 -c "import base64, os; print(base64.b32encode(os.urandom(20)).decode())"
# or:
openssl rand 20 | base32

2. Add to config file and enable setup mode:

TOTP_SECRET=YOUR_BASE32_SECRET_HERE
TOTP_SETUP=enabled

3. Reload config:

kill -HUP $(pidof tg-bot)

4. Get import link for your app:

/totp_setup

Copy the otpauth:// URI into Aegis, Google Authenticator or Authy.

5. After adding to your app β€” disable setup mode:

TOTP_SETUP=disabled

Then reload config again. This prevents the secret from being exposed if someone gains access to the bot.

How it works

you:  /reboot
bot:  πŸ” Confirm: /reboot
      Enter the code from your authenticator app:
      /confirm <code>

you:  /confirm 428798
bot:  ♻️ Rebooting system...

When TOTP_SECRET is not configured, the bot falls back to the classic stateless token flow automatically β€” no configuration change needed.

Security note

TOTP_SETUP=disabled (default) prevents /totp_setup from showing the secret after initial setup. Even if someone gains access to the bot, they cannot retrieve the TOTP secret via chat.


πŸ–₯️ CLI Interface

▢️ Run

tg-bot --config /etc/tg-bot/config.conf

βš™οΈ Setup (first run)

cp config/config.example.conf config/config.conf
# edit config.conf β€” set TOKEN and CHAT_ID

πŸ”§ Options

  • -c, --config <path> β€” config file path
  • -h, --help β€” show help
  • -v, --version β€” show version with build info

πŸ“¦ Example Commands

General
/start   β€” welcome message with system summary + selfcheck (RSS, log file)
/help    β€” list all commands

System info
/status  β€” detailed system status (CPU, memory, disk, uptime)
/health  β€” compact health check + bot metrics (with used/total MB and GB)
/about   β€” bot version, build info, library versions
/ping    β€” latency test (processing time, inbound, RTT)
/logstat β€” bot log file statistics (SSE4.2 accelerated)

Services
/services                      β€” status of all monitored services
/service ssh status            β€” status of a single service
/service ssh restart           β€” restart a service (requires confirmation)
/service shadowsocks stop      β€” stop a service (requires confirmation)
/users                         β€” active login sessions
/logs ssh                      β€” last 30 lines from ssh journal
/logs ssh 50                   β€” last 50 lines
/logs ssh error                β€” filtered by "error" (semantic)
/logs ssh 100 brute            β€” last 100 lines filtered for brute-force patterns

Security
/fail2ban status           β€” show all jails
/fail2ban status sshd      β€” show sshd jail
/fail2ban ban 1.2.3.4      β€” ban IP
/fail2ban unban 1.2.3.4    β€” unban IP

System control (two-step confirmation required)
/reboot      β€” reboot the server
/restart     β€” restart the bot process
/totp_setup  β€” show TOTP setup info and import link
/confirm     β€” confirm a pending operation (TOTP code or token)

πŸ— Architecture

Modular C design β€” each module has a single responsibility:

  • main.c β€” orchestration, main event loop, signal handling
  • lifecycle.c β€” process lifecycle (signals, shutdown, reboot, restart)
  • telegram_poll.c β€” long polling with fork() isolation for libcurl, RSS sampling
  • telegram_http.c β€” low-level HTTP via libcurl
  • telegram_parser.c β€” JSON parsing, markdown escaping
  • telegram_offset.c β€” update offset persistence
  • commands.c β€” command dispatcher, two-step confirmation logic
  • security.c β€” access control, rate limiting, token validation
  • totp.c β€” TOTP implementation (RFC 6238, HMAC-SHA1 via OpenSSL)
  • config.c β€” configuration file parsing and reload
  • logger.c β€” thread-safe logging with early buffer
  • diagnostics.c β€” runtime diagnostics (loop timing)
  • services_config.c β€” shared service definitions (single source of truth)
  • services.c β€” systemd service status queries and control
  • system.c β€” system metrics (CPU, memory, disk, uptime)
  • exec.c β€” external command execution with deadline timeout
  • logs.c + logs_filter.c β€” journalctl integration and semantic filtering
  • users.c β€” active session enumeration via utmp
  • metrics.c β€” bot usage statistics
  • utils.c β€” shared helpers

πŸ§ͺ Production-Ready Details

  • Offset saved atomically via temp file + rename (no corruption on crash)
  • pipe2(O_CLOEXEC) β€” no fd leaks into child processes
  • Deadline-based select() β€” total timeout is always exactly timeout_ms
  • Blocking waitpid() after pipe EOF β€” no zombie window
  • Dynamic heap buffer for Telegram API responses β€” no fixed cap, handles 100+ updates
  • getrandom(2) for token salt β€” cryptographically unpredictable
  • All timeout constants in telegram_timeouts.h with _Static_assert chain
  • Config reload on SIGHUP without restart
  • Log reopen on SIGUSR1 for logrotate integration
  • TOTP verification uses Β±1 step window to compensate for clock skew
  • TOKEN and TOTP_SECRET never appear in log files β€” masked even at DEBUG level
  • f2b-wrapper logs all operations to syslog (LOG_AUTH) with PID

πŸ” Security Notes

  • Bot responds only to one chat_id β€” hardcoded in config
  • All unauthorized attempts are logged with chat_id
  • No shell injection β€” IP validation via inet_pton, service names via character whitelist
  • No direct root commands β€” all privileged operations via sudo whitelist
  • Token salt generated via getrandom(2) at startup β€” unpredictable across restarts
  • TOTP secret never logged β€” not even at DEBUG level
  • TOTP_SETUP=disabled by default β€” secret not exposed via /totp_setup after setup
  • f2b-wrapper rejects private/loopback IP addresses for ban/unban operations

⚠️ Requirements

Primarily tested on:

  • OS: Ubuntu 18.04.6 LTS x86_64
  • Compiler: GCC 7.5.0
  • Libraries (all statically linked):
    • 🌐 libcurl 8.20.0 β€” HTTP client (curl license)
    • πŸ”’ OpenSSL 3.0.20 β€” TLS/SSL (Apache 2.0)
    • 🧭 c-ares 1.34.6 β€” async DNS resolver (MIT)
    • πŸ“„ cJSON 1.7.19 β€” JSON parser (MIT)

⚑ The binary is fully self-contained (~5.5 MB stripped). Only libc is required at runtime.

πŸ“¦ Install

No dependencies required on the target system:

chmod +x tg-bot
sudo cp tg-bot /usr/local/bin/

Build Notes

Built in Ubuntu 18.04 environment using Docker for reproducibility.

Linking model:

  • Fully static: libcurl, OpenSSL, c-ares, cJSON compiled from source
  • Only libc (glibc) remains dynamically linked

⚠️ Do NOT modify linker flags unless you know what you are doing.


Optional Dependencies

f2b-wrapper β€” required only for /fail2ban commands.
Source: tools/f2b-wrapper.c

The f2b-wrapper binary must be built on the target system.
Using a binary compiled elsewhere may cause GLIBC_X.Y not found errors.

If you see this at startup:

[ERROR] [SYS] fail2ban-wrapper: FAIL (EXEC_FAILED)

Rebuild f2b-wrapper locally on the target machine.


🚧 Roadmap

Recently Completed

  • /service <alias> <action> β€” start, stop, restart individual services via Telegram

Planned

  • Log filtering by time (--since 1h)
  • /df β€” disk usage quick view
  • /top β€” top processes by CPU/RAM
  • /fail2ban status <jail> β€” detailed jail statistics
  • /ssh keys β€” show authorized SSH keys
  • Scheduled commands (/reboot in 5)
  • Alerts β€” bot notifies on high CPU/RAM load
  • /backup β€” trigger backup script via Telegram

Low Priority

  • Notification on bot stop
  • Unit tests (TOTP RFC 6238 vectors, security.c, logs_filter.c)
  • Prometheus metrics export (requires server with >2GB RAM)

Philosophy

Built with focus on reliability, control and independence.
Inspired by the idea that infrastructure should remain in your hands.

Stay independent. πŸ™‚


πŸ“„ License License

MIT License Β© 2026 ironmist45

About

Minimal self-hosted Telegram bot for monitoring and controlling systemd services on Linux (Ubuntu 18.04.6).

Topics

Resources

License

Code of conduct

Contributing

Stars

Watchers

Forks

Releases

No releases published

Packages

 
 
 

Contributors