BAB 13 - KEAMANAN SERVER
PENGANTAR BAB
Server adalah jantung infrastruktur IT modern. Dari website yang Anda kunjungi, email yang Anda kirim, hingga transaksi banking - semuanya berjalan di atas server. Menurut W3Techs 2024, 94% server web dunia menggunakan Linux, menjadikannya platform server paling dominan.
Server berbeda dari workstation biasa. Server harus selalu tersedia (24/7), menangani ribuan koneksi simultan, menyimpan data kritis, dan menjadi target utama penyerang profesional. Menurut IBM Cost of a Data Breach 2023, breach yang melibatkan server memiliki biaya rata-rata $4.45 juta - tertinggi dari semua jenis breach.
Bab ini akan membawa Anda dari konsep dasar keamanan server hingga praktik hardening, konfigurasi SSH, firewall, log management, dan monitoring. Setelah bab ini, Anda akan mampu mengamankan server Linux production dari berbagai ancaman.
W3Techs 2024
IBM 2023
IBM 2023
Industry Standard
- Memahami konsep server security dan perbedaannya dengan workstation
- Mengenal jenis-jenis server dan layanan yang berjalan
- Melakukan server hardening berdasarkan CIS Benchmarks
- Mengelola user, group, dan permission dengan aman
- Mengamankan remote access dan SSH
- Mengonfigurasi firewall server
- Mengelola patch management otomatis
- Mengimplementasikan log management
- Membuat strategi backup dan recovery
- Memantau server dengan tools monitoring
KONSEP SERVER SECURITY
Definisi
"Server security is the practice of protecting servers, the data they store and process, and the network connections they maintain from unauthorized access, attack, and disruption."
Server vs Workstation
| ASPEK | SERVER | WORKSTATION |
|---|---|---|
| Tujuan | Melayani request dari client | Untuk penggunaan individual |
| Uptime | 24/7 (99.9%+) | Jam kerja saja |
| User | Banyak user remote | Satu user lokal |
| Hardware | Enterprise-grade, redundant | Consumer-grade |
| OS | Linux/Windows Server | Windows/macOS/Linux Desktop |
| GUI | Minimal/no GUI | Full GUI |
| Security focus | Network-facing, service hardening | Endpoint protection |
CIA Triad dalam Konteks Server
| ASPEK | IMPLEMENTASI DI SERVER | TOOLS |
|---|---|---|
| Confidentiality | Enkripsi data at-rest & in-transit, access control | LVM encryption, TLS, SSH keys |
| Integrity | File integrity monitoring, digital signatures | AIDE, Tripwire, GPG |
| Availability | Redundancy, failover, load balancing | HAProxy, Keepalived, RAID |
Ancaman Utama Server
DDoS ATTACK
Membanjiri server dengan request
UNAUTHORIZED ACCESS
Brute force, credential theft
MALWARE
Rootkit, ransomware, crypto miner
EXPLOIT
Eksploitasi vulnerability software
INSIDER THREAT
Karyawan jahat/ceroboh
DATA BREACH
- Server = bank dengan vault berisi uang nasabah
- Service = teller yang melayani nasabah
- Firewall = satpam di pintu masuk
- Encryption = brankas dengan kombinasi
- Logs = CCTV yang merekam semua aktivitas
- Backup = cadangan uang di bank lain
- Monitoring = manajer yang mengawasi 24/7
- NIST SP 800-123 - Guide to General Server Security
- CIS - CIS Benchmarks for Linux Servers
- Red Hat - Security Guide
- IBM - Cost of a Data Breach Report 2023
JENIS & LAYANAN SERVER
Server memiliki berbagai jenis berdasarkan fungsi dan layanannya. Memahami jenis server penting untuk menerapkan keamanan yang tepat sesuai konteks.
Jenis Server Berdasarkan Fungsi
| JENIS SERVER | FUNGSI | PORT UMUM | KEAMANAN KHUSUS |
|---|---|---|---|
| Web Server | Melayani HTTP/HTTPS request | 80, 443 | WAF, TLS, input validation |
| Database Server | Menyimpan & mengelola data | 3306 (MySQL), 5432 (PostgreSQL) | Encryption at-rest, access control |
| Mail Server | Mengirim & menerima email | 25, 587, 993, 995 | SPF, DKIM, DMARC, TLS |
| DNS Server | Menerjemahkan domain ke IP | 53 | DNSSEC, rate limiting |
| File Server | Menyimpan & berbagi file | 445 (SMB), 2049 (NFS) | ACL, encryption, audit |
| Application Server | Menjalankan aplikasi bisnis | 8080, 8443 | Authentication, authorization |
| Proxy Server | Perantara antara client & server | 3128, 8080 | Access control, logging |
| VPN Server | Menyediakan akses remote aman | 1194 (OpenVPN), 51820 (WireGuard) | Strong encryption, MFA |
| Authentication Server | Autentikasi user (LDAP, AD) | 389, 636 | TLS, strong password policy |
| Backup Server | Menyimpan backup data | 873 (rsync) | Encryption, offsite storage |
Server Berdasarkan Deployment
| TIPE | DESKRIPSI | KELEBIHAN | KEKURANGAN |
|---|---|---|---|
| Physical Server | Hardware dedicated di data center | Performa maksimal, kontrol penuh | Mahal, butuh maintenance |
| Virtual Server (VPS) | Server virtual di atas physical host | Fleksibel, scalable, murah | Noisy neighbor, shared resource |
| Cloud Server | Server di cloud provider (AWS, GCP) | Pay-as-you-go, auto-scaling | Vendor lock-in, data sovereignty |
| Dedicated Server | Hardware dedicated disewa | Performa tinggi, full control | Mahal, butuh expertise |
| Container | Lightweight virtualization (Docker) | Portable, cepat, efisien | Security isolation terbatas |
Layanan Server Umum di Linux
Bash - Common Server Services # Cek service yang berjalan $ systemctl list-units --type=service --state=running # Contoh layanan server umum: # Web Server: $ systemctl status nginx # Nginx web server $ systemctl status apache2 # Apache web server # Database: $ systemctl status mysql # MySQL/MariaDB $ systemctl status postgresql # PostgreSQL # Mail: $ systemctl status postfix # Postfix MTA $ systemctl status dovecot # Dovecot IMAP/POP3 # DNS: $ systemctl status bind9 # BIND DNS server # SSH: $ systemctl status sshd # SSH daemon # File sharing: $ systemctl status smbd # Samba (SMB/CIFS) $ systemctl status nfs-server # NFS server # FTP: $ systemctl status vsftpd # vsftpd FTP server # Application: $ systemctl status tomcat # Tomcat Java app server $ systemctl status docker # Docker container runtime # Cek port yang digunakan $ sudo ss -tulpn $ sudo netstat -tulpn
- Web server = pelayan yang menerima pesanan
- App server = koki yang memasak pesanan
- Database server = gudang bahan makanan
- Firewall = satpam di pintu masuk
- Load balancer = manajer yang membagi pesanan ke beberapa pelayan
- Backup server = cabang restoran cadangan
- Red Hat - Enterprise Linux Server Administration
- AWS - EC2 Instance Types Documentation
- Docker - Container Security Best Practices
SERVER HARDENING
Server hardening adalah proses mengurangi attack surface server dengan menonaktifkan fitur tidak perlu, mengonfigurasi security settings, dan menerapkan best practices. Ini adalah langkah paling kritis setelah install server baru.
CIS Benchmarks
CIS Benchmarks adalah standar industri untuk hardening sistem. Tersedia untuk Ubuntu, CentOS, RHEL, Debian, Windows Server, dan banyak lagi. Menjadi acuan utama untuk compliance (PCI DSS, HIPAA, ISO 27001).
Checklist Server Hardening
- Update sistem - install semua patch terbaru
- Minimal install - hanya install package yang dibutuhkan
- Disable root SSH - gunakan user biasa + sudo
- SSH key authentication - disable password auth
- Firewall - default deny, allow only needed ports
- Disable unused services - kurangi attack surface
- Set password policy - kompleksitas, aging
- Enable audit logging - catat semua aktivitas
- File integrity monitoring - deteksi perubahan file
- Disable USB storage - cegah malware via USB
- Configure SELinux/AppArmor - mandatory access control
- Set file permissions - least privilege
- Enable automatic updates - security patches
- Configure NTP - sinkronisasi waktu
- Setup backup - rutin dan teruji
Praktik: Server Hardening Script
Bash - Server Hardening Script (Ubuntu/Debian) #!/bin/bash # server-hardening.sh # Server Hardening Script untuk Ubuntu/Debian # Jalankan sebagai root atau dengan sudo # PERINGATAN: Test di environment non-production dulu! echo "=== SERVER HARDENING SCRIPT ===" echo "Starting hardening process..." # 1. Update system echo "[1/15] Updating system..." apt update && apt upgrade -y apt autoremove -y # 2. Install essential security tools echo "[2/15] Installing security tools..." apt install -y ufw fail2ban unattended-upgrades auditd aide # 3. Configure SSH echo "[3/15] Hardening SSH..." cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup sed -i 's/^#*PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config sed -i 's/^#*PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config sed -i 's/^#*X11Forwarding.*/X11Forwarding no/' /etc/ssh/sshd_config sed -i 's/^#*MaxAuthTries.*/MaxAuthTries 3/' /etc/ssh/sshd_config systemctl restart sshd # 4. Configure firewall echo "[4/15] Configuring firewall..." ufw default deny incoming ufw default allow outgoing ufw allow ssh ufw allow http ufw allow https ufw --force enable # 5. Configure fail2ban echo "[5/15] Configuring fail2ban..." cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local systemctl enable fail2ban systemctl restart fail2ban # 6. Enable automatic security updates echo "[6/15] Enabling auto-updates..." dpkg-reconfigure -plow unattended-upgrades # 7. Configure password policy echo "[7/15] Setting password policy..." apt install -y libpam-pwquality sed -i 's/^#*minlen.*/minlen = 12/' /etc/security/pwquality.conf sed -i 's/^PASS_MAX_DAYS.*/PASS_MAX_DAYS 90/' /etc/login.defs sed -i 's/^PASS_MIN_DAYS.*/PASS_MIN_DAYS 1/' /etc/login.defs # 8. Enable auditd echo "[8/15] Enabling audit logging..." systemctl enable auditd systemctl start auditd # 9. Configure AIDE (file integrity) echo "[9/15] Configuring AIDE..." aideinit cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db # 10. Disable USB storage echo "[10/15] Disabling USB storage..." echo "blacklist usb-storage" | tee /etc/modprobe.d/disable-usb.conf # 11. Configure AppArmor echo "[11/15] Enabling AppArmor..." systemctl enable apparmor systemctl start apparmor # 12. Set secure file permissions echo "[12/15] Setting file permissions..." chmod 600 /etc/shadow chmod 644 /etc/passwd chmod 600 /etc/ssh/sshd_config # 13. Disable unused services echo "[13/15] Disabling unused services..." systemctl disable avahi-daemon 2>/dev/null systemctl disable cups 2>/dev/null # 14. Configure NTP echo "[14/15] Configuring NTP..." timedatectl set-ntp true # 15. Final security check echo "[15/15] Running security check..." ufw status systemctl status sshd fail2ban auditd echo "=== HARDENING COMPLETE ===" echo "Please reboot the server to apply all changes."
Praktik: Security Audit dengan Lynis
Bash - Lynis Security Audit # 1. Install Lynis $ sudo apt install lynis # 2. Run full audit $ sudo lynis audit system # 3. Run with specific profile $ sudo lynis audit system --profile custom.profile # 4. Check specific group $ sudo lynis audit system --tests-from-group malware,authentication,networking # 5. Generate report $ sudo lynis audit system --report-file /var/log/lynis-report.dat # 6. View report $ cat /var/log/lynis-report.dat # 7. Update Lynis $ sudo lynis update release # Contoh output: # -[ Lynis 3.0.0 ] # # ################################################################################ # # Program version: 3.0.0 # Operating system: Ubuntu # Operating system name: Ubuntu 22.04 # Kernel version: 5.15.0 # Hardware platform: x86_64 # Hostname: server01 # Audit started: 2026-09-09 14:30:00 # Audit ended: 2026-09-09 14:35:00 # # Hardening index: 72/100 # Tests performed: 156 # Warnings: 0 # Suggestions: 24
Tahun 2019, Capital One mengalami breach yang membocorkan data 100 juta nasabah. Penyebab: misconfigured firewall di AWS yang memungkinkan SSRF (Server-Side Request Forgery) attack. Attacker mendapatkan credentials IAM dan mengakses S3 buckets.
Dampak: denda $80 juta, CEO teknologi mundur. Pelajaran: hardening + configuration management sangat kritis di cloud.
- Minimal install = hanya bangun apa yang dibutuhkan, tidak ada ruangan kosong
- Firewall = parit dan jembatan angkat
- SSH hardening = gerbang utama dengan penjaga ketat
- File permissions = kunci berbeda untuk setiap ruangan
- Monitoring = menara pengawas dengan CCTV
- CIS - CIS Benchmarks (cisecurity.org/benchmark)
- STIG - Security Technical Implementation Guides (public.cyber.mil)
- NIST SP 800-123 - Guide to General Server Security
- Lynis - Security Auditing Tool (cisofy.com/lynis)
USER, GROUP & PERMISSION
Manajemen user, group, dan permission adalah pondasi keamanan Linux. Prinsip least privilege - setiap user hanya mendapat akses minimal yang dibutuhkan - adalah kunci keamanan server.
User Management
Bash - User Management # 1. List all users $ cat /etc/passwd $ getent passwd # 2. Create new user $ sudo useradd -m -s /bin/bash newuser # 3. Create user with specific options $ sudo useradd -m -s /bin/bash -c "John Doe" -G sudo,developers john # 4. Set password $ sudo passwd newuser # 5. Modify user $ sudo usermod -aG sudo newuser # Add to sudo group $ sudo usermod -s /bin/zsh newuser # Change shell $ sudo usermod -L newuser # Lock account $ sudo usermod -U newuser # Unlock account # 6. Delete user $ sudo userdel newuser # Delete user only $ sudo userdel -r newuser # Delete user + home dir # 7. Check user info $ id newuser $ groups newuser # 8. Switch user $ su - newuser $ sudo -u newuser whoami # 9. List logged in users $ who $ w # 10. Last login $ last $ lastlog
Group Management
Bash - Group Management # 1. List all groups $ cat /etc/group $ getent group # 2. Create new group $ sudo groupadd developers # 3. Add user to group $ sudo usermod -aG developers john # 4. Remove user from group $ sudo gpasswd -d john developers # 5. Change group owner $ sudo chgrp developers /var/www/project # 6. Delete group $ sudo groupdel developers # 7. List group members $ getent group developers $ members developers # 8. Create system group $ sudo groupadd -r servicegroup
File Permissions
Bash - File Permissions # 1. View permissions $ ls -l file.txt -rw-r--r-- 1 john developers 1024 Sep 9 14:30 file.txt # 2. Change permissions (symbolic) $ chmod u+x script.sh # Add execute for owner $ chmod g+w file.txt # Add write for group $ chmod o-r file.txt # Remove read for others $ chmod a+r file.txt # Add read for all # 3. Change permissions (numeric) $ chmod 755 script.sh # rwxr-xr-x $ chmod 644 file.txt # rw-r--r-- $ chmod 600 secret.txt # rw------- (owner only) $ chmod 700 private_dir/ # rwx------ (owner only) # 4. Change owner $ sudo chown john file.txt $ sudo chown john:developers file.txt $ sudo chown -R john:developers /var/www/project # 5. Change group only $ sudo chgrp developers file.txt # 6. Set default permissions for directory $ sudo chmod g+s /var/www/project # Set GID bit $ sudo chmod o+t /tmp # Set sticky bit # 7. Find files with specific permissions $ find / -perm 777 -type f 2>/dev/null # World-writable files $ find / -perm -4000 -type f 2>/dev/null # SUID files # 8. Recursive permissions $ chmod -R 755 /var/www/project
Sudo Configuration
Bash - Sudo Configuration # 1. Edit sudoers file (ALWAYS use visudo!) $ sudo visudo # 2. Common sudo configurations: # Allow user full sudo access john ALL=(ALL:ALL) ALL # Allow user sudo without password john ALL=(ALL) NOPASSWD: ALL # Allow user to run specific commands only john ALL=(ALL) /usr/bin/systemctl restart nginx, /usr/bin/systemctl restart apache2 # Allow group sudo access %developers ALL=(ALL) /usr/bin/docker # Allow user to run commands as specific user john ALL=(www-data) /usr/bin/systemctl restart apache2 # 3. Check sudo privileges $ sudo -l # 4. Run command as another user $ sudo -u www-data whoami # 5. Sudo with shell $ sudo -i # Root shell with login $ sudo -s # Root shell without login # 6. Sudo logging $ sudo tail -f /var/log/auth.log
Best Practices
- Disable root login - gunakan user biasa + sudo
- Least privilege - hanya berikan akses yang dibutuhkan
- Use groups - kelola akses via group, bukan individual user
- Regular audit - review user & permission secara berkala
- Strong passwords - atau gunakan SSH keys
- Lock unused accounts - disable akun tidak aktif
- Use sudo wisely - batasi command yang boleh dijalankan
- Set secure umask - default permission untuk file baru
- Avoid world-writable - jangan chmod 777!
- Monitor sudo usage - log semua sudo commands
- User = orang dengan ID card
- Group = departemen (HR, IT, Finance)
- Permission = akses ke ruangan tertentu
- chmod 755 = pemilik bisa masuk, keluar-masuk, modifikasi; yang lain hanya bisa masuk
- chmod 600 = hanya pemilik yang bisa masuk dan lihat isi
- sudo = kunci master untuk situasi darurat
- Linux man pages - chmod, chown, useradd, sudo
- Red Hat - Managing Users and Groups
- Ubuntu - Permissions Documentation
SECURE REMOTE ACCESS
Remote access adalah kebutuhan utama untuk mengelola server, tapi juga menjadi vektor serangan utama. Mengamankan remote access adalah prioritas kritis.
Metode Remote Access
| METODE | PROTOKOL | ENKRIPSI | STATUS |
|---|---|---|---|
| SSH | SSH (22) | Strong (AES, ChaCha20) | RECOMMENDED |
| Telnet | Telnet (23) | None (plaintext) | JANGAN PAKAI |
| RDP | RDP (3389) | Optional | Windows only |
| VPN | OpenVPN, WireGuard, IPsec | Strong | RECOMMENDED |
| Web-based | HTTPS (443) | TLS | Cockpit, Webmin |
Best Practices Remote Access
- Use VPN - jangan expose SSH langsung ke internet
- Bastion/Jump host - satu entry point untuk semua server
- SSH key authentication - disable password auth
- Multi-factor authentication - untuk akses kritis
- Restrict source IPs - firewall hanya allow IP tertentu
- Change default port - kurangi noise dari scanner
- Use non-root user - disable root login
- Session timeout - auto-logout setelah idle
- Logging & monitoring - catat semua akses
- Regular audit - review access logs berkala
Praktik: VPN Setup (WireGuard)
Bash - WireGuard VPN Server # 1. Install WireGuard $ sudo apt install wireguard # 2. Generate server keys $ cd /etc/wireguard $ umask 077 $ wg genkey | tee server_private.key | wg pubkey > server_public.key # 3. Create server config $ sudo nano /etc/wireguard/wg0.conf # [Interface] # PrivateKey = <server-private-key> # Address = 10.0.0.1/24 # ListenPort = 51820 # PostUp = iptables -A FORWARD -i wg0 -j ACCEPT; iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE # PostDown = iptables -D FORWARD -i wg0 -j ACCEPT; iptables -t nat -D POSTROUTING -o eth0 -j MASQUERADE # [Peer] # PublicKey = <client-public-key> # AllowedIPs = 10.0.0.2/32 # 4. Generate client keys $ wg genkey | tee client_private.key | wg pubkey > client_public.key # 5. Create client config $ nano client.conf # [Interface] # PrivateKey = <client-private-key> # Address = 10.0.0.2/24 # DNS = 1.1.1.1 # [Peer] # PublicKey = <server-public-key> # Endpoint = server-ip:51820 # AllowedIPs = 0.0.0.0/0 # PersistentKeepalive = 25 # 6. Start WireGuard $ sudo wg-quick up wg0 # 7. Enable IP forwarding $ echo "net.ipv4.ip_forward=1" | sudo tee -a /etc/sysctl.conf $ sudo sysctl -p # 8. Allow in firewall $ sudo ufw allow 51820/udp # 9. Check status $ sudo wg show
- VPN = terowongan rahasia menuju kantor
- Bastion host = resepsionis di lobi - semua tamu harus lewat sini
- SSH keys = ID card dengan chip biometrik
- MFA = ID card + PIN + sidik jari
- IP restriction = hanya orang dari departemen tertentu yang boleh masuk
- WireGuard - Documentation (wireguard.com)
- OpenVPN - Documentation (openvpn.net)
- NIST SP 800-77 - Guide to IPsec VPNs
SSH SECURITY
SSH (Secure Shell) adalah protokol paling umum untuk remote access ke server Linux. Karena menjadi entry point utama, SSH harus dikeraskan (hardened) dengan konfigurasi yang aman.
Praktik: SSH Hardening
Bash - SSH Hardening Configuration # 1. Backup original config $ sudo cp /etc/ssh/sshd_config /etc/ssh/sshd_config.backup # 2. Edit SSH config $ sudo nano /etc/ssh/sshd_config # === CRITICAL SETTINGS === # Disable root login PermitRootLogin no # Use key-based authentication only PasswordAuthentication no PubkeyAuthentication yes # Disable empty passwords PermitEmptyPasswords no # === SECURITY SETTINGS === # Limit authentication attempts MaxAuthTries 3 MaxSessions 3 # Disable X11 forwarding (unless needed) X11Forwarding no # Disable TCP forwarding (unless needed) AllowTcpForwarding no # Disable agent forwarding (unless needed) AllowAgentForwarding no # Set login grace time LoginGraceTime 60 # Set idle timeout (5 minutes) ClientAliveInterval 300 ClientAliveCountMax 2 # Use strong ciphers only Ciphers chacha20-poly1305@openssh.com,aes256-gcm@openssh.com,aes128-gcm@openssh.com,aes256-ctr,aes192-ctr,aes128-ctr # Use strong MACs only MACs hmac-sha2-512-etm@openssh.com,hmac-sha2-256-etm@openssh.com,hmac-sha2-512,hmac-sha2-256 # Use strong key exchange algorithms KexAlgorithms curve25519-sha256,curve25519-sha256@libssh.org,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512 # === ACCESS CONTROL === # Allow specific users only AllowUsers john admin # Or allow specific groups AllowGroups sshusers admins # === LOGGING === LogLevel VERBOSE # 3. Restart SSH $ sudo systemctl restart sshd # 4. Test before closing session! $ ssh -v user@server
SSH Key Management
Bash - SSH Key Management # 1. Generate SSH key pair (Ed25519 - recommended) $ ssh-keygen -t ed25519 -C "john@example.com" # 2. Generate RSA key (4096-bit) $ ssh-keygen -t rsa -b 4096 -C "john@example.com" # 3. Copy public key to server $ ssh-copy-id user@server # 4. Manual copy $ cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys" # 5. Set proper permissions $ chmod 700 ~/.ssh $ chmod 600 ~/.ssh/id_ed25519 $ chmod 644 ~/.ssh/id_ed25519.pub $ chmod 600 ~/.ssh/authorized_keys # 6. Use SSH agent for passphrase-protected keys $ eval $(ssh-agent -s) $ ssh-add ~/.ssh/id_ed25519 # 7. SSH config file (~/.ssh/config) $ nano ~/.ssh/config # Host production # HostName 192.168.1.100 # User admin # IdentityFile ~/.ssh/id_ed25519 # Port 2222 # 8. Connect using config $ ssh production # 9. Revoke compromised key $ ssh user@server "sed -i '/compromised-key-comment/d' ~/.ssh/authorized_keys" # 10. Check SSH key fingerprint $ ssh-keygen -lf ~/.ssh/id_ed25519.pub
Praktik: Fail2Ban for SSH
Bash - Fail2Ban Configuration # 1. Install fail2ban $ sudo apt install fail2ban # 2. Create local config $ sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local # 3. Edit config $ sudo nano /etc/fail2ban/jail.local # [DEFAULT] # bantime = 3600 # findtime = 600 # maxretry = 5 # backend = systemd # [sshd] # enabled = true # port = ssh # filter = sshd # logpath = /var/log/auth.log # maxretry = 3 # bantime = 86400 # 4. Restart fail2ban $ sudo systemctl restart fail2ban # 5. Check status $ sudo fail2ban-client status $ sudo fail2ban-client status sshd # 6. Manual ban/unban $ sudo fail2ban-client set sshd banip 192.168.1.100 $ sudo fail2ban-client set sshd unbanip 192.168.1.100 # 7. Check banned IPs $ sudo fail2ban-client get sshd banip
- SSH key = kunci rumah yang unik dan tidak bisa diduplikasi
- Password auth = kombinasi gembok - bisa ditebak
- PermitRootLogin no = tidak ada pintu khusus untuk bos
- Fail2ban = satpam yang mengusir orang mencurigakan
- AllowUsers = daftar putih - hanya orang tertentu yang boleh masuk
- OpenSSH - Manual Pages (man.openbsd.org)
- CIS - CIS Benchmark for SSH
- Mozilla - Modern SSH Configuration
- Fail2Ban - Documentation (fail2ban.org)
FIREWALL SERVER
Firewall server adalah lini pertahanan pertama yang memfilter trafik masuk dan keluar. Konfigurasi yang tepat sangat kritis untuk keamanan server.
Firewall Tools di Linux
| TOOL | TYPE | KELEBIHAN | USE CASE |
|---|---|---|---|
| iptables | Legacy | Fleksibel, powerful | Complex rules, legacy systems |
| nftables | Modern | Faster, simpler syntax | New installations |
| UFW | Frontend | Simple, user-friendly | Ubuntu/Debian servers |
| firewalld | Dynamic | Zone-based, dynamic | RHEL/CentOS/Fedora |
Praktik: UFW (Uncomplicated Firewall)
Bash - UFW Configuration # 1. Install UFW $ sudo apt install ufw # 2. Reset to defaults $ sudo ufw default deny incoming $ sudo ufw default allow outgoing # 3. Allow SSH (IMPORTANT: do this first!) $ sudo ufw allow ssh # or specific port $ sudo ufw allow 2222/tcp # 4. Allow web services $ sudo ufw allow http $ sudo ufw allow https # 5. Allow specific port $ sudo ufw allow 8080/tcp # 6. Allow from specific IP $ sudo ufw allow from 192.168.1.100 $ sudo ufw allow from 192.168.1.0/24 to any port 22 # 7. Deny specific IP $ sudo ufw deny from 10.0.0.5 # 8. Enable firewall $ sudo ufw enable # 9. Check status $ sudo ufw status verbose # 10. List rules with numbers $ sudo ufw status numbered # 11. Delete rule $ sudo ufw delete 3 # 12. Disable firewall $ sudo ufw disable # 13. Reset firewall $ sudo ufw reset # 14. Logging $ sudo ufw logging on $ sudo tail -f /var/log/ufw.log
Praktik: iptables Advanced
Bash - iptables Advanced Configuration # 1. View current rules $ sudo iptables -L -n -v # 2. Flush all rules $ sudo iptables -F # 3. Set default policies $ sudo iptables -P INPUT DROP $ sudo iptables -P FORWARD DROP $ sudo iptables -P OUTPUT ACCEPT # 4. Allow loopback $ sudo iptables -A INPUT -i lo -j ACCEPT # 5. Allow established connections $ sudo iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT # 6. Allow SSH $ sudo iptables -A INPUT -p tcp --dport 22 -j ACCEPT # 7. Rate limit SSH (anti brute force) $ sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --set $ sudo iptables -A INPUT -p tcp --dport 22 -m state --state NEW -m recent --update --seconds 60 --hitcount 4 -j DROP # 8. Allow HTTP/HTTPS $ sudo iptables -A INPUT -p tcp --dport 80 -j ACCEPT $ sudo iptables -A INPUT -p tcp --dport 443 -j ACCEPT # 9. Block specific IP $ sudo iptables -A INPUT -s 192.168.1.100 -j DROP # 10. Block ping (ICMP) $ sudo iptables -A INPUT -p icmp --icmp-type echo-request -j DROP # 11. Log dropped packets $ sudo iptables -A INPUT -j LOG --log-prefix "IPTABLES DROP: " --log-level 4 # 12. Save rules (Ubuntu/Debian) $ sudo apt install iptables-persistent $ sudo netfilter-persistent save # 13. Save rules (manual) $ sudo iptables-save > /etc/iptables/rules.v4 # 14. Restore rules $ sudo iptables-restore < /etc/iptables/rules.v4
- Default deny = semua tamu ditolak kecuali yang diizinkan
- Allow rules = daftar tamu yang diizinkan
- Rate limiting = batasi jumlah tamu per menit
- Logging = buku tamu yang mencatat siapa masuk
- Stateful = satpam ingat tamu yang sudah masuk
- Ubuntu - UFW Documentation
- Netfilter - iptables Tutorial
- NIST SP 800-41 - Guide to Firewalls
PATCH MANAGEMENT
Patch management adalah proses mengidentifikasi, memperoleh, menguji, dan menginstall patch (update) untuk software. Server yang tidak di-patch adalah target empuk bagi attacker.
Praktik: Manual Patching
Bash - Manual Patching # Ubuntu/Debian $ sudo apt update $ sudo apt upgrade -y $ sudo apt dist-upgrade -y $ sudo apt autoremove -y # CentOS/RHEL $ sudo yum check-update $ sudo yum update -y $ sudo yum clean all # Check if reboot required $ [ -f /var/run/reboot-required ] && echo "Reboot required" # List security updates only $ sudo apt upgrade -s | grep -i security
Praktik: Automatic Updates
Bash - Automatic Security Updates # 1. Install unattended-upgrades $ sudo apt install unattended-upgrades apt-listchanges # 2. Configure $ sudo dpkg-reconfigure -plow unattended-upgrades # 3. Edit config $ sudo nano /etc/apt/apt.conf.d/50unattended-upgrades # Unattended-Upgrade::Allowed-Origins { # "${distro_id}:${distro_codename}-security"; # "${distro_id}:${distro_codename}-updates"; # }; # Unattended-Upgrade::AutoFixInterruptedDpkg "true"; # Unattended-Upgrade::MinimalSteps "true"; # Unattended-Upgrade::Remove-Unused-Dependencies "true"; # Unattended-Upgrade::Automatic-Reboot "true"; # Unattended-Upgrade::Automatic-Reboot-Time "02:00"; # 4. Enable automatic updates $ sudo nano /etc/apt/apt.conf.d/20auto-upgrades # APT::Periodic::Update-Package-Lists "1"; # APT::Periodic::Unattended-Upgrade "1"; # APT::Periodic::Download-Upgradeable-Packages "1"; # APT::Periodic::AutocleanInterval "7"; # 5. Check status $ sudo systemctl status unattended-upgrades $ cat /var/log/unattended-upgrades/unattended-upgrades.log # 6. Test dry run $ sudo unattended-upgrades --dry-run
- Vulnerability = penyakit
- Patch = vaksin
- Unpatched server = orang tidak divaksin - rentan sakit
- Automatic updates = jadwal imunisasi otomatis
- NIST SP 800-40 - Guide to Patch Management
- Ubuntu - Automatic Security Updates
LOG MANAGEMENT
Log management adalah proses mengumpulkan, menyimpan, menganalisis, dan mengamankan log dari server. Log adalah bukti forensik terpenting saat investigasi insiden.
Jenis Log Server
| JENIS LOG | LOKASI | ISI |
|---|---|---|
| Auth log | /var/log/auth.log | Login attempts, sudo usage, SSH |
| Syslog | /var/log/syslog | System messages |
| Kernel log | /var/log/kern.log | Kernel messages |
| Web access | /var/log/nginx/access.log | HTTP requests |
| Web error | /var/log/nginx/error.log | HTTP errors |
| Database | /var/log/mysql/error.log | DB queries, errors |
| Cron | /var/log/cron.log | Scheduled tasks |
| /var/log/mail.log | Mail server activity |
Praktik: Log Analysis
Bash - Log Analysis Commands # 1. View recent auth logs $ sudo tail -n 50 /var/log/auth.log # 2. Search for failed logins $ sudo grep "Failed password" /var/log/auth.log # 3. Count failed logins by IP $ sudo grep "Failed password" /var/log/auth.log | awk '{print $(NF-3)}' | sort | uniq -c | sort -nr # 4. Search for successful logins $ sudo grep "Accepted" /var/log/auth.log # 5. Search for sudo usage $ sudo grep "sudo:" /var/log/auth.log # 6. View web access logs $ sudo tail -f /var/log/nginx/access.log # 7. Search for 404 errors $ sudo grep " 404 " /var/log/nginx/access.log # 8. Count requests by IP $ sudo awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -nr | head # 9. Use journalctl (systemd) $ sudo journalctl -u ssh --since today $ sudo journalctl -p err --since yesterday # 10. Real-time monitoring $ sudo tail -f /var/log/auth.log /var/log/syslog
Praktik: Log Rotation
Bash - Log Rotation with logrotate # 1. Check logrotate config $ cat /etc/logrotate.conf # 2. Create custom logrotate config $ sudo nano /etc/logrotate.d/myapp # /var/log/myapp/*.log { # daily # rotate 30 # compress # delaycompress # missingok # notifempty # create 0640 www-data adm # postrotate # /usr/bin/systemctl reload myapp > /dev/null 2>/dev/null || true # endscript # } # 3. Test logrotate $ sudo logrotate -d /etc/logrotate.d/myapp # 4. Force logrotate $ sudo logrotate -f /etc/logrotate.d/myapp
Praktik: Centralized Logging
Bash - Rsyslog to Remote Server # 1. Install rsyslog $ sudo apt install rsyslog # 2. Configure remote logging $ sudo nano /etc/rsyslog.d/50-remote.conf # Send all logs to remote server # *.* @logserver.example.com:514 # Send via TCP (more reliable) # *.* @@logserver.example.com:514 # Send via TLS (encrypted) # *.* @@(o)logserver.example.com:6514 # 3. Restart rsyslog $ sudo systemctl restart rsyslog # 4. Check status $ sudo systemctl status rsyslog
- Auth log = buku tamu yang mencatat siapa masuk/keluar
- Access log = CCTV yang merekam semua aktivitas
- Log rotation = mengganti kaset CCTV yang sudah penuh
- Centralized logging = semua CCTV terhubung ke ruang kontrol
- NIST SP 800-92 - Guide to Computer Security Log Management
- Rsyslog - Documentation (rsyslog.com)
- ELK Stack - Documentation (elastic.co)
BACKUP & RECOVERY
Backup dan recovery adalah lini pertahanan terakhir terhadap ransomware, data corruption, hardware failure, dan bencana. Tanpa backup yang baik, Anda bisa kehilangan semua data secara permanen.
Prinsip 3-2-1 Backup
Praktik: Backup dengan rsync
Bash - rsync Backup # 1. Basic rsync backup $ rsync -avh /var/www/ /backup/www/ # 2. Incremental backup with delete $ rsync -avh --delete /var/www/ /backup/www/ # 3. Backup with progress $ rsync -avh --progress /var/www/ /backup/www/ # 4. Backup to remote server $ rsync -avh -e ssh /var/www/ user@backup-server:/backup/www/ # 5. Exclude files $ rsync -avh --exclude='*.log' --exclude='cache/' /var/www/ /backup/www/ # 6. Backup with compression $ rsync -avzh /var/www/ /backup/www/ # 7. Dry run (test) $ rsync -avhn /var/www/ /backup/www/ # 8. Backup script $ nano backup.sh #!/bin/bash # Backup script DATE=$(date +%Y%m%d) BACKUP_DIR="/backup/$DATE" # Create backup directory mkdir -p $BACKUP_DIR # Backup web files rsync -avh --delete /var/www/ $BACKUP_DIR/www/ # Backup database mysqldump -u root -p'password' --all-databases > $BACKUP_DIR/database.sql # Backup config files rsync -avh /etc/ $BACKUP_DIR/etc/ # Compress backup tar -czvf /backup/backup-$DATE.tar.gz $BACKUP_DIR # Remove uncompressed rm -rf $BACKUP_DIR # Keep only last 7 days find /backup -name "backup-*.tar.gz" -mtime +7 -delete # Upload to remote rsync -avh /backup/backup-$DATE.tar.gz user@remote:/backup/ echo "Backup completed: backup-$DATE.tar.gz"
Praktik: Database Backup
Bash - Database Backup # MySQL/MariaDB # 1. Backup all databases $ mysqldump -u root -p --all-databases > all_databases.sql # 2. Backup specific database $ mysqldump -u root -p database_name > database.sql # 3. Backup with compression $ mysqldump -u root -p database_name | gzip > database.sql.gz # 4. Backup with date $ mysqldump -u root -p database_name > database_$(date +%Y%m%d).sql # 5. Restore database $ mysql -u root -p database_name < database.sql # 6. Restore compressed $ gunzip < database.sql.gz | mysql -u root -p database_name # PostgreSQL # 1. Backup all databases $ sudo -u postgres pg_dumpall > all_databases.sql # 2. Backup specific database $ sudo -u postgres pg_dump database_name > database.sql # 3. Backup with custom format $ sudo -u postgres pg_dump -Fc database_name > database.dump # 4. Restore database $ sudo -u postgres psql database_name < database.sql # 5. Restore custom format $ sudo -u postgres pg_restore -d database_name database.dump
Praktik: Automated Backup with Cron
Bash - Cron Backup # 1. Edit crontab $ crontab -e # 2. Add backup jobs # Daily backup at 2 AM 0 2 * * * /home/user/backup.sh >> /var/log/backup.log 2>&1 # Weekly full backup on Sunday at 3 AM 0 3 * * 0 /home/user/full-backup.sh >> /var/log/backup.log 2>&1 # Monthly archive on 1st at 4 AM 0 4 1 * * /home/user/monthly-archive.sh >> /var/log/backup.log 2>&1 # 3. Check cron jobs $ crontab -l # 4. View cron logs $ grep CRON /var/log/syslog
- Data = nyawa Anda
- Backup = asuransi kehidupan
- Restore = klaim asuransi saat musibah
- Test restore = cek polis asuransi masih valid
Anda tidak tahu kapan butuh asuransi sampai musibah terjadi. Jangan tunggu kehilangan data baru sadar pentingnya backup.
- NIST SP 800-34 - Contingency Planning Guide
- rsync - Documentation (rsync.samba.org)
- Bacula - Backup Documentation
SERVER MONITORING
Server monitoring adalah proses continuous monitoring performa, ketersediaan, dan keamanan server. Tujuannya: deteksi dini masalah sebelum menjadi insiden.
Monitoring Tools
| TOOL | TIPE | FUNGSI | LISENSI |
|---|---|---|---|
| Nagios | Infrastructure | Host & service monitoring | Open source |
| Zabbix | Enterprise | Full-featured monitoring | Open source |
| Prometheus + Grafana | Metrics | Time-series monitoring | Open source |
| Netdata | Real-time | Real-time performance | Open source |
| Monit | Lightweight | Process & resource monitoring | Open source |
| Datadog | Cloud | Full-stack monitoring | Commercial |
Praktik: Basic Monitoring Commands
Bash - Basic Monitoring Commands # 1. System uptime $ uptime # 2. CPU usage $ top $ htop $ mpstat -P ALL 1 # 3. Memory usage $ free -h $ vmstat 1 # 4. Disk usage $ df -h $ du -sh /var/* # 5. Disk I/O $ iostat -x 1 # 6. Network connections $ ss -tulpn $ netstat -an # 7. Process list $ ps aux $ pgrep -a nginx # 8. System logs $ dmesg | tail $ journalctl -p err --since today # 9. Temperature (if supported) $ sensors # 10. Real-time monitoring $ watch -n 1 'df -h; echo; free -h'
Praktik: Netdata Installation
Bash - Netdata Real-time Monitoring # 1. Install Netdata $ wget -O /tmp/netdata-kickstart.sh https://my-netdata.io/kickstart.sh $ sh /tmp/netdata-kickstart.sh # 2. Access dashboard # http://server-ip:19999 # 3. Check status $ systemctl status netdata # 4. Configure $ sudo nano /etc/netdata/netdata.conf # 5. Restart $ sudo systemctl restart netdata
Praktik: Prometheus + Grafana
Bash - Prometheus + Grafana Setup # 1. Install Prometheus $ sudo apt install prometheus prometheus-node-exporter # 2. Configure Prometheus $ sudo nano /etc/prometheus/prometheus.yml # scrape_configs: # - job_name: 'node' # static_configs: # - targets: ['localhost:9100'] # 3. Install Grafana $ wget -q -O - https://packages.grafana.com/gpg.key | sudo apt-key add - $ echo "deb https://packages.grafana.com/oss/deb stable main" | sudo tee /etc/apt/sources.list.d/grafana.list $ sudo apt update $ sudo apt install grafana # 4. Start services $ sudo systemctl start prometheus prometheus-node-exporter grafana-server $ sudo systemctl enable prometheus prometheus-node-exporter grafana-server # 5. Access Grafana # http://server-ip:3000 # Default login: admin/admin # 6. Add Prometheus data source # Configuration -> Data Sources -> Add data source -> Prometheus # URL: http://localhost:9090 # 7. Import dashboard # Dashboards -> Import -> Import ID: 1860 (Node Exporter Full)
Praktik: Custom Monitoring Script
Bash - Custom Monitoring Script #!/bin/bash # server-monitor.sh - Custom server monitoring LOG_FILE="/var/log/server-monitor.log" ALERT_EMAIL="admin@example.com" # Check disk usage DISK_USAGE=$(df -h / | awk 'NR==2 {print $5}' | sed 's/%//') if [ $DISK_USAGE -gt 90 ]; then echo "$(date): ALERT - Disk usage is ${DISK_USAGE}%" >> $LOG_FILE echo "Disk usage critical: ${DISKUSAGE}%" | mail -s "Disk Alert" $ALERT_EMAIL fi # Check memory usage MEM_USAGE=$(free | awk '/Mem/{printf("%.2f"), $3/$2*100}') if (( $(echo "$MEM_USAGE > 90" | bc -l) )); then echo "$(date): ALERT - Memory usage is ${MEM_USAGE}%" >> $LOG_FILE fi # Check if critical services are running for service in nginx mysql ssh; do if ! systemctl is-active --quiet $service; then echo "$(date): ALERT - $service is not running" >> $LOG_FILE echo "$service is down!" | mail -s "Service Alert" $ALERT_EMAIL fi done # Check failed login attempts FAILED_LOGINS=$(grep "Failed password" /var/log/auth.log | wc -l) if [ $FAILED_LOGINS -gt 100 ]; then echo "$(date): ALERT - $FAILED_LOGINS failed login attempts" >> $LOG_FILE fi # Log normal status echo "$(date): OK - All checks passed" >> $LOG_FILE
- Speedometer = CPU usage
- Tachometer = memory usage
- Fuel gauge = disk space
- Temperature = server temperature
- Warning lights = alerts & alarms
Tanpa dashboard, Anda tidak tahu kondisi mobil. Tanpa monitoring, Anda tidak tahu kondisi server.
- Prometheus - Documentation (prometheus.io)
- Grafana - Documentation (grafana.com)
- Netdata - Documentation (netdata.cloud)
- Nagios - Documentation (nagios.org)
DIAGNOSTIK KOMPETENSI
Uji pemahaman Anda tentang Bab 13! Target minimal: 70% untuk melanjutkan ke Bab 14.
- Total 10 pertanyaan pilihan ganda
- Klik opsi untuk menjawab - feedback langsung
- Benar = HIJAU, salah = MAGENTA
- Penjelasan muncul setelah menjawab
- Klik "LIHAT HASIL AKHIR" untuk skor final
-
- NIST SP 800-123 - Guide to General Server Security
- CIS - CIS Benchmarks for Linux
- Red Hat - Security Guide
- Ubuntu - Server Guide
- STIG - Security Technical Implementation Guides
- OpenSSH - Manual Pages
- Prometheus - Documentation
- rsync - Documentation