☀️Siang
Cybersecurity

Cheatsheet Linux Security: Command Line, Firewall, dan Hardening

GRATIS

Referensi cepat keamanan Linux — iptables, nftables, SSH hardening, fail2ban, SELinux, nmap, openssl, GPG, dan log analysis



1. iptables Firewall

⚠️ Peringatan

Salah konfigurasi iptables bisa mengunci akses SSH Anda! Selalu tambahkan rule ACCEPT untuk SSH sebelum DROP/REJECT.

Struktur Dasar

# Lihat semua rule
iptables -L -v -n --line-numbers

# Chain: INPUT (masuk), OUTPUT (keluar), FORWARD (forwarding)

# Izinkan SSH (wajib pertama!)
iptables -A INPUT -p tcp --dport 22 -j ACCEPT

# Izinkan HTTP/HTTPS
iptables -A INPUT -p tcp --dport 80 -j ACCEPT
iptables -A INPUT -p tcp --dport 443 -j ACCEPT

# Izinkan loopback
iptables -A INPUT -i lo -j ACCEPT

# Izinkan established connections
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT

# Blokir semua traffic masuk
iptables -P INPUT DROP

# Hapus rule tertentu (berdasarkan nomor)
iptables -D INPUT 3

# Flush semua rule
iptables -F

iptables — Common Options

OptionKeteranganContoh
-AAppend ruleiptables -A INPUT ...
-DDelete ruleiptables -D INPUT 3
-IInsert di posisi tertentuiptables -I INPUT 1 ...
-pProtocol (tcp/udp/icmp)-p tcp
--dportDestination port--dport 80
--sportSource port--sport 1024
-sSource IP-s 192.168.1.0/24
-dDestination IP-d 10.0.0.1
-iInput interface-i eth0
-jTarget (ACCEPT/DROP/REJECT)-j ACCEPT
-mMatch extension-m state

Simpan & Restore Rules

# Simpan rules
iptables-save > /etc/iptables/rules.v4
ip6tables-save > /etc/iptables/rules.v6

# Restore rules
iptables-restore < /etc/iptables/rules.v4

# Auto-load saat boot (Debian/Ubuntu)
apt install iptables-persistent
netfilter-persistent save

2. nftables (Pengganti iptables)

# Cek status
nft list ruleset

# Buat table dan chain
nft add table inet filter
nft add chain inet filter input { type filter hook input priority 0 \; policy drop \; }

# Tambah rule
nft add rule inet filter input tcp dport 22 accept
nft add rule inet filter input tcp dport {80, 443} accept
nft add rule inet filter input ct state established,related accept
nft add rule inet filter input iif lo accept

# Hapus rule (pakai handle)
nft --handle list chain inet filter input
nft delete rule inet filter input handle 4

# Config file: /etc/nftables.conf
nft -f /etc/nftables.conf

3. SSH Hardening

Konfigurasi /etc/ssh/sshd_config

# Ubah port default
Port 2222

# Nonaktifkan root login
PermitRootLogin no

# Nonaktifkan password auth (pakai key only)
PasswordAuthentication no
PubkeyAuthentication yes

# Batasi user tertentu
AllowUsers admin deploy

# Timeout
ClientAliveInterval 300
ClientAliveCountMax 2

# Nonaktifkan X11 forwarding
X11Forwarding no

# Nonaktifkan DNS lookup (cepat)
UseDNS no

# Limit authentication attempts
MaxAuthTries 3

# Disable empty passwords
PermitEmptyPasswords no

# Restart SSH setelah ubah config
sudo systemctl restart sshd

SSH Key Authentication

# Generate key pair (di komputer lokal)
ssh-keygen -t ed25519 -C "komentar"
# Atau RSA 4096-bit:
ssh-keygen -t rsa -b 4096

# Copy public key ke server
ssh-copy-id -i ~/.ssh/id_ed25519.pub user@server

# Manual copy
cat ~/.ssh/id_ed25519.pub | ssh user@server "mkdir -p ~/.ssh && cat >> ~/.ssh/authorized_keys"

# Set permission yang benar
chmod 700 ~/.ssh
chmod 600 ~/.ssh/authorized_keys

4. Fail2Ban

# Install
sudo apt install fail2ban

# Status
sudo systemctl status fail2ban
sudo fail2ban-client status
sudo fail2ban-client status sshd

# Konfigurasi: /etc/fail2ban/jail.local
cat > /etc/fail2ban/jail.local <<'EOF'
[DEFAULT]
bantime = 3600
findtime = 600
maxretry = 5
backend = systemd

[sshd]
enabled = true
port = 2222
filter = sshd
logpath = /var/log/auth.log
maxretry = 3
bantime = 86400
EOF

