Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversHalloween DealsAmazon USHalloween week deals: useful picks before month-endAmazon US: current deals, useful picks and tech finds.Check DealsSlow PC?RecommendedPC slow today? Run a repair scan before it gets worseResolve common Windows issues and optimize system performance.Scan Now×
FREEDOM251

Freedom251 › Blog › cloud security

My Linux VPS Was Hacked: A Safe Recovery and Hardening Runbook

By Freedom251 Team · · 11 min read

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Contain the server first, preserve evidence, then assume every secret reachable from it is exposed. For a VPS where an attacker obtained root or administrative control, the dependable recovery path is to isolate it, rotate credentials from a trusted device, preserve the information you may need, and rebuild from a trusted image or reproducible configuration. Restore only reviewed data and code, then reconnect behind restrictive controls and monitor closely.

What to do in the first hour

1. Isolate the VPS without destroying useful evidence

Use your provider’s firewall, security group, virtual network, or control-panel power options to remove public exposure. Block inbound traffic except the minimum management path needed for investigation. Stop nonessential services, but avoid immediately deleting the disk or reinstalling the operating system if an investigation, insurance claim, legal hold, or regulatory review may be required.

As an Amazon Associate I earn from qualifying purchases.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Coordinate isolation with the people responsible for adjacent systems. An attacker may have moved from the VPS into a database, CI/CD account, object storage, DNS account, or another host. Use an out-of-band communication channel if the compromised environment could be monitoring email, chat, or ticketing systems.

  • Record the UTC time of every action.
  • Save provider snapshots or disk images before destructive changes when practical.
  • Preserve authentication, web-server, database, kernel, firewall, and application logs.
  • Record suspicious IP addresses, usernames, commands, processes, services, scheduled jobs, and outbound connections.
  • Capture a process list, listening sockets, mounted filesystems, active network connections, and provider audit events if those records are available.

A snapshot taken after compromise is evidence of the incident, not automatically a clean image for restoration. Keep the original copy read-only and restrict who can access it.

#1 Best Overall

2. Protect the provider and identity plane

Before changing files on the VPS, sign in from a trusted, updated device and secure the provider account, organization account, identity provider, VPN, bastion, and source-control accounts that can reach the host. If the attacker can still use a provider API token or a stolen administrator session, a rebuilt server can be compromised again immediately.

  • Reset provider-console and organization passwords.
  • Re-enroll or replace multi-factor authentication on privileged accounts.
  • Revoke cloud API tokens, temporary credentials, automation tokens, and personal access tokens.
  • Review provider IAM users, roles, service accounts, firewall changes, snapshots, new instances, billing events, and audit logs.

Should you clean the VPS or rebuild it?

When root or equivalent administrative control was obtained, rebuilding is normally the only practical way to regain high confidence that persistence is gone. An attacker with root may have changed system binaries, kernel modules, user accounts, SSH authorization, sudo rules, cron jobs, systemd units, application files, logs, and security tools. Removing the visible malware does not prove that a hidden account, altered binary, or startup hook is absent.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

“Rebuild systems based on prioritization of critical services (e.g., health and safety or revenue-generating services), using pre-configured standard images, if possible.” — Cybersecurity and Infrastructure Security Agency, StopRansomware Guide.

DigitalOcean, for example, describes a rebuild as wiping a Droplet’s disk and replacing it with a selected image, and lists suspected compromise as a reason to rebuild. The exact labels and behavior differ by provider, so verify what happens to attached volumes, snapshots, reserved addresses, backups, and metadata before confirming the operation.

Recovery path Eradication confidence Evidence retained Downtime When it fits
Clean rebuild High when the image and build inputs are trusted Requires a separate forensic snapshot or copy Usually higher initially, but predictable Root compromise, unknown persistence, or an untrusted operating system
In-place repair Limited; hidden persistence can remain Best access to the live system’s context Potentially lower Minor, well-bounded incident with strong evidence that administrative control was not obtained
Provider recovery environment Depends on whether the installed disk is reused or replaced Useful for copying logs and data before a rebuild Varies by provider and region Lost SSH access, disk inspection, or controlled data extraction

Choose in-place repair only when you can bound the incident, prove that privileged control was not lost, and accept that eradication confidence is lower. If the entry point or duration is uncertain, treat the host as fully compromised, preserve a forensic copy, and rebuild.

Rotate every secret reachable from the host

