Security • Sains • Technology • Informasi

Panduan Mengamankan VPS Ubuntu untuk Proyek Pribadi & UMKM

Iklan

Ringkasan Cepat

  • Tiga fondasi keamanan VPS Ubuntu: SSH key tanpa password, firewall UFW dengan aturan minimal, dan pembaruan keamanan otomatis.
  • Uji setiap perubahan konfigurasi SSH sebelum menutup sesi lama agar tidak terkunci di luar server.
  • Pembaruan otomatis menangani celah keamanan, tetapi tetap butuh backup, monitoring, dan reboot terjadwal.

Mengamankan VPS Ubuntu pada dasarnya adalah tiga pekerjaan awal: masuk dengan SSH key alih-alih password, menutup semua port kecuali yang benar-benar dipakai melalui UFW, dan membiarkan sistem memasang pembaruan keamanan sendiri. Panduan ini membahas ketiganya secara praktis, dengan asumsi Anda mengelola server untuk proyek pribadi atau layanan kecil UMKM dan belum tentu berlatar administrator sistem.

Mengapa VPS Baru Perlu Diamankan Sejak Menit Pertama

VPS yang baru dibuat umumnya berada dalam kondisi cukup terbuka. Penyedia menyerahkan akses root beserta password awal, dan dalam hitungan menit setelah alamat IP aktif, bot otomatis mulai mencoba login. Ini bukan serangan yang ditargetkan khusus kepada Anda, melainkan pemindaian massal yang menyapu rentang alamat IP di internet setiap hari.

Untuk proyek pribadi, risikonya sederhana: bila kredensial berhasil ditebak, server Anda bisa dipakai untuk menambang kripto, mengirim spam, atau menjadi bagian dari botnet. Untuk UMKM yang menaruh aplikasi katalog, kasir, atau data pelanggan, dampaknya lebih serius karena menyangkut kepercayaan dan kepatuhan.

  • Kredensial default dan password lemah adalah pintu masuk paling umum.
  • Layanan yang mendengarkan di semua antarmuka (0.0.0.0) tanpa sengaja membuka database ke publik.
  • Perangkat lunak yang tidak dipatch menyimpan kerentanan yang sudah diketahui publik dan rutin dipindai penyerang.

Sebelum masuk ke server, pastikan lapisan di luarnya juga aman. Akun domain dan DNS yang menunjuk ke VPS Anda sebaiknya sudah dikunci dengan autentikasi dua faktor, seperti dijelaskan pada panduan mengamankan akun domain dan DNS.

Langkah 1: SSH Key dan Menonaktifkan Login Password

SSH key jauh lebih kuat daripada password karena kuncinya panjang secara matematis dan tidak bisa ditebak lewat percobaan berulang. Buat pasangan kunci di komputer lokal, bukan di server:

ssh-keygen -t ed25519 -C admin@laptop

Saat diminta passphrase, isi dengan kalimat sandi yang Anda ingat. Passphrase ini melindungi private key bila laptop Anda hilang atau dicuri. Selanjutnya salin kunci publik ke VPS:

ssh-copy-id -i ~/.ssh/id_ed25519.pub user@IP_VPS

Setelah berhasil masuk tanpa diminta password, buat satu akun non-root yang punya hak sudo, lalu sesuaikan /etc/ssh/sshd_config:

  1. PermitRootLogin no agar root tidak bisa login langsung.
  2. PasswordAuthentication no untuk mematikan login berbasis password.
  3. PubkeyAuthentication yes supaya kunci publik diterima.
  4. KbdInteractiveAuthentication no untuk menutup jalur interaktif lain.
  5. AllowUsers namauser agar hanya akun tertentu yang boleh masuk.

Uji dulu sintaksnya dengan sudo sshd -t, baru jalankan sudo systemctl restart ssh. Aturan penting: buka sesi terminal baru untuk memastikan login tetap berhasil sebelum menutup sesi lama. Sebagai lapisan tambahan, pasang fail2ban supaya alamat IP yang gagal berulang kali otomatis diblokir sementara.

