📑 Table of Contents

This lab is organized into logical sections that build upon each other progressively. We begin with foundational concepts, move through hands-on implementation, and conclude with security hardening and professional resources. Each section includes detailed explanations, practical exercises, and real-world context to ensure you develop both theoretical understanding and practical skills.

🎯 Lab Overview & What You Will Build

In this beginner-friendly lab, you will learn how to set up passwordless SSH authentication using cryptographic key pairs. SSH (Secure Shell) is the standard protocol for securely accessing remote systems, and key-based authentication is the gold standard for security in enterprise environments. You will generate your own public and private key pair, understand the mathematical relationship between them, deploy your public key to a remote server, configure SSH for optimal usability, and establish secure connections without ever typing a password. By the end of this lab, you will have mastered one of the most fundamental security skills in IT—the same technique used by system administrators, DevOps engineers, cloud architects, and security professionals to securely access thousands of servers across enterprise environments worldwide.

👋 New to Linux or Command Line?

Don't worry! This lab is designed for absolute beginners. We explain every command in detail, what it does, why we're using it, and what output to expect. Take your time, read each step carefully, and don't hesitate to re-read sections if needed. Building a solid foundation in secure authentication will benefit your entire IT career. Remember: every expert was once a beginner.

What You Will Build

By completing this lab, you will create a complete SSH authentication infrastructure including:

Learning Objectives

Upon completing this lab, you will be able to:

🔑 Understanding SSH Key Authentication

Before we start generating keys, it's essential to understand what SSH key authentication is, how it works, and why it's significantly more secure than password-based authentication. This conceptual foundation will help you make better security decisions throughout your career and troubleshoot issues more effectively. Cryptography can seem intimidating at first, but the core concepts are straightforward once explained properly. Let's break down these concepts using clear explanations and real-world analogies.

🧠 What is SSH?

SSH (Secure Shell) is a cryptographic network protocol that provides secure communication between two computers over an untrusted network like the internet. When you "SSH into a server," you're establishing an encrypted tunnel that protects all data traveling between your computer and the server from eavesdropping, tampering, and interception. SSH was designed in 1995 to replace insecure protocols like Telnet and rlogin, which transmitted data (including passwords) in plain text. Today, SSH is used by millions of system administrators, developers, and security professionals daily.

🏠 Real-World Analogy

Think of SSH like a secure phone call in a spy movie. Before discussing sensitive information, the spies use a special scrambling device that encrypts their voices. Even if someone taps the phone line, they only hear gibberish. Similarly, SSH encrypts everything you type and everything the server sends back, so even if a hacker intercepts the traffic, they can't understand it.

🔐 Password vs. Key Authentication

There are two main ways to prove your identity when connecting via SSH, and understanding the difference is crucial for making good security decisions:

  • Password Authentication: You type a secret password that only you know. The server compares it against a stored hash. Simple and familiar, but passwords have significant weaknesses: they can be guessed through brute force, stolen via phishing, intercepted if typed on a compromised system, or exposed in data breaches if reused across services.
  • Key Authentication: You prove you possess a secret cryptographic key without ever transmitting that key. This is mathematically secure—even with unlimited computing power, an attacker cannot derive your private key from the public key or the authentication exchange. Keys are essentially impossible to guess because they contain hundreds of random bits.
🏠 Real-World Analogy

Password authentication is like telling a doorman a secret word to enter a building. It works, but someone could overhear you, trick you into saying it (phishing), or try common words until they guess correctly (brute force). Key authentication is like having a unique physical key that only fits your lock. Even if someone watches you open the door, they can't duplicate the key just by observation. They would need the actual key, which never leaves your possession.

🗝️ Public Key + Private Key = Key Pair

SSH key authentication uses asymmetric cryptography (also called public-key cryptography), which means you have TWO mathematically related but different keys:

  • Private Key (🔴 SECRET): This key stays on YOUR computer and must never be shared with anyone, ever. It's used to create digital signatures that prove your identity. If someone obtains your private key, they can impersonate you on any system that trusts your public key.
  • Public Key (🟢 SHAREABLE): This key can be freely distributed to any server you want to access. It's mathematically derived from your private key, but the reverse derivation is computationally infeasible. Servers use your public key to verify signatures created by your private key.
🏠 Real-World Analogy

Imagine a special padlock (public key) and its unique key (private key). You can manufacture thousands of identical padlocks and give them to anyone—they can all lock things intended for you. But only YOU have the key that opens these padlocks. In SSH, the server has your "padlock" (public key) and uses it to create a cryptographic challenge (locking a random message). Only your "key" (private key) can solve this challenge (unlock the message), proving you are who you claim to be.

Why Keys Are More Secure Than Passwords

The following comparison illustrates the dramatic security advantages of key-based authentication over passwords:

Security Factor Password SSH Key
Entropy (Randomness) 8-20 characters typical (40-100 bits) 256+ bits (Ed25519) to 4096 bits (RSA)
Brute Force Resistance Can be cracked in hours to days with modern hardware Would take billions of years with all computers on Earth
Phishing Risk High—fake login pages can steal passwords None—private key is never transmitted
Reuse Risk People often reuse passwords across services Best practice: unique key per device/purpose
Network Transmission Sent over network (encrypted, but still transmitted) Never transmitted—only cryptographic proof
Keylogger Vulnerability High—keyloggers capture every keystroke Lower—key file itself must be stolen

🌍 Real-World Scenario & Skills Application

Understanding theory is important, but seeing how skills apply in actual work environments makes learning more meaningful and memorable. This section presents a realistic enterprise scenario that mirrors what you'll encounter in IT roles, followed by a detailed breakdown of how the skills from this lab translate to daily job tasks across various career paths.

🏢 Enterprise Scenario: Your First Day as a Junior SysAdmin

Congratulations! You've just started as a Junior Systems Administrator at CloudScale Inc., a growing SaaS company with 200 employees and infrastructure spanning AWS, Azure, and an on-premises data center. On your first day, the senior admin hands you a company laptop and says:

"Here's your workstation. You'll need to access about 50 Linux servers for monitoring, maintenance, and deployments. First order of business—set up your SSH keys. We have a strict no-password policy on all servers. Password authentication is disabled company-wide because we had a security incident last year where an attacker brute-forced a weak password on a staging server."

This is a real scenario that happens every day in IT departments worldwide. Companies of all sizes have learned (often the hard way) that password-based SSH access is a significant security risk. The skills you learn in this lab directly translate to these job responsibilities:

  • Server Administration: Securely accessing Linux/Unix servers for maintenance, log analysis, software updates, configuration changes, and troubleshooting production issues at 3 AM when the monitoring system alerts you
  • Cloud Infrastructure: Connecting to AWS EC2 instances, Azure Virtual Machines, and Google Cloud Compute instances—all major cloud providers use SSH keys as the default (and often only) authentication method
  • DevOps Workflows: Enabling CI/CD pipelines where Jenkins, GitLab CI, or GitHub Actions SSH into servers to deploy code automatically. These automated systems can't type passwords!
  • Git Operations: Pushing code to GitHub, GitLab, and Bitbucket repositories using SSH instead of HTTPS—more secure and eliminates the need to type credentials for every push/pull
  • Container Orchestration: Accessing Kubernetes nodes to debug pod issues, review container logs, or perform node maintenance in production clusters
  • Security Compliance: Meeting regulatory requirements (SOC 2, PCI-DSS, HIPAA) that mandate strong authentication controls and audit trails for system access

🎯 Skills You Will Gain & How They Apply

Cryptographic Key Management

Generate, store, protect, and rotate cryptographic keys. This foundational skill transfers directly to managing TLS/SSL certificates, GPG keys for code signing, encryption keys for data protection, and PKI infrastructure in enterprise environments.

Linux File Permissions

Understand and set correct permissions on sensitive files using chmod. Critical for passing security audits, protecting configuration files, securing web applications, and maintaining principle of least privilege across systems.

Remote Server Access

Connect securely to any Linux/Unix server from anywhere in the world. This is the #1 daily task for system administrators, site reliability engineers, DevOps practitioners, and cloud engineers.

SSH Configuration

Create shortcuts, manage multiple identities, configure jump hosts, and tune connection settings. Dramatically improves daily productivity when managing dozens or hundreds of servers.

Security Mindset

Develop habits around protecting secrets, verifying authenticity, and thinking like an attacker. This mindset transfers to all security domains: application security, network security, cloud security, and incident response.

Troubleshooting Skills

Debug "Permission denied" errors, analyze verbose logs, and systematically identify root causes. Highly valued in support, operations, and engineering roles where problems must be solved under pressure.

📋 Prerequisites & Requirements

One of the advantages of this lab is its accessibility—you don't need expensive hardware, complex software, or completion of previous labs. SSH clients are built into modern operating systems, and you can practice key authentication even without a remote server by connecting to your own machine. This section outlines everything you need to get started and provides options for different learning environments.

💡 This Lab is Self-Contained

Unlike Labs 1 and 2, this lab does NOT require any previous labs to be completed. You can start fresh with just a computer and a terminal! If you've already completed Lab 1 (LDAP) or Lab 2 (SAML), you can use your existing Ubuntu VM for this lab. If not, all exercises can be performed on your local machine or with a free cloud VM.

What You Need

Requirement Options Notes
Computer Any modern computer (2015 or newer) Windows 10/11, macOS 10.14+, or any Linux distribution
Terminal Access Built-in terminal application Windows: PowerShell, CMD, or Windows Terminal
macOS: Terminal.app or iTerm2
Linux: GNOME Terminal, Konsole, or any terminal emulator
SSH Client OpenSSH (usually pre-installed) Windows 10 1809+ includes OpenSSH by default
macOS and Linux include it in base install
Optional: Remote Server Ubuntu VM, cloud instance, or Raspberry Pi For practicing SSH between machines; you can use localhost for initial learning