# Restart
sudo systemctl restart fail2ban

# Unban IP
sudo fail2ban-client set sshd unbanip 192.168.1.100

# Ban IP manual
sudo fail2ban-client set sshd banip 192.168.1.100

# Lihat banned IPs
sudo fail2ban-client get sshd banned

5. chmod & chown

Permission Angka (Octal)

AngkaPermissionKeterangan
7rwxBaca + Tulis + Eksekusi
6rw-Baca + Tulis
5r-xBaca + Eksekusi
4r--Baca saja
0---Tidak ada akses
# Format: chmod [owner][group][others] file
chmod 755 script.sh      # rwxr-xr-x (owner:all, group/others:rx)
chmod 644 config.txt     # rw-r--r-- (owner:rw, others:r)
chmod 600 id_rsa         # rw------- (hanya owner)
chmod 700 ~/.ssh         # rwx------ (hanya owner)
chmod +x script.sh       # Tambah execute

# Recursive
chmod -R 755 /var/www

# chown — ubah pemilik
chown user:group file.txt
chown -R www-data:www-data /var/www

# Special bits
chmod 4755 binary    # SUID — eksekusi sebagai pemilik
chmod 2755 dir       # SGID — file baru inherit group
chmod 1777 /tmp      # Sticky bit — hanya owner bisa hapus

6. User Management

# Tambah user
sudo useradd -m -s /bin/bash -G sudo newuser
sudo passwd newuser

# Ubah user
sudo usermod -aG docker newuser    # Tambah ke group
sudo usermod -L newuser            # Lock user
sudo usermod -U newuser            # Unlock user

# Hapus user
sudo userdel -r newuser            # -r hapus home dir

# Group
sudo groupadd devops
sudo gpasswd -a user devops        # Tambah user ke group
sudo gpasswd -d user devops        # Hapus user dari group

# Lihat info
id user                            # UID, GID, groups
groups user                        # Daftar group
whoami                             # User saat ini
last                               # Login history
lastb                              # Failed logins

# Sudo
sudo visudo                        # Edit sudoers
user ALL=(ALL:ALL) ALL             # Full sudo
user ALL=(ALL) NOPASSWD: ALL       # Sudo tanpa password

7. SELinux Basics

# Cek status
getenforce                 # Enforcing / Permissive / Disabled
sestatus                   # Detail status

# Set mode sementara
sudo setenforce 0          # Permissive
sudo setenforce 1          # Enforcing

# Set mode permanen: /etc/selinux/config
SELINUX=enforcing          # enforcing / permissive / disabled

# Lihat context file
ls -Z /var/www/html
# -rw-r--r--. root root unconfined_u:object_r:httpd_sys_content_t:s0 index.html

