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 • Edited on

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

Hello, I'm Maneshwar. I'm building git-lrc, an AI code reviewer that runs on every commit. It is free, unlimited, and source-available on Github. Star Us to help devs discover the project. Do give it a try and share your feedback for improving the product.

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!


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

git-lrc
*AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.*

Any feedback or contributors are welcome! It's online, source-available, and ready for anyone to use.

⭐ Star it on GitHub:

GitHub logo HexmosTech / git-lrc

Free, Unlimited AI Code Reviews That Run on Commit

git-lrc logo

git-lrc

Free, Unlimited AI Code Reviews That Run on Commit


git-lrc - Free, unlimited AI code reviews that run on commit | Product Hunt

AI agents write code fast. They also silently remove logic, change behavior, and introduce bugs -- without telling you. You often find out in production.

git-lrc fixes this. It hooks into git commit and reviews every diff before it lands. 60-second setup. Completely free.

See It In Action

See git-lrc catch serious security issues such as leaked credentials, expensive cloud operations, and sensitive material in log statements

git-lrc-intro-60s.mp4

Why

  • 🤖 AI agents silently break things. Code removed. Logic changed. Edge cases gone. You won't notice until production.
  • 🔍 Catch it before it ships. AI-powered inline comments show you exactly what changed and what looks wrong.
  • 🔁 Build a habit, ship better code. Regular review → fewer bugs → more robust code → better results in your team.
  • 🔗 Why git? Git is universal. Every editor, every IDE, every AI…




Top comments (3)

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.

Collapse
 
chintan_udani profile image
Chintan Udani

There are some critical things, such as protecting api from xss by giving appropriate headers using helmet, rate limiting apis of products listed on e commerce store, providing input sanitization. Also serialization and deserialization of data to provide extra protection and increase speed of apis

Collapse
 
devh0us3 profile image
Alex P

Hello, why JS 0_o?