Hypervisor Options (Optional)

If you want to create a dedicated practice environment or simulate SSH between two machines, you can set up an Ubuntu VM using either:

Refer to Lab 1 for detailed VM installation instructions if you want to set up a dedicated Ubuntu VM.

Knowledge Prerequisites

This lab is designed for beginners, but having these foundational skills will help you progress faster:

🏗️ How SSH Keys Work (Visual Guide)

Visual representations make complex concepts easier to understand. This section provides diagrams showing the relationship between your local machine, your key pair, and the remote server, followed by a step-by-step walkthrough of the authentication process. Understanding this flow will help you troubleshoot issues and appreciate why key authentication is so secure.

▼ SSH KEY AUTHENTICATION FLOW ▼

🔴
PRIVATE KEY

Stays on YOUR machine
NEVER share this
Used to prove identity

~/.ssh/id_ed25519
🟢
PUBLIC KEY

Copied to SERVER
Safe to share anywhere
Used to verify identity

~/.ssh/id_ed25519.pub
YOUR COMPUTER

Has private key
+ public key

➡️
SSH CONNECTION

Encrypted tunnel
Port 22

➡️
REMOTE SERVER

Has your public key
in authorized_keys

AUTHENTICATION STEPS (WHAT HAPPENS WHEN YOU TYPE ssh user@server)
1. You initiate: ssh user@server 2. Server sends a random challenge (a number encrypted with YOUR public key) 3. Only YOUR private key can decrypt this challenge—no other key in the world can 4. Your SSH client decrypts the challenge and sends back the answer 5. Server verifies the answer matches → Access Granted! ✓ 6. An encrypted session is established for all subsequent communication

🔐 The Key Point (Pun Intended)

Your private key never leaves your computer and is never transmitted over the network. The server doesn't need your private key—it only needs your public key to create challenges and verify responses. This is fundamentally different from password authentication, where the password (or a hash of it) must be sent to the server. With SSH keys, even if an attacker intercepts all network traffic, they cannot obtain your private key or replay the authentication.

🏷️ Environment Setup

Before diving into key generation, let's prepare your environment and verify that SSH is properly installed on your system. This section also introduces the device badge system used throughout the lab to clearly indicate where each command should be executed—an important distinction when working with multiple machines.

Device Badges Legend

Throughout this lab, code blocks are tagged with badges indicating where to run commands. Pay attention to these badges—running a command on the wrong machine is a common source of confusion and errors:

Local Machine Your personal computer (where you generate and store your private key)
SSH Server The remote server you want to access (where your public key is deployed)
Ubuntu VM Optional virtual machine for practice (can serve as your test server)
1

Open Your Terminal

The terminal (also called command line, console, or shell) is where you'll type commands to generate and manage SSH keys. If you've never used a terminal before, don't worry—it's simply a text-based way to interact with your computer that's more precise and powerful than clicking through menus. Every IT professional uses the terminal daily, so this is a valuable skill to develop.

How to open the terminal on your operating system:

  • Windows 10/11: Press Win + X, then click "Windows Terminal" or "PowerShell". Alternatively, press Win + R, type cmd or powershell, and press Enter.
  • macOS: Press Cmd + Space to open Spotlight, type "Terminal", and press Enter. Or navigate to Applications → Utilities → Terminal.
  • Linux: Press Ctrl + Alt + T (works on most distributions), or search for "Terminal" in your applications menu.
2

Verify SSH is Installed

Check that SSH client software is installed on your computer. Most modern operating systems include OpenSSH by default, but let's verify. Run the following command to check the SSH version. If you see a version number, SSH is ready to use.

Local Machine
ssh -V

Expected output: Something like OpenSSH_8.9p1, OpenSSH_9.0p1, or similar. The exact version doesn't matter for this lab—any version from the past 10 years will work. If you see a version number, you're ready to proceed!

❓ Don't see a version number? Here's how to install SSH:

Windows: SSH is included in Windows 10 version 1809 (October 2018) and later. If missing, go to Settings → Apps → Optional Features → Add a feature → search for "OpenSSH Client" → Install. Restart your terminal after installation.

macOS: SSH is always pre-installed. If you somehow get an error, reinstall Command Line Tools by running xcode-select --install in Terminal.

Linux: SSH client is almost always pre-installed. If missing, run sudo apt install openssh-client (Debian/Ubuntu) or sudo dnf install openssh-clients (Fedora/RHEL).

3

Check for Existing SSH Keys

Before generating new keys, let's check if you already have SSH keys from previous work, school, or personal projects. If you do, you might want to use them instead of creating new ones. If you don't have any keys yet, that's perfectly fine—we'll create them in the next section.

Local Machine
ls -la ~/.ssh/

