Skip to main content

Configuring SSH for Secure Server Access

Generate Ed25519 keys, write ~/.ssh/config, use ProxyJump bastions, tunnel ports and harden sshd for secure Linux server access.

30 Terms

Overview and What You Will Learn

SSH (Secure Shell) is an encrypted protocol for logging in to and running commands on remote Linux servers. Most engineers only use ssh user@host, but key pairs, a well-written ~/.ssh/config, jump hosts and tunnels make it faster, safer and far more capable.

By the end of this lab you will be able to:

  • Generate and deploy an Ed25519 key pair with a passphrase
  • Write ~/.ssh/config so a long command becomes ssh payment-prod-db-1
  • Reach private servers through a bastion host with ProxyJump
  • Forward ports to internal services such as PostgreSQL and Grafana
  • Harden sshd_config and keep a recovery path while you do it
  • Troubleshoot connection failures in a fixed order

Why This Matters in Production

Production servers at companies like Razorpay or Grab usually have no public address. Engineers reach them through a single bastion host that is the controlled entry point, so every connection needs a jump. Without a good SSH config that is a long command with several flags. With one, it is ssh payment-prod-api-1. The other side of the coin is risk: password logins, root access and unprotected private keys are among the most common ways SSH-reachable servers are compromised.

Core Principles

SSH uses public-key authentication: the server stores your public key, and you prove you own the private key by signing a challenge, so no secret crosses the network. Permissions matter because SSH refuses to use files that other users can read or write.

TEXT
~/.ssh/ 700 directory
~/.ssh/config 600 client settings
~/.ssh/id_ed25519 600 private key (never share)
~/.ssh/id_ed25519.pub 644 public key (safe to share)
~/.ssh/authorized_keys 600 public keys allowed to log in (on servers)
~/.ssh/known_hosts 600 fingerprints of servers you trust
sequenceDiagram participant C as Client participant S as sshd Server C->>S: Connect on port 22 S-->>C: Host key and algorithms Note over C,S: Encrypted session established C->>S: Username and public key S-->>C: Challenge C->>S: Signature from private key S-->>C: Verified, shell opens

The bastion pattern keeps application servers off the internet. Your laptop opens one SSH connection to the bastion, and ProxyJump tunnels the second connection through it without ever exposing your private key to the bastion.

flowchart LR A([Laptop]) -->|SSH 22| B[Bastion
public IP] subgraph V[Private subnet ap-south-1] C[payment-prod-api-1] D[(payment-prod-db-1)] end B -->|ProxyJump| C B -->|ProxyJump| D classDef person fill:#8B5CF6,color:#FFFFFF classDef edge fill:#F97316,color:#FFFFFF classDef inner fill:#326CE5,color:#FFFFFF class A person class B edge class C,D inner

Detailed Step-by-Step Practical Lab

How to Generate an Ed25519 SSH Key Pair

Ed25519 is a modern elliptic-curve key type that is fast, produces short keys and is supported by current OpenSSH. Generate one per device, protect it with a passphrase, and copy only the public half to servers.

Bash
ssh-keygen -t ed25519 -C "rahul@devops.in"
# Enter file in which to save the key (/home/rahul/.ssh/id_ed25519): [Enter]
# Enter passphrase (empty for no passphrase): [use a strong passphrase]
# Check permissions
ls -la ~/.ssh/
# -rw------- id_ed25519
# -rw-r--r-- id_ed25519.pub
# Show the public key (safe to share)
cat ~/.ssh/id_ed25519.pub
# Install it on a server, then test
ssh-copy-id -i ~/.ssh/id_ed25519.pub rahul@10.0.1.50
ssh rahul@10.0.1.50

When you first connect to a new server, SSH shows its host key fingerprint. Compare it with a trusted source (cloud console output or your provisioning tool) before typing yes, because accepting blindly defeats server authentication.

Common Mistake

Creating a key with no passphrase "for convenience". If the laptop is stolen or compromised, an unprotected private key gives instant access to every server that trusts it. Use a passphrase and ssh-agent so you only type it once per session.

Tip

For the strongest protection, use a hardware security key with ssh-keygen -t ed25519-sk. The private key never leaves the device, and the server must also see a physical touch.

How to Configure ~/.ssh/config for One-Command Access

The client config file maps short aliases to full connection settings. OpenSSH uses the first value it finds for each option, so put specific Host blocks first and the catch-all Host * last.

