VPS Security Hardening: 15 Steps to Protect Your Mail Server
A mail server is one of the most attractive targets on the internet. It holds valuable correspondence, it can send messages that other systems trust, and it is probed by automated scanners within minutes of going online. Attackers do not need your server to be famous; they scan entire address ranges looking for weak passwords, outdated software and open relays. The good news is that hardening a VPS is not mysterious. It is a sequence of well-understood steps, most of which take minutes and need doing only once, plus a few habits that keep the server secure afterwards. This guide walks through fifteen of them in the order we recommend applying them on a new mail VPS, explaining what each step protects against so you can judge priorities sensibly. You do not need to be a security specialist to follow it, but you do need console access to your server and the discipline to finish the list rather than stopping after the firewall. Work through it before the server handles real mail, and revisit it every few months.
1. Apply All Updates Before Anything Else
A fresh VPS image is rarely current. It may have been built months ago, and every package on it carries the vulnerabilities discovered since. Your first task on a new server should be to update the package lists and apply all available upgrades, including a reboot if the kernel changes. Only then should you install or configure mail software, because building on an outdated base means inheriting known holes from day one. Note which services were updated so you understand what you are running.
Make Updating a System, Not an Event
Then make updating a system, not an event. Enable automatic security updates for the operating system if your distribution supports them, and follow the security announcements for your mail stack. Set a monthly maintenance window for larger upgrades and reboots, and treat critical vulnerabilities as exceptions that justify an immediate patch. Most compromised mail servers were not beaten by exotic attacks; they were running software with a fix that had been available for months. Patching discipline is the least glamorous step on this list and the one that prevents the most incidents.
2. Create a Named Admin User and Disable Root Login
Working directly as root hides who did what and gives any successful guess of the root password total control. Create a personal administrator account with a strong, unique password, grant it sudo privileges, and use it for all routine work. Once you have confirmed the new account can log in and elevate privileges, disable direct root login over SSH entirely. An attacker now needs two secrets, a username they must guess and a password, rather than one well-known target.
Keep a record of who has accounts on the server, and review it whenever staff change. Old accounts belonging to former colleagues or contractors are a classic back door that nobody remembers creating. Remove accounts promptly when people leave, and never share a single admin login across a team: shared credentials destroy accountability and cannot be revoked for one person. If you inherit a server with unknown accounts, treat the audit as urgent, check authorised SSH keys as well as passwords, and look for accounts with login shells that nobody can explain.
3. Switch SSH to Key Authentication
Password guessing against SSH is constant background noise on the internet. Key-based authentication replaces something you know, which can be guessed or leaked, with a cryptographic key pair that effectively cannot be brute-forced. Generate a key pair on your own computer, install the public key on the server, and verify you can log in with it. Only after that verification should you disable password authentication in the SSH configuration, because disabling it first can lock you out.
Protect the private key with a passphrase and keep it only on devices you control. For a team, each administrator should have their own key, added and removed individually as people join and leave. Consider also changing the SSH port: it does not make the server truly safer, since scanners find open ports quickly, but it dramatically reduces log noise, which makes real attacks easier to spot. Whatever port you choose, document it in your runbook so a colleague is not locked out during an emergency because the number lived only in your head.
4. Configure a Firewall With a Default-Deny Policy
A mail VPS needs only a handful of open ports: SSH for administration, SMTP on ports 25 and 587, IMAP and POP3 over their encrypted ports, and HTTPS if webmail runs on the same machine. Everything else should be closed. Configure the host firewall with a default-deny policy for inbound traffic, then open exactly the services you intend to provide. This limits the damage from software you did not realise was listening, which is more common than most administrators expect on a default install.
- Inbound: SSH (your chosen port), 25 SMTP, 587 submission, 993 IMAPS, 995 POP3S, 443 HTTPS for webmail
- Outbound: generally allow, but watch for unexpected outbound connections from a server that rarely initiates them
- Closed by default: databases, unencrypted mail ports you do not use, panel ports you have disabled, everything not on your list
Test after every change from an external connection, because a firewall mistake can lock you out of SSH or silently break incoming mail. Change one rule at a time and keep a session open through your provider's web console if available, so a bad rule never strands you. Document the intended port list in the same runbook as your other settings; when you later wonder whether a port should be open, the document, not memory, should answer.
5. Install Fail2ban and Tune It for Mail
Even with key authentication and a firewall, attackers will keep trying passwords on your mail services, because IMAP, POP3 and SMTP authentication still accept passwords from the internet. Fail2ban watches the logs for repeated failures and temporarily bans the offending address at the firewall. Install it, enable jails for SSH and for each mail service you run, and set ban thresholds that catch scanners without punishing a forgetful user who mistypes twice. A handful of failures within ten minutes, banned for an hour or more, is a reasonable starting balance.
Tuning and Reviewing Bans
Review Fail2ban's own logs occasionally to understand your attack traffic, and whitelist your office address only if it is genuinely static, since a stale whitelist entry can become someone else's address. Remember that Fail2ban reduces noise and slows attackers; it is not a substitute for strong passwords. Pair it with sensible account policies in the mail software itself. Attackers who cannot make progress quickly usually move on, because the internet offers them millions of softer targets.
6. Enforce TLS Everywhere and Configure It Properly
Unencrypted mail protocols send passwords and message content across networks in plain text. Require TLS for IMAP, POP3 and message submission, and disable plain-text login options on unencrypted ports or close those ports altogether. Obtain a certificate from a public certificate authority, automated free options exist, and configure automatic renewal so an expired certificate never surprises you. Test the renewal, because an expired certificate trains users to click through warnings, which destroys the habit TLS depends on.
For server-to-server SMTP on port 25, TLS is usually opportunistic: your server offers encryption and uses it when the other side supports it. Enable it, publish a proper hostname, and make sure your certificate matches that hostname. Then check your configuration's protocol and cipher settings against current guidance, disabling obsolete protocol versions kept only for compatibility with software long retired. Finally, consider publishing MTA-STS or DANE records once basic TLS is stable; they strengthen encryption with correspondents whose servers check them, and they are a natural second phase rather than a day-one task.
7. Make Sure You Are Not an Open Relay
An open relay accepts mail from anyone and forwards it anywhere. It is the single most damaging mail server misconfiguration: spammers find open relays within hours, your IP address is blocklisted, your legitimate mail stops delivering, and your provider may suspend the server. Test your configuration deliberately. Your server should accept outbound mail only from authenticated users or trusted local processes, accept inbound mail only for domains you host, and reject everything else. Run an external open-relay check after any change to relay settings, not just at installation.
Pay special attention to web applications on the same server. A contact form or an old script that sends mail without authentication, or that lets visitors control the recipient address, can turn your server into a spam source just as effectively as a relay setting. Keep such applications updated, use authenticated SMTP for their sending, and restrict which local accounts may submit mail. If the server does not need a local submission path for web apps at all, close it. Every sending path you do not need is a path an attacker will eventually find.
8. Publish and Maintain SPF, DKIM and DMARC
Authentication records protect your domain rather than the server itself, but a hardening guide would be incomplete without them, because a spoofed domain causes real damage and undermines the trust your server builds. Publish an SPF record listing exactly the servers allowed to send for your domain, sign outbound mail with DKIM using a key of at least 2048 bits, and publish a DMARC policy that moves from monitoring to enforcement once your legitimate sources are all covered. Keep an inventory of every service that sends as your domain, marketing platforms, invoicing tools and helpdesks, so the records stay accurate as the business changes.
Rotate DKIM keys periodically and remove records for services you stop using. Stale SPF entries pointing at a decommissioned server are more than untidy: if that address is reassigned, someone else may gain the ability to send authenticated mail as your domain. Treat DNS changes with the same care as server changes, recording what changed, why, and who requested it. Our dedicated SMTP email server plans include SPF, DKIM, DMARC, MX and reverse DNS set up for you, which removes this whole category of error for senders who would rather not manage it themselves.
9. Harden the Mail Software Itself
Beyond relay rules, review the mail server's own settings with a least-privilege mindset. Disable protocol features you do not use, such as the VRFY and ETRN commands, which help strangers enumerate accounts or probe the server. Set sensible size limits for messages and mailboxes so a single user or attacker cannot fill the disk. Configure rate limits for authentication attempts and for outbound sending per account, so one compromised mailbox cannot blast out a campaign before you notice. One hijacked account is an incident; one hijacked account that sent a huge volume overnight is a reputation catastrophe.
Run mail services with the minimum privileges they need, keep configuration files readable only by the appropriate users, and check file permissions after restores or migrations, which are notorious for loosening them. If your stack supports it, separate roles as you grow: the machine accepting inbound mail does not have to be the one storing mailboxes or sending campaigns. Separation limits what a single compromised component can reach, and it makes each part easier to reason about and to rebuild.
10. Turn On Logging and Actually Monitor It
A secure server is a watched server. Ensure mail, authentication and system logs are enabled with enough retention to investigate an incident discovered late, at least a few weeks, stored within your disk budget. Then look at them. A weekly skim of authentication failures, queue volumes and delivery errors catches most problems while they are small: a mailbox suddenly sending at 3 a.m., a queue growing for one destination, a login success from a country nobody in your company visits.
- Daily automated summary of messages sent per account, with alerts on unusual spikes
- Alerts for queue length, disk space above 80 per cent, and failed services
- Login reports highlighting successful authentications from new locations
- Blocklist checks for your IP addresses, run automatically and alerted
Centralising logs onto a second system is better still, because an attacker who controls the server can edit local logs. Even a simple arrangement that forwards key logs elsewhere, or emails you a daily summary, gives you evidence that survives the server itself. Monitoring converts hardening from a one-off project into an ongoing state: without it, you will learn about compromises from your customers or your provider instead of from your own systems.
11. Back Up Like You Expect to Restore
Backups belong in a security guide because ransomware, disk failure and administrator error do not care how good your firewall is. Back up mailbox data, mail configuration, certificates and user databases, automatically, on a schedule, to storage outside the VPS itself. Encrypt backups that leave the server, and restrict who can access them, since a backup of a mail server is a copy of everyone's correspondence. Keep several generations so you can restore to a point before a compromise or corruption began, not merely to last night.
Test Your Restores
Then test a restore. A backup that has never been restored is a hope, not a plan. Once or twice a year, rebuild the service from your backups in a test environment and time how long it takes. That exercise reveals missing configuration files, undocumented manual steps and credentials that exist only on the broken server. Write the restore procedure down as you go. During a real incident you will be tired and hurried, and the runbook you wrote calmly is the difference between an outage of hours and an outage of days.
12. Reduce the Attack Surface: Remove What You Do Not Need
Every installed package and running service is code an attacker can target and you must patch. Audit a new VPS for software you will never use: extra web servers, unused database engines, compilers, file-sharing services and sample applications from the base image. Remove or disable them. Development tools in particular do not belong on a production mail server; build and test elsewhere. The smaller the installed base, the shorter your patch list and the fewer surprises in your open-port scans.
Repeat the audit after major changes and at least annually. Software accumulates: a tool installed for one migration, a panel module enabled for a trial, a test mailbox with a weak password created during troubleshooting. Keep a simple inventory of what the server runs and why, and question anything on the list that nobody can justify. This discipline also speeds up incident response, because when a vulnerability is announced you can answer immediately whether your server is affected instead of logging in to find out.
13. Secure Webmail and Admin Panels Separately
If webmail or a control panel runs on the server, it becomes your most exposed application: a public login page, written in a large codebase, updated on its own schedule. Keep it patched as aggressively as the operating system, enforce HTTPS with no plain-HTTP fallback, and require strong passwords. Where the software supports it, enable two-factor authentication for administrator access at minimum, and ideally for all users. Restrict panel access by IP address if your administrators work from predictable locations.
Also think about session behaviour and password reset flows, which are frequent weak points. Long-lived sessions on shared computers and reset links that never expire quietly undo good password policies. Encourage users to treat webmail credentials as seriously as banking passwords, because an attacker with one mailbox can reset passwords at many other services that send recovery mail to it. A mail account is a master key to a person's digital life, and your policies should say so plainly.
14. Set Password and Account Policies With Teeth
Require long passphrases rather than short complex strings users write down. Set a sensible minimum length, screen new passwords against known breached lists if your tools allow, and never reuse the mail password for other services, a rule administrators must follow first. Provide a password manager recommendation to staff; policies that ignore human behaviour get quietly circumvented. When an account shows signs of compromise, force a reset, review its sent mail and login history, and check for forwarding rules or filters the attacker may have added to keep access after the password change.
Dormant accounts deserve special suspicion. Disable mailboxes for people who have left, archive their data according to policy, and delete them on schedule. An unused account that nobody watches is the perfect vehicle for spam: the sending looks legitimate because it is, until you trace it to a mailbox whose owner left last year. A quarterly account review, comparing mailboxes against your staff and client list, is dull work that prevents exciting incidents.
15. Write an Incident Plan Before You Need It
The last step is paperwork, and it is the one that saves you when all others fail. Write a short plan: who to call, how to reach the provider's support team, how to snapshot the server for evidence, how to reset all credentials, how to switch sending to a backup service, and who communicates with affected customers. Store the plan somewhere that does not depend on the mail server working. Decide in advance who has authority to take the server offline, because that argument should not happen during an attack.
After any incident, hold a brief review. What was the entry point, which step on this list would have prevented or detected it, and what will you change? Feed the answers back into your configuration and this checklist. Security hardening is a loop, not a destination: each of the fifteen steps is simple, but together, maintained over time, they make your server a hard, well-watched target that most attackers will abandon for easier prey.
Conclusion: Hardening Is a Habit, Not a Project
None of these fifteen steps requires exotic tools or a security department. Updates, keys, a firewall, Fail2ban, TLS, closed relays, authentication records, monitoring and tested backups cover the overwhelming majority of real-world mail server compromises. What they require is completeness and upkeep: do all of them, then keep doing the recurring ones. If you would rather start from a platform where the server is provisioned, authenticated and maintained for you, look at our dedicated SMTP email server plans, or choose a VPS from our range and work through this checklist on day one: your future self, reading calm logs instead of incident reports, will thank you.