Interpreting the output:

  • id_rsa and id_rsa.pub — You have RSA keys (older but still secure with 4096 bits)
  • id_ed25519 and id_ed25519.pub — You have Ed25519 keys (modern, recommended)
  • id_ecdsa and id_ecdsa.pub — You have ECDSA keys (another modern option)
  • No such file or directory — No keys exist yet; we'll create them!
  • Empty directory — The .ssh folder exists but contains no keys yet

🔑 Generating SSH Key Pairs

Key generation is the foundation of SSH security. In this section, you will create your personal cryptographic key pair using the Ed25519 algorithm, which is the current industry recommendation for new keys. Ed25519 provides excellent security (equivalent to RSA-3072) with smaller key sizes and faster performance. Understanding the key generation process empowers you to make informed decisions about algorithm selection, key strength, and passphrase protection—choices you'll face throughout your career when setting up SSH access to cloud instances, Git repositories, and enterprise servers.

4

Generate an Ed25519 Key Pair

Run the following command to generate a new Ed25519 SSH key pair. The -t ed25519 flag specifies the algorithm type. The -C flag adds a comment (typically your email address) to help identify the key later—this is especially useful when you have keys on multiple devices or for different purposes.

Local Machine
ssh-keygen -t ed25519 -C "your.email@example.com"

You'll be prompted with three questions. Here's how to answer them:

  1. "Enter file in which to save the key" — Press Enter to accept the default location (~/.ssh/id_ed25519). Only change this if you have a specific reason, like maintaining separate keys for work and personal use.
  2. "Enter passphrase" — Type a strong passphrase (highly recommended for security) or press Enter for no passphrase (acceptable for learning, but risky for production).
  3. "Enter same passphrase again" — Confirm your passphrase by typing it again.

🔒 Should I Use a Passphrase? Understanding the Trade-offs

Yes, for maximum security! A passphrase encrypts your private key file using symmetric encryption. Even if someone steals the file, they cannot use it without knowing the passphrase. This protects you if your laptop is stolen, your backup drive is compromised, or malware copies files from your system.

For this lab: You can skip the passphrase (just press Enter twice) for simplicity while learning. However, develop the habit of using passphrases for any keys that access production systems or sensitive data.

Pro tip: Use a memorable sentence as your passphrase, like "My first car was a 1997 Honda Civic!" — long, easy to remember, hard to guess.

5

Verify Your Keys Were Created

After generating the keys, verify that both files were created successfully. You should see two new files in your .ssh directory. Pay attention to the file permissions shown in the first column—they're important for security.

Local Machine
ls -la ~/.ssh/

Expected output (look for these two files):

  • -rw------- id_ed25519 — Your private key (permissions should be 600, readable only by you)
  • -rw-r--r-- id_ed25519.pub — Your public key (permissions can be more open, 644 is fine)
6

View Your Public Key

Let's look at your public key. This is the key you'll share with servers, GitHub, cloud providers, and colleagues. It's a single long line of text that starts with the algorithm name (ssh-ed25519) and ends with your comment (email). The middle section is the actual cryptographic key encoded in base64.

Local Machine
cat ~/.ssh/id_ed25519.pub

✅ Your Public Key is Safe to Share!