# Ubah context
sudo chcon -t httpd_sys_content_t /data/web/*
sudo restorecon -Rv /var/www    # Restore default context

# SELinux boolean
getsebool -a | grep httpd
sudo setsebool -P httpd_can_network_connect on

# Cek log audit
sudo ausearch -m AVC -ts recent

8. Log Analysis

# journalctl (systemd)
journalctl -xe                          # Error terbaru
journalctl -u sshd --since "1 hour ago" # Log SSH 1 jam terakhir
journalctl -u sshd -f                   # Follow log SSH real-time
journalctl --priority=err               # Hanya error
journalctl --disk-usage                  # Ukuran log
journalctl --vacuum-size=500M           # Bersihkan hingga 500MB

# Log file umum
/var/log/auth.log           # Autentikasi (login, sudo, SSH)
/var/log/syslog             # System log
/var/log/kern.log           # Kernel log
/var/log/dmesg              # Boot messages
/var/log/fail2ban.log       # Fail2Ban log
/var/log/nginx/access.log   # Nginx access
/var/log/nginx/error.log    # Nginx error

# Grep auth log
grep "Failed password" /var/log/auth.log
grep "Accepted publickey" /var/log/auth.log
grep "sudo:" /var/log/auth.log

# Hitung percobaan login gagal per IP
grep "Failed password" /var/log/auth.log | \
  awk '{print $(NF-3)}' | sort | uniq -c | sort -rn | head -10

# Real-time monitoring
tail -f /var/log/auth.log | grep "Failed"
watch -n 1 'who'             # Monitor login aktif

9. Network Scanning

nmap

# Scan port umum
nmap 192.168.1.1

# Scan semua port
nmap -p- 192.168.1.1

# Scan dengan service detection
nmap -sV 192.168.1.1

# Scan jaringan (host discovery)
nmap -sn 192.168.1.0/24

# Scan dengan OS detection
nmap -O 192.168.1.1

# Scan cepat (top 100 ports)
nmap --top-ports 100 192.168.1.1

# Stealth scan
nmap -sS 192.168.1.1

# Output ke file
nmap -oN scan.txt 192.168.1.1

netstat & ss

# netstat (legacy)
netstat -tulnp              # Listening ports + PID
netstat -anp | grep ESTAB   # Established connections
netstat -i                  # Interface statistics

# ss (modern, lebih cepat)
ss -tulnp                   # Listening TCP/UDP + PID
ss -s                       # Statistik koneksi
ss -t state established     # Koneksi established
ss dst 192.168.1.1          # Koneksi ke IP tertentu

# netstat/ss umum
ss -tulnp | grep :22        # Cek SSH listening
ss -tulnp | grep :80        # Cek HTTP listening

Command Network Lainnya

# Cek IP dan interface
ip addr show
ip route show

# Ping & traceroute
ping -c 4 google.com
traceroute google.com

# DNS lookup
dig google.com
nslookup google.com
host google.com

# Cek koneksi
curl -I https://example.com
wget --spider https://example.com

# TCPDump (packet capture)
tcpdump -i eth0 port 80
tcpdump -i any -w capture.pcap
tcpdump -r capture.pcap

10. Encryption — GPG & OpenSSL

GPG (GNU Privacy Guard)

# Generate key pair
gpg --full-generate-key

# List keys
gpg --list-keys
gpg --list-secret-keys

# Export public key
gpg --armor --export user@email.com > public.asc

# Import public key
gpg --import public.asc

# Enkripsi file
gpg -e -r user@email.com rahasia.txt
# Output: rahasia.txt.gpg

# Dekripsi file
gpg -d rahasia.txt.gpg > rahasia.txt

# Sign file
gpg --armor --sign dokumen.txt

# Verify signature
gpg --verify dokumen.txt.asc

OpenSSL

# Generate random password
openssl rand -base64 32

# Hash
echo -n "password" | openssl dgst -sha256
openssl dgst -sha256 file.txt

# Generate self-signed SSL cert
openssl req -x509 -nodes -days 365 \
  -newkey rsa:2048 \
  -keyout server.key \
  -out server.crt \
  -subj "/CN=localhost"

# Generate CSR (Certificate Signing Request)
openssl req -new -newkey rsa:2048 \
  -nodes -keyout server.key \
  -out server.csr

# Cek SSL certificate
openssl s_client -connect example.com:443
openssl x509 -in server.crt -text -noout

# Enkripsi file (AES-256)
openssl enc -aes-256-cbc -salt -pbkdf2 -in data.txt -out data.enc
openssl enc -aes-256-cbc -d -pbkdf2 -in data.enc -out data.txt

# Generate DH parameters
openssl dhparam -out dhparam.pem 2048

11. Security Tools Umum

ToolFungsiInstall
nmapPort scanning & network discoveryapt install nmap
fail2banBrute-force protectionapt install fail2ban
ufwUncomplicated Firewall (frontend iptables)apt install ufw
lynisSecurity audit & hardeningapt install lynis
rkhunterRootkit detectionapt install rkhunter
clamavAntivirus scannerapt install clamav
chkrootkitRootkit checkerapt install chkrootkit
aideFile integrity monitoringapt install aide
tcpdumpPacket captureapt install tcpdump
netcat (nc)Network Swiss army knifeapt install netcat
wiresharkNetwork protocol analyzerapt install wireshark
hydraPassword brute-forceapt install hydra

Quick Security Audit Commands

# Cek listening ports
ss -tulnp

# Cek crontab mencurigakan
crontab -l
for user in $(cut -f1 -d: /etc/passwd); do crontab -u $user -l 2>/dev/null; done

# Cek SUID binaries
find / -perm -4000 -type f 2>/dev/null

# Cek file world-writable
find / -perm -o+w -type f 2>/dev/null | grep -v proc

# Cek user dengan UID 0 (root)
awk -F: '$3 == 0 {print $1}' /etc/passwd

# Cek authorized_keys yang mencurigakan
find / -name "authorized_keys" 2>/dev/null

# Cek recent logins
last -20
lastb -20   # Failed logins

# Lynis security audit
sudo lynis audit system

UFW (Simple Firewall Alternative)

# Enable firewall
sudo ufw enable
sudo ufw default deny incoming
sudo ufw default allow outgoing

# Allow services
sudo ufw allow 2222/tcp     # SSH custom port
sudo ufw allow 80/tcp       # HTTP
sudo ufw allow 443/tcp      # HTTPS

# Allow from specific IP
sudo ufw allow from 192.168.1.0/24

# Status
sudo ufw status verbose

# Delete rule
sudo ufw delete allow 80/tcp
← Sebelumnya API Security Testing Selanjutnya → Artikel Lainnya
🔍 Zoom
100%
🎨 Tema