OpenSSH Server and Client

Level: Intermediate Module: Security & Authentication 7 min read Lesson 47 of 66

Overview

  • What you will learn: How to install and configure the OpenSSH server and client, set up key-based authentication, disable password login, harden sshd_config, use SSH tunneling (local, remote, dynamic), configure ProxyJump for bastion hosts, and manage connections with ssh-agent and ~/.ssh/config.
  • Prerequisites: Lesson 46 (Linux Security Fundamentals)
  • Estimated reading time: 25 minutes

Introduction

OpenSSH is the standard tool for secure remote administration of Linux servers. It provides encrypted communication, strong authentication, and a suite of utilities for file transfer and network tunneling. Nearly every Linux server runs an SSH daemon, making it the primary entry point for administrators.

In this lesson we cover the full lifecycle of SSH configuration: installing the server, generating and deploying key pairs, hardening the daemon configuration, and using advanced client features that simplify daily operations across multi-server environments.

Proper SSH configuration is one of the single most impactful security measures you can take — a misconfigured SSH server is a common target for automated attacks.

Installing and Starting OpenSSH

# Install the server (usually pre-installed on Ubuntu Server)
$ sudo apt install openssh-server

# Check status
$ sudo systemctl status sshd

# Key configuration file
$ ls -la /etc/ssh/sshd_config

# View current settings (non-default only)
$ sudo sshd -T | head -30

Key-Based Authentication

Key-based authentication is more secure than passwords because it relies on a cryptographic key pair. The private key stays on your workstation; the public key is placed on the server.

Generating a Key Pair

# Generate an Ed25519 key (recommended)
$ ssh-keygen -t ed25519 -C "admin@example.com"
Generating public/private ed25519 key pair.
Enter file in which to save the key (/home/admin/.ssh/id_ed25519):
Enter passphrase (empty for no passphrase):

# For legacy systems that require RSA
$ ssh-keygen -t rsa -b 4096 -C "admin@example.com"

# View the public key
$ cat ~/.ssh/id_ed25519.pub
ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAI... admin@example.com

Deploying the Public Key

# Method 1: ssh-copy-id (easiest)
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# Method 2: Manual copy
$ cat ~/.ssh/id_ed25519.pub | ssh user@server 'mkdir -p ~/.ssh && chmod 700 ~/.ssh && cat >> ~/.ssh/authorized_keys && chmod 600 ~/.ssh/authorized_keys'

# Verify
$ ssh user@server   # should not prompt for password

Hardening sshd_config

After key-based authentication works, harden the server configuration.

# /etc/ssh/sshd_config — recommended settings
Port 2222                          # Change from default 22
AddressFamily inet                 # IPv4 only if IPv6 not needed
ListenAddress 0.0.0.0

# Authentication
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AuthenticationMethods publickey
PermitEmptyPasswords no
MaxAuthTries 3
LoginGraceTime 30

# Access control
AllowUsers admin deploy
# Or restrict by group:
# AllowGroups ssh-users

# Security
X11Forwarding no
AllowTcpForwarding yes
AllowAgentForwarding yes
ClientAliveInterval 300
ClientAliveCountMax 2
MaxSessions 5
Banner /etc/ssh/banner

# Cryptography (modern algorithms only)
KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org
Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com
MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com
HostKeyAlgorithms ssh-ed25519,rsa-sha2-512
# Validate configuration before restarting
$ sudo sshd -t

# Restart the service
$ sudo systemctl restart sshd

# Test from another terminal BEFORE closing your current session
$ ssh -p 2222 admin@server

SSH Tunneling

SSH tunnels allow you to securely forward network traffic through an encrypted SSH connection.

Local Port Forwarding (-L)

Access a remote service through a local port. Useful for reaching databases or admin panels that only listen on localhost.

# Forward local port 3307 to remote MySQL (127.0.0.1:3306)
$ ssh -L 3307:127.0.0.1:3306 admin@dbserver

# Now connect to MySQL locally
$ mysql -h 127.0.0.1 -P 3307 -u app_user -p

Remote Port Forwarding (-R)

Expose a local service to a remote server. Useful for making a development server accessible through a public host.

# Make local port 8080 accessible as port 9090 on the remote server
$ ssh -R 9090:127.0.0.1:8080 admin@public-server