Langkah 2: Firewall UFW dengan Aturan Seketika Perlu

UFW adalah antarmuka sederhana untuk aturan iptables. Prinsipnya deny by default: semua koneksi masuk ditolak, lalu Anda buka satu per satu hanya untuk layanan yang dipakai.

sudo ufw default deny incoming && sudo ufw default allow outgoing

Sebelum mengaktifkan, izinkan SSH lebih dulu agar Anda tidak terkunci:

sudo ufw allow OpenSSH

Jika server melayani situs atau API, tambahkan port web:

sudo ufw allow 80/tcp && sudo ufw allow 443/tcp

Baru kemudian aktifkan dan periksa hasilnya:

sudo ufw enable && sudo ufw status verbose

Berikut gambaran port yang biasanya perlu dipertimbangkan:

PortLayananRekomendasi
22/tcpSSHBuka, batasi sumber IP bila memungkinkan
80/tcpHTTPBuka hanya jika ada web server, idealnya dialihkan ke HTTPS
443/tcpHTTPSBuka untuk situs, panel, atau API
3306/tcpMySQL/MariaDBTutup dari publik, akses cukup lewat localhost
6379/tcpRedisWajib ditutup dari publik
25/587SMTPBuka hanya jika server memang mengirim email

Jika alamat IP Anda relatif tetap, batasi SSH hanya dari sana dengan perintah seperti sudo ufw allow from 103.10.10.10 to any port 22 proto tcp. Setelah itu hapus aturan OpenSSH yang terbuka untuk semua. Cara ini memangkas hampir seluruh upaya login acak dari internet.

Langkah 3: Pembaruan Keamanan Otomatis di Ubuntu

VPS yang rutin tidak disentuh biasanya ketinggalan patch. Ubuntu menyediakan paket unattended-upgrades yang memasang pembaruan keamanan tanpa intervensi manual. Pasang dan aktifkan:

sudo apt update && sudo apt install unattended-upgrades apt-listchanges
sudo dpkg-reconfigure --priority=low unattended-upgrades

Periksa berkas /etc/apt/apt.conf.d/20auto-upgrades agar berisi minimal tiga baris berikut:

APT::Periodic::Update-Package-Lists "1"; APT::Periodic::Unattended-Upgrade "1"; APT::Periodic::AutocleanInterval "7";

Selanjutnya tinjau /etc/apt/apt.conf.d/50unattended-upgrades untuk mengatur perilaku lanjutan:

  • Pastikan pola security pada Origins-Pattern aktif agar patch keamanan selalu ikut.
  • Setel Automatic-Reboot "true" beserta Automatic-Reboot-Time "03:00" agar reboot kernel terjadi di jam sepi.
  • Aktifkan Remove-Unused-Kernel-Packages dan Remove-Unused-Dependencies supaya /boot tidak penuh.
  • Isi Unattended-Upgrade::Mail bila ingin notifikasi hasil pembaruan.

Verifikasi konfigurasi dengan menjalankan mode uji: sudo unattended-upgrade --dry-run --debug. Riwayat pemasangan bisa dibaca di /var/log/unattended-upgrades/unattended-upgrades.log. Perlu diingat, pembaruan otomatis bukan pengganti reboot terjadwal dan bukan pengganti restart layanan. Beberapa patch pustaka baru benar-benar berlaku setelah proses aplikasi dijalankan ulang.

Kebiasaan Lanjutan dan Kesalahan yang Sering Terjadi