Your public key is designed to be distributed freely. You can email it, paste it into web forms (like GitHub's SSH key settings), post it on your website, or add it to any number of servers. It cannot be used to impersonate you or derive your private key. The mathematical relationship between public and private keys is "one-way"—easy to compute the public key from the private key, but computationally infeasible to reverse.

7

Understand Your Private Key (DO NOT SHARE)

Your private key is stored in ~/.ssh/id_ed25519 (without the .pub extension). Let's verify that its permissions are secure. The private key file should only be readable by you (owner)—SSH will actually refuse to use a private key with overly permissive permissions as a security precaution.

Local Machine
ls -la ~/.ssh/id_ed25519

Expected output: -rw------- — This permission string means only you (the owner) can read and write the file. No group members or other users on the system can access it. If you see different permissions, we'll fix them in the security section.

⚠️ NEVER Share Your Private Key!

Your private key is the master key to your digital identity. Treat it like you would treat your house key, bank PIN, or passport. Never email it, paste it into websites, share it on messaging apps, commit it to Git repositories, or show it to anyone including IT support. If your private key is compromised, an attacker can access every server and service that trusts your public key.

If you suspect your private key has been compromised: Immediately generate a new key pair and replace the public key on all servers and services. Then securely delete the compromised private key.

📤 Deploying Public Keys

Now that you have your key pair, you need to install your public key on each server you want to access. This is called "deploying" or "copying" your public key. The server stores your public key in a special file called authorized_keys, which contains the public keys of all users allowed to connect. There are multiple methods to deploy keys, each suited to different situations—we'll cover both automated and manual approaches so you're prepared for any environment.

8

Method 1: Using ssh-copy-id (Easiest)

The ssh-copy-id command is the easiest way to deploy your public key. It automatically copies your public key to the remote server, creates the .ssh directory if needed, appends the key to authorized_keys, and sets correct permissions—all in one command. This method requires password authentication to be enabled on the server (which it usually is initially).

Replace username with your username on the remote server, and server-ip with the server's IP address or hostname. You'll be prompted for your password on the server—this is the last time you'll need it!

Local Machine
ssh-copy-id username@server-ip

Example: ssh-copy-id john@192.168.1.100 or ssh-copy-id admin@myserver.example.com

Expected output after entering your password:

Number of key(s) added: 1 Now try logging into the machine, with: "ssh 'username@server-ip'" and check to make sure that only the key(s) you wanted were added.
9

Method 2: Manual Copy (When ssh-copy-id Unavailable)

If ssh-copy-id isn't available (common on Windows without WSL, or on some minimal Linux installations), you can manually copy your public key. This method involves displaying your public key, copying it to your clipboard, then SSH-ing to the server and pasting it into the authorized_keys file.

Step 1: Display your public key and copy it:

Local Machine
cat ~/.ssh/id_ed25519.pub

Select and copy the entire output (one long line starting with ssh-ed25519).

Step 2: SSH into the server using password authentication, then create the .ssh directory and authorized_keys file with correct permissions:

SSH Server
mkdir -p ~/.ssh chmod 700 ~/.ssh echo "PASTE_YOUR_PUBLIC_KEY_HERE" >> ~/.ssh/authorized_keys chmod 600 ~/.ssh/authorized_keys

Replace PASTE_YOUR_PUBLIC_KEY_HERE with the public key you copied. Make sure to include the entire line including ssh-ed25519 at the beginning and your email at the end.

10

Practice: Set Up SSH to Localhost (No Server Needed)

Don't have a remote server? You can practice SSH key authentication by connecting to your own computer! This is a great way to learn the concepts without needing additional hardware or cloud accounts. First, ensure the SSH server daemon is running on your machine (this allows incoming SSH connections).

Ubuntu VM or Linux
sudo apt update sudo apt install -y openssh-server sudo systemctl enable ssh sudo systemctl start ssh sudo systemctl status ssh

Then copy your key to localhost (you're deploying your public key to your own machine):

Ubuntu VM or Linux
ssh-copy-id $USER@localhost

Enter your user password when prompted. Now you can SSH to yourself without a password! This might seem silly, but it's perfect for practicing and understanding the authentication flow.

✅ Testing SSH Connection

With your public key deployed, it's time for the moment of truth—testing whether key-based authentication works. This section walks you through connecting to your server and using verbose mode to observe the authentication process in detail. Understanding the connection process helps you troubleshoot issues and verify that security is configured correctly.

11

Connect Using SSH Key Authentication

Now test your passwordless SSH connection! Connect to the server where you deployed your public key. If everything is set up correctly, you'll be logged in automatically without being asked for a password (though you may be asked for your key's passphrase if you set one).

Local Machine
ssh username@server-ip

Success indicators:

  • You're logged in immediately without a password prompt
  • If you set a passphrase on your key, you'll be asked for that instead (this is expected and correct)
  • You see the server's command prompt (hostname, username, directory)

🎉 Congratulations!

If you successfully logged in without entering a server password, you've completed the core objective of this lab! You now have a working SSH key authentication setup—the same secure access method used by professionals worldwide to manage millions of servers.

12

Verbose Mode for Debugging

If SSH isn't working as expected, or if you want to understand what happens during connection, use verbose mode. The -v flag shows detailed debug information about each step of the authentication process. You can use up to three v's (-vvv) for maximum detail.

Local Machine
ssh -v username@server-ip

Key phrases to look for in the verbose output:

  • Offering public key — SSH is trying to authenticate with a key
  • Server accepts key — Key authentication succeeded!
  • Authentication succeeded (publickey) — Confirmation of key auth
  • Permission denied — Key was rejected (check troubleshooting section)

⚙️ SSH Configuration File

Now that you can connect with SSH keys, let's make your daily workflow more efficient. The SSH configuration file (~/.ssh/config) is a powerful tool that lets you create shortcuts for servers, specify which key to use for each connection, configure jump hosts for bastion setups, and customize dozens of connection settings. System administrators managing hundreds of servers rely heavily on SSH config to stay productive.

13

Create SSH Config File

Create or edit the SSH configuration file. This file uses a simple format: Host followed by a nickname, then indented settings that apply to that host. The Host * block sets defaults for all connections.

Local Machine
nano ~/.ssh/config

Add configuration blocks for your servers. Here's a comprehensive example:

# Default settings for all hosts Host * AddKeysToAgent yes IdentitiesOnly yes ServerAliveInterval 60 ServerAliveCountMax 3 # Production web server Host webserver HostName 192.168.1.100 User admin IdentityFile ~/.ssh/id_ed25519 Port 22 # Development server with non-standard port Host devbox HostName dev.example.com User developer IdentityFile ~/.ssh/id_ed25519 Port 2222 # AWS EC2 instance Host aws-prod HostName ec2-12-34-56-78.compute-1.amazonaws.com User ec2-user IdentityFile ~/.ssh/aws-key.pem # Local VM for testing Host labvm HostName localhost User iamstudent IdentityFile ~/.ssh/id_ed25519

Save the file: Press Ctrl + O, then Enter to confirm, then Ctrl + X to exit nano.

14

Set Config File Permissions

The SSH config file must have restrictive permissions to be used. SSH ignores config files that are readable by other users as a security precaution (the file might contain sensitive information like server addresses).

Local Machine
chmod 600 ~/.ssh/config
15

Use SSH Config Shortcuts

Now instead of typing long SSH commands with all the options, you can simply use the short nickname you defined. SSH reads the config file and fills in all the details automatically.

Local Machine
# Instead of: ssh admin@192.168.1.100 ssh webserver # Instead of: ssh developer@dev.example.com -p 2222 ssh devbox # Instead of: ssh ec2-user@ec2-12-34-56-78.compute-1.amazonaws.com -i ~/.ssh/aws-key.pem ssh aws-prod

Much simpler! This also works with scp for file transfers: scp file.txt webserver:/home/admin/

🔒 Security Best Practices

Generating keys and deploying them is just the beginning. Proper key management throughout the key lifecycle—creation, storage, usage, rotation, and revocation—is essential for maintaining security. This section covers the practices that security-conscious organizations require, helping you develop habits that will serve you well in enterprise environments and pass security audits.

16

Verify and Fix File Permissions

SSH is strict about file permissions for security reasons. If your private key, config file, or the .ssh directory have overly permissive settings, SSH will refuse to use them or warn you. Run these commands to set all permissions correctly:

Local Machine
# Set correct permissions on SSH directory and files chmod 700 ~/.ssh chmod 600 ~/.ssh/id_ed25519 chmod 644 ~/.ssh/id_ed25519.pub chmod 600 ~/.ssh/config 2>/dev/null chmod 600 ~/.ssh/authorized_keys 2>/dev/null # Verify the permissions are correct ls -la ~/.ssh/

Permission reference (what each setting means):

  • ~/.ssh/ directory: drwx------ (700) — Only owner can read, write, enter
  • id_ed25519 (private key): -rw------- (600) — Only owner can read and write
  • id_ed25519.pub (public key): -rw-r--r-- (644) — Owner can write, everyone can read
  • config: -rw------- (600) — Only owner can read and write
  • authorized_keys: -rw------- (600) — Only owner can read and write

🛡️ Common Vulnerabilities & Best Practices

Understanding security vulnerabilities is just as important as building secure solutions. This section examines common attack vectors that target SSH key authentication, explains how attackers exploit these weaknesses in real-world scenarios, and provides specific hardening steps to protect your infrastructure. Whether you're preparing for a security interview, conducting a risk assessment, or simply want to understand the threat landscape, this knowledge is invaluable.

CRITICAL

Private Key Exposure

If your private key is stolen or exposed, attackers can impersonate you on every server where your public key is authorized. This is the most severe SSH vulnerability.

⚔️ Attack Scenario

An attacker gains access to a developer's laptop through malware or physical theft. They copy the private key from ~/.ssh/, then use it to SSH into production servers, exfiltrate customer data, and deploy ransomware—all while appearing as the legitimate developer in audit logs.

🛡️ Mitigation
  • Always use a strong passphrase on private keys
  • Enable full-disk encryption on all devices
  • Never commit keys to version control (add *.pem, id_* to .gitignore)
  • Use ssh-agent with timeout to limit exposure window
  • Consider hardware security keys (FIDO2) for high-value access
CRITICAL

Weak Key Algorithms

Using deprecated algorithms (DSA, RSA with less than 2048 bits, or ECDSA with weak curves) makes keys vulnerable to cryptographic attacks.

⚔️ Attack Scenario

A company still uses 1024-bit RSA keys generated in 2010. A nation-state adversary with significant compute resources factors the key, deriving the private key from the publicly-available public key. They now have persistent, undetected access.

🛡️ Mitigation
  • Use Ed25519 (recommended) or RSA 4096-bit for new keys
  • Never use DSA (deprecated since OpenSSH 7.0)
  • Audit existing keys: ssh-keygen -l -f key.pub
  • Replace any key smaller than 2048 bits immediately
HIGH

SSH Agent Forwarding Abuse

Agent forwarding (-A flag) allows a compromised intermediate server to use your local SSH agent to authenticate to other servers without your knowledge.

⚔️ Attack Scenario

You SSH to a jump host with agent forwarding enabled. Unknown to you, that server was compromised last week. The attacker's malware detects your forwarded agent and immediately uses it to connect to production databases, all authenticated as you.

🛡️ Mitigation
  • Avoid ssh -A unless absolutely necessary
  • Use ProxyJump (-J flag) instead of agent forwarding
  • Set ForwardAgent no in ~/.ssh/config
  • Use ssh-add -c to require confirmation for each use
HIGH

Man-in-the-Middle (MITM) Attacks

When connecting to a new server, SSH asks you to verify the host key fingerprint. Blindly accepting creates MITM risk.

⚔️ Attack Scenario

An attacker on your network intercepts your connection to a new cloud server. They present their own SSH server with a different host key. You accept without verifying, and now all your traffic passes through the attacker who can capture credentials and modify commands.

🛡️ Mitigation
  • Always verify host key fingerprints through a separate channel
  • Pre-populate known_hosts via configuration management
  • Use StrictHostKeyChecking yes in production
  • Investigate any host key change warnings seriously
MEDIUM

Unauthorized Key Accumulation

Over time, authorized_keys files accumulate stale keys from former employees, contractors, and decommissioned systems.

⚔️ Attack Scenario

A developer leaves the company but their SSH key is never removed from production servers. Six months later, they use their old key (still on their personal laptop) to access sensitive data, either maliciously or accidentally.

🛡️ Mitigation
  • Audit authorized_keys files quarterly
  • Use centralized key management (LDAP, Vault SSH)
  • Implement SSH certificates with expiration dates
  • Automate key removal in offboarding process
MEDIUM

Insecure File Permissions

Overly permissive file permissions on key files allow other users on shared systems to read private keys or modify authorized_keys.

⚔️ Attack Scenario

A junior developer on a shared development server accidentally sets their private key to 644 (world-readable). Another user on the same system copies the key and uses it to access the developer's cloud resources and personal repositories.

🛡️ Mitigation
  • Set ~/.ssh to 700, private keys to 600
  • Enable StrictModes yes in sshd_config (default)
  • Regularly audit permissions with automated scripts
  • Use configuration management to enforce permissions

✅ Production Hardening Checklist

  • ✅ Disable password authentication: PasswordAuthentication no in sshd_config
  • ✅ Disable root login: PermitRootLogin no
  • ✅ Use Ed25519 or RSA 4096-bit keys only
  • ✅ Require passphrases on all private keys
  • ✅ Set idle timeout: ClientAliveInterval 300 and ClientAliveCountMax 2
  • ✅ Limit access by user/group: AllowUsers or AllowGroups
  • ✅ Use fail2ban or similar to block brute force attempts
  • ✅ Consider changing SSH port (reduces automated scans)
  • ✅ Enable detailed logging for security monitoring
  • ✅ For large environments, consider SSH certificates over static keys

⚠️ Lab vs Production Configuration

Setting Lab Value Production Value
PasswordAuthentication yes (for initial setup) no
PermitRootLogin yes (convenience) no or prohibit-password
Key Passphrase Optional (learning) Required (mandatory policy)
StrictHostKeyChecking ask yes (with pre-seeded known_hosts)
Key Algorithm Any (for learning) Ed25519 or RSA-4096 only
SSH Port 22 (default) Non-standard (e.g., 2222) recommended
Fail2ban/Rate Limiting Not installed Active with aggressive rules

🔧 Troubleshooting Guide

Even experienced administrators encounter SSH issues. The good news is that SSH problems are usually straightforward to diagnose once you know what to look for. This section covers the most common issues you'll encounter, their root causes, and step-by-step solutions. Bookmark this section—you'll likely reference it many times throughout your career.

Common Issues and Solutions

Issue: "Permission denied (publickey)"

Root Cause: The server doesn't have your public key, or file permissions prevent SSH from reading it.

Diagnostic Steps:

  • Verify your public key is in the server's ~/.ssh/authorized_keys
  • Check authorized_keys permissions on server: chmod 600 ~/.ssh/authorized_keys
  • Check .ssh directory permissions on server: chmod 700 ~/.ssh
  • Check home directory permissions: should not be group/world writable
  • Use verbose mode to see which keys are being tried: ssh -v user@server

Issue: "Bad permissions" or "Key ignored" warnings

Root Cause: Your private key file has permissions that are too open. SSH refuses to use insecure keys.

Solution: Fix permissions on your local machine:

Local Machine
chmod 600 ~/.ssh/id_ed25519 chmod 700 ~/.ssh

Issue: SSH still asks for password despite key setup

Possible Causes and Solutions:

  • Wrong key being used: Specify explicitly: ssh -i ~/.ssh/id_ed25519 user@server
  • Key not in authorized_keys: Re-run ssh-copy-id user@server
  • Server configuration: Check that PubkeyAuthentication yes in /etc/ssh/sshd_config
  • SELinux blocking: Check restorecon -Rv ~/.ssh on RHEL/CentOS

Issue: "Connection refused" error

Root Cause: SSH server isn't running, or a firewall is blocking the connection.

Solutions:

  • Check if SSH is running: sudo systemctl status ssh (or sshd on some systems)
  • Start SSH service: sudo systemctl start ssh
  • Check firewall: sudo ufw allow 22 or sudo firewall-cmd --add-service=ssh --permanent
  • Verify you're connecting to the right port

🧹 Cleanup & Reset

While you'll likely want to keep the SSH keys you created (they're useful!), there may be times when you need to start fresh, remove test keys, or clean up after experimentation. This section provides commands for various cleanup scenarios. Always be careful when deleting keys—losing access to servers is frustrating and time-consuming to fix.