Dynamic Port Forwarding (-D) — SOCKS Proxy

# Create a SOCKS5 proxy on local port 1080
$ ssh -D 1080 admin@server

# Configure your browser to use SOCKS5 proxy 127.0.0.1:1080
# All browser traffic is tunneled through the SSH connection

ProxyJump and Bastion Hosts

A bastion host (jump server) is a hardened server that serves as the only entry point to a private network.

# Direct jump via command line
$ ssh -J bastion.example.com internal-server

# Multi-hop
$ ssh -J bastion1,bastion2 internal-server

~/.ssh/config for ProxyJump

# ~/.ssh/config
Host bastion
    HostName bastion.example.com
    User admin
    Port 2222
    IdentityFile ~/.ssh/id_ed25519

Host internal-*
    ProxyJump bastion
    User deploy
    IdentityFile ~/.ssh/id_ed25519

Host internal-web
    HostName 10.0.1.10

Host internal-db
    HostName 10.0.1.20

# Usage: just type
$ ssh internal-web
$ ssh internal-db

SSH Agent

The SSH agent holds your decrypted private keys in memory so you do not have to type your passphrase repeatedly.

# Start the agent (usually automatic in desktop environments)
$ eval $(ssh-agent -s)
Agent pid 12345

# Add your key
$ ssh-add ~/.ssh/id_ed25519
Enter passphrase for /home/admin/.ssh/id_ed25519:
Identity added: /home/admin/.ssh/id_ed25519

# List loaded keys
$ ssh-add -l

# Forward agent to remote server (use with caution)
$ ssh -A admin@server

Advanced ~/.ssh/config

# ~/.ssh/config — global defaults
Host *
    ServerAliveInterval 60
    ServerAliveCountMax 3
    AddKeysToAgent yes
    IdentitiesOnly yes
    HashKnownHosts yes
    VisualHostKey yes

# Per-host overrides
Host production
    HostName prod.example.com
    User deploy
    Port 2222
    IdentityFile ~/.ssh/id_ed25519_prod
    ForwardAgent no
    LocalForward 5433 127.0.0.1:5432

Host staging
    HostName staging.example.com
    User deploy
    IdentityFile ~/.ssh/id_ed25519
    DynamicForward 1080

SCP and SFTP

# Copy a file to a remote server
$ scp -P 2222 localfile.tar.gz admin@server:/tmp/

# Copy from remote to local
$ scp admin@server:/var/log/syslog ./syslog.bak

# Recursive copy
$ scp -r ./project admin@server:/opt/

# SFTP interactive session
$ sftp admin@server
sftp> put localfile.txt /tmp/
sftp> get /var/log/auth.log ./
sftp> ls -la /etc/
sftp> bye

Key Takeaways

  • Always use key-based authentication (Ed25519 preferred) and disable password login in sshd_config.
  • Harden the server: change the port, set PermitRootLogin no, limit users with AllowUsers/AllowGroups, reduce MaxAuthTries.
  • Use modern cryptographic algorithms and disable legacy ciphers.
  • SSH tunneling (-L, -R, -D) provides secure access to services without exposing them to the network.
  • ProxyJump simplifies multi-hop access through bastion hosts.
  • ssh-agent manages key passphrases; ~/.ssh/config centralizes per-host connection settings.
  • Always test new SSH configurations from a second session before closing your active connection.

What’s Next

In the next lesson you will learn about AppArmor Mandatory Access Control — how to confine applications using security profiles that restrict file access, network capabilities, and system call usage.

繁體中文

概述

  • 學習目標:如何安裝和設定 OpenSSH 伺服器和客戶端、設定金鑰認證、停用密碼登入、強化 sshd_config、使用 SSH 通道(本地、遠端、動態)、設定 ProxyJump 用於跳板主機,以及使用 ssh-agent 和 ~/.ssh/config 管理連線。
  • 先決條件:第 46 課(Linux 安全基礎)
  • 預計閱讀時間:25 分鐘

簡介

OpenSSH 是 Linux 伺服器安全遠端管理的標準工具。它提供加密通訊、強認證,以及一套用於檔案傳輸和網路通道的工具。幾乎每台 Linux 伺服器都運行 SSH 守護程式,使其成為管理員的主要入口。

