0% found this document useful (0 votes)
3 views12 pages

ssh hardening (Copy 2)

This guide provides comprehensive steps to secure an SSH server on Ubuntu 22.04, detailing essential configurations such as disabling root login, enabling key-based authentication, and configuring firewalls. It emphasizes the importance of backups, idle timeouts, and using tools like Fail2Ban for added security. Additionally, it offers best practices for ongoing maintenance and resources for further learning.

Uploaded by

delebritz66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views12 pages

ssh hardening (Copy 2)

This guide provides comprehensive steps to secure an SSH server on Ubuntu 22.04, detailing essential configurations such as disabling root login, enabling key-based authentication, and configuring firewalls. It emphasizes the importance of backups, idle timeouts, and using tools like Fail2Ban for added security. Additionally, it offers best practices for ongoing maintenance and resources for further learning.

Uploaded by

delebritz66
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 12

1.

[Backup SSH Configuration](#1-backup-ssh-configuration)


2. [Disable Root Login](#2-disable-root-login)
3. [Enable Key-Based Authentication](#3-enable-key-based-authentication)
4. [Disable Password Authentication](#4-disable-password-authentication)
5. [Change Default SSH Port](#5-change-default-ssh-port)
6. [Restrict SSH Users](#6-restrict-ssh-users)
7. [Set Idle Timeout](#7-set-idle-timeout)
8. [Configure Firewall for SSH](#8-configure-firewall-for-ssh)
9. [Install and Configure Fail2Ban](#9-install-and-configure-fail2ban)
10. [Audit SSH Configuration](#10-audit-ssh-configuration)
11. [Best Practices and Maintenance](#11-best-practices-and-maintenance)
12. [Resources](#12-resources)

## Introduction

This guide provides step-by-step instructions to harden an SSH server on a Ubuntu


22.04 VPS. SSH (Secure Shell) is a critical service for remote server management
but is often targeted by attackers through brute-force attacks, weak credentials,
or misconfigurations. By following these steps, you’ll learn how to secure SSH,
making it safer for real-world use. Each step includes a description, rationale,
commands, and testing instructions to ensure clarity for beginners.

**Prerequisites**:
- Ubuntu 22.04 VPS with OpenSSH installed (`sudo apt install openssh-server`).
- Root or sudo access.
- Basic Linux command-line knowledge (e.g., editing files with `nano`).
- A client machine to test SSH connections.

**Safety Tip**: Always test changes in a virtual machine (VM) or keep a backup SSH
session open to avoid lockouts.

---

## 1. Backup SSH Configuration

**Description**: Create a backup of the SSH configuration file to restore settings


if misconfigurations occur.
**Why**: SSH changes can disable access to your VPS, especially remotely. A backup
ensures you can recover quickly.
**Steps**:
1. Copy the configuration file:
```bash
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.bak

Verify the backup exists:


bash

ls /etc/ssh/sshd_config.bak

Test: Check that the backup is readable:


bash

cat /etc/ssh/sshd_config.bak

Note: Always back up before editing critical files to prevent lockouts.


2. Disable Root Login
Description: Prevent direct SSH logins as the root user, forcing attackers to guess
both username and credentials.
Why: The root account has unrestricted privileges, making it a prime target for
brute-force attacks.
Steps:
Edit the SSH configuration file:
bash

sudo nano /etc/ssh/sshd_config

Find or add the line:


bash

PermitRootLogin no

Save and exit (Ctrl+O, Enter, Ctrl+X in nano).

Restart the SSH service:


bash

sudo systemctl restart sshd

Test: Attempt to SSH as root:


bash

ssh root@server_ip

It should fail with “Permission denied.”


Note: Ensure a non-root user with sudo privileges exists (e.g., adduser username;
usermod -aG sudo username).
3. Enable Key-Based Authentication
Description: Configure SSH to use public/private key pairs for authentication
instead of passwords.
Why: Keys are more secure than passwords, resisting brute-force attacks and
eliminating weak credentials.
Steps:
On your client machine, generate a key pair:
bash

ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519 -C "[email protected]"

Press Enter for no passphrase (or set one for extra security).

Copy the public key to the server:


bash

ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server_ip

Verify key-based login:


bash

ssh -i ~/.ssh/id_ed25519 username@server_ip

Secure key files on the client:


bash

chmod 600 ~/.ssh/id_ed25519


chmod 644 ~/.ssh/id_ed25519.pub

Test: Log in without a password prompt using the key.


Note: Use Ed25519 for modern, secure keys; avoid older RSA keys.
4. Disable Password Authentication
Description: Prevent SSH logins using passwords, enforcing key-based authentication
only.
Why: Passwords are vulnerable to brute-force and phishing attacks.
Steps:
Edit the SSH configuration:
bash

sudo nano /etc/ssh/sshd_config

Set:
bash

PasswordAuthentication no

Restart the SSH service:


bash

sudo systemctl restart sshd

Test: Attempt to SSH with a password:


bash

ssh username@server_ip

It should fail unless a key is used.


Note: Ensure key-based authentication works before disabling passwords to avoid
lockouts.
5. Change Default SSH Port
Description: Change the SSH port from 22 to a non-standard port (e.g., 2222) to
reduce automated attacks.
Why: Port 22 is the default target for bots scanning for SSH vulnerabilities.
Steps:
Edit the SSH configuration:
bash

sudo nano /etc/ssh/sshd_config

Change or add:
bash

Port 2222

Restart the SSH service:


bash

sudo systemctl restart sshd

Test: Connect using the new port:


bash

ssh -p 2222 username@server_ip

Note: Update firewall rules (Step 8) before testing to avoid lockouts. This is
security through obscurity; combine with other measures.
6. Restrict SSH Users
Description: Limit SSH access to specific users to prevent unauthorized accounts
from logging in.
Why: Reduces the attack surface by restricting access to trusted users.
Steps:
Edit the SSH configuration:
bash

sudo nano /etc/ssh/sshd_config

Add:
bash

AllowUsers username

Replace username with the allowed user (e.g., student1).

Restart the SSH service:


bash

sudo systemctl restart sshd

Test: Attempt to SSH with a non-allowed user:


bash

ssh otheruser@server_ip

It should fail.
Note: List multiple users if needed (e.g., AllowUsers user1 user2).
7. Set Idle Timeout
Description: Automatically disconnect idle SSH sessions to reduce the risk of
hijacking.
Why: Idle sessions can be exploited if a user leaves a terminal open.
Steps:
Edit the SSH configuration:
bash

sudo nano /etc/ssh/sshd_config

Add or modify:
bash

ClientAliveInterval 300
ClientAliveCountMax 0

300 seconds (5 minutes) before checking; 0 means disconnect after one missed check.

Restart the SSH service:


bash

sudo systemctl restart sshd

Test: Log in, remain idle for 5 minutes, and verify disconnection.
Note: Adjust ClientAliveInterval based on use case (e.g., 600 for 10 minutes).
8. Configure Firewall for SSH
Description: Use a firewall to restrict SSH access to trusted IPs or ports,
blocking unauthorized traffic.
Why: Limits exposure to only necessary network connections.
Steps:
Install Uncomplicated Firewall (UFW):
bash

sudo apt install ufw


Allow the SSH port (e.g., 2222):
bash

sudo ufw allow 2222/tcp

Optional: Restrict to a specific IP range:

bash

sudo ufw allow from 192.168.1.0/24 to any port 2222

Deny all other incoming traffic:


bash

sudo ufw default deny incoming


sudo ufw default allow outgoing

Enable the firewall:


bash

sudo ufw enable

Verify rules:
bash

sudo ufw status

Test: Attempt SSH from an allowed IP (should succeed) and a disallowed IP (should
fail).
Note: Allow the new SSH port before enabling UFW to avoid lockouts.
9. Install and Configure Fail2Ban
Description: Deploy Fail2Ban to block IPs after repeated failed login attempts,
protecting against brute-force attacks.
Why: Automated attacks try thousands of credentials; Fail2Ban stops them
dynamically.
Steps:
Install Fail2Ban:
bash

sudo apt install fail2ban

Copy the default configuration:


bash

sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local

Edit the SSH jail settings:


bash

sudo nano /etc/fail2ban/jail.local

Add or modify:
ini

[sshd]
enabled = true
port = 2222
maxretry = 3
bantime = 600
Restart Fail2Ban:
bash

sudo systemctl restart fail2ban

Verify status:
bash

sudo fail2ban-client status sshd

Test: Simulate failed logins:


bash

ssh wronguser@server_ip

Check if the IP is banned:


bash

sudo fail2ban-client status sshd

Note: Adjust maxretry and bantime (e.g., 3600 for 1-hour bans).
10. Audit SSH Configuration
Description: Use ssh-audit to identify weak ciphers, algorithms, or configurations
and apply recommended fixes.
Why: Ensures the SSH server uses modern, secure settings and detects
misconfigurations.
Steps:
Install ssh-audit:
bash

sudo pip install ssh-audit

Run the audit:


bash

ssh-audit server_ip:2222

Review the output and apply recommendations, such as disabling weak ciphers:
Edit /etc/ssh/sshd_config:

bash

Ciphers [email protected],[email protected],[email protected]
KexAlgorithms [email protected]
MACs [email protected],[email protected]

Restart SSH:
bash

sudo systemctl restart sshd

Test: Re-run ssh-audit to confirm improvements.


Note: Regularly audit to stay aligned with security best practices.
11. Best Practices and Maintenance
Description: Adopt ongoing practices to maintain SSH security and monitor for
threats.
Why: Security is not a one-time task; continuous monitoring and updates are
essential.
Steps:
Keep SSH updated:
bash

sudo apt update


sudo apt upgrade openssh-server

Monitor logs for suspicious activity:


bash

sudo tail -f /var/log/auth.log

Rotate keys periodically (every 6–12 months):


Generate new keys and update ~/.ssh/authorized_keys.

Test changes safely:


Use a test VM or keep a backup SSH session open.

Enable automatic system updates:


bash

sudo apt install unattended-upgrades


sudo dpkg-reconfigure --priority=low unattended-upgrades

Test: Review logs and test SSH access after updates.


Note: Document all changes for troubleshooting and compliance.
12. Resources
Mozilla SSH Guidelines: https://infosec.mozilla.org

SSH Audit Tool: https://github.com/jtesta/ssh-audit

LabEx SSH Labs: https://labex.io

Ubuntu Security Guide: https://ubuntu.com/security

TryHackMe: Practical Linux hardening rooms

Notes for Students


Safety First: Test SSH changes in a separate session to avoid lockouts.

Order Matters: Complete steps in sequence (e.g., enable key-based authentication


before disabling passwords).

Combine Defenses: Use multiple layers (keys, firewall, Fail2Ban) for robust
security.

Practice: Apply these steps on a test VM before a production VPS.

Ask Questions: If stuck, check logs (/var/log/auth.log) or ask your instructor.

Classroom Activities
Hands-On Lab: Apply steps 1–4 on a provided Ubuntu VM, then test SSH access.

Troubleshooting: Fix a misconfigured SSH port or sshd_config error.

Audit Challenge: Run ssh-audit and propose fixes based on the report.

Discussion: Debate the trade-offs of changing the SSH port vs. relying on Fail2Ban.
End of Guide

---

### **Instructions to Create and Download the PDF**

Follow one of these methods to convert the Markdown content into a professional PDF
for your class:

#### **Option 1: Google Docs (Easiest)**


1. **Copy the Markdown**:
- Copy the entire Markdown content above.
2. **Paste into Google Docs**:
- Open a new Google Docs document (https://docs.google.com).
- Paste the content.
3. **Format for PDF**:
- **Title**: Make “SSH Hardening Guide for Ubuntu VPS” bold, 16pt, centered.
- **Headings**: Use Heading 1 for “Table of Contents”, “Introduction”, etc., and
Heading 2 for each step (e.g., “1. Backup SSH Configuration”).
- **Subheadings**: Bold “Description”, “Why”, “Steps”, “Test”, “Note” (12pt).
- **Commands**: Use a monospace font (e.g., Consolas, Courier New) for code
blocks. Select code, go to `Format > Paragraph styles > Normal Text`, and apply a
monospace font.
- **Table of Contents**: Update links to section headings if needed (Google Docs
may not auto-link Markdown anchors).
- **Spacing**: Add line breaks between sections for readability.
- **Header/Footer**: Add a header with “SSH Hardening Guide” and a footer with
page numbers (`Insert > Header & Footer`).
- **Optional**: Add your institution’s logo in the header (`Insert > Image`).
4. **Export to PDF**:
- Go to `File > Download > PDF Document (.pdf)`.
- Save as `SSH_Hardening_Guide_Ubuntu_VPS.pdf`.
5. **Verify**:
- Open the PDF to ensure commands are readable and formatting is clean.
6. **Distribute**:
- Upload to a cloud service (e.g., Google Drive, Dropbox) or email to students.
- Print copies for classroom handouts if needed.

#### **Option 2: Microsoft Word**


1. **Copy the Markdown**:
- Copy the content above.
2. **Paste into Word**:
- Open a new Word document.
- Paste the content.
3. **Format**:
- **Title**: Bold, 16pt, centered.
- **Headings**: Use “Heading 1” for main sections, “Heading 2” for steps.
- **Subheadings**: Bold “Description”, “Why”, etc. (12pt).
- **Commands**: Select code blocks, set font to Consolas or Courier New.
- **Table of Contents**: Use Word’s `References > Table of Contents` to auto-
generate after formatting headings.
- **Header/Footer**: Add title and page numbers (`Insert > Header/Footer`).
- **Styling**: Use 1.15 line spacing, 11pt Arial or Times New Roman for body
text.
4. **Save as PDF**:
- Go to `File > Save As`, choose `PDF`.
- Name it `SSH_Hardening_Guide_Ubuntu_VPS.pdf`.
5. **Verify and Distribute**:
- Check the PDF for clarity.
- Share via email, cloud, or print.

#### **Option 3: Pandoc (For Tech-Savvy Users)**


1. **Save Markdown**:
- Copy the Markdown content into a file named `ssh_hardening.md`.
- Save it on your computer (e.g., `~/Documents/ssh_hardening.md`).
2. **Install Pandoc and LaTeX**:
- On Ubuntu:
```bash
sudo apt install pandoc texlive-xetex
```
- On macOS (with Homebrew):
```bash
brew install pandoc
brew install basictex
```
- On Windows: Download Pandoc (https://pandoc.org/installing.html) and a LaTeX
distribution like MiKTeX.
3. **Convert to PDF**:
- Run:
```bash
pandoc ssh_hardening.md -o SSH_Hardening_Guide_Ubuntu_VPS.pdf --pdf-
engine=xelatex -V geometry:margin=1in
```
- This generates a PDF with 1-inch margins.
4. **Customize (Optional)**:
- Add a LaTeX preamble for styling:
- Create a file `header.tex`:
```latex
\usepackage{geometry}
\geometry{a4paper, margin=1in}
\usepackage{listings}
\usepackage{tocloft}
\lstset{basicstyle=\ttfamily,breaklines=true}
```
- Run:
```bash
pandoc ssh_hardening.md -o SSH_Hardening_Guide_Ubuntu_VPS.pdf --pdf-
engine=xelatex --include-in-header=header.tex
```
5. **Verify and Distribute**:
- Open the PDF to check formatting.
- Share via cloud or print.

#### **Option 4: Overleaf (Online LaTeX Editor)**


1. **Create an Overleaf Account**:
- Go to https://www.overleaf.com and sign up.
2. **New Project**:
- Start a new project (`New Project > Blank Project`).
3. **Convert Markdown to LaTeX**:
- Copy the Markdown content and manually structure it in LaTeX, or use a
simplified template:
```latex
\documentclass{article}
\usepackage{geometry}
\geometry{a4paper, margin=1in}
\usepackage{listings}
\usepackage{tocloft}
\usepackage{hyperref}
\hypersetup{colorlinks=true,linkcolor=blue}
\lstset{basicstyle=\ttfamily,breaklines=true}
\title{SSH Hardening Guide for Ubuntu VPS}
\author{[Your Name]}
\date{April 21, 2025}

\begin{document}
\maketitle
\tableofcontents
\newpage

\section{Introduction}
This guide provides step-by-step instructions to harden an SSH server on a
Ubuntu 22.04 VPS...

\section{Backup SSH Configuration}


\textbf{Description}: Create a backup of the SSH configuration file...\\
\textbf{Why}: Prevents lockouts...\\
\textbf{Steps}:
\begin{enumerate}
\item Copy the configuration file: \lstinline{sudo cp /etc/ssh/sshd_config
/etc/ssh/sshd_config.bak}
\item Verify: \lstinline{ls /etc/ssh/sshd_config.bak}
\end{enumerate}
\textbf{Test}: Check that the backup is readable: \lstinline{cat
/etc/ssh/sshd_config.bak}\\
\textbf{Note}: Always back up before editing critical files.

% Repeat for other steps

\section{Resources}
\begin{itemize}
\item Mozilla SSH Guidelines: \url{https://infosec.mozilla.org}
\item SSH Audit Tool: \url{https://github.com/jtesta/ssh-audit}
\item LabEx SSH Labs: \url{https://labex.io}
\item Ubuntu Security Guide: \url{https://ubuntu.com/security}
\end{itemize}

\end{document}
```
4. **Paste Steps**:
- Add each step as a `\section` with `\textbf{Description}`, `\textbf{Why}`,
etc., as shown.
- Use `\lstinline{}` for inline commands or `\begin{lstlisting}` for code
blocks.
5. **Compile and Download**:
- Click “Compile” in Overleaf to generate the PDF.
- Download via `Menu > Download > PDF`.
- Name it `SSH_Hardening_Guide_Ubuntu_VPS.pdf`.
6. **Distribute**:
- Share the PDF with students.

---

### **Formatting Tips for a Professional PDF**


- **Font**: Use Arial, Times New Roman, or a clean sans-serif font (11–12pt for
body, 16pt for title, 14pt for section headings).
- **Headings**: Bold and numbered for steps (e.g., “1. Backup SSH Configuration”).
- **Code Blocks**: Monospace font (e.g., Consolas, Courier New) for commands, with
a light gray background if possible (LaTeX or Word styles).
- **Spacing**: 1.15 line spacing, extra line breaks between “Description”, “Why”,
“Steps”, etc.
- **Header/Footer**: Include “SSH Hardening Guide” in the header and page numbers
in the footer.
- **Table of Contents**: Ensure it’s clickable (auto-generated in Word/Google Docs,
`\tableofcontents` in LaTeX).
- **Logo (Optional)**: Add your institution’s logo on the title page or header.
- **Length**: Expect 8–10 pages, depending on formatting.

---

### **Classroom Integration**


- **Handout**: Print the PDF or share digitally via email or a learning management
system (e.g., Canvas, Google Classroom).
- **Lab Setup**: Provide students with Ubuntu 22.04 VMs (e.g., via VirtualBox or
AWS EC2) pre-installed with OpenSSH.
- **Activities**:
- **Step-by-Step Lab**: Students follow the PDF to harden a VM, testing each step
(e.g., disable root login, verify key-based authentication).
- **Troubleshooting**: Introduce errors (e.g., wrong port in `sshd_config`) for
students to fix using the guide.
- **Audit Task**: Have students run `ssh-audit` and document findings.
- **Discussion**: Use the “Notes for Students” section to spark questions (e.g.,
“Why combine multiple defenses?”).
- **Safety**: Emphasize backups and testing (e.g., `sudo sshd -t`, separate SSH
session) to avoid lockouts.

---

### **Troubleshooting PDF Creation**


- **Commands Not Readable**: Ensure monospace font is applied to code blocks.
- **Table of Contents Broken**: Regenerate in Word (`References > Table of
Contents`) or Google Docs after formatting headings.
- **Pandoc Errors**: Install LaTeX (`texlive-xetex`) and verify Pandoc version
(`pandoc --version`).
- **Large File Size**: Reduce logo image size or simplify formatting (e.g., remove
heavy styles in LaTeX).

---

### **Alternative: Request Assistance**


If you’re unable to create the PDF (e.g., no access to tools), consider:
- **Emailing the Markdown**: Share the Markdown content with a colleague or IT
staff to convert to PDF.
- **Online Converters**: Paste the Markdown into https://www.markdowntopdf.com or
https://smallpdf.com for quick conversion (may require manual formatting).
- **Contact Support**: If using a learning platform, check if it can convert
documents to PDF.

---

### **Customizations**
If you need specific additions, let me know:
- A shortened version (e.g., only steps 1–5 for a shorter class).
- A LaTeX template with advanced styling (e.g., colored code blocks).
- Integration with broader VPS hardening steps.
- A slide deck outline to complement the PDF.
Once you’ve created the PDF, you’ll have a professional, downloadable resource
ready for your beginner students. If you encounter issues during conversion or need
further help, share details, and I’ll guide you through the process!

learn about Fail2Ban

firewall configuration tips

more concise instructions

You might also like