Assume a root-level attacker could read any secret stored in files, environment variables, process arguments, shell history, memory, mounted volumes, backups, or deployment tooling. Lack of evidence that a token was used is not evidence that it remained private.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Secret or access class Required action Priority
Provider and identity accounts Reset passwords, replace MFA, revoke sessions, remove unknown users and keys, and review IAM activity. First
SSH keys Revoke authorized keys on the old host and replace keys used by administrators, automation, bastions, and deployment systems. First
Cloud and API tokens Revoke tokens in application files, environment files, CI/CD variables, scripts, and local credential stores; issue new, narrowly scoped tokens. First
Local and sudo passwords Replace passwords for all local users, service accounts, and privileged identities; delete accounts that are not required. Before reconnection
Database credentials Change database passwords, rotate connection strings, and review database users, grants, and audit records. Before data restore
Application and webhook secrets Replace session-signing keys, encryption keys where applicable, webhook secrets, OAuth client secrets, and payment or messaging credentials. Before application launch
VPN, bastion, and deployment access Revoke old certificates, deploy keys, agent credentials, and automation identities; issue replacements from a trusted workstation. Before management access

Rotate in this order: provider and identity plane, clean replacement access, application and data-plane credentials, then customer-managed encryption keys where applicable. Coordinate key changes with applications so that old and new values do not create an accidental outage. Invalidate web sessions and refresh tokens if application secrets or user data may have been exposed.

Build a clean replacement VPS

  1. Select a supported image. Use a current, supported distribution release from the provider or an image you maintain and can verify. Do not clone the compromised disk as the production base.
  2. Apply updates before exposure. Boot with networking restricted, install security updates, remove unnecessary packages, and reboot if the kernel or core libraries require it.
  3. Create a non-root administrator. Add one named account with narrowly scoped sudo rights. Use a newly generated SSH key from a trusted device and verify its fingerprint through a separate channel.
  4. Disable weak SSH access. Disable direct root login and password authentication where feasible. Permit SSH only from a management IP range, VPN, bastion, or provider firewall. Keep a tested recovery-console path before closing the public route.
  5. Configure host and provider firewalls. Allow only required service ports. Separate administrative access from public application traffic, and document every rule.
  6. Install only trusted software. Recreate packages from a recorded manifest or build script. Verify repositories, package signatures, container images, and release artifacts.
  7. Replace certificates and keys. Issue new TLS certificates, host keys, service certificates, and application signing or encryption material where the old host could read them.
  8. Record the build. Capture the image identifier, package versions, firewall policy, SSH settings, users, service definitions, and configuration changes in infrastructure-as-code or a version-controlled runbook.

A clean build should be reproducible by another administrator without relying on undocumented commands typed during the emergency.

Restore data and code selectively

Restore application code from a trusted repository, signed release artifact, or a known-good build made before the incident. Review the commit history and release process for unauthorized changes before deployment.

For data, scan and review before importing it into the replacement. Pay particular attention to records that can create executable behavior, such as uploaded PHP, JavaScript, template, plugin, shell, or serialized files. Check for unexpected administrator accounts, modified permissions, embedded scripts, and files with recent timestamps that do not match the application’s normal deployment pattern.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Do not copy these items blindly

  • /etc or other system configuration trees from the compromised operating system.
  • Unknown executables, shared libraries, kernel modules, package caches, or temporary directories.
  • Home-directory SSH authorization files, private keys, shell histories, and startup files.
  • Cron entries, systemd units, timers, init scripts, service overrides, and supervisor configurations.
  • Web-server configuration or plugins that have not been compared with a trusted baseline.
  • Container images, build caches, CI/CD artifacts, and scripts whose provenance is uncertain.

Recreate system configuration manually or from reviewed templates. Import only the minimum data needed, and retain the original disk separately for investigation.

Find persistence and the initial entry point

Recovery is incomplete until you understand how access occurred and close that route. Review the period before the earliest suspicious event as well as the period after it; attackers often establish multiple footholds.

Identity and access review

  • Compare local users, groups, sudo rules, password hashes, and account creation dates with your inventory.
  • Inspect every authorized_keys file and provider-managed key.
  • Review SSH, VPN, provider IAM, source-control, and CI/CD authentication logs for unfamiliar locations, user agents, and times.
  • Revoke dormant accounts, old deploy keys, and service identities that no longer have a documented owner.

Persistence and execution review

  • List listening sockets, running processes, loaded modules, services, timers, cron jobs, and shell startup files.
  • Search for recently modified binaries, scripts, web roots, upload directories, and configuration files.
  • Check web-server routes for web shells and unrecognized PHP or other executable files.
  • Review firewall rules, DNS changes, reverse proxies, container definitions, and scheduled automation.
  • Look for unexplained outbound connections, new domains, cryptocurrency-mining indicators, data transfers, and unusual resource or billing activity.

Patch the vulnerable internet-facing software, remove exposed management interfaces, correct unsafe permissions, and revoke credentials stored in application environment files. If no single entry point can be proven, inspect other systems that shared credentials, dependencies, networks, or deployment pipelines.

If SSH access is gone

