Server security is one of the most critical aspects of infrastructure management, yet many organizations overlook fundamental hardening practices until a security incident occurs. This article covers the most common server threats—cryptominers, credential harvesting, and weak SSH configuration—along with practical prevention, detection, and response strategies.
Understanding the Threat Landscape
What Makes Servers Attractive Targets?
Servers are targeted by attackers for several reasons:
| Target | Why It’s Valuable | Common Exploit |
|---|---|---|
| CPU/RAM Resources | Mining cryptocurrency, running botnets, distributed attacks | Weak SSH, unpatched software, exposed services |
| Credentials & Secrets | Access to cloud accounts, databases, payment systems | Compromised SSH keys, environment variables, credential files |
| Network Access | Lateral movement to other systems, internal networks | Poorly segmented networks, trust-based authentication |
| Data | Ransomware, data theft, compliance violations | Unencrypted storage, weak file permissions, no backup isolation |
The common thread: attackers exploit weak authentication, poor configuration, and lack of monitoring.
Threat #1: Cryptominers and Resource Exhaustion
What Are Cryptominers?
Cryptominers are malicious programs that use a compromised server’s CPU and GPU to mine cryptocurrency without authorization. The attacker profits while your server pays the costs: increased electricity, reduced performance, and service degradation.
How They Impact Your Services
When a cryptominer runs unchecked:
| Impact | Consequence |
|---|---|
| High CPU usage | Web applications become slow, timeouts increase, users experience poor performance |
| High memory consumption | Linux OOM (Out-of-Memory) Killer terminates processes, including critical services |
| Disk I/O stress | Database queries slow down, file access becomes bottleneck |
| Network congestion | Mining pools communicate constantly, consuming bandwidth |
| Service crashes | Important services like databases, web servers, or application servers restart unexpectedly |
Real-World Example
A Gitea (Git hosting) server experiencing repeated 502 Bad Gateway errors was investigated. The root cause was not a configuration issue, but a cryptominer consuming all available memory:
Cryptominer active
↓
RAM + Swap exhausted
↓
Linux OOM Killer triggers
↓
Gitea service killed
↓
Nginx cannot connect to upstream
↓
502 Bad Gateway returned to users
Threat #2: Credential Harvesting and Secret Theft
Beyond Mining: The Bigger Threat
Many malware packages don’t just mine cryptocurrency—they also actively hunt for credentials and secrets on the infected server. This is often a more serious threat than the mining itself.
What Attackers Look For
Malicious scripts typically attempt to steal:
Environment variables
SSH private keys
AWS/GCP/Azure credentials
Database passwords
API tokens and API keys
JWT secrets
Application configuration
SMTP credentials
SSH authorized_keys
Bash history
The Credential Harvesting Pipeline
Malware infects server
↓
Script enumerates credential sources
↓
Collects secrets and metadata
↓
Sends data to attacker's C2 server
↓
Attacker gains persistent access
↓
Lateral movement to other systems
↓
Cloud account compromise
↓
Data breach / ransomware deployment
Once credentials are harvested, the attacker has a backdoor into your infrastructure that persists even after you remove the original malware.
Threat #3: Weak SSH Configuration
The Foundation of Server Access
SSH (Secure Shell) is the primary method of accessing and administering servers. Weak SSH configuration is often the entry point for attackers.
Dangerous Default Settings
| Configuration | Risk Level | Problem |
|---|---|---|
PermitRootLogin yes | 🔴 Critical | Allows direct root login, bypassing normal access controls |
PasswordAuthentication yes | 🔴 Critical | Vulnerable to brute-force attacks; passwords can be guessed or stolen |
X11Forwarding yes | 🟠 High | Allows graphical application tunneling; potential for privilege escalation |
AllowUsers * | 🟠 High | No restriction on which users can connect via SSH |
Port 22 | 🟡 Medium | Standard SSH port is heavily scanned; increases brute-force attempts |
LoginGraceTime 120 | 🟡 Medium | Long timeout window for authentication; more time for attacker to guess credentials |
Attack Flow with Weak SSH
Attacker scans internet for SSH on port 22
↓
Finds server with PermitRootLogin yes
↓
Launches brute-force attack against root
↓
Guesses weak password or finds compromised password
↓
Logs in as root
↓
Downloads and runs malware script
↓
Server fully compromised
Prevention: Hardening Your Server
Step 1: Secure SSH Configuration
Create a non-root user for administration:
sudo useradd -m -s /bin/bash deploy
sudo usermod -aG sudo deploy
Generate SSH key pair (on your local machine):
ssh-keygen -t ed25519 -f ~/.ssh/deploy_key -C "deploy@production"
Add the public key to the server:
# On the server, as the deploy user:
mkdir -p ~/.ssh
echo "your-public-key-here" >> ~/.ssh/authorized_keys
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys
Modify SSH configuration (/etc/ssh/sshd_config):
# Disable root login
PermitRootLogin no
# Use key-based authentication only
PasswordAuthentication no
PubkeyAuthentication yes
# Limit authentication attempts
MaxAuthTries 3
MaxSessions 5
# Use SSH key types only (disable weaker methods)
HostKeyAlgorithms ssh-ed25519
# Disable X11 forwarding
X11Forwarding no
# Restrict root access even more
PermitEmptyPasswords no
AllowUsers deploy
# Increase grace time to detect active attacks faster
LoginGraceTime 20
Test SSH configuration before reloading:
sudo sshd -t
If no errors, reload SSH:
sudo systemctl reload ssh
Verify the deploy user can login before logging out of root:
ssh -i ~/.ssh/deploy_key deploy@your-server
sudo whoami # Should return "root"
Step 2: Firewall on Multiple Layers
Use both cloud firewall and host firewall for defense-in-depth.
Cloud Firewall (DigitalOcean, AWS, GCP, etc.):
Allow 22/TCP from your office IP
Allow 80/TCP from 0.0.0.0/0 (HTTP)
Allow 443/TCP from 0.0.0.0/0 (HTTPS)
Deny all else
Host Firewall (UFW – Uncomplicated Firewall):
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 22/tcp
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw enable
Step 3: Limit Exposed Services
Only expose ports that absolutely need to be public.
| Service | Port | Should Be Public? |
|---|---|---|
| SSH | 22 | Yes (but restricted by IP) |
| HTTP | 80 | Yes |
| HTTPS | 443 | Yes |
| Gitea Web | 3000 | Yes (via HTTPS) |
| Gitea SSH | 2222 | Restricted |
| MySQL | 3306 | No (internal only) |
| PostgreSQL | 5432 | No (internal only) |
| Redis | 6379 | No (internal only) |
| Memcached | 11211 | No (internal only) |
Use iptables rules to restrict internal services:
# Allow MySQL only from localhost and internal subnet
sudo iptables -A INPUT -p tcp --dport 3306 -s 127.0.0.1 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 3306 -s 10.0.0.0/8 -j ACCEPT
sudo iptables -A INPUT -p tcp --dport 3306 -j DROP
Step 4: Principle of Least Privilege
Run each service as a dedicated non-root user with minimal permissions.
# Example: Gitea should run as 'git' user, not 'root'
sudo systemctl status gitea
# Should show: User=git
# Example: Nginx should run as 'www-data', not 'root'
ps aux | grep nginx
# Should show master process as root, worker processes as www-data
Step 5: Disable Unnecessary Services
Audit running services:
sudo systemctl list-units --type=service --state=running
Disable services you don’t need:
# Example: If you don't need Dovecot (email), disable it
sudo systemctl disable dovecot
sudo systemctl stop dovecot
Each service is a potential entry point. Fewer services = smaller attack surface.
Step 6: Keep Everything Updated
Set up automatic security updates:
sudo apt install unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades
Manually check for updates periodically:
sudo apt update
sudo apt upgrade
Ensure these are updated:
- Operating system kernel
- Web server (Nginx, Apache)
- Database server (MySQL, PostgreSQL)
- Programming runtimes (PHP, Node.js, Python)
- Application-specific software
Step 7: Never Store Secrets in Code or Files
Do NOT commit to Git:
passwords
API keys
private SSH keys
JWT secrets
database credentials
AWS/GCP credentials
Instead, use environment variables or secret management:
# .env file (add to .gitignore)
DATABASE_PASSWORD=secure_password_here
API_KEY=your_api_key_here
# Or use a secrets manager
# Vault, 1Password, AWS Secrets Manager, etc.
In your application code:
# Python example
import os
db_password = os.getenv('DATABASE_PASSWORD')
# Never do this:
# db_password = "secure_password_here" # WRONG!
Detection: Identifying Compromised Servers
Daily Health Checks
Check memory and disk usage:
free -h # Memory usage
df -h # Disk usage
top -b -n1 # Top processes
Watch for:
RAM consistently > 80% usage
Swap increasing constantly
Disk > 90% full
Monitor Top Processes
ps aux --sort=-%mem | head -20
ps aux --sort=-%cpu | head -20
Be suspicious of:
xmrig,miner,cryptominer, or unknown binaries- Processes running from
/tmp,/dev/shm, or/var/tmp - Processes with obfuscated names
- Child processes spawning many instances
Check Network Connections
sudo ss -tpn | grep ESTABLISHED
sudo ss -tpn | grep LISTEN
Be suspicious of:
- Outbound connections to unknown IPs
- Connections to mining pools (typically high-numbered ports)
- Connections to unusual countries/regions
- Long-lived idle connections
Examine Cron Jobs
Root cron:
sudo crontab -l
User cron (e.g., git user):
sudo crontab -u git -l
System cron directories:
ls -la /etc/cron.d/
ls -la /etc/cron.daily/
ls -la /etc/cron.hourly/
Be suspicious of cron entries containing:
curl ... | bash
wget ... | sh
base64 -d | bash
/tmp/...
/dev/shm/...
@reboot
Check SSH Access Logs
sudo grep -E "Accepted|Failed|Invalid user" /var/log/auth.log | tail -100
Be suspicious of:
- Login attempts from unusual IPs
- Failed login attempts in high volumes
- Successful root logins (if PermitRootLogin is still enabled)
- Logins at unusual times
Search for Persistence Mechanisms
Systemd services:
sudo systemctl list-unit-files --state=enabled | grep -v "^enabled-runtime"
Look for services with suspicious names.
Cron jobs (as covered above).
Startup scripts:
ls -la /etc/init.d/
ls -la /etc/rc*.d/
SSH hooks:
cat ~/.ssh/authorized_keys
# Look for commands before the SSH key:
# command="..." ssh-rsa AAAA...
Check Disk for Hidden Files
# Find recently modified files
sudo find / -type f -mtime -1 2>/dev/null | head -20
# Find executables in /tmp or /dev/shm (very suspicious)
sudo find /tmp /dev/shm -type f -executable 2>/dev/null
# Look for hidden directories
sudo find / -name ".*" -type d 2>/dev/null | grep -E "(tmp|dev|var|home)" | head -20
Response: If You Suspect Compromise
Step 1: Isolate the Server
If you have confirmed malware, isolate the server immediately:
# Block all outbound traffic except DNS
sudo iptables -P OUTPUT DROP
sudo iptables -A OUTPUT -p tcp --dport 53 -j ACCEPT
sudo iptables -A OUTPUT -p udp --dport 53 -j ACCEPT
sudo iptables -A OUTPUT -p tcp --dport 443 -j ACCEPT # HTTPS for updates
Step 2: Collect Evidence
Before taking action, preserve logs and evidence for analysis:
# Copy logs
sudo cp -r /var/log ~/incident-logs/
sudo cp -r /root/.bash_history ~/incident-logs/
sudo crontab -l > ~/incident-crontab.txt
# List running processes
ps aux > ~/incident-processes.txt
# Network connections
sudo netstat -tlnp > ~/incident-network.txt
Step 3: Kill Malicious Processes
# Kill by process name (carefully!)
sudo pkill -KILL -f 'xmrig'
sudo pkill -KILL -f 'miner'
sudo pkill -KILL -f 'cryptominer'
# Or by specific path
sudo pkill -KILL -f '/tmp/.syslogd'
Verify processes are gone:
ps aux | grep -E 'xmrig|miner|cryptominer' | grep -v grep
# Should return nothing
Step 4: Remove Persistence
Remove malicious cron jobs:
sudo crontab -e # Remove suspicious entries
sudo crontab -u git -e # For user 'git'
Remove malicious systemd services:
sudo systemctl disable malicious-service
sudo rm /etc/systemd/system/malicious-service.service
sudo systemctl daemon-reload
Step 5: Rotate ALL Credentials
This is critical because the attacker may have harvested your secrets:
SSH keys (generate new pairs)
Root password
Database passwords
API tokens
Application secrets
JWT secrets
SMTP credentials
Cloud provider credentials
Step 6: Consider Rebuilding vs. Recovery
| Option | When to Use | Pros | Cons |
|---|---|---|---|
| Clean & Monitor | Minor incident, contained scope | Faster recovery, minimal disruption | May miss hidden persistence |
| Rebuild from Backup | Moderate incident, trusted backups | More thorough, fresh start | Data loss possible, requires downtime |
| Rebuild from Scratch | Major incident, credential compromise | Most secure, guaranteed clean | Longest downtime, most effort |
For serious compromises (credential harvesting, persistent backdoors), rebuilding from a clean image is safer than attempting to clean in-place.
Long-Term Monitoring and Maintenance
Set Up Automated Monitoring
Use a monitoring tool (Prometheus, Zabbix, New Relic, Datadog, etc.) to track:
| Metric | Alert Threshold |
|---|---|
| CPU usage | > 80% for 5 minutes |
| Memory usage | > 85% for 5 minutes |
