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/configso a long command becomesssh 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_configand 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.
~/.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 trustThe 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.
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.
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 permissionsls -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 testssh-copy-id -i ~/.ssh/id_ed25519.pub rahul@10.0.1.50ssh rahul@10.0.1.50When 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 MistakeCreating 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-agentso you only type it once per session.
TipFor 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.
mkdir -p ~/.ssh && chmod 700 ~/.sshtouch ~/.ssh/config && chmod 600 ~/.ssh/confignano ~/.ssh/config# ~/.ssh/config # Bastion hostHost bastion HostName 52.66.100.200 User rahul IdentityFile ~/.ssh/id_ed25519 # Production servers, reached through the bastionHost 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 accountHost 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# Connect with the aliasssh 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.
# Install your key on the bastion, then on the internal server through the aliasssh-copy-id -i ~/.ssh/id_ed25519.pub bastionssh-copy-id -i ~/.ssh/id_ed25519.pub payment-prod-api-1 # One-off jump without a config entryssh -J rahul@52.66.100.200 rahul@10.0.1.50 # Multiple hopsssh -J bastion1,bastion2 rahul@internal-server # Copy files through the same pathscp ./release.tar.gz payment-prod-api-1:/tmp/Common MistakeUsing
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.ProxyJumpgives 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.
# Local forward: localhost:5433 reaches the database 10.0.2.100:5432 via payment-prod-api-1ssh -L 5433:10.0.2.100:5432 payment-prod-api-1 # In another terminal, use it as if it were localpsql -h localhost -p 5433 -U postgres payments # Reach an internal Grafana on the server's own localhostssh -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 serverssh -D 1080 payment-prod-api-1The 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.
# Start an agent if your desktop has not alreadyeval "$(ssh-agent -s)" # Add a key (prompts for the passphrase once)ssh-add ~/.ssh/id_ed25519 # Add a key that expires after 8 hoursssh-add -t 8h ~/.ssh/id_ed25519 # List and clear loaded keysssh-add -lssh-add -DHow 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.
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 noPasswordAuthentication noKbdInteractiveAuthentication noAllowUsers rahul deploy jenkinsMaxAuthTries 3LoginGraceTime 30ClientAliveInterval 300ClientAliveCountMax 2X11Forwarding noAllowAgentForwarding noLogLevel VERBOSE # Disable tunnels globally, then allow them for named engineersAllowTcpForwarding noMatch User rahul AllowTcpForwarding yesEOF # Validate, inspect the effective values, then reloadsudo sshd -tsudo sshd -T | grep -E 'passwordauthentication|permitrootlogin|allowtcpforwarding'sudo systemctl reload ssh || sudo systemctl reload sshdVerify from a second terminal before you close the first one:
ssh payment-prod-api-1RememberAlways keep an existing session open while you change
sshdsettings. If the new configuration locks you out, that session lets you fix it without console access.
SecurityTreat every private key as a credential. Use one key per person and device, remove keys from
authorized_keyswhen 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.
# Client side: show every step of the handshakessh -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 -tor 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/configsnippet (without keys) so the team uses the same aliases. - Test config before reloading. Run
sshd -t, inspect withsshd -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 60sends 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 |