Lewati ke konten
Kembali ke Blog

Tutorial Konfigurasi SSH Server di Linux untuk Remote Access Aman

· · 9 menit baca

SSH (Secure Shell) adalah protokol standar untuk remote access server secara aman. Konfigurasi SSH yang tepat sangat penting untuk keamanan server Anda. Artikel ini akan membahas panduan lengkap mulai dari instalasi hingga hardening SSH server untuk keamanan maksimal.

1. Instalasi SSH Server

Install OpenSSH Server

# Ubuntu/Debian
sudo apt update
sudo apt install openssh-server

Fedora/RHEL/CentOS

sudo dnf install openssh-server

atau untuk versi lama:

sudo yum install openssh-server

Arch Linux

sudo pacman -S openssh

Verifikasi Instalasi dan Status Service

# Cek status SSH service
sudo systemctl status ssh
# atau untuk Fedora/RHEL:
sudo systemctl status sshd

Start SSH service jika belum running

sudo systemctl start ssh sudo systemctl enable ssh

Cek apakah SSH listening di port 22

sudo ss -tlnp | grep ssh

atau:

sudo netstat -tlnp | grep ssh

Cek IP Address untuk Remote Access

# Cek IP address
ip addr show
# atau:
ipconfig

Untuk public IP (jika behind NAT)

curl ifconfig.me curl icanhazip.com

2. Konfigurasi Dasar SSH Client

Cara Remote ke Server

# Remote dengan username dan hostname/IP
ssh username@hostname_or_ip

Contoh:

ssh [email protected] ssh [email protected]

Remote dengan port custom

ssh -p 2222 username@hostname

Remote dengan private key

ssh -i ~/.ssh/private_key username@hostname

Remote dan jalankan command langsung

ssh user@server "ls -la /var/www/"

Konfigurasi SSH Client (~/.ssh/config)

Buat file konfigurasi untuk memudahkan koneksi:

nano ~/.ssh/config

Contoh konfigurasi:

# Server Production
Host prod
    HostName 203.0.113.10
    User admin
    Port 2222
    IdentityFile ~/.ssh/prod_key
    ServerAliveInterval 60
    ServerAliveCountMax 3

Server Development

Host dev HostName 192.168.1.50 User developer IdentityFile ~/.ssh/dev_key

GitHub

Host github HostName github.com User git IdentityFile ~/.ssh/github_key

Wildcard untuk semua host

Host * User defaultuser IdentitiesOnly yes AddKeysToAgent yes UseKeychain yes ServerAliveInterval 60

Dengan konfigurasi ini, Anda bisa koneksi dengan simple:

ssh prod    # Akan connect ke 203.0.113.10:2222 dengan user admin
ssh dev     # Akan connect ke 192.168.1.50 dengan user developer

3. SSH Key Authentication (Passwordless Login)

SSH key authentication lebih aman dan convenient daripada password.

Generate SSH Key Pair

# Generate key dengan default (RSA 3072-bit)
ssh-keygen

Generate key dengan custom type dan comment

ssh-keygen -t ed25519 -C "[email protected]"

Generate key dengan custom filename

ssh-keygen -t rsa -b 4096 -f ~/.ssh/myserver_key -C "myserver access"

Generate key dengan passphrase (recommended)

ssh-keygen -t ed25519 -C "[email protected]"

Enter passphrase: [type secure passphrase]

Recommended: Gunakan Ed25519 untuk key modern, atau RSA 4096-bit untuk compatibility.

Copy Public Key ke Server

# Method 1: Menggunakan ssh-copy-id (recommended)
ssh-copy-id username@hostname

Method 2: Manual copy dengan scp

scp ~/.ssh/id_ed25519.pub username@hostname:~/.ssh/authorized_keys

Method 3: Append ke authorized_keys

ssh username@hostname "mkdir -p ~/.ssh && chmod 700 ~/.ssh" cat ~/.ssh/id_ed25519.pub | ssh username@hostname "cat >> ~/.ssh/authorized_keys"

Verifikasi Key-based Authentication

# Test login dengan key
ssh username@hostname
# Jika berhasil, Anda login tanpa diminta password

SSH Agent untuk Key Management

# Start SSH agent
eval "$(ssh-agent -s)"

Add key ke agent

ssh-add ~/.ssh/id_ed25519

Add key dengan passphrase (hanya perlu enter sekali)

ssh-add ~/.ssh/id_ed25519 Enter passphrase for ~/.ssh/id_ed25519: [enter passphrase]

List keys dalam agent

ssh-add -l

Remove specific key

ssh-add -d ~/.ssh/id_ed25519

Remove all keys

ssh-add -D

Untuk persistency, tambahkan ke ~/.bashrc atau ~/.zshrc:

# Auto-start ssh-agent
if [ -z "$SSH_AUTH_SOCK" ]; then
   eval "$(ssh-agent -s)"
   ssh-add ~/.ssh/id_ed25519
fi

4. Hardening SSH Server (Keamanan)

Edit Konfigurasi SSH Server

# Backup konfigurasi original
sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup

Edit konfigurasi

sudo nano /etc/ssh/sshd_config

Konfigurasi Keamanan yang Direkomendasikan

Disable Root Login

# Jangan izinkan login langsung sebagai root
PermitRootLogin no
# atau jika butuh key-only:
# PermitRootLogin prohibit-password

Disable Password Authentication (Setelah Key Setup)

# Gunakan hanya key authentication
PasswordAuthentication no
ChallengeResponseAuthentication no

Change Default Port (Optional tapi Recommended)

# Ganti dari port 22 ke port custom
Port 2222
# atau:
Port 49152

Update firewall rules setelah mengganti port

Allow Specific Users Only

# Hanya izinkan user tertentu
AllowUsers developer deploy git

Atau izinkan group

AllowGroups sshusers developers

Disable Empty Passwords

PermitEmptyPasswords no

Limit Authentication Attempts

MaxAuthTries 3
MaxSessions 2

Set Timeout untuk Idle Sessions

ClientAliveInterval 300
ClientAliveCountMax 2

Disable X11 Forwarding (jika tidak dibutuhkan)

X11Forwarding no

Use Protocol 2 Only

Protocol 2

Enable Verbose Logging

LogLevel VERBOSE

Contoh Konfigurasi sshd_config Lengkap

# Port dan Protocol
Port 2222
Protocol 2

HostKeys

HostKey /etc/ssh/ssh_host_rsa_key HostKey /etc/ssh/ssh_host_ed25519_key

Logging

SyslogFacility AUTH LogLevel VERBOSE

Authentication

PermitRootLogin no PasswordAuthentication no ChallengeResponseAuthentication no PubkeyAuthentication yes PermitEmptyPasswords no MaxAuthTries 3 MaxSessions 2

Allowed Users

AllowUsers developer backup

Security

X11Forwarding no AllowTcpForwarding no PermitTunnel no GatewayPorts no

Idle timeout

ClientAliveInterval 300 ClientAliveCountMax 2

Disable unused features

UsePAM yes PrintMotd no PrintLastLog yes AcceptEnv LANG LC_*

Subsystem

Subsystem sftp /usr/lib/openssh/sftp-server

Verifikasi dan Restart SSH Service

# Test konfigurasi sebelum restart (penting!)
sudo sshd -t

Jika tidak ada error, restart service

sudo systemctl restart ssh

atau:

sudo systemctl restart sshd

Cek status setelah restart

sudo systemctl status ssh

5. Firewall Configuration untuk SSH

UFW (Ubuntu/Debian)

# Allow SSH di port default
sudo ufw allow ssh
# atau:
sudo ufw allow 22/tcp

Allow SSH di port custom

sudo ufw allow 2222/tcp

Deny semua incoming kecuali SSH

sudo ufw default deny incoming sudo ufw default allow outgoing sudo ufw allow 2222/tcp sudo ufw enable

Cek status

sudo ufw status verbose

Firewalld (Fedora/RHEL/CentOS)

# Add SSH service
sudo firewall-cmd --permanent --add-service=ssh
# atau untuk port custom:
sudo firewall-cmd --permanent --add-port=2222/tcp

Reload firewall

sudo firewall-cmd --reload

Cek active zones

sudo firewall-cmd --get-active-zones sudo firewall-cmd --list-all

iptables (Manual)

# Allow SSH di port 2222
sudo iptables -A INPUT -p tcp --dport 2222 -m state --state NEW,ESTABLISHED -j ACCEPT
sudo iptables -A OUTPUT -p tcp --sport 2222 -m state --state ESTABLISHED -j ACCEPT

Save rules

sudo iptables-save > /etc/iptables/rules.v4

6. Fail2Ban untuk Brute Force Protection

Fail2Ban memonitor log SSH dan block IP yang mencoba brute force.

Instalasi Fail2Ban

# Ubuntu/Debian
sudo apt install fail2ban

Fedora/RHEL

sudo dnf install fail2ban

Enable service

sudo systemctl enable fail2ban sudo systemctl start fail2ban

Konfigurasi Fail2Ban untuk SSH

sudo nano /etc/fail2ban/jail.local
[DEFAULT]
# Ban time: 1 jam
bantime = 3600
# Find time: 10 menit
findtime = 600
# Max retry: 3 kali
maxretry = 3

[sshd] enabled = true port = 2222 filter = sshd logpath = /var/log/auth.log backend = systemd maxretry = 3 bantime = 3600

Verifikasi Fail2Ban

# Cek status
sudo fail2ban-client status