Bash
mkdir -p ~/.ssh && chmod 700 ~/.ssh
touch ~/.ssh/config && chmod 600 ~/.ssh/config
nano ~/.ssh/config
Bash
# ~/.ssh/config
# Bastion host
Host bastion
HostName 52.66.100.200
User rahul
IdentityFile ~/.ssh/id_ed25519
# Production servers, reached through the bastion
Host payment-prod-*
User rahul
ProxyJump bastion
IdentityFile ~/.ssh/id_ed25519
Host payment-prod-api-1
HostName 10.0.1.50
Host payment-prod-db-1
HostName 10.0.2.100
# Staging uses a separate key and account
Host staging-*
User deploy
ProxyJump bastion
IdentityFile ~/.ssh/id_ed25519_staging
Host staging-api
HostName 10.0.10.50
# Defaults for everything else (keep this block last)
Host *
ServerAliveInterval 60
ServerAliveCountMax 3
AddKeysToAgent yes
IdentitiesOnly yes
# Reuse one connection for repeated ssh and scp commands
ControlMaster auto
ControlPath ~/.ssh/cm-%C
ControlPersist 10m
# macOS only: ignored on Linux instead of causing an error
IgnoreUnknown UseKeychain
UseKeychain yes
Bash
# Connect with the alias
ssh payment-prod-api-1
# Show the effective settings SSH will use for a host (great for debugging)
ssh -G payment-prod-api-1 | grep -E '^(hostname|user|proxyjump|identityfile) '
How to Use ProxyJump to Reach Servers Through a Bastion

ProxyJump (-J) connects to a bastion first and then opens a second SSH session through it. Your keys stay on your machine and the bastion only relays encrypted traffic.

Bash
# Install your key on the bastion, then on the internal server through the alias
ssh-copy-id -i ~/.ssh/id_ed25519.pub bastion
ssh-copy-id -i ~/.ssh/id_ed25519.pub payment-prod-api-1
# One-off jump without a config entry
ssh -J rahul@52.66.100.200 rahul@10.0.1.50
# Multiple hops
ssh -J bastion1,bastion2 rahul@internal-server
# Copy files through the same path
scp ./release.tar.gz payment-prod-api-1:/tmp/
Common Mistake

Using ssh -A (agent forwarding) on every connection. It exposes your agent socket on the remote host, so anyone with root there can use your keys to reach other servers as you. ProxyJump gives the same reach without exposing the agent.

How to Use SSH Port Forwarding to Reach Internal Services

Port forwarding wraps another TCP connection in your SSH session. Use it to reach a database or dashboard that is not exposed to the internet, instead of opening a firewall port.

Bash
# Local forward: localhost:5433 reaches the database 10.0.2.100:5432 via payment-prod-api-1
ssh -L 5433:10.0.2.100:5432 payment-prod-api-1
# In another terminal, use it as if it were local
psql -h localhost -p 5433 -U postgres payments
# Reach an internal Grafana on the server's own localhost
ssh -L 3000:localhost:3000 payment-prod-api-1
# then open http://localhost:3000
# Run in the background (-f) without a shell (-N)
ssh -fN -L 5433:10.0.2.100:5432 payment-prod-api-1
# Remote forward: expose your local port 3000 on the server's port 8080 (webhook testing)
ssh -R 8080:localhost:3000 payment-prod-api-1
# Dynamic SOCKS proxy for browsing through the server
ssh -D 1080 payment-prod-api-1

The server must allow it: tunnels need AllowTcpForwarding yes. If you disabled it globally, enable it for specific users in a Match block (shown below).

How to Manage Keys with ssh-agent

ssh-agent holds your decrypted key in memory so you enter the passphrase once. Add keys with a lifetime so they expire at the end of the working day.

Bash
# Start an agent if your desktop has not already
eval "$(ssh-agent -s)"
# Add a key (prompts for the passphrase once)
ssh-add ~/.ssh/id_ed25519
# Add a key that expires after 8 hours
ssh-add -t 8h ~/.ssh/id_ed25519
# List and clear loaded keys
ssh-add -l
ssh-add -D
How to Harden sshd on the Server

The server side is configured in sshd_config, and the safest method is a drop-in file that is read before cloud-provided ones (sshd uses the first value it reads per option). The full production baseline, including firewall and fail2ban, is covered in the server hardening lab. The essentials are below.

