Back to skill

Security audit

Telegram Bot

Security checks for vulnerabilities and agentic risk

Overview

This Telegram bot skill is mostly purpose-aligned, but it automatically installs an unpinned package at runtime and handles bot tokens in ways users should review carefully.

Review before installing. Use an isolated virtual environment or container, install and pin `python-telegram-bot` yourself instead of relying on the script's automatic pip install, pass Telegram tokens through a safer secret mechanism rather than command-line arguments, and only use handler files you fully trust. Be cautious with the group admin example because it can remove users from chats when run by an authorized bot/admin setup.

Vulnerability Patterns
  • Insecure DependenciesIntroduces malicious components through unsafe dependency sources
  • Insecure Skill Coding PracticesFinds exploitable flaws such as hardcoded secrets or command injection
  • Skill Instruction HijackingAlters the agent's session goals or safety constraints when the skill loads
  • Agent Memory PoisoningWrites attacker-controlled rules into memory that affect later sessions
  • Remote Payload Retrieval and ExecutionFetches external code whose behavior can change after review
Findings (2)

T08 · Insecure Dependencies

Error
Location
scripts/bot.py:9
Finding

Automatic Runtime Installation of an Unpinned Dependency

Content
View full analysis

Vulnerability Details

File Location: scripts/bot.py:9-16
Vulnerability Type: Unpinned runtime dependency installation
Risk Level: High

Vulnerable Code:

python
# Try to import telegram, install if needed
try:
    from telegram import Update
    from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
except ImportError:
    print("Installing python-telegram-bot...")
    os.system("pip install python-telegram-bot")
    from telegram import Update
    from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

Technical Analysis

The script automatically invokes pip when the Telegram dependency cannot be imported. The package has no exact version constraint, integrity hash, lockfile, trusted artifact restriction, or user confirmation. Consequently, the code installed depends on whatever package release and transitive dependencies the package index supplies at execution time.

Although the command itself is constant and does not create a direct shell-injection issue, this design creates a supply-chain exposure. Installation may run package build or installation logic, and the subsequent import executes the installed package's module-level code. It also modifies the active Python environment without an explicit setup operation.

Attack Path

  1. The bot is started in an environment where python-telegram-bot is unavailable or fails to import.
  2. The ImportError handler automatically invokes pip install python-telegram-bot.
  3. Pip resolves the latest available package and its transitive dependencies without checking project-pinned versions or expected hashes.
  4. A compromised, malicious, or unexpectedly changed upstream artifact is downloaded and installed.
  5. Installation logic or the imports immediately following installation execute attacker-controlled code.
  6. The code runs with the same operating-system ...[truncated 590 chars]
Remediation
View remediation

Remediation Suggestions

  • Remove all runtime package installation from the application.
  • Declare python-telegram-bot and its reviewed version in a dependency manifest or lockfile.
  • Pin exact versions and verify downloaded artifacts with cryptographic hashes, such as through pip --require-hashes.
  • Install dependencies during a separate, explicit deployment or build phase inside an isolated virtual environment or container.
  • Use an approved internal package mirror where appropriate and continuously scan direct and transitive dependencies.
  • If the dependency is missing at runtime, terminate with a clear error rather than modifying the environment automatically.
  • Avoid os.system() for process execution. Where a fixed administrative subprocess is genuinely necessary, use subprocess.run() with an argument list, explicit interpreter selection, and failure checking.

T09 · Insecure Skill Coding Practices

Warning
Location
scripts/bot.py:89
Finding

Telegram Bot Token Exposed Through Command-Line Arguments

Content
View full analysis

Vulnerability Details

File Locations: SKILL.md:13, SKILL.md:30-33, and scripts/bot.py:89-96
Vulnerability Type: Sensitive credential passed through process arguments
Risk Level: Medium

Documented Invocation:

bash
# Get bot token from @BotFather on Telegram
# Create bot.py:
python scripts/bot.py --token YOUR_TOKEN --handler my_handler.py

Documented Option:

text
Options:
  --token TEXT        Bot API token (required)
  --handler PATH      Python handler file

Token Handling Code:

python
def main():
    parser = argparse.ArgumentParser(description='Telegram Bot')
    parser.add_argument('--token', required=True, help='Bot API token')
    parser.add_argument('--handler', help='Custom handler Python file')
    parser.add_argument('--webhook-url', help='Webhook URL')
    parser.add_argument('--port', type=int, default=8443, help='Webhook server port')
    parser.add_argument('--poll', action='store_true', help='Use polling instead of webhook')
    
    args = parser.parse_args()
    run_bot(args.token, args.handler, args.poll)

Technical Analysis

The documented and implemented interface requires operators to provide the Telegram bot token as a command-line argument. Command-line credentials can be retained in shell history and may be captured by process inspection, command auditing, orchestration metadata, diagnostic tooling, monitoring agents, or deployment logs.