Tiga fondasi di atas menutup sebagian besar permukaan serangan dasar, tetapi keamanan server adalah kebiasaan, bukan sekali setel. Beberapa hal berikut layak dijadikan rutinitas:

  • Backup teruji. Simpan salinan basis data dan berkas konfigurasi di lokasi lain, lalu sesekali uji proses restore. Backup yang tidak pernah diuji belum bisa disebut backup.
  • Pantau log masuk. Periksa /var/log/auth.log atau journalctl -u ssh untuk melihat pola percobaan login yang tidak wajar.
  • Jaga rahasia tetap rahasia. Berkas .env, kunci API, dan token tidak boleh masuk ke repositori publik maupun dikirim lewat kanal yang tidak aman.
  • Kunci akun pendukung. Panel hosting, email pemulihan, dan kanal komunikasi bisnis sebaiknya memakai autentikasi dua faktor. Untuk UMKM yang melayani pelanggan lewat pesan instan, langkah ini dibahas di panduan mengamankan WhatsApp Business untuk UMKM.
  • Waspadai kode pihak ketiga. Tema, plugin, atau skrip yang dipasang dari sumber tidak jelas bisa membuka celah serius.
  • Amankan media penyimpanan. Flash drive yang dipakai memindahkan berkas konfigurasi atau sertifikat sebaiknya dipindai dan dienkripsi, seperti pada tutorial mengamankan USB flash drive.

Kesalahan yang paling sering terjadi justru sepele. Mengaktifkan UFW tanpa mengizinkan port SSH lebih dulu membuat Anda langsung terkunci. Mengubah port SSH tanpa memperbarui aturan firewall menimbulkan masalah yang sama. Menyalakan pembaruan otomatis lalu berharap semuanya beres tanpa pernah memeriksa log juga berisiko, karena kegagalan pemasangan biasanya hanya terlihat di log.

Terakhir, jangan mengandalkan satu lapisan saja. SSH key, UFW, pembaruan otomatis, fail2ban, dan backup bekerja sebagai lapisan yang saling menutupi. Jika satu lapisan gagal, lapisan lain masih memberi waktu untuk mendeteksi dan merespons.

Pertanyaan yang Sering Diajukan (FAQ)

Apakah SSH key bisa dicuri penyerang?
Bisa, terutama jika private key tidak dilindungi passphrase atau tersimpan di perangkat yang terinfeksi malware. Karena itu gunakan passphrase pada kunci, jangan menyalin private key ke server, dan batasi file lokalnya agar hanya bisa dibaca pemiliknya.
Bagaimana kalau saya salah konfigurasi sehingga terkunci dari SSH?
Gunakan konsol darurat dari panel penyedia VPS atau mode rescue. Hampir semua penyedia memberi akses konsol berbasis browser. Dari sana Anda bisa memperbaiki sshd_config atau aturan UFW tanpa perlu memuat ulang seluruh server.
Apakah UFW saja cukup sebagai firewall?
Cukup sebagai lapisan dasar untuk menutup port yang tidak dipakai. Namun UFW tidak membatasi laju percobaan login, tidak memfilter lalu lintas aplikasi, dan tidak menghentikan serangan pada port yang memang terbuka. Kombinasikan dengan fail2ban, pembaruan rutin, dan firewall dari sisi penyedia cloud bila tersedia.
Apakah perlu mengganti port SSH dari 22 ke port lain?
Mengganti port memang mengurangi banjir percobaan login di log, tetapi bukan pengamanan yang sesungguhnya karena pemindai tetap bisa menemukannya. Fokus utama tetap pada SSH key, menonaktifkan login password, dan pembatasan alamat IP sumber.
Seberapa sering VPS perlu di-reboot setelah pembaruan otomatis?
Reboot hanya diperlukan ketika pembaruan kernel atau pustaka inti dipasang. Aktifkan Automatic-Reboot pada jam sepi, misalnya dini hari, dan pastikan layanan yang berjalan sudah dikonfigurasi untuk hidup kembali otomatis lewat systemd.
English Version — Guide to Securing an Ubuntu VPS for Personal Projects & MSMEs

Quick Summary

  • The three foundations of Ubuntu VPS security: passwordless SSH keys, a UFW firewall with minimal rules, and automatic security updates.
  • Test every SSH configuration change before closing the old session so you do not get locked out of the server.
  • Automatic updates handle security vulnerabilities, but you still need backups, monitoring, and scheduled reboots.