Do not keep guessing passwords against the public SSH endpoint. Use the provider’s out-of-band console, serial console, rescue system, or recovery environment. The workflow varies, but the safe pattern is consistent:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  1. Open the provider’s recovery-console or rescue option and authenticate through the secured provider account.
  2. Take a snapshot or forensic copy if required before changing the disk.
  3. Mount the filesystem read-only first when the provider supports it; copy logs and configuration evidence to protected storage.
  4. Reset access by installing a newly generated public key for a clean administrative account, or use the provider’s documented temporary root-password procedure.
  5. Test key-based access from a trusted workstation, then remove temporary passwords and revoke compromised keys.
  6. Use the recovered access to extract required data and rebuild rather than treating console access as proof that the host is clean.

Filenames and service-restart commands differ among distributions. Follow the provider’s current recovery documentation and keep a second management path available while changing SSH settings.

Reconnect in stages and monitor the cutover

Bring services back in priority order on a clean network path. Start with the smallest necessary management and health-check surface, then add databases, internal services, and public endpoints after each dependency has been validated.

  • Confirm that only reviewed code, data, images, and configuration are connected.
  • Verify DNS records, TLS certificates, firewall rules, service accounts, and outbound allow-lists.
  • Watch authentication, process, file-integrity, DNS, outbound-network, provider-IAM, and billing activity continuously after cutover.
  • Set alerts for new users, SSH-key changes, privilege changes, unexpected listening ports, disabled logging, and unusual egress.
  • Keep the old disk or snapshot according to incident-response, legal, insurance, and retention requirements.
  • Document indicators of compromise, actions taken, recovery times, and decisions that should change the next runbook.

Have a rollback plan that returns traffic to a known state without reintroducing the compromised disk or its credentials.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Hardening controls for the replacement

Management access

Use SSH keys rather than passwords, a named non-root account with limited sudo, and a restricted management network. Protect provider, VPN, bastion, source-control, CI/CD, and administrative accounts with phishing-resistant MFA, such as a FIDO2 security key. Hardware MFA protects the account used to reach the VPS; it does not clean a compromised operating system.

Patching and software supply chain

Enable unattended security updates where they are appropriate for the workload, or operate a scheduled patch process with maintenance windows and rollback. Pin and review dependencies, verify package and container sources, and rebuild images when a base image or critical library changes.

Network and service minimization

Expose only required ports, bind administrative services to private interfaces when possible, and separate public web traffic from databases and internal control planes. Remove unused daemons and default accounts. Restrict outbound traffic for workloads that do not need unrestricted internet access.

Logging and detection

Send authentication, provider, firewall, application, and system logs to storage the VPS cannot erase. Synchronize time, retain enough history to investigate, and alert on privilege escalation, authentication anomalies, configuration changes, and unexpected egress. File-integrity monitoring is useful only when its baseline and alert destination are protected from the host.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Backups and rebuild capability

Maintain encrypted backups that are offline or otherwise attacker-resistant, with access separated from the production account. Test restoration on a schedule and record how long it takes. Keep a current golden image or infrastructure-as-code template so a rebuild is a routine operation rather than an improvised emergency.

Provider controls belong in the incident plan

Every provider has different recovery-console, snapshot, rebuild, firewall, IAM, and API-token behavior. Document the exact account owners, recovery contacts, MFA methods, permitted administrators, network controls, snapshot retention, backup locations, and escalation process. Include how to recover the provider account if its primary administrator is unavailable.

Review provider activity for newly created instances, changed firewall rules, altered DNS, unexpected snapshots, unusual regions, quota changes, support-ticket activity, and billing spikes. A VPS rebuild that leaves a stolen provider token active is not a completed recovery.

Turn the incident into a repeatable recovery plan

Keep a written checklist that another administrator can execute under pressure. It should include:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
  • Isolation commands and provider-console paths.
  • Evidence preservation, UTC time recording, and retention decisions.
  • Provider-account recovery, MFA replacement, and token revocation.
  • SSH configuration, firewall rules, VPN or bastion requirements, and emergency console access.
  • Golden-image or infrastructure-as-code locations and approved package sources.
  • DNS, certificate, webhook, database, application, and encryption-key replacement steps.
  • Data-validation checks and explicit exclusions for system files, startup state, and unknown executables.
  • Monitoring, alert routing, rollback criteria, and a list of people authorized to reconnect services.
  • Backup restoration tests with measured recovery time and recovery-point objectives.

Exercise the plan on a nonproduction VPS. A checklist that has never been tested is an assumption, not a recovery capability.

How to judge that recovery is complete

  • The compromised VPS is isolated or preserved solely as evidence.
  • Provider, identity, SSH, application, database, deployment, VPN, and encryption secrets have been rotated from trusted devices.
  • The replacement was built from a supported, verified image and a documented process.
  • Only reviewed data and code were restored.
  • The initial access path was patched or closed, and related systems were checked.
  • Administrative access requires strong MFA, key-based SSH, least privilege, and restricted network paths.
  • Logs and alerts are protected from the host, backups have been tested, and a rollback path exists.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

cloud securityhardeningincident responseLinuxserver recoverySSHVPS security

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.