Exposure depends on the host's process visibility and logging configuration, but command-line arguments are not an appropriate secret-transport mechanism. The application does not provide a safer built-in source such as a protected file, secret manager, or non-echoing prompt.

Attack Path

  1. An operator follows the documented command and substitutes a real Telegram bot token for YOUR_TOKEN.
  2. The full command is stored in shell history, deployment configuration, audit l ...[truncated 891 chars]
Remediation
View remediation

Remediation Suggestions

  • Remove the required --token command-line option as the primary credential interface.
  • Load the token from a secret manager, protected credential file, container secret, or another deployment-native secret mechanism.
  • If environment variables are supported, document their process-environment exposure limitations and ensure they are not logged or included in diagnostic output.
  • For interactive use, accept the token through a non-echoing prompt such as getpass.getpass().
  • Set restrictive filesystem permissions on any token file and avoid storing it in source control.
  • Update SKILL.md so examples never instruct users to place real tokens directly in command lines.
  • Redact credentials from application logs, process supervisors, CI/CD output, and error reports.
  • Rotate the Telegram bot token through BotFather if it has previously been supplied through exposed command lines or retained logs.
Vulnerability Patterns
  • Supply ChainUnpinned Dependencies, External Script Fetching, Obfuscated Code
  • Excessive AgencyUnrestricted Tool Access, Autonomous Decision Making, Scope Creep
  • Behavioral ASTexec() Call, eval() Call, Dynamic Import
  • MCP Least PrivilegeUnderdeclared Capability, Wildcard Permission, Missing Permission Declaration
  • Prompt InjectionInstruction Override, Hidden Instructions, Exfiltration Commands
Findings (7)

os.system() or os exec-family call

High
Category
Dangerous Code Execution
Confidence
95% confidence
Finding

The script invokes a shell command to install a package automatically at runtime. Even though the command string is constant, executing pip through the shell expands the skill's capabilities beyond bot operation, introduces supply-chain risk, and performs system modification without explicit user consent.

Content

Scanner excerpt · scripts/bot.py (reported line 17)May include surrounding context.

python
from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes
except ImportError:
    print("Installing python-telegram-bot...")
    os.system("pip install python-telegram-bot")
    from telegram import Update
    from telegram.ext import Application, CommandHandler, MessageHandler, filters, ContextTypes

Context-Inappropriate Capability

High
Category
Not specified by scanner
Confidence
99% confidence
Finding

Allowing a --handler argument that points to an arbitrary Python file gives the skill a general-purpose code execution feature unrelated to simply creating or managing Telegram bots. In the skill context this is more dangerous because operators may treat it as a bot utility, while it can actually run any local code with the user's privileges.

Content

No source excerpt is available for this finding.

Undeclared Tool Scope

Medium
Category
MCP Least Privilege
Confidence
91% confidence
Finding

The skill instructs users to run shell commands and invoke a local Python script with sensitive parameters such as a Telegram bot token, but it declares no tool scope or allowed-tools restrictions. In an agent environment, this mismatch can enable broader-than-intended shell execution and unsafe handling of secrets, increasing the chance of unauthorized command use or token exposure.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
89% confidence
Finding

This markdown file includes an example admin bot that performs a destructive moderation action by banning users from a group. The example shows the action and authorization check, but the surrounding documentation does not warn readers that it can remove users from chats or should be used cautiously in administrative contexts.

Content

No source excerpt is available for this finding.

Context-Inappropriate Capability

Medium
Category
Not specified by scanner
Confidence
94% confidence
Finding

The skill attempts to install packages at runtime by invoking pip through the shell, which is broader than the declared bot-management purpose. This can alter the host environment, fetch unpinned code from package sources, and surprise users who did not authorize system changes.

Content

No source excerpt is available for this finding.

Missing User Warnings

Medium
Category
Not specified by scanner
Confidence
95% confidence
Finding

The script automatically performs package installation without warning or confirmation, causing unprompted environment changes. In a bot skill, this violates least surprise and increases operational and supply-chain risk because network retrieval and installation happen implicitly.

Content

No source excerpt is available for this finding.

Dynamic import via __import__()

Medium
Category
Dangerous Code Execution
Confidence
98% confidence
Finding

The code dynamically imports a module derived from a user-supplied file path after modifying sys.path, which causes top-level code in that file to execute immediately. This enables arbitrary local Python code execution and can also load an unintended module via path/module-name confusion.

Content

Scanner excerpt · scripts/bot.py (reported line 60)May include surrounding context.

python
# Import module
    module_name = Path(handler_path).stem
    try:
        return __import__(module_name)
    except Exception as e:
        print(f"Error loading handler: {e}")
        return None

Static analysis

No suspicious patterns detected.