17

Remove Test Keys (If Needed)

If you want to start fresh or remove keys created during this lab, use these commands. Warning: Deleting your private key means losing access to any server that only has the corresponding public key. Make sure you have alternative access (like a password or console access) before deleting keys.

Local Machine
# Remove Ed25519 keys created in this lab rm ~/.ssh/id_ed25519 rm ~/.ssh/id_ed25519.pub # Remove SSH config (optional) rm ~/.ssh/config # Remove known_hosts entries for a specific server ssh-keygen -R server-ip-or-hostname

To remove your public key from a server's authorized_keys: SSH into the server (using password if key is removed) and edit ~/.ssh/authorized_keys. Delete the line containing your public key.

🎓 Key Takeaways

Congratulations on completing this lab! You've gained foundational security skills that every IT professional needs. This section summarizes what you've learned and points you toward the next steps in your IAM and security journey.

Skills Mastered in This Lab

Key Concepts to Remember

Next Labs in the Series

📚 Additional Learning Resources

Your learning doesn't have to stop here. This section provides carefully curated resources to deepen your SSH and cryptography knowledge, practice in real-world environments, and prepare for professional certifications. Whether you prefer reading documentation, watching videos, or hands-on practice, there's something here for you.

📖 Official Documentation
  • OpenSSH Manual Pages The authoritative reference for all SSH commands, options, and configuration. Essential for understanding advanced features.
  • ssh(1) Man Page Complete documentation of the SSH client with every flag and option explained.
  • ssh-keygen(1) Man Page Deep dive into key generation including advanced topics like certificates and key conversion.
  • sshd_config(5) Man Page Every server-side configuration option. Essential reading for hardening SSH servers.