Securing an Ubuntu VPS is essentially three initial tasks: log in with an SSH key instead of a password, close every port except those actually in use via UFW, and let the system install security updates on its own. This guide covers all three practically, assuming you manage a server for a personal project or a small MSME service and do not necessarily have a systems administrator background.

Why a New VPS Needs to Be Secured from the First Minute

A newly created VPS is generally in a fairly open state. The provider hands over root access along with an initial password, and within minutes of the IP address becoming active, automated bots start trying to log in. This is not an attack targeted specifically at you, but mass scanning that sweeps IP address ranges on the internet every day.

For personal projects, the risk is simple: if credentials are successfully guessed, your server can be used to mine cryptocurrency, send spam, or become part of a botnet. For MSMEs that host catalog applications, point-of-sale systems, or customer data, the impact is more serious because it involves trust and compliance.

  • Default credentials and weak passwords are the most common entry point.
  • Services listening on all interfaces (0.0.0.0) unintentionally expose databases to the public.
  • Unpatched software contains publicly known vulnerabilities that attackers routinely scan for.

Before logging in to the server, make sure the layers outside it are also secure. The domain and DNS accounts pointing to your VPS should already be locked down with two-factor authentication, as explained in the guide to securing domain and DNS accounts.

Step 1: SSH Keys and Disabling Password Login

SSH keys are far stronger than passwords because the key is mathematically long and cannot be guessed through repeated attempts. Generate a key pair on your local computer, not on the server:

ssh-keygen -t ed25519 -C admin@laptop

When prompted for a passphrase, enter a memorable passphrase. This passphrase protects the private key if your laptop is lost or stolen. Next, copy the public key to the VPS:

ssh-copy-id -i ~/.ssh/id_ed25519.pub user@IP_VPS

After successfully logging in without being asked for a password, create a non-root account with sudo privileges, then adjust /etc/ssh/sshd_config:

  1. PermitRootLogin no so root cannot log in directly.
  2. PasswordAuthentication no to disable password-based login.
  3. PubkeyAuthentication yes so public keys are accepted.
  4. KbdInteractiveAuthentication no to close other interactive pathways.
  5. AllowUsers username so only specific accounts may log in.

First test the syntax with sudo sshd -t, then run sudo systemctl restart ssh. Important rule: open a new terminal session to make sure login still works before closing the old session. As an additional layer, install fail2ban so that IP addresses that fail repeatedly are automatically blocked temporarily.

Step 2: UFW Firewall with Only Necessary Rules

UFW is a simple interface for iptables rules. Its principle is deny by default: all incoming connections are rejected, then you open them one by one only for the services in use.

sudo ufw default deny incoming && sudo ufw default allow outgoing

Before enabling it, allow SSH first so you do not lock yourself out:

sudo ufw allow OpenSSH

If the server serves a website or API, add the web ports:

sudo ufw allow 80/tcp && sudo ufw allow 443/tcp

Only then enable it and check the result:

sudo ufw enable && sudo ufw status verbose

Here is an overview of ports that usually need to be considered:

PortServiceRecommendation
22/tcpSSHOpen, restrict source IPs if possible
80/tcpHTTPOpen only if there is a web server; ideally redirect to HTTPS
443/tcpHTTPSOpen for websites, panels, or APIs
3306/tcpMySQL/MariaDBClose to the public; access via localhost is sufficient
6379/tcpRedisMust be closed to the public
25/587SMTPOpen only if the server actually sends email

If your IP address is relatively static, restrict SSH to it only with a command such as sudo ufw allow from 103.10.10.10 to any port 22 proto tcp. After that, delete the OpenSSH rule that is open to everyone. This approach eliminates almost all random login attempts from the internet.

Step 3: Automatic Security Updates on Ubuntu

A VPS that is routinely left untouched usually falls behind on patches. Ubuntu provides the unattended-upgrades package, which installs security updates without manual intervention. Install and enable it:

sudo apt update && sudo apt install unattended-upgrades apt-listchanges
sudo dpkg-reconfigure --priority=low unattended-upgrades

Check the /etc/apt/apt.conf.d/20auto-upgrades file so it contains at least the following three lines:

APT::Periodic::Update-Package-Lists "1"; APT::Periodic::Unattended-Upgrade "1"; APT::Periodic::AutocleanInterval "7";

Next, review /etc/apt/apt.conf.d/50unattended-upgrades to configure advanced behavior:

  • Make sure the security pattern in Origins-Pattern is enabled so security patches are always included.
  • Set Automatic-Reboot "true" along with Automatic-Reboot-Time "03:00" so kernel reboots occur during off-peak hours.
  • Enable Remove-Unused-Kernel-Packages and Remove-Unused-Dependencies so /boot does not fill up.
  • Set Unattended-Upgrade::Mail if you want notifications about update results.

Verify the configuration by running test mode: sudo unattended-upgrade --dry-run --debug. Installation history can be read in /var/log/unattended-upgrades/unattended-upgrades.log. Keep in mind that automatic updates are not a replacement for scheduled reboots or service restarts. Some library patches only truly take effect after the application process is restarted.

Ongoing Habits and Common Mistakes

The three foundations above close most basic attack surface, but server security is a habit, not a one-time setup. The following are worth making part of your routine:

  • Tested backups. Store copies of databases and configuration files in another location, then occasionally test the restore process. A backup that has never been tested cannot yet be called a backup.
  • Monitor login logs. Check /var/log/auth.log or journalctl -u ssh to look for unusual login attempt patterns.
  • Keep secrets secret. .env files, API keys, and tokens must not enter public repositories or be sent over insecure channels.
  • Lock down supporting accounts. Hosting panels, recovery email, and business communication channels should use two-factor authentication. For MSMEs that serve customers via instant messaging, this step is covered in the guide to securing WhatsApp Business for MSMEs.
  • Be wary of third-party code. Themes, plugins, or scripts installed from unclear sources can open serious vulnerabilities.
  • Secure storage media. Flash drives used to transfer configuration files or certificates should be scanned and encrypted, as in the tutorial on securing USB flash drives.

The most common mistakes are actually trivial. Enabling UFW without allowing the SSH port first locks you out immediately. Changing the SSH port without updating firewall rules creates the same problem. Turning on automatic updates and then hoping everything is fine without ever checking the logs is also risky, because installation failures usually only appear in the logs.

Finally, do not rely on a single layer. SSH keys, UFW, automatic updates, fail2ban, and backups work as layers that cover one another. If one layer fails, another still gives you time to detect and respond.

FAQ (English)

Can an SSH key be stolen by an attacker?
Yes, it can, especially if the private key is not protected by a passphrase or is stored on a malware-infected device. Therefore, use a passphrase on the key, do not copy the private key to the server, and restrict the local file so only its owner can read it.
What if I misconfigure something and get locked out of SSH?
Use the emergency console from your VPS provider's panel or rescue mode. Almost all providers offer browser-based console access. From there you can fix sshd_config or UFW rules without needing to reload the entire server.
Is UFW alone enough as a firewall?
It is sufficient as a basic layer to close unused ports. However, UFW does not rate-limit login attempts, does not filter application traffic, and does not stop attacks on ports that are open. Combine it with fail2ban, regular updates, and a cloud provider-side firewall if available.
Should I change the SSH port from 22 to another port?
Changing the port does reduce the flood of login attempts in the logs, but it is not real security because scanners can still find it. The main focus should remain on SSH keys, disabling password login, and restricting source IP addresses.
How often does a VPS need to be rebooted after automatic updates?
A reboot is only needed when kernel or core library updates are installed. Enable Automatic-Reboot during off-peak hours, such as early morning, and make sure running services are configured to come back up automatically via systemd.
Iklan

Komentar