正確的 SSH 設定是您可以採取的最具影響力的安全措施之一——設定錯誤的 SSH 伺服器是自動化攻擊的常見目標。

安裝和啟動 OpenSSH

# 安裝伺服器
$ sudo apt install openssh-server

# 檢查狀態
$ sudo systemctl status sshd

金鑰認證

金鑰認證比密碼更安全,因為它依賴密碼學金鑰對。私鑰留在您的工作站上;公鑰放置在伺服器上。

# 產生 Ed25519 金鑰(推薦)
$ ssh-keygen -t ed25519 -C "admin@example.com"

# 部署公鑰
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# 驗證
$ ssh user@server   # 不應提示輸入密碼

強化 sshd_config

# /etc/ssh/sshd_config — 建議設定
Port 2222                          # 從預設 22 更改
PermitRootLogin no                 # 禁止 root 登入
PasswordAuthentication no          # 停用密碼認證
PubkeyAuthentication yes           # 啟用公鑰認證
AllowUsers admin deploy            # 僅允許特定使用者
MaxAuthTries 3                     # 限制認證嘗試次數
ClientAliveInterval 300            # 空閒連線超時
X11Forwarding no                   # 停用 X11 轉發
# 重啟前驗證設定
$ sudo sshd -t

# 重啟服務
$ sudo systemctl restart sshd

# 從另一個終端測試,在關閉當前連線之前
$ ssh -p 2222 admin@server

SSH 通道

本地埠轉發(-L)

透過本地埠存取遠端服務。適用於存取僅監聽在 localhost 的資料庫或管理面板。

# 將本地埠 3307 轉發到遠端 MySQL
$ ssh -L 3307:127.0.0.1:3306 admin@dbserver

遠端埠轉發(-R)

將本地服務暴露給遠端伺服器。

$ ssh -R 9090:127.0.0.1:8080 admin@public-server

動態埠轉發(-D)— SOCKS 代理

$ ssh -D 1080 admin@server
# 設定瀏覽器使用 SOCKS5 代理 127.0.0.1:1080

ProxyJump 和跳板主機

# 透過命令列直接跳轉
$ ssh -J bastion.example.com internal-server

# ~/.ssh/config 設定
Host bastion
    HostName bastion.example.com
    User admin
    Port 2222

Host internal-*
    ProxyJump bastion
    User deploy

SSH Agent

# 啟動 agent
$ eval $(ssh-agent -s)

# 添加金鑰
$ ssh-add ~/.ssh/id_ed25519

# 列出已載入的金鑰
$ ssh-add -l

SCP 和 SFTP

# 複製檔案到遠端伺服器
$ scp -P 2222 localfile.tar.gz admin@server:/tmp/

# 互動式 SFTP 工作階段
$ sftp admin@server

重點摘要

  • 始終使用金鑰認證(推薦 Ed25519)並在 sshd_config 中停用密碼登入。
  • 強化伺服器:更改埠、設定 PermitRootLogin no、使用 AllowUsers/AllowGroups 限制使用者。
  • 使用現代加密演算法並停用傳統密碼。
  • SSH 通道(-L-R-D)提供安全存取服務而無需將其暴露到網路。
  • ProxyJump 簡化透過跳板主機的多跳存取。
  • ssh-agent 管理金鑰密碼;~/.ssh/config 集中每台主機的連線設定。
  • 在關閉活動連線之前,始終從第二個工作階段測試新的 SSH 設定。

下一步

在下一課中,您將學習 AppArmor 強制存取控制——如何使用安全設定檔來限制應用程式的檔案存取、網路能力和系統呼叫使用。

日本語

概要

  • 学習内容:OpenSSH サーバーとクライアントのインストールと設定、鍵ベースの認証の設定、パスワードログインの無効化、sshd_config の強化、SSH トンネリング(ローカル、リモート、ダイナミック)の使用、踏み台ホスト用の ProxyJump の設定、ssh-agent と ~/.ssh/config による接続管理。
  • 前提条件:レッスン46(Linux セキュリティ基礎)
  • 推定読了時間:25分

はじめに