🎓 Online Courses & Tutorials
  • DigitalOcean SSH Tutorial Excellent step-by-step guide with clear explanations and troubleshooting tips.
  • SSH Academy Comprehensive learning platform from SSH Communications Security, the company that created SSH.
  • Linuxize SSH Guide Practical tutorial with Ubuntu-specific instructions and common scenarios.
  • SSH Crash Course (YouTube) Video walkthrough covering SSH basics to advanced tunneling in under an hour.
🔧 Tools & Utilities
  • PuTTYgen Windows GUI tool for generating SSH keys and converting between formats (OpenSSH, PuTTY, etc.).
  • SSH Audit Online tool to scan and audit SSH server configurations. Identifies weak algorithms and misconfigurations.
  • Termius Cross-platform SSH client with sync, SFTP, and team features. Free tier available.
  • mRemoteNG Windows connection manager supporting SSH, RDP, VNC, and more in a tabbed interface.
📚 Books & Publications
🔐 Security Standards & Best Practices
☁️ Cloud Provider SSH Documentation
  • AWS EC2 Key Pairs How SSH keys work with AWS EC2 instances, including creation, rotation, and best practices.
  • Azure SSH to Linux VMs Microsoft's guide to SSH key setup for Azure virtual machines.
  • Google Cloud SSH Keys Managing SSH keys in Google Cloud Platform, including project-wide and instance-specific keys.
  • GitHub SSH Setup Configure SSH keys for GitHub to push/pull without passwords. Essential for developers.
