Setup VM Production Ready Best Practice

V1 (GENERATED BY DEEPSEEK)

Berikut adalah langkah-langkah best practice untuk setup VM production ready:

1. Update & Upgrade Sistem

sudo apt update && sudo apt upgrade -y
sudo apt dist-upgrade -y
sudo apt autoremove -y
sudo apt clean

2. Buat User Baru (Non-Root)

sudo adduser deployer  # Ganti dengan username yang diinginkan
sudo usermod -aG sudo deployer  # Tambah ke group sudo

3. Setup SSH Security

# Ganti port SSH (pilih antara 1024-65535)
sudo nano /etc/ssh/sshd_config

# Ubah konfigurasi:
Port 2222  # Contoh port custom
PermitRootLogin no
PasswordAuthentication no
AllowUsers deployer

# Restart SSH
sudo systemctl restart sshd

# SEBELUM KELUAR: Buka terminal baru untuk test koneksi ke port baru!

4. Setup Firewall (UFW)

sudo ufw allow 2222/tcp  # Port SSH custom
sudo ufw allow http
sudo ufw allow https
sudo ufw enable

5. Install Nginx

sudo apt install nginx -y
sudo systemctl start nginx
sudo systemctl enable nginx

6. Install Fail2Ban

sudo apt install fail2ban -y
sudo systemctl enable fail2ban
sudo systemctl start fail2ban

7. Install Certbot (SSL)

sudo apt install certbot python3-certbot-nginx -y
sudo certbot --nginx -d example.com -d www.example.com  # Ganti dengan domain Anda
# Setup auto-renewal
sudo crontab -e
# Tambahkan line:
0 12 * * * /usr/bin/certbot renew --quiet

8. Install PHP & Dependencies untuk CI3

sudo apt install php-fpm php-mysql php-curl php-cli php-gd php-mbstring php-xml php-zip -y
sudo systemctl restart php8.1-fpm  # Sesuaikan versi PHP

9. Install CodeIgniter 3

cd /var/www
sudo git clone https://github.com/bcit-ci/CodeIgniter.git example.com
cd example.com

# Install dependencies via Composer
sudo apt install composer -y
sudo composer install --no-dev

# Set permissions
sudo chown -R www-data:www-data /var/www/example.com
sudo chmod -R 755 /var/www
sudo chmod -R 755 /var/www/example.com/application/cache/
sudo chmod -R 755 /var/www/example.com/application/logs/

10. Konfigurasi Nginx

sudo nano /etc/nginx/sites-available/example.com

# Isi konfigurasi:
server {
    listen 80;
    listen [::]:80;
    server_name example.com www.example.com;
    return 301 https://$server_name$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    
    server_name example.com www.example.com;
    
    root /var/www/example.com;
    index index.php index.html;
    
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.1-fpm.sock;  # Sesuaikan versi PHP
    }
    
    location ~ /\.ht {
        deny all;
    }
    
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}

# Aktifkan konfigurasi
sudo ln -s /etc/nginx/sites-available/example.com /etc/nginx/sites-enabled/
sudo nginx -t
sudo systemctl reload nginx

11. Database Setup (Opsional)

sudo apt install mariadb-server -y
sudo mysql_secure_installation

# Buat database dan user
sudo mysql -u root -p
CREATE DATABASE ci_db;
CREATE USER 'ci_user'@'localhost' IDENTIFIED BY 'strong_password';
GRANT ALL PRIVILEGES ON ci_db.* TO 'ci_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

12. Hardening Security Tambahan

# Disable directory listing
sudo sed -i 's/Options Indexes FollowSymLinks/Options -Indexes +FollowSymLinks/' /etc/apache2/apache2.conf

# Install ModSecurity (WAF)
sudo apt install libapache2-mod-security2 -y
sudo mv /etc/modsecurity/modsecurity.conf-recommended /etc/modsecurity/modsecurity.conf
sudo systemctl reload apache2

# Install Rootkit Scanner
sudo apt install chkrootkit rkhunter -y

13. Auto Update Security

sudo nano /etc/apt/apt.conf.d/10periodic
# Ubah menjadi:
APT::Periodic::Update-Package-Lists "1";
APT::Periodic::Download-Upgradeable-Packages "1";
APT::Periodic::AutocleanInterval "7";
APT::Periodic::Unattended-Upgrade "1";

14. Final Check

sudo reboot
# Setelah reboot, check:
- Koneksi SSH dengan port baru
- Status semua service
- Website via HTTPS
- Logs untuk error

Best Practice Tambahan:

  1. Gunakan SSH Key Authentication

  2. Setup monitoring (seperti Netdata atau Prometheus)

  3. Implementasi backup harian

  4. Setup intrusion detection system (IDS)

  5. Gunakan Cloudflare sebagai additional security layer

  6. Regular security audit

  7. Monitor logs dengan tools seperti Logwatch

Pastikan untuk:

  • Mengganti semua placeholder (example.com, deployer, dll)

  • Menyimpan SSH key di tempat aman

  • Membuat backup sebelum melakukan perubahan besar

  • Memonitor resource usage secara berkala

V2 (GENERATED BY DEEPSEEK)

Berikut revisi yang lebih lengkap dengan PHP 7.3 dan tambahan hardening security:

1. Initial Setup & System Hardening

# Update sistem
sudo apt update && sudo apt upgrade -y
sudo apt install -y software-properties-common ufw fail2ban

# Buat swap file (jika VM kecil)
sudo fallocate -l 2G /swapfile
sudo chmod 600 /swapfile
sudo mkswap /swapfile
sudo swapon /swapfile
echo '/swapfile none swap sw 0 0' | sudo tee -a /etc/fstab

# Tambahkan repositori PHP 7.3
sudo add-apt-repository ppa:ondrej/php -y
sudo apt update

2. User Management & SSH Hardening

# Buat user baru
sudo adduser deployer --gecos ""
sudo usermod -aG sudo deployer

# Generate SSH Key di local machine (laptop Anda)
ssh-keygen -t ed25519 -C "your_email@example.com"  # Lakukan di komputer lokal

# Copy public key ke server (MASIH SEBAGAI ROOT)
sudo mkdir /home/deployer/.ssh
sudo nano /home/deployer/.ssh/authorized_keys  # Paste public key
sudo chown -R deployer:deployer /home/deployer/.ssh
sudo chmod 700 /home/deployer/.ssh
sudo chmod 600 /home/deployer/.ssh/authorized_keys

# Edit SSH config
sudo nano /etc/ssh/sshd_config

# Konfigurasi:
Port 48956  # Port acak antara 1024-65535
PermitRootLogin no
PasswordAuthentication no
PubkeyAuthentication yes
AllowUsers deployer
ClientAliveInterval 300
ClientAliveCountMax 2
MaxAuthTries 3
LoginGraceTime 60

# Restart SSH
sudo systemctl restart sshd

# JANGAN TUTUP SESSION SAAT INI! Buka terminal baru untuk test koneksi

3. Firewall Configuration

sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow 48956/tcp  # Port SSH custom
sudo ufw allow http
sudo ufw allow https
sudo ufw enable

4. Install PHP 7.3 & Ekstensi

sudo apt install -y php7.3-fpm php7.3-cli php7.3-mysql php7.3-curl \
php7.3-gd php7.3-mbstring php7.3-xml php7.3-zip php7.3-opcache php7.3-bcmath

# PHP Hardening
sudo nano /etc/php/7.3/fpm/php.ini

# Ubah parameter:
expose_php = Off
cgi.fix_pathinfo=0
display_errors=Off
log_errors=On
allow_url_fopen=Off
session.cookie_httponly=1
session.cookie_secure=1
disable_functions = exec,passthru,shell_exec,system,proc_open,popen,show_source

sudo systemctl restart php7.3-fpm

5. Install Nginx dengan Optimalisasi

sudo apt install -y nginx

# Konfigurasi Nginx
sudo nano /etc/nginx/nginx.conf

# Tambahkan dalam http block:
server_tokens off;
client_max_body_size 10m;
keepalive_timeout 10;

# Buat direktori untuk cache
sudo mkdir -p /var/cache/nginx
sudo chown -R www-data:www-data /var/cache/nginx

sudo systemctl restart nginx

6. Install MariaDB & Hardening

sudo apt install -y mariadb-server

sudo mysql_secure_installation

# Buat database untuk CI3
sudo mysql -u root -p

CREATE DATABASE ci_db CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
CREATE USER 'ci_user'@'localhost' IDENTIFIED BY 'StrongP@ssw0rd!123';
GRANT ALL PRIVILEGES ON ci_db.* TO 'ci_user'@'localhost';
FLUSH PRIVILEGES;
EXIT;

7. Install CodeIgniter 3 dengan Secure Configuration

sudo apt install -y git unzip
cd /var/www
sudo git clone https://github.com/bcit-ci/CodeIgniter.git example.com
cd example.com

# Download composer
curl -sS https://getcomposer.org/installer | sudo php -- --install-dir=/usr/local/bin --filename=composer
sudo composer install --no-dev

# File permissions
sudo chown -R www-data:www-data /var/www/example.com
sudo find /var/www/example.com -type d -exec chmod 755 {} \;
sudo find /var/www/example.com -type f -exec chmod 644 {} \;
sudo chmod 777 /var/www/example.com/application/cache
sudo chmod 777 /var/www/example.com/application/logs

# Secure .htaccess (jika pakai Apache)
sudo nano /var/www/example.com/.htaccess

# Isi:
<IfModule mod_rewrite.c>
    RewriteEngine On
    RewriteBase /
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteRule ^(.*)$ index.php?/$1 [L]
    
    # Block suspicious requests
    RewriteCond %{QUERY_STRING} (;|<|>|'|"|\)|%0A|%0D|%22|%27|%3C|%3E|%00) [NC]
    RewriteRule ^(.*)$ - [F,L]
</IfModule>

8. SSL dengan Certbot & Optimalisasi

sudo apt install -y certbot python3-certbot-nginx
sudo certbot --nginx -d example.com -d www.example.com --non-interactive --agree-tos -m admin@example.com

# Auto-renewal dengan cron
(crontab -l 2>/dev/null; echo "0 3 * * * /usr/bin/certbot renew --quiet --post-hook 'systemctl reload nginx'") | sudo crontab -

9. Nginx Server Block Configuration

sudo nano /etc/nginx/sites-available/example.com

# Konfigurasi:
server {
    listen 80;
    server_name example.com www.example.com;
    return 301 https://$host$request_uri;
}

server {
    listen 443 ssl http2;
    listen [::]:443 ssl http2;
    
    server_name example.com www.example.com;
    
    root /var/www/example.com;
    index index.php index.html;
    
    # SSL Configuration
    ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem;
    ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem;
    ssl_trusted_certificate /etc/letsencrypt/live/example.com/chain.pem;
    ssl_protocols TLSv1.2 TLSv1.3;
    ssl_ciphers ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:DHE-RSA-AES128-GCM-SHA256:DHE-RSA-AES256-GCM-SHA384;
    ssl_prefer_server_ciphers on;
    ssl_session_cache shared:SSL:10m;
    ssl_session_timeout 1d;
    ssl_session_tickets off;
    
    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;
    add_header Content-Security-Policy "default-src 'self' https: 'unsafe-inline' 'unsafe-eval'; img-src 'self' data:;" always;
    
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }
    
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
        include fastcgi_params;
        
        # Security additions
        fastcgi_hide_header X-Powered-By;
        fastcgi_param HTTP_PROXY "";
    }
    
    location ~ /\.(?!well-known).* {
        deny all;
    }
    
    access_log /var/log/nginx/example.com.access.log;
    error_log /var/log/nginx/example.com.error.log;
}

# Test dan reload
sudo nginx -t
sudo systemctl reload nginx

10. Advanced Security Setup

# Kernel hardening
sudo nano /etc/sysctl.conf

# Tambahkan:
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.secure_redirects = 1
net.ipv4.conf.default.secure_redirects = 1
net.ipv6.conf.all.accept_redirects = 0
net.ipv6.conf.default.accept_redirects = 0
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.icmp_ignore_bogus_error_responses = 1
fs.protected_hardlinks = 1
fs.protected_symlinks = 1

# Apply changes
sudo sysctl -p

# Install auditd untuk monitoring
sudo apt install -y auditd
sudo auditctl -e 1

# Install dan konfigurasi Fail2Ban
sudo cp /etc/fail2ban/jail.conf /etc/fail2ban/jail.local
sudo nano /etc/fail2ban/jail.local

# Modifikasi:
[sshd]
enabled = true
port = 48956
maxretry = 3
bantime = 1h

[nginx-botsearch]
enabled = true

sudo systemctl restart fail2ban

11. Final Touches

# Auto security updates
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

# File integrity monitoring
sudo apt install -y aide
sudo aideinit
sudo cp /var/lib/aide/aide.db.new /var/lib/aide/aide.db

# Backup script
sudo nano /usr/local/bin/backup.sh

# Isi script:
#!/bin/bash
DATE=$(date +%Y%m%d)
mysqldump -u ci_user -p'StrongP@ssw0rd!123' ci_db > /var/backups/ci_db_$DATE.sql
tar czf /var/backups/web_$DATE.tar.gz /var/www/example.com

# Jadwalkan cron job
(crontab -l 2>/dev/null; echo "0 2 * * * /usr/local/bin/backup.sh") | sudo crontab -

