Lesson 19 of 29 ↓
- 1.Rhel 9 Administration Guide
- 2.Ubuntu Boot Process Guide
- 3.Linux Basic Commands Guide
- 4.Comprehensive Unix Shells Guide
- 5.Mastering Vim Deep & Practical Guide
- 6.Magic Numbers in Linux Deep Systems Guide
- 7.Wildcards & Globbing in Linux Deep Cli Guide
- 8.Linux Users & Groups Deep Administration Guide
- 9.Journaling in Linux Filesystems Deep Systems Guide
- 10.Getopt & Getoptlong Deep System-level Option Parsing Guide
- 11.Su Command in Linux Complete Guide with Environment Variables
- 12.Linux File Permissions and Ownership Complete Practical Guide
- 13.Ubuntu Package Management Apt Complete Guide
- 14.Bash Scripting Basics
- 15.Linux File System Essentials
- 16.Process and Thread Management
- 17.Session 10 : Introduction to Networking & the Application Layer
- 18.Linux Networking Cli & Introduction to Yocto for Machine Routing
- 19.Comprehensive Guide to Ssh (secure Shell)
- 20.Logical Volume Management (lvm) Guide
- 21.C Build Process & Libraries Guide
- 22.Archiving and Compression in Linux
- 23.Linux Package Managers: a Detailed Guide
- 24.Misra-c Guidelines Detailed Cheat Sheet
- 25.Mqtt Server Setup (pc as Server)
- 26.Detailed Explanation of Tty and Pts in Linux
- 27.Vim Cheat Sheet
- 28.Difference Between apt and apt-get
- 29.Difference Between apt Upgrade and apt Full-upgrade
8 min read
Comprehensive Guide to Ssh (secure Shell)
Overview
This README provides an in-depth understanding of SSH (Secure Shell), its underlying principles, and practical applications. It covers generating and managing SSH keys, connecting to servers securely, and setting up robust authentication methods. The guide explains public/private key concepts, details on different SSH key types, and advanced configuration options to harden your SSH connections. In addition, it discusses best practices and advanced topics such as two-factor authentication (2FA), SSH certificate-based authentication, and centralized key management.
What is Ssh?
SSH (Secure Shell) is a protocol that securely connects to remote systems over an untrusted network. It uses cryptographic techniques to ensure data confidentiality, integrity, and secure user authentication. SSH is commonly used for remote server administration, secure file transfers, and tunneling other protocols through an encrypted connection.
The Science Behind Ssh
SSH utilizes a client–server model. When you connect, a "handshake" occurs to establish trust.
-
Encryption: Data transmitted between the client and server is encrypted (symmetric encryption), preventing eavesdroppers from intercepting information.
-
Authentication: SSH supports multiple authentication methods including passwords, public key authentication (asymmetric encryption), and two-factor authentication (2FA).
-
Integrity: Cryptographic checksums and Message Authentication Codes (MACs) ensure that data is not tampered with during transit.
Public and Private Key Concepts
SSH key pairs are the industry standard for secure access.
-
Public Key: Shared openly and placed on remote systems in the
authorized_keysfile. Think of this as the "lock." -
Private Key: Kept secret on the client machine; it is used to decrypt data encrypted with the public key. Think of this as the "key."
How They Secure Connections:
-
A key pair is generated (e.g., with
ssh-keygen). -
The public key is shared with the server.
-
When connecting, the server issues a challenge that only the holder of the corresponding private key can solve.
-
Once verified, a secure session is established.
Types of Ssh Keys
Different algorithms offer various trade-offs in security and performance:
-
Ed25519: (Recommended) Offers the fastest performance and very strong security with small key sizes. It is the modern standard.
-
RSA: Widely supported and the "classic" choice. If using RSA, ensure key lengths are 3072 bits or higher (4096 is preferred).
-
ECDSA: Uses elliptic curves; offers strong security with smaller key sizes.
-
DSA: Deprecated due to security concerns. Do not use.
Generating Ssh Keys
To generate a key pair, use ssh-keygen.
Option A: The Modern Standard (Ed25519)
ssh-keygen -t ed25519 -C "your_email@example.com"Option B: The Legacy Standard (RSA)
ssh-keygen -t rsa -b 4096 -C "your_email@example.com"Explanation:
-
-t: Specifies the algorithm (ed25519 or rsa). -
-b 4096: Specifies bit size (only needed for RSA). -
-C: Adds a comment (typically your email) to help identify the key later.
Follow the prompts to set the file location (default is ~/.ssh/id_...) and optionally set a passphrase for extra security.
Installing Ssh
Most Linux distributions come with an SSH client installed, but you may need to install the server if you want to connect to that machine.
Ubuntu and Debian:
sudo apt update && sudo apt install openssh-serverRed Hat and CentOS:
sudo yum install openssh-serverFedora:
sudo dnf install openssh-serverArch Linux:
sudo pacman -S opensshConnecting to a Server Via Ssh
To connect to a remote server:
ssh username@hostname_or_ipExample:
ssh root@192.168.1.50Notes:
-
On the first connection, you will be asked to accept the server’s fingerprint. Type
yes. -
Use
-p <port>if the server listens on a non-standard port (e.g.,ssh -p 2222 user@host).
Note: you make it with telnetd to see data with out encrypted
The Ssh Config File (time Saver)
Instead of remembering IP addresses and usernames, you can configure aliases in your local SSH config file.
-
Create or edit the config file:
bash nano ~/.ssh/config -
Add your server details:
bash # Alias for a web server Host my-web-server HostName 203.0.113.10 User admin IdentityFile ~/.ssh/id_ed25519 # Alias for a development box on a custom port Host dev-box HostName 192.168.1.50 User developer Port 2222 -
Secure the file (Important): SSH is sensitive to permissions. If your config file is readable by others, SSH might ignore it.
code chmod 600 ~/.ssh/config -
Connect using the alias:
code ssh my-web-server
Sharing and Using Ssh Keys
To log in without a password, you must place your Public Key on the server.
Method 1: The Easy Way (ssh-copy-id) This command automatically copies your public key to the remote server's authorized_keys file.
ssh-copy-id username@server_ip
# or specifying a key
ssh-copy-id -i ~/.ssh/id_ed25519.pub username@server_ipMethod 2: The Pipe Way (Command Line) If ssh-copy-id is not available, you can send the key over an SSH pipe:
cat ~/.ssh/id_ed25519.pub | ssh username@server_ip "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"Method 3: The Copy-Paste Way (Fully Manual) If the above methods fail, you can manually copy the text of the key.
-
On your local machine, display the public key content:
bash cat ~/.ssh/id_ed25519.pubHighlight the output (it starts with
ssh-ed25519orssh-rsa) and copy it to your clipboard. -
SSH into the remote server:
bash ssh username@server_ip -
On the server, ensure the directory exists and open the file with your preferred editor (e.g.,
nvim,nano,vim):bash mkdir -p ~/.ssh nvim ~/.ssh/authorized_keys -
Paste the key into the file (ensure it is on a new line), save the file, and exit.
Important Permission Fix: If authentication fails, ensure permissions are correct on the server:
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keysSetting Up Ssh Key Authentication
Once your key is copied, test it:
-
Login:
bash ssh username@server_ipYou should log in without a password (unless you set a passphrase for the key).
-
Disable Password Auth (Optional but Recommended): Edit
/etc/ssh/sshd_configon the server:bash PubkeyAuthentication yes PasswordAuthentication noThen restart SSH:
sudo systemctl restart ssh
Transferring Data & Browsing (scp, Rsync, Wget, Curl, Lynx, W3m)
Option 1: scp (secure Copy)
Best for simple, one-off file transfers.
One-line command to upload file:
scp file.txt username@server_ip:/path/to/destinationDownload file from remote:
scp username@remote_ip:/var/www/html/file.txt /local/destination/Copy directory recursively:
scp -r /local/folder username@remote_ip:/remote/folderOption 2: rsync (remote Sync)
rsync is superior to scp for large directories or unstable connections. It only transfers the differences between files (deltas), saving bandwidth, and can resume interrupted transfers.
Basic Syntax:
rsync -avz /local/path username@server_ip:/remote/path-
-a: Archive mode (preserves permissions, timestamps, symbolic links). -
-v: Verbose (shows progress). -
-z: Compress data during transfer (faster for slow networks).
Resume a failed transfer (Large Files): If a 10GB transfer fails at 90%, scp starts over. rsync resumes where it left off.
rsync -avz --partial --progress big_file.iso username@server_ip:/remote/path/Option 3: wget (web Get)
While not an SSH tool itself, wget is essential when you are already logged in to a remote server and need to download files directly from the internet.
Download a file:
wget [https://example.com/software.zip](https://example.com/software.zip)Download and rename:
wget -O installer.zip [https://example.com/software-v1.2.3.zip](https://example.com/software-v1.2.3.zip)Option 4: curl (client Url)
Like wget, curl is used to download files from the internet while logged into a server. It is often installed by default on systems (like macOS or minimal containers) where wget might be missing.
Download and save with original filename:
curl -O [https://example.com/software.zip](https://example.com/software.zip)(Note the uppercase O)
Download and rename:
curl -o installer.zip [https://example.com/software.zip](https://example.com/software.zip)(Note the lowercase o)
Option 5: Terminal Web Browsers (lynx and w3m)
If you are stuck in a terminal but need to visit a webpage to find a download link, sign in, or read documentation, these text-based browsers are lifesavers.
Lynx: The classic text-only browser. It is great for keyboard navigation.
sudo apt install lynx
lynx [https://google.com](https://google.com)-
Use
Up/Downarrows to navigate links. -
Press
Enterto follow a link. -
Press
dto download the selected file. -
Press
qto quit.
w3m: A slightly more modern alternative that can sometimes render tables and frames better.
sudo apt install w3m
w3m [https://duckduckgo.com](https://duckduckgo.com)-
Use mouse clicks (in compatible terminals) or arrow keys.
-
Press
Shift+Uto see the URL of a link. -
Press
Bto go back. -
Press
qto quit.
Advanced Ssh Configuration and Security Best Practices
Key Hardening and Enhanced Security
-
Disable Root Login: Edit
/etc/ssh/sshd_configand set:bash PermitRootLogin noWhy? Prevents attackers from guessing the password for the
rootaccount, which exists on every Linux system. -
Change the Default Port: Change
Port 22to something arbitrary (e.g.,2244) insshd_configto reduce noise from automated bots. -
Client Keep-Alive: Prevent your session from freezing by adding this to your local
~/.ssh/config:bash Host * ServerAliveInterval 60 -
Implement Two-Factor Authentication (2FA): Install
libpam-google-authenticatorand configure PAM to require a code from your phone in addition to your SSH key or password.
Centralized Ssh Key Management
As environments scale, managing SSH keys manually becomes unfeasible. Consider these strategies:
-
Inventory and Automated Discovery: Use tools to catalog active keys.
-
Key Rotation Policies: Regularly rotate keys to limit the window of compromise.
-
Certificates: Use SSH Certificate Authorities (CA) instead of static keys. This allows you to issue keys that expire automatically after a set time (e.g., 8 hours).
Conclusion
Managing SSH from the command line provides unparalleled control over your network’s security. By understanding SSH’s principles, employing robust key-based authentication, and leveraging advanced configuration options, you can significantly reduce your attack surface.
Comments
Loading the discussion…