Cek status SSH jail

sudo fail2ban-client status sshd

List banned IPs

sudo fail2ban-client status sshd | grep "Banned IP list"

Unban IP manually

sudo fail2ban-client set sshd unbanip 192.168.1.100

7. SSH Tunneling dan Port Forwarding

Local Port Forwarding

Forward port local ke remote server:

# Akses MySQL di remote server via port local 3307
ssh -L 3307:localhost:3306 user@remote-server

Sekarang konek ke MySQL via:

mysql -h 127.0.0.1 -P 3307 -u dbuser -p

Remote Port Forwarding

Expose port local ke remote server:

# Expose web server local (port 8080) ke remote server (port 9090)
ssh -R 9090:localhost:8080 user@remote-server

Sekarang orang bisa akses http://remote-server:9090

Dynamic Port Forwarding (SOCKS Proxy)

# Create SOCKS proxy di port 1080
ssh -D 1080 user@remote-server

Configure browser untuk gunakan SOCKS proxy localhost:1080

8. SFTP (Secure File Transfer)

SFTP adalah cara aman untuk transfer file via SSH.

Setup SF-only User (No Shell Access)

# Buat group untuk SFTP-only users
sudo groupadd sftpusers

Buat user baru

sudo useradd -m -G sftpusers -s /sbin/nologin sftpuser sudo passwd sftpuser

Atau modify user existing

sudo usermod -G sftpusers -s /sbin/nologin username

Konfigurasi Chroot Jail di sshd_config

Match Group sftpusers
    ChrootDirectory /srv/sftp/%u
    AllowTcpForwarding no
    X11Forwarding no
    ForceCommand internal-sftp

Setup Directory Structure

# Buat directory untuk chroot jail
sudo mkdir -p /srv/sftp/sftpuser/upload
sudo chown root:root /srv/sftp/sftpuser
sudo chmod 755 /srv/sftp/sftpuser
sudo chown sftpuser:sftpusers /srv/sftp/sftpuser/upload

Restart SSH

sudo systemctl restart ssh

Menggunakan SFTP Client

# Command line SFTP
sftp -P 2222 user@hostname

Transfer file

sftp> put localfile.txt sftp> get remotefile.txt sftp> put -r localdirectory/ sftp> get -r remotedirectory/

GUI client: FileZilla, WinSCP

Host: hostname

Port: 2222

Protocol: SFTP

Logon Type: Key file

9. Monitoring dan Logging SSH

Cek Log SSH

# Debian/Ubuntu
sudo tail -f /var/log/auth.log

Fedora/RHEL

sudo tail -f /var/log/secure

Systemd journal

sudo journalctl -u ssh -f

Analisis Login Attempts

# Cek failed login attempts
sudo grep "Failed password" /var/log/auth.log

Cek successful logins

sudo grep "Accepted" /var/log/auth.log

Cek invalid users

sudo grep "Invalid user" /var/log/auth.log | awk '{print $9}' | sort | uniq -c | sort -rn

Statistik login per IP

sudo grep "Accepted" /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -rn

Real-time Monitoring

# Pantau login real-time
sudo tail -f /var/log/auth.log | grep "Accepted"

Pantau semua SSH connections

watch -n 1 "ss -tn | grep :22"

Cek user yang sedang login

who w last

10. Backup dan Recovery SSH Keys

Backup SSH Keys

# Backup seluruh direktori .ssh
tar -czvf ssh-backup-$(date +%Y%m%d).tar.gz ~/.ssh/

Copy ke external drive atau cloud storage

JANGAN pernah share private key!

Generate New Keys (Jika Compromised)

# Revoke old key dari server
ssh-keygen -R hostname

Generate new key pair

ssh-keygen -t ed25519 -f ~/.ssh/id_ed25519_new

Copy new public key ke server

ssh-copy-id -i ~/.ssh/id_ed25519_new.pub user@hostname

Update SSH config

Kesimpulan

SSH server yang dikonfigurasi dengan baik adalah fondasi keamanan infrastruktur IT modern. Dengan mengikuti panduan ini, Anda mendapatkan:

  1. Remote access aman dengan enkripsi strong
  2. Key-based authentication tanpa password
  3. Hardened configuration yang menghambat attacker
  4. Brute force protection dengan fail2ban
  5. Secure file transfer via SFTP

Ingat selalu untuk:
– Backup private keys dengan aman
– Gunakan passphrase untuk extra security
– Monitor logs secara berkala
– Update OpenSSH untuk security patches
– Test konfigurasi sebelum apply ke production

Dengan SSH yang terkonfigurasi benar, Anda bisa mengelola server dari mana saja dengan aman dan nyaman.

Ditulis oleh

Hendra Wijaya

Tinggalkan Komentar

Email tidak akan ditampilkan.