💻 Practice Platforms
  • OverTheWire: Bandit Free wargame teaching Linux and SSH through progressively harder challenges. Great for beginners.
  • TryHackMe Guided cybersecurity training with SSH-based labs. Free and paid tiers available.
  • VulnHub Download vulnerable VMs to practice SSH attacks and defenses in a safe environment.
👥 Community Resources

💡 Practice Recommendations

  • Set up GitHub SSH: Add your public key to GitHub (Settings → SSH and GPG keys) and practice pushing/pulling repositories without entering credentials. This is used daily by millions of developers.
  • Create multiple keys: Generate separate key pairs for work and personal use, or for different security levels. Practice specifying which key to use with the -i flag and SSH config.
  • Master ssh-agent: Learn to use ssh-agent to cache decrypted keys in memory, avoiding passphrase prompts while maintaining security. Use ssh-add -t 3600 for time-limited caching.
  • Set up a cloud VM: Create a free-tier VM on AWS, Azure, or Google Cloud. Practice SSH key authentication with real cloud infrastructure.
  • Harden an SSH server: On a test system, edit /etc/ssh/sshd_config to disable password authentication, change the port, and enable other security measures. Test that you can still connect!
  • Learn SSH tunneling: Practice local port forwarding (ssh -L), remote port forwarding (ssh -R), and dynamic SOCKS proxy (ssh -D). These are powerful techniques for secure access to internal services.
  • Try SSH certificates: For advanced practice, set up an SSH Certificate Authority. This is how large organizations manage SSH access at scale without distributing authorized_keys files.
  • Complete OverTheWire Bandit: Work through all levels of the Bandit wargame. It teaches SSH skills through practical challenges and is completely free.