Executive Summary
The core question: How do you secure a self-hosted AI assistant that has shell access, can execute commands, and messages on your behalf?
The short answer: Defense in depth. Bind the Gateway to localhost with strong token authentication, use Docker sandboxing for untrusted sessions, lock down DM policies to pairing-only, choose high-tier models (Claude Opus 4.5) for better prompt injection resistance, and maintain strict file permissions on credentials. No single measure is sufficient; security requires layered controls across network, application, and access management.
Key Takeaways
- Gateway Security: Always bind to loopback (127.0.0.1) with mandatory token authentication—never expose port 18789 to the internet
- Sandboxing: Run untrusted sessions in Docker containers with no network access, memory limits, and read-only root filesystems
- DM Policies: Use "pairing" mode (default) to require verification before processing messages from unknown contacts
- Model Selection: Use Claude Opus 4.5 or equivalent top-tier models for tool-enabled agents; smaller models are more vulnerable to prompt injection
- Credentials: Store secrets in environment variables, maintain 600 permissions on config files, and rotate tokens quarterly
- Monitoring: Run
moltbot security audit --deepweekly and establish logging with sensitive data redaction
Running a self-hosted AI assistant with shell access demands treating security as the foundation rather than an afterthought. Moltbot's capabilities (executing commands, accessing files, and messaging on your behalf) create significant attack surface when misconfigured.
This guide provides actionable hardening steps organized by deployment environment. Whether you're running Moltbot in a virtual machine, on dedicated hardware, or need practices that apply universally, each section delivers specific configurations to protect your API keys, chat data, and system access from malicious actors.
Virtual Environment Security
Virtual machines and containerized deployments offer inherent isolation benefits, but they introduce unique attack vectors around hypervisor escapes, shared resources, and snapshot exposure. These practices focus specifically on securing Moltbot within virtualized infrastructure, whether cloud-hosted VMs, local hypervisors, or container orchestration platforms.
Hypervisor and VM Isolation
The foundation of virtual environment security lies in proper isolation between your Moltbot VM and other workloads. You should configure your hypervisor to prevent VM escape vulnerabilities by keeping the hypervisor software current with security patches. VMware, Hyper-V, and KVM all release regular security updates that address privilege escalation risks. Enable hardware-assisted virtualization features like Intel VT-x/VT-d or AMD-V, which provide CPU-level isolation that software-only virtualization cannot match.
Disable unnecessary VM features that expand attack surface. Shared folders between host and guest should be removed entirely or configured as read-only with explicit path restrictions. Clipboard sharing, drag-and-drop functionality, and USB passthrough create channels that malicious processes could exploit to escape the VM boundary. The VM tools or guest additions packages should be kept minimal; install only the components required for basic operation.
Docker Sandboxing Configuration
Moltbot's built-in sandboxing system leverages Docker to isolate sessions from your main system. When running in a virtual environment, this creates nested isolation: the VM isolates Moltbot from your host, while Docker containers isolate individual sessions from each other. Configure sandbox mode to run non-main sessions (group chats and channels) in isolated containers while keeping your direct conversations with faster host access.
The scope: "session" setting creates one container per conversation, providing the strongest isolation. Each sandboxed session receives no network access (network: "none"), preventing exfiltration attempts. Memory and CPU limits prevent resource exhaustion attacks where a malicious prompt might attempt infinite loops or memory allocation bombs. The read-only root filesystem ensures that even if code execution occurs, persistent modifications to the container are impossible.
Critical Warning
The tools.elevated configuration runs commands on the host system, bypassing all Docker sandboxing. Keep tools.elevated.allowFrom restricted to only your trusted owner identity; never allow elevated access from group chats or untrusted contacts.
Virtual Network Segmentation
Virtual networks should segment Moltbot from other VMs and from direct internet exposure. Create a dedicated virtual network (VLAN or virtual switch) for your Moltbot instance that routes through a firewall VM or the host's firewall before reaching external networks. This architecture ensures that even if Moltbot is compromised, lateral movement to other virtual machines on your infrastructure becomes significantly more difficult.
For cloud deployments on AWS, GCP, or Azure, use security groups and network ACLs to achieve equivalent isolation. Place your Moltbot instance in a private subnet with no public IP address. Route all outbound traffic through a NAT gateway, and use VPC flow logs to monitor for unusual connection patterns. Inbound access should only occur through a bastion host or VPN connection; never expose the Gateway port directly to the internet.
Snapshot and Backup Security
VM snapshots capture the complete state of your Moltbot instance, including all credentials stored in memory and on disk. These snapshots represent a significant security risk if accessed by unauthorized parties. Encrypt all VM snapshots using your hypervisor's built-in encryption features or by storing them on encrypted storage volumes. Implement strict access controls on snapshot storage locations, and establish retention policies that automatically purge snapshots older than your operational requirements.
Before creating snapshots for backup purposes, consider running moltbot gateway stop to clear session data from memory. Avoid snapshotting while active conversations contain sensitive information. For cloud environments, use customer-managed encryption keys (CMEK) rather than provider-managed keys, giving you the ability to revoke access by rotating the key material.
Container Registry Security
If you're pulling Moltbot's Docker images or building custom sandbox images, the container registry becomes a trust boundary. Use only official images from verified sources, and enable content trust (Docker Content Trust or Sigstore signatures) to verify image integrity before deployment. For private registries, enable vulnerability scanning on all images and block deployment of images with critical CVEs.
Dedicated Machine Security
Running Moltbot on dedicated hardware, whether a home server, rack-mounted system, or single-board computer like a Raspberry Pi, provides direct control over the entire stack but requires comprehensive hardening at every layer. Without the isolation benefits of virtualization, your operating system configuration, physical security, and network architecture become critical defense lines.
Operating System Hardening
Begin with a minimal operating system installation. Ubuntu Server LTS or Debian provide stable foundations without unnecessary desktop packages that expand attack surface. During installation, enable full-disk encryption (LUKS) to protect data at rest, which prevents credential extraction if the physical drive is stolen or improperly decommissioned. Create a dedicated non-root service account for Moltbot that cannot log in interactively.
Harden the SSH configuration to prevent brute-force attacks and unauthorized access. Change the default port, disable root login, require key-based authentication only, and limit which users can connect. Install fail2ban to automatically block IP addresses after repeated failed authentication attempts.
Host-Based Firewall Configuration
The firewall represents your primary network defense on dedicated hardware. Configure UFW (Uncomplicated Firewall) or iptables to default-deny all incoming connections, then explicitly allow only required services. The Gateway should never be exposed to the public internet; restrict it to localhost or your Tailscale network range for remote access.
Important
Never add a rule allowing port 18789 from 0.0.0.0/0 or any. Public internet exposure of the Gateway, even with token authentication, significantly increases risk of credential theft and brute-force attacks.
Systemd Service Hardening
Running Moltbot as a systemd service provides automatic startup, crash recovery, and (critically) additional security sandboxing through systemd's built-in isolation features. These directives restrict the service's access to the filesystem, network namespaces, and kernel capabilities beyond what the application code itself enforces.
These directives work together to create multiple defense layers. NoNewPrivileges prevents the process from gaining additional privileges through setuid binaries or capabilities. ProtectSystem=strict mounts the entire filesystem read-only except for explicitly allowed paths. MemoryDenyWriteExecute blocks common exploitation techniques that require writing executable code to memory.
Physical Security Considerations
Dedicated hardware introduces physical attack vectors that don't exist in cloud or virtualized environments. An attacker with physical access could boot from external media, extract the hard drive, or install hardware keyloggers. For servers in accessible locations, configure BIOS/UEFI passwords and disable booting from USB or network sources. Enable Secure Boot to prevent unauthorized bootloader modifications.
Full-disk encryption with LUKS becomes essential for physical security. Configure the system to require a passphrase at boot, or use a TPM (Trusted Platform Module) chip to automatically unlock the drive only when the hardware configuration matches expectations, which prevents drive extraction attacks while allowing unattended reboots after power failures.
Automatic Security Updates
Dedicated machines require proactive patch management since there's no cloud provider handling infrastructure updates for you. Configure unattended-upgrades to automatically install security patches, and schedule regular reboots during maintenance windows to apply kernel updates. The January 2026 audit found 20 CVEs in Moltbot's dependencies alone, so keeping the entire system current is essential.
Hardware Security Modules (Optional)
For high-security deployments, consider using a hardware security module (HSM) or a YubiKey HSM to store API keys and Gateway authentication tokens. These devices keep cryptographic secrets in tamper-resistant hardware, making extraction through software attacks impossible. While this adds complexity, it provides the strongest protection for your Anthropic API key and other provider credentials.
Universal Security Practices
Regardless of whether Moltbot runs in a virtual environment or on dedicated hardware, certain security practices apply universally. These address the application layer: Gateway configuration, secrets management, access control, and monitoring, where the deployment substrate doesn't change the threat model.
Gateway Authentication and Binding
The Gateway daemon serves as Moltbot's control plane, making its security configuration your highest priority regardless of deployment environment. The Gateway should bind exclusively to the loopback interface with mandatory token authentication. Even for local-only deployments, token authentication prevents other processes on the same system from accessing the Gateway API.
Generate a cryptographically secure token using openssl rand -hex 32 rather than choosing a memorable password. Store this token in an environment variable rather than directly in the configuration file, as demonstrated by the ${MOLTBOT_GATEWAY_TOKEN} reference above. Disabling mDNS discovery prevents the Gateway from broadcasting its presence on the local network, which could reveal your infrastructure to other devices.
Remote Access Recommendation
For remote administration, use Tailscale Serve or SSH port forwarding rather than exposing the Gateway directly. Configure "tailscale": { "mode": "serve" } in the gateway settings, or tunnel via ssh -N -L 18789:127.0.0.1:18789 user@server.
Secrets and API Key Protection
The January 2026 security audit identified plaintext credential storage as a critical vulnerability. OAuth tokens and API keys stored in ~/.moltbot/credentials/ and ~/.moltbot/agents/*/agent/auth-profiles.json use JSON format with only filesystem permissions for protection (no encryption). This makes proper file permissions and environment variable usage essential.
| Path | Contents | Required Permission |
|---|---|---|
| ~/.moltbot/ | Configuration root directory | 700 (rwx------) |
| ~/.moltbot/moltbot.json | Main configuration with tokens | 600 (rw-------) |
| ~/.moltbot/credentials/* | Channel credentials, pairing lists | 600 (rw-------) |
| ~/.moltbot/agents/*/agent/auth-profiles.json | API keys and OAuth tokens | 600 (rw-------) |
| ~/.moltbot/sessions/* | Conversation transcripts | 600 (rw-------) |
For production deployments, consider integrating with a secrets manager like HashiCorp Vault or AWS Secrets Manager for dynamic credential injection. This approach eliminates secrets from disk entirely, rotating them automatically and providing audit trails for access.
Channel Security and DM Policies
The DM policy system controls who can interact with your assistant, and this represents your primary defense against prompt injection from untrusted sources. The default "pairing" mode sends unknown contacts a time-limited code and ignores their messages until you explicitly approve the relationship. This friction is intentional and valuable.
| Policy | Behavior | Risk Level |
|---|---|---|
| pairing | Unknown senders receive code, messages ignored until approved | Recommended |
| allowlist | Only explicitly configured senders allowed | Good |
| disabled | Ignore all direct messages | Restrictive |
| open | Allow anyone to message (requires explicit allowFrom: ["*"]) | Dangerous |
Group chats present the highest prompt injection risk because messages from strangers are mixed with trusted contacts. Always configure requireMention: true for group contexts, ensuring the bot only processes messages explicitly directed at it. This prevents attackers from injecting malicious prompts into group conversations that the bot might process accidentally.
Logging and Security Monitoring
Comprehensive logging with sensitive data redaction enables security monitoring without creating additional exposure vectors. Configure Moltbot to redact API keys, tokens, and other secrets from log output, then establish monitoring for security-relevant events like authentication failures, rate limit triggers, and unusual tool execution patterns.
Protect log files with appropriate permissions (chmod 640) and ownership (chown moltbot:adm). Implement log rotation to prevent disk exhaustion and establish retention policies aligned with your compliance requirements. For high-security environments, consider shipping logs to a SIEM (Security Information and Event Management) system for centralized analysis and alerting.
Security Events to Monitor
- ◈ Authentication failures from unusual IP addresses or at unusual rates, which may indicate brute-force attempts against the Gateway
- ◈ Rate limit triggers that could indicate denial-of-service attempts or automated scanning
- ◈ Pairing requests from unknown numbers, especially in rapid succession
- ◈ Tool execution patterns, particularly filesystem operations accessing sensitive paths
- ◈ Session transcript anomalies such as repeated injection attempts or requests for system information
- ◈ Configuration changes, especially modifications to DM policies or elevated tool access
Prompt Injection Mitigation
Prompt injection (where malicious content tricks the AI into taking unintended actions) represents the primary security concern for any AI assistant with system access. On Day 1 of Moltbot's testing, a "friendly" user asked the bot to run find ~ and share the output. The bot complied, dumping the entire home directory structure to a group chat and revealing project names, configuration locations, and system layout.
Defense requires multiple layers working together. Use modern models with better instruction following; the official documentation recommends Anthropic's Claude Opus 4.5 for "long-context strength and better prompt-injection resistance." Keep DMs locked down with pairing or allowlists. Require mentions in groups to avoid processing untrusted messages. Run sensitive tools in sandboxes. Treat all external content (web results, emails, attachments) as potentially hostile.
Regular Security Audits
Moltbot includes a built-in security audit command that checks configuration, file permissions, and Gateway exposure. Run this regularly as part of your maintenance routine, and use the --fix flag to automatically apply safe guardrails.
The --fix flag automatically tightens groupPolicy="open" configurations to allowlist mode, enables sensitive data redaction in logs, and corrects file permissions on credential directories. Schedule these audits weekly using cron or systemd timers to catch configuration drift.
Dependency and Update Management
The January 2026 audit identified 20 CVEs in Moltbot's dependencies: 1 critical, 15 high severity, and 4 medium. Regular updates are essential for both the application and its dependency tree. Establish a routine that includes checking for updates, reviewing changelogs for security fixes, and testing updates in a staging environment before production deployment.
Incident Response Procedure
When a security incident occurs, whether suspected credential exposure, unusual bot behavior, or confirmed compromise, follow a structured response process to contain damage, preserve evidence, and restore secure operation.
- 01 Contain: Stop the Gateway immediately with moltbot gateway stop, close any exposed network paths, and freeze access to the system
- 02 Rotate: Replace all potentially exposed credentials: Gateway auth token, Anthropic API key, provider tokens (Telegram, Discord, Slack), and any browser control tokens
- 03 Audit: Review logs at ~/.moltbot/logs/, examine session transcripts for suspicious activity, check for configuration changes, and verify file integrity
- 04 Report: For vulnerabilities in Moltbot itself, contact security@steipete.me following responsible disclosure practices
Security Maintenance Checklist
Weekly Tasks
- ☸ Run moltbot security audit --deep
- ☸ Review logs for authentication failures and unusual patterns
- ☸ Check for application and dependency updates
Monthly Tasks
- ☸ Review and prune the pairing allowlist
- ☸ Verify backup integrity and encryption
- ☸ Test incident response procedures
Quarterly Tasks
- ☸ Rotate Gateway authentication token
- ☸ Rotate API keys for all providers
- ☸ Review and update firewall rules
- ☸ Audit session transcripts for sensitive data exposure
Frequently Asked Questions
What is the most important security step when deploying Moltbot?
The most critical step is configuring Gateway authentication with a strong, randomly generated token and binding exclusively to the loopback interface. This prevents unauthorized access to Moltbot's control plane. Use openssl rand -hex 32 to generate a secure token and store it in an environment variable rather than your configuration file.
Should I run Moltbot in a VM or on bare metal?
Both approaches are viable with proper hardening. Virtual machines provide an additional isolation layer that can contain potential breaches, making them ideal for environments with multiple workloads. Bare metal offers better performance and simpler architecture but requires more rigorous OS-level hardening. For most users, a dedicated VM with Docker sandboxing enabled provides the best balance of security and usability.
What is prompt injection and how do I prevent it?
Prompt injection occurs when malicious content tricks the AI into performing unintended actions, such as revealing system information or executing harmful commands. Prevent it by: using DM pairing or allowlists to control who can message the bot, requiring mentions in group chats, running tools in sandboxed containers, using modern models like Claude Opus 4.5 with better instruction following, and treating all external content as potentially hostile.
How often should I rotate my API keys and tokens?
Rotate Gateway authentication tokens and API keys quarterly as part of routine maintenance. Immediately rotate all credentials if you suspect any security incident, if a team member with access leaves, or if credentials may have been exposed in logs, backups, or version control. Use the Security Maintenance Checklist in this guide to establish a rotation schedule.
Is it safe to expose Moltbot to the internet?
Never expose the Gateway port directly to the public internet. For remote access, use Tailscale Serve (which handles authentication and encryption) or SSH port forwarding. If you must expose services, place them behind a reverse proxy with proper authentication, configure trustedProxies, and implement rate limiting. Even with these precautions, treat any internet-facing deployment as higher risk.
What DM policy should I use?
Use pairing (the default) for most deployments. This requires unknown senders to complete a verification code exchange before the bot processes their messages, preventing random strangers from accessing your assistant. Only use open if you explicitly intend to create a public-facing bot, and even then, combine it with aggressive sandboxing and tool restrictions.
Are plugins safe to install?
Plugins run in-process with the Gateway and have the same access privileges, so treat them as trusted code. Only install plugins from sources you fully trust. Use explicit plugins.allow allowlists, pin exact versions when installing from npm, and inspect the unpacked code at ~/.moltbot/extensions/ before enabling. Remember that npm lifecycle scripts can execute code during installation.