OpenSSH は Linux サーバーの安全なリモート管理のための標準ツールです。暗号化された通信、強力な認証、ファイル転送やネットワークトンネリングのためのユーティリティスイートを提供します。

適切な SSH 設定は、最も影響力のあるセキュリティ対策の一つです。設定が不適切な SSH サーバーは自動化された攻撃の一般的なターゲットです。

OpenSSH のインストールと起動

# サーバーのインストール
$ sudo apt install openssh-server

# ステータスの確認
$ sudo systemctl status sshd

鍵ベースの認証

鍵ベースの認証は、暗号鍵ペアに依存するため、パスワードよりも安全です。秘密鍵はワークステーションに保管し、公開鍵はサーバーに配置します。

# Ed25519 鍵の生成(推奨)
$ ssh-keygen -t ed25519 -C "admin@example.com"

# 公開鍵のデプロイ
$ ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# 検証
$ ssh user@server   # パスワードを求められないはず

sshd_config の強化

# /etc/ssh/sshd_config — 推奨設定
Port 2222                          # デフォルトの22から変更
PermitRootLogin no                 # rootログインを禁止
PasswordAuthentication no          # パスワード認証を無効化
PubkeyAuthentication yes           # 公開鍵認証を有効化
AllowUsers admin deploy            # 特定のユーザーのみ許可
MaxAuthTries 3                     # 認証試行回数を制限
ClientAliveInterval 300            # アイドル接続タイムアウト
X11Forwarding no                   # X11転送を無効化
# 再起動前に設定を検証
$ sudo sshd -t

# サービスの再起動
$ sudo systemctl restart sshd

# 現在の接続を閉じる前に別のターミナルからテスト
$ ssh -p 2222 admin@server

SSH トンネリング

ローカルポートフォワーディング(-L)

ローカルポートを通じてリモートサービスにアクセスします。localhost のみでリッスンするデータベースや管理パネルへのアクセスに便利です。

# ローカルポート3307をリモートMySQL(127.0.0.1:3306)に転送
$ ssh -L 3307:127.0.0.1:3306 admin@dbserver

リモートポートフォワーディング(-R)

ローカルサービスをリモートサーバーに公開します。

$ ssh -R 9090:127.0.0.1:8080 admin@public-server

ダイナミックポートフォワーディング(-D)— SOCKSプロキシ

$ ssh -D 1080 admin@server
# ブラウザで SOCKS5 プロキシ 127.0.0.1:1080 を使用するように設定

ProxyJump と踏み台ホスト

# コマンドラインからの直接ジャンプ
$ ssh -J bastion.example.com internal-server

# ~/.ssh/config の設定
Host bastion
    HostName bastion.example.com
    User admin
    Port 2222

Host internal-*
    ProxyJump bastion
    User deploy

SSH エージェント

# エージェントの起動
$ eval $(ssh-agent -s)

# 鍵の追加
$ ssh-add ~/.ssh/id_ed25519

# ロードされた鍵の一覧
$ ssh-add -l

SCP と SFTP

# リモートサーバーにファイルをコピー
$ scp -P 2222 localfile.tar.gz admin@server:/tmp/

# インタラクティブ SFTP セッション
$ sftp admin@server

重要ポイント

  • 常に鍵ベースの認証(Ed25519 推奨)を使用し、sshd_config でパスワードログインを無効化する。
  • サーバーを強化:ポートの変更、PermitRootLogin no の設定、AllowUsers/AllowGroups でユーザーを制限。
  • 最新の暗号アルゴリズムを使用し、レガシー暗号を無効化する。
  • SSH トンネリング(-L-R-D)はサービスをネットワークに公開せずに安全なアクセスを提供する。
  • ProxyJump は踏み台ホストを介したマルチホップアクセスを簡素化する。
  • ssh-agent は鍵のパスフレーズを管理し、~/.ssh/config はホストごとの接続設定を集約する。
  • アクティブな接続を閉じる前に、必ず2番目のセッションから新しい SSH 設定をテストする。

次のステップ

次のレッスンでは、AppArmor 強制アクセス制御について学びます。セキュリティプロファイルを使用してアプリケーションのファイルアクセス、ネットワーク機能、システムコールの使用を制限する方法を学びます。

You Missed