Bash
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup
sudo tee /etc/ssh/sshd_config.d/00-ssh-access.conf > /dev/null << 'EOF'
PermitRootLogin no
PasswordAuthentication no
KbdInteractiveAuthentication no
AllowUsers rahul deploy jenkins
MaxAuthTries 3
LoginGraceTime 30
ClientAliveInterval 300
ClientAliveCountMax 2
X11Forwarding no
AllowAgentForwarding no
LogLevel VERBOSE
# Disable tunnels globally, then allow them for named engineers
AllowTcpForwarding no
Match User rahul
AllowTcpForwarding yes
EOF
# Validate, inspect the effective values, then reload
sudo sshd -t
sudo sshd -T | grep -E 'passwordauthentication|permitrootlogin|allowtcpforwarding'
sudo systemctl reload ssh || sudo systemctl reload sshd

Verify from a second terminal before you close the first one:

Bash
ssh payment-prod-api-1
Remember

Always keep an existing session open while you change sshd settings. If the new configuration locks you out, that session lets you fix it without console access.

Security

Treat every private key as a credential. Use one key per person and device, remove keys from authorized_keys when people leave, and never copy a private key to a server or chat tool.

How to Troubleshoot SSH Connection Failures

Work from the outside in: reach the host, reach the port, authenticate, then check permissions. Verbose mode shows exactly which step fails.

Bash
# Client side: show every step of the handshake
ssh -vvv payment-prod-api-1
# Is the port reachable at all?
nc -zv 10.0.1.50 22
# Server side: read the log for the failed attempt (unit is ssh or sshd)
sudo journalctl -u ssh -n 50 --no-pager
Symptom Likely cause Fix
Connection timed out Firewall, security group or wrong IP Check security group, ufw status and the route
Connection refused sshd not running or wrong port systemctl status ssh, confirm the port
Permission denied (publickey) Key not installed or wrong user Check authorized_keys, AllowUsers, ssh -vvv
Bad permissions or key ignored Loose file modes chmod 700 ~/.ssh and chmod 600 on keys and config
Host key verification failed Server was rebuilt or you are being intercepted Confirm with the owner, then ssh-keygen -R host
Drops after idle time NAT or firewall timeout Set ServerAliveInterval 60 in ~/.ssh/config

Production Best Practices & Common Pitfalls

  • One key per person and device. Shared keys cannot be revoked for one person and make audit logs meaningless.
  • Always use a passphrase. Combine it with ssh-agent -t or a hardware key for convenience without weakening protection.
  • Prefer ProxyJump to agent forwarding. It reaches the same servers without exposing your agent.
  • Keep infrastructure in version control. Store a shared ~/.ssh/config snippet (without keys) so the team uses the same aliases.
  • Test config before reloading. Run sshd -t, inspect with sshd -T, and keep a second session open.
  • Close ports instead of hiding them. Use tunnels for databases and dashboards rather than exposing them. Changing the SSH port only reduces scan noise and is not a security control.
Scenario Wrong Correct
New server Leave passwords enabled Disable password auth once keys work
Team access Share one key One key per engineer
Debugging Guess ssh -vvv user@host
Internal database Open the DB port to the internet SSH local port forward
Config change Apply and close the session sshd -t, then test from a second terminal
Tip

ServerAliveInterval 60 sends a keepalive every 60 seconds, so connections through NAT or firewalls with idle timeouts stay open instead of dying silently.

Quick Reference & Troubleshooting Commands

Task Command
Generate a key ssh-keygen -t ed25519 -C "email"
Copy key to server ssh-copy-id -i ~/.ssh/id_ed25519.pub user@host
Connect via bastion ssh -J bastion user@internal-host
Local port forward ssh -L localport:remotehost:remoteport user@host
Show effective client config ssh -G host
Debug a connection ssh -vvv user@host
Test sshd config sudo sshd -t
Show effective sshd config sudo sshd -T
Load a key in the agent ssh-add ~/.ssh/id_ed25519
Remove a stale host key ssh-keygen -R host

Resources

Explore More in Linux Networking and Security

All 4 Topics

Frequently Asked Questions

Is Configuring SSH for Secure Server Access free to learn on DevOps Network?

Yes - this topic, like everything on DevOps Network, is 100% free with no paywall or sign-up gate.

What does the Configuring SSH for Secure Server Access topic cover?

Generate Ed25519 keys, write ~/.ssh/config, use ProxyJump bastions, tunnel ports and harden sshd for secure Linux server access.

Found a mistake, an outdated step or a broken link?