DEV Community

Cover image for Locking Down Your Servers: A Developer's Guide to Server Security & Hardening
Athreya aka Maneshwar
Athreya aka Maneshwar

Posted on

6 2 2 2 2

Locking Down Your Servers: A Developer's Guide to Server Security & Hardening

In the digital battleground, your server is both a fortress and a target.

Whether you're managing a cloud instance, an on-prem machine, or a hybrid infrastructure, securing your servers is a non-negotiable responsibility.

This guide breaks down the essentials of server security and hardening with practical steps, tools, and a few JavaScript snippets to reinforce concepts programmatically.

Why Server Security Matters

Servers hold your applications, databases, and critical business logic.

A compromised server can lead to data breaches, unauthorized access, and financial losses.

The goal of server security is to minimize vulnerabilities while ensuring high availability and performance.

Fundamentals of Server Security

1. Keep Your System Updated

Security vulnerabilities are constantly being discovered in operating systems, databases, and software dependencies.

Keeping your system updated ensures patches are applied before attackers can exploit them.

Automate Updates (Linux):

sudo apt update && sudo apt upgrade -y
Enter fullscreen mode Exit fullscreen mode

Automate Updates (Node.js Example):

const { exec } = require('child_process');
exec('sudo apt update && sudo apt upgrade -y', (err, stdout, stderr) => {
    if (err) console.error(`Error: ${stderr}`);
    else console.log(`Updated Successfully: ${stdout}`);
});
Enter fullscreen mode Exit fullscreen mode

2. Implement Access Controls

Who has access to your server matters.

Limit access using role-based authentication and enforce strong password policies.

Restrict SSH Access

  • Disable root login (PermitRootLogin no in /etc/ssh/sshd_config).
  • Change the default SSH port.
  • Use SSH key-based authentication.
sudo nano /etc/ssh/sshd_config
# Change Port 22 to a custom number (e.g., 2202)
# Set PermitRootLogin no
Enter fullscreen mode Exit fullscreen mode

Restart SSH:

sudo systemctl restart sshd
Enter fullscreen mode Exit fullscreen mode

Enforce Strong Passwords (Node.js Example)

const bcrypt = require('bcrypt');
const saltRounds = 12;
const userPassword = 'SuperSecure123!';

bcrypt.hash(userPassword, saltRounds, (err, hash) => {
    if (err) console.error(err);
    else console.log(`Hashed Password: ${hash}`);
});
Enter fullscreen mode Exit fullscreen mode

3. Use Firewalls & Intrusion Detection Systems

Firewalls control inbound and outbound traffic, blocking unauthorized access.

Setting Up UFW (Uncomplicated Firewall) on Linux:

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 2202/tcp  # Replace with your SSH port
sudo ufw enable
Enter fullscreen mode Exit fullscreen mode

Monitor Unauthorized Access (JavaScript Example using Fail2Ban Logs)

const fs = require('fs');
const logPath = '/var/log/fail2ban.log';

fs.watch(logPath, (event, filename) => {
    if (event === 'change') {
        console.log(`Security alert: ${filename} updated. Check for possible intrusions!`);
    }
});
Enter fullscreen mode Exit fullscreen mode

4. Encrypt Data in Transit and at Rest

Encryption prevents unauthorized users from reading sensitive data.

  • Use TLS/SSL for Web Applications: Let’s Encrypt provides free SSL certificates.
  • Encrypt Database Fields: Store sensitive user data in an encrypted format.

Example: Encrypt User Data Before Storing (Node.js + Crypto)

const crypto = require('crypto');
const secretKey = 'your-very-secure-key';

function encryptData(data) {
    const cipher = crypto.createCipher('aes-256-ctr', secretKey);
    return cipher.update(data, 'utf8', 'hex') + cipher.final('hex');
}

const encryptedValue = encryptData('Sensitive User Info');
console.log(`Encrypted Data: ${encryptedValue}`);
Enter fullscreen mode Exit fullscreen mode

5. Monitor Logs & Set Up Alerts

Tracking server logs helps detect suspicious activities in real time.

Enable Logging with journalctl (Linux)

journalctl -u sshd --no-pager --since "1 hour ago"
Enter fullscreen mode Exit fullscreen mode

Automate Alerts (Node.js)

const { exec } = require('child_process');
exec('grep "Failed password" /var/log/auth.log | tail -n 5', (err, stdout) => {
    if (stdout) console.log(`ALERT! Failed SSH Attempts:\n${stdout}`);
});
Enter fullscreen mode Exit fullscreen mode

Server Hardening Checklist

Task Status
Disable unnecessary services
Change default ports
Set up SSH key authentication
Install fail2ban
Configure firewall rules
Encrypt sensitive data
Automate security updates
Implement MFA
Regularly audit logs
Backup data frequently

Server security is an ongoing process, not a one-time fix.

By continuously patching vulnerabilities, restricting access, encrypting data, and monitoring activity, you can significantly reduce the risk of attacks.

Start implementing these best practices today, and keep your fortress safe!


I’ve been working on a super-convenient tool called LiveAPI.

LiveAPI helps you get all your backend APIs documented in a few minutes

With LiveAPI, you can quickly generate interactive API documentation that allows users to execute APIs directly from the browser.

image

If you’re tired of manually creating docs for your APIs, this tool might just make your life easier.

Image of Datadog

Create and maintain end-to-end frontend tests

Learn best practices on creating frontend tests, testing on-premise apps, integrating tests into your CI/CD pipeline, and using Datadog’s testing tunnel.

Download The Guide

Top comments (1)

Collapse
 
smjburton profile image
Scott • Edited

1) Keep Your System Updated

If you're using a Debian-based Linux distribution, you can also set up unattended-upgrades.

5) Monitor Logs & Set Up Alerts

A good way to do this is using Prometheus/Grafana/Loki to visualize your logs to make it easier to review. You could also set up something like ntfy or Gotify to alert you about unauthorized access.

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

If you found this article helpful, please give a ❤️ or share a friendly comment!

Got it