#cloud-config
# Debian 13 Trixie VPN/SOCKS5 Proxy Server Cloud-init

# 1. Install basic tools
packages:
  - curl
  - wget
  - ca-certificates
  - apt-transport-https
  - gnupg
  - fail2ban
  - ufw

# 2. Write installation scripts and config files
write_files:
  # Docker installation script
  - path: /root/install-docker.sh
    content: |
      #!/bin/bash
      set -e

      echo "Starting Docker installation..."

      # Install prerequisites
      apt-get update
      apt-get install -y ca-certificates curl gnupg lsb-release

      # Add Docker GPG key
      install -m 0755 -d /etc/apt/keyrings
      curl -fsSL https://download.docker.com/linux/debian/gpg | gpg --dearmor -o /etc/apt/keyrings/docker.gpg
      chmod a+r /etc/apt/keyrings/docker.gpg

      # Add Docker repository (Debian 13 Trixie)
      echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/debian trixie stable" | tee /etc/apt/sources.list.d/docker.list > /dev/null

      # Install Docker
      apt-get update
      apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin

      # Enable and start Docker
      systemctl enable --now docker

      echo "Docker installation completed"
    permissions: '0755'
    owner: root:root

  # Kernel parameter tuning
  - path: /etc/sysctl.d/99-vpn-optimize.conf
    content: |
      # VPN/SOCKS5 Proxy Kernel Parameter Tuning

      # ============================================================================
      # 1. IP Forwarding (Required for VPN/Proxy)
      # ============================================================================
      # Enable IPv4 packet forwarding - required for proxy to forward traffic
      net.ipv4.ip_forward = 1

      # Enable IPv6 packet forwarding
      net.ipv6.conf.all.forwarding = 1

      # ============================================================================
      # 2. Security: Disable ICMP Redirects
      # ============================================================================
      # ICMP redirects can be exploited by attackers to perform MITM attacks.
      # Disabling them improves security for publicly accessible servers.
      net.ipv4.conf.all.accept_redirects = 0
      net.ipv4.conf.default.accept_redirects = 0
      net.ipv6.conf.all.accept_redirects = 0
      net.ipv6.conf.default.accept_redirects = 0

      # ============================================================================
      # 3. Security: Disable Source Routing
      # ============================================================================
      # Source routing allows sender to specify packet route, which can bypass
      # security controls. Disable to prevent routing spoofing attacks.
      net.ipv4.conf.all.send_redirects = 0
      net.ipv4.conf.default.send_redirects = 0

      # ============================================================================
      # 4. Connection Tracking Optimization (High Concurrency)
      # ============================================================================
      # nf_conntrack_max: Maximum number of connections to track.
      # Each TCP connection uses one entry. Increase for high-concurrency proxy.
      net.netfilter.nf_conntrack_max = 262144

      # Hash table size for connection tracking lookup performance
      net.netfilter.nf_conntrack_hashsize = 65536

      # Reduce established connection timeout from default 5 days to 1 hour.
      # Helps reclaim memory from idle connections faster.
      net.netfilter.nf_conntrack_tcp_timeout_established = 3600

      # ============================================================================
      # 5. Socket Optimization (High Concurrency)
      # ============================================================================
      # somaxconn: TCP listen queue length. Default 128 is too small for high
      # concurrency. Increase to avoid "connection refused" under load.
      net.core.somaxconn = 65535

      # tcp_max_syn_backlog: SYN queue length for handling burst connections.
      # Increase for servers with many simultaneous new connections.
      net.ipv4.tcp_max_syn_backlog = 16384

      # fs.file-max: System-wide limit for file descriptors.
      # Each connection uses one FD. Increase for high-concurrency proxy.
      fs.file-max = 524288

      # ============================================================================
      # 6. Socket Buffer Tuning (High Throughput)
      # ============================================================================
      # VPN/Proxy servers handle large amounts of traffic and need larger buffers.
      # Default socket buffer sizes are too small for high-throughput.

      # Default and max socket receive buffer sizes.
      # Format: default, max
      net.core.rmem_default = 262144
      net.core.rmem_max = 16777216

      # Default and max socket send buffer sizes.
      net.core.wmem_default = 262144
      net.core.wmem_max = 16777216

      # TCP buffer sizes (min, default, max).
      # Format: min, default, max
      net.ipv4.tcp_rmem = 4096 87380 16777216
      net.ipv4.tcp_wmem = 4096 65536 16777216

      # TCP keepalive: Detect dead connections/tunnels faster.
      # Important for VPN tunnels that may go idle.
      net.ipv4.tcp_keepalive_time = 300
      net.ipv4.tcp_keepalive_intvl = 30
      net.ipv4.tcp_keepalive_probes = 5

      # TCP TIME_WAIT optimization: Faster socket recycling.
      net.ipv4.tcp_fin_timeout = 15
      net.ipv4.tcp_tw_reuse = 1
      net.ipv4.tcp_max_tw_buckets = 200000

      # IP local port range: Increase ephemeral ports for more connections.
      net.ipv4.ip_local_port_range = 10240 65535

      # ============================================================================
      # 7. MTU Optimization (VPN Tunnel)
      # ============================================================================
      # VPN tunnels often suffer from fragmentation issues due to encapsulation.
      # These settings enable MTU discovery to avoid fragmentation.
      net.ipv4.ip_no_pmtu_disc = 0
      net.ipv4.tcp_mtu_probing = 1

      # ============================================================================
      # 8. PostgreSQL Shared Memory (Small/Medium DB)
      # ============================================================================
      # kernel.shmmax: Max size of shared memory segment (bytes)
      # 4GB for small/medium PostgreSQL
      kernel.shmmax = 4294967296

      # kernel.shmall: Total shared memory pages available
      # 4GB / 4096 bytes per page = 1048576 pages
      kernel.shmall = 1048576
    owner: root:root
    permissions: '0644'

  # Security limits for high-concurrency VPN
  - path: /etc/security/limits.d/vpn.conf
    content: |
      # ============================================================================
      # Increase file descriptor limits for VPN/Proxy servers
      # Each VPN tunnel and connection uses file descriptors
      # ============================================================================

      # Soft limit for max open files
      * soft nofile 524288

      # Hard limit for max open files
      * hard nofile 524288

      # For root user
      root soft nofile 524288
      root hard nofile 524288

  # BBR acceleration config
  - path: /etc/sysctl.d/99-tcp-bbr.conf
    content: |
      # BBR TCP Congestion Control Algorithm
      # BBR (Bottleneck Bandwidth and Round-trip propagation time) is developed
      # by Google. It performs better than traditional CUBIC/Reno, especially
      # on high-latency, high-bandwidth links (like overseas VPN connections).
      net.core.default_qdisc = fq
      net.ipv4.tcp_congestion_control = bbr
    owner: root:root
    permissions: '0644'

  # SSH port change script
  - path: /root/ssh-port-change.sh
    content: |
      #!/bin/bash
      sed -i 's/^#Port 22/Port 22022/' /etc/ssh/sshd_config
      sed -i 's/^Port 22/Port 22022/' /etc/ssh/sshd_config
      # Only listen on new port
      echo "ListenAddress 0.0.0.0" >> /etc/ssh/sshd_config
      systemctl restart sshd
    permissions: '0755'
    owner: root:root

  # Docker log configuration
  - path: /etc/docker/daemon.json
    content: |
      {
        "log-driver": "json-file",
        "log-opts": {
          "max-size": "10m",
          "max-file": "3"
        }
      }
    owner: root:root
    permissions: '0644'

  # Weekly auto-update script
  - path: /root/auto-update.sh
    content: |
      #!/bin/bash
      # Weekly auto-update script for security patches

      echo "========== $(date) Starting system update ==========" >> /var/log/auto-update.log 2>&1
      apt-get update >> /var/log/auto-update.log 2>&1
      apt-get upgrade -y >> /var/log/auto-update.log 2>&1
      echo "========== $(date) Update completed ==========" >> /var/log/auto-update.log 2>&1
    permissions: '0755'
    owner: root:root

# 3. Commands to run on first boot
runcmd:
  # Enable and configure UFW firewall
  - ufw --force reset
  - ufw default deny incoming
  - ufw default allow outgoing
  - ufw allow 22022/tcp comment 'SSH'
  - ufw allow 443/tcp comment 'HTTPS'
  - ufw allow 80/tcp comment 'HTTP'
  - ufw allow 1080/tcp comment 'SOCKS5'
  - ufw --force enable

  # Enable fail2ban
  - systemctl enable --now fail2ban

  # Change SSH port to 22022
  - /root/ssh-port-change.sh

  # Load BBR kernel module
  - modprobe tcp_bbr || true

  # Apply kernel parameters
  - sysctl -p /etc/sysctl.d/99-vpn-optimize.conf
  - sysctl -p /etc/sysctl.d/99-tcp-bbr.conf

  # Install Docker
  - /root/install-docker.sh

  # Set script permissions
  - chmod +x /root/auto-update.sh

  # Add cron job: Every Monday at 2:00 AM
  - |
    echo "0 2 * * 1 /root/auto-update.sh" >> /etc/crontab

  # Enable docker service
  - systemctl enable docker || true

# 4. Timezone
timezone: Asia/Singapore