12. Post-Install Checklist

  1. Test PHP info: Buat file info.php dan pastikan PHP 7.3 terinstall

  2. Test koneksi database dari CI3

  3. Cek semua log (/var/log/nginx/*.log, /var/log/fail2ban.log)

  4. Test SSL: https://www.ssllabs.com/ssltest/

  5. Scan port dari luar: nmap -sV -p- your_server_ip

  6. Setup monitoring (cth: Netdata atau Prometheus)

  7. Implementasi WAF (ModSecurity)

  8. Setup log rotation untuk aplikasi

Yang perlu diperhatikan:

  • Ganti semua contoh domain (example.com) dengan domain Anda

  • Simpan SSH key di tempat aman

  • Backup konfigurasi sebelum melakukan perubahan besar

  • Update password database dengan yang lebih kuat

  • Setup monitoring resource (memory, CPU, disk)

  • Lakukan audit security secara berkala

Revisi ini mencakup:

  • PHP 7.3 spesifik

  • Kernel hardening

  • SSL optimalisasi

  • Security headers lengkap

  • File integrity monitoring

  • Backup otomatis

  • Tambahan WAF dan monitoring

  • Konfigurasi database yang lebih aman

  • Perlindungan terhadap serangan umum di level server

Pastikan untuk menyesuaikan semua placeholder (example.com, deployer, password, dll) sesuai kebutuhan Anda!

MYSQL 5.7

It's important to note that MySQL 5.7 is quite old and is no longer actively supported by the MySQL community. It's highly recommended to install a more recent and secure version of MySQL, such as 8.0. However, if you have a specific reason to install MySQL 5.7 on Ubuntu 24.04.2 LTS, here are the steps:

Warning: Installing older, unsupported software can introduce security vulnerabilities. Proceed with caution and ensure you understand the risks involved.

Step 1: Download the MySQL 5.7 APT Repository Configuration Package

Ubuntu 24.04 repositories do not include MySQL 5.7 by default. You need to download and install the MySQL APT repository configuration package for older Ubuntu versions.

Bash

wget https://repo.mysql.com/mysql-apt-config_0.8.29-1_all.deb

Step 2: Install the Repository Configuration Package

Install the downloaded package using dpkg.

Bash

sudo dpkg -i mysql-apt-config_0.8.29-1_all.deb

During the installation, you will be presented with a configuration menu. Carefully navigate this menu using the arrow keys and select the following:

  1. MySQL Server and Cluster: Choose mysql-5.7.

  2. MySQL Tools & Connectors: You can keep the default selections or choose specific components if needed.

  3. MySQL Workbench: You can keep the default or deselect if you don't need it on the server.

  4. MySQL Shell: You can keep the default or deselect if you don't need it on the server.

Use the arrow keys to move between options and the Enter key to select. Use the Tab key to move between "Ok" and "Cancel" buttons. Select "Ok" when you have made your choices.

Step 3: Update the APT Package Index

After configuring the repository, update the APT package index to reflect the new available packages.

Bash

sudo apt update

Step 4: Install the MySQL 5.7 Server

Now you can install the MySQL 5.7 server package.

Bash

sudo apt install mysql-server=5.7*

During the installation, you will be prompted to set a root password for your MySQL server. Remember this password carefully!

Step 5: Verify MySQL 5.7 is Running

After the installation is complete, check if the MySQL service is running.

Bash

sudo systemctl status mysql

You should see output indicating that the mysql.service is active (running).

Step 6: Secure Your MySQL Installation

It's crucial to secure your MySQL installation. Run the mysql_secure_installation script.

Bash

sudo mysql_secure_installation

This script will guide you through several security-related steps:

  • Validate Password Plugin: You can choose to enable or disable the password validation plugin. It's recommended to enable it for stronger passwords.

  • Change the root password: If you didn't set a strong password during installation, you'll be prompted to change it now.

  • Remove anonymous users: It's recommended to remove anonymous users for security.

  • Disallow root login remotely: Unless you have a specific need, it's generally recommended to disallow root login from remote hosts.

  • Remove test database and access to it: Removing the test database and related privileges is a good security practice.

Answer the prompts according to your security requirements.

Step 7: (Optional) Configure Firewall

If you have a firewall enabled (like ufw), you might need to allow connections to the MySQL port (default is 3306).

Bash

sudo ufw allow 3306/tcp

Step 8: (Optional) Connect to the MySQL Server

You can now try connecting to your MySQL 5.7 server using the mysql client.

Bash

mysql -u root -p

You will be prompted for the root password you set during the installation.

Important Considerations:

  • Security: As mentioned earlier, MySQL 5.7 is no longer actively supported. This means it won't receive security updates, making your server vulnerable. Consider upgrading to a newer version as soon as feasible.

  • Compatibility: Some newer applications or libraries might have compatibility issues with older MySQL versions.

  • Repository Stability: The availability of the MySQL 5.7 repository for Ubuntu 24.04 in the long term is not guaranteed.

By following these steps, you should be able to install MySQL 5.7 on your Ubuntu 24.04.2 LTS server. However, remember the security implications and consider upgrading to a supported version.

Last updated