Advertisement
pathankp

OVPN Installer with Load Balancing

Jan 14th, 2025 (edited)
153
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 21.56 KB | Source Code | 0 0
  1. #!/bin/bash
  2.  
  3. # Version
  4. VERSION="1.0"
  5.  
  6. # Add this near the start of the script
  7. trap 'echo "Installation interrupted. Cleaning up..."; cleanup_installation; exit 1' INT TERM
  8.  
  9. # Logging setup
  10. LOG_FILE="/var/log/openvpn_lb_installer.log"
  11. CLEANUP_ON_ERROR=true
  12.  
  13. # Clear screen and show logo
  14. clear
  15.  
  16. # ASCII Art Logo
  17. cat << 'EOF'
  18.   _____ _                 _      ____            _     ____  
  19.  / ____| |               | |    |  _ \          | |   |  _ \
  20. | |    | | __ _ _   _  __| | ___| |_) | __ _  __| |   | |_) |
  21. | |    | |/ _` | | | |/ _` |/ _ \  _ < / _` |/ _` |   |  _ <
  22. | |____| | (_| | |_| | (_| |  __/ |_) | (_| | (_| |_ _| |_) |
  23.  \_____|_|\__,_|\__,_|\__,_|\___|____/ \__,_|\__,_(_|_)____/
  24.                                                              
  25.      OpenVPN Load Balancer Installer v${VERSION}
  26.      Published by Naveed Alam Khan
  27.      Powered by Anthropic's Claude AI
  28. =============================================================
  29. EOF
  30.  
  31. # Function definitions
  32. setup_logging() {
  33.     LOG_FILE="/var/log/openvpn_lb_installer.log"
  34.     touch "$LOG_FILE"
  35.     chmod 640 "$LOG_FILE"
  36.     exec 1> >(tee -a "$LOG_FILE")
  37.     exec 2> >(tee -a "$LOG_FILE" >&2)
  38.     echo "$(date): Installation started" > "$LOG_FILE"
  39. }
  40.  
  41. handle_error() {
  42.     local error_code=$1
  43.     local error_msg=$2
  44.     local error_log="/var/log/openvpn_lb_installer_error.log"  # Separate error log file
  45.     echo "$(date): ERROR ($error_code) - $error_msg" | tee -a "$LOG_FILE" "$error_log"
  46.     case $error_code in
  47.         1) echo "Fatal: System requirements not met" ;;
  48.         2) echo "Fatal: Network configuration failed" ;;
  49.         3) echo "Fatal: Container creation failed" ;;
  50.         4) echo "Fatal: OpenVPN configuration failed" ;;
  51.         5) echo "Fatal: Load balancer configuration failed" ;;
  52.         *) echo "Unknown error occurred" ;;
  53.     esac
  54.    
  55.     echo "Installation failed. Starting cleanup..."
  56.     cleanup_installation
  57.    
  58.     exit "$error_code"
  59. }
  60.  
  61. cleanup_installation() {
  62.     echo "Cleaning up failed installation..."
  63.    
  64.     # Stop services
  65.     systemctl stop keepalived 2>/dev/null
  66.     systemctl disable keepalived 2>/dev/null
  67.    
  68.     # Remove containers
  69.     for i in $(seq 1 "$NUM_CONTAINERS"); do
  70.         echo "Removing container ovpn${i}..."
  71.         lxc-stop -n "ovpn${i}" 2>/dev/null
  72.         lxc-destroy -n "ovpn${i}" -f 2>/dev/null
  73.     done
  74.    
  75.     # Remove network configuration
  76.     echo "Removing network configuration..."
  77.     ip link set lxcbr1 down 2>/dev/null
  78.     ip link delete lxcbr1 2>/dev/null
  79.    
  80.     # Clean up iptables rules
  81.     echo "Cleaning up firewall rules..."
  82.     iptables -t nat -F
  83.     iptables -F FORWARD
  84.    
  85.     # Remove configuration files
  86.     echo "Removing configuration files..."
  87.     rm -f /etc/keepalived/keepalived.conf
  88.     rm -rf /etc/lxc/dnsmasq.conf
  89.     rm -f /etc/network/if-up.d/iptables-rules
  90.     rm -f /usr/local/bin/setup-iptables.sh
  91.    
  92.     # Remove systemd services
  93.     echo "Removing systemd services..."
  94.     rm -f /etc/systemd/system/openvpn-iptables.service
  95.     systemctl daemon-reload
  96.    
  97.     # Optional: Remove logs
  98.     echo "Cleaning up logs..."
  99.     rm -f /var/log/openvpn-lb-installer.log
  100.     rm -f /var/log/openvpn-lb-updates.log
  101.    
  102.     echo "Cleanup complete. System restored to pre-installation state."
  103. }
  104.  
  105. check_root() {
  106.     if [ "$(id -u)" != "0" ]; then
  107.         handle_error 1 "This script must be run as root"
  108.     fi
  109. }
  110.  
  111. show_terms() {
  112.     clear
  113.     cat << "EOF"
  114. Terms and Conditions
  115.  
  116. 1. This is an open-source installer for:
  117.    - Keepalived IPVS load balancer
  118.    - LXC containers with OpenVPN
  119.    - Ubuntu 22.04 or higher required
  120.  
  121. 2. Usage Agreement:
  122.    - This software is provided "as is"
  123.    - No warranty or guarantee is provided
  124.    - For testing and educational purposes only
  125.    - Use at your own risk
  126.  
  127. 3. Components installed:
  128.    - LXC containers
  129.    - OpenVPN servers
  130.    - Keepalived with IPVS
  131.    - Required networking tools
  132.  
  133. Do you accept these terms? (yes/no):
  134. EOF
  135.     read -r accept
  136.     if [[ ! "$accept" =~ ^[yY][eE]?[sS]?$ ]]; then
  137.         echo "Terms must be accepted to continue."
  138.         exit 1
  139.     fi
  140. }
  141.  
  142. show_progress() {
  143.     local current=$1
  144.     local total=$2
  145.     local width=50
  146.     local percentage=$((current * 100 / total))
  147.     local completed=$((width * current / total))
  148.     local remaining=$((width - completed))
  149.    
  150.     printf "\rProgress: ["
  151.     printf "%${completed}s" | tr ' ' '='
  152.     printf "%${remaining}s" | tr ' ' ' '
  153.     printf "] %d%%" "$percentage"
  154. }
  155.  
  156. check_system() {
  157.     echo "Performing system checks..."
  158.    
  159.     if ! grep -q "Ubuntu" /etc/os-release; then
  160.         handle_error 1 "This installer requires Ubuntu 22.04 or higher"
  161.     fi
  162.    
  163.     mem_total=$(grep MemTotal /proc/meminfo | awk '{print $2}')
  164.     if [ "$mem_total" -lt 2097152 ]; then
  165.         handle_error 1 "Minimum 2GB RAM required"
  166.     fi
  167.    
  168.     disk_space=$(df -BG / | awk 'NR==2 {print $4}' | tr -d 'G')
  169.     if [ "$disk_space" -lt 10 ]; then
  170.         handle_error 1 "Minimum 10GB free disk space required"
  171.     fi
  172. }
  173.  
  174. check_apparmor_selinux() {
  175.     # Check if AppArmor is enabled and running
  176.     if [[ $(systemctl is-active apparmor) == "active" ]]; then
  177.         echo "AppArmor is enabled. Stopping and disabling it..."
  178.         systemctl stop apparmor
  179.         systemctl disable apparmor
  180.     fi
  181.  
  182.     # Check if SELinux is enabled
  183.     if [[ $(getenforce) != "Disabled" ]]; then
  184.         echo "SELinux is enabled. Setting it to Permissive mode..."
  185.         setenforce 0  # Set to Permissive mode
  186.     fi
  187. }
  188.  
  189. get_server_info() {
  190.     clear
  191.     echo "Server Configuration"
  192.     echo "==================="
  193.     read -p "Enter your server's public IPv4 address: " SERVER_IP
  194.     read -p "Number of OpenVPN LXC containers (2-10): " NUM_CONTAINERS
  195.    
  196.     if [[ ! "$NUM_CONTAINERS" =~ ^[2-9]$|^10$ ]]; then
  197.         handle_error 1 "Number of containers must be between 2 and 10"
  198.     fi
  199. }
  200.  
  201. show_install_menu() {
  202.     clear
  203.     cat << "EOF"
  204. Installation Options
  205. ==================
  206. 1. Express Install (Recommended)
  207.    - Default configurations
  208.    - Automatic IP assignment
  209.    - Standard security settings
  210.  
  211. 2. Custom Install
  212.    - Choose container configurations
  213.    - Custom IP ranges
  214.    - Advanced security options
  215.  
  216. 3. Expert Install
  217.    - Full manual configuration
  218.    - Custom network topology
  219.    - Advanced load balancing options
  220.  
  221. Select an option (1-3):
  222. EOF
  223.     read -r install_type
  224. }
  225.  
  226. get_certificate_info() {
  227.     clear
  228.     echo "OpenVPN Certificate Configuration"
  229.     echo "================================"
  230.     echo "Please provide the following information for your certificates."
  231.     echo "Press Enter to use the default value shown in brackets."
  232.     echo
  233.  
  234.     read -p "Country Code (2 letters) [US]: " CERT_COUNTRY
  235.     CERT_COUNTRY=${CERT_COUNTRY:-US}
  236.  
  237.     read -p "State/Province [California]: " CERT_PROVINCE
  238.     CERT_PROVINCE=${CERT_PROVINCE:-California}
  239.  
  240.     read -p "City [San Francisco]: " CERT_CITY
  241.     CERT_CITY=${CERT_CITY:-San Francisco}
  242.  
  243.     read -p "Organization [OpenVPN-LB]: " CERT_ORG
  244.     CERT_ORG=${CERT_ORG:-OpenVPN-LB}
  245.  
  246.     read -p "Email [admin@example.com]: " CERT_EMAIL
  247.     CERT_EMAIL=${CERT_EMAIL:-admin@example.com}
  248.  
  249.     # Validate inputs
  250.     if [[ ! $CERT_COUNTRY =~ ^[A-Za-z]{2}$ ]]; then
  251.         handle_error 1 "Invalid country code. Must be exactly 2 letters."
  252.     fi
  253.  
  254.     if [[ ! $CERT_EMAIL =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]]; then
  255.         handle_error 1 "Invalid email address format."
  256.     fi
  257. }
  258.  
  259. install_dependencies() {
  260.     echo "Installing required packages..."
  261.     apt-get update &>/dev/null
  262.     local packages=(lxc keepalived ipvsadm curl wget iptables)
  263.     local total=${#packages[@]}
  264.     local current=0
  265.    
  266.     for package in "${packages[@]}"; do
  267.         current=$((current + 1))
  268.         show_progress "$current" "$total"
  269.         DEBIAN_FRONTEND=noninteractive apt-get install -y "$package" &>/dev/null
  270.     done
  271.     echo
  272. }
  273.  
  274. setup_networking() {
  275.     echo "Configuring network..."
  276.     local base_port=1194
  277.     local base_ip="10.0.5"
  278.    
  279.     # Check if bridge exists and remove if necessary
  280.     if ip link show lxcbr1 >/dev/null 2>&1; then
  281.         ip link set lxcbr1 down
  282.         ip link delete lxcbr1
  283.     fi
  284.    
  285.     # Create bridge network
  286.     ip link add name lxcbr1 type bridge
  287.     ip link set lxcbr1 up
  288.     ip addr add "${base_ip}.254/24" dev lxcbr1
  289.    
  290.     # Enable IP forwarding
  291.     echo 1 > /proc/sys/net/ipv4/ip_forward
  292.    
  293.     # Setup NAT (clear existing rules first)
  294.     iptables -t nat -F
  295.     iptables -t nat -A POSTROUTING -s "${base_ip}.0/24" ! -d "${base_ip}.0/24" -j MASQUERADE
  296.     iptables -A FORWARD -i lxcbr1 -o eth0 -j ACCEPT
  297.     iptables -A FORWARD -i eth0 -o lxcbr1 -j ACCEPT
  298.  
  299.     # Wait for network to be ready
  300.     sleep 2
  301.  
  302.     # Add DNS configuration
  303.     mkdir -p /etc/lxc
  304.     cat > /etc/lxc/default.conf << EOF
  305. lxc.net.0.type = veth
  306. lxc.net.0.link = lxcbr1
  307. lxc.net.0.flags = up
  308. lxc.net.0.hwaddr = 00:16:3e:xx:xx:xx
  309. EOF
  310.  
  311.     # Ensure DNS resolving works in containers
  312.     cat > /etc/lxc/dnsmasq.conf << EOF
  313. dhcp-range=10.0.5.2,10.0.5.253
  314. dhcp-option=3,10.0.5.254
  315. dhcp-option=6,1.1.1.1,1.0.0.1
  316. EOF
  317. }
  318.  
  319. create_containers() {
  320.     local num_containers=$1
  321.     echo "Creating $num_containers OpenVPN containers..."
  322.     local total=$num_containers
  323.     local current=0
  324.  
  325.     for i in $(seq 1 "$num_containers"); do
  326.         if lxc-info -n "ovpn${i}" >/dev/null 2>&1; then
  327.             echo "Container ovpn${i} already exists. Stopping and deleting it..."
  328.             lxc-stop -n "ovpn${i}" 2>/dev/null
  329.             lxc-destroy -n "ovpn${i}" 2>/dev/null
  330.         fi
  331.     done
  332.    
  333.     for i in $(seq 1 "$num_containers"); do
  334.         current=$((current + 1))
  335.         show_progress "$current" "$total"
  336.        
  337.         # Remove existing container if any
  338.         lxc-stop -n "ovpn${i}" 2>/dev/null
  339.         lxc-destroy -n "ovpn${i}" 2>/dev/null
  340.        
  341.         # Create new container
  342.         lxc-create -n "ovpn${i}" -t download -- -d ubuntu -r jammy -a amd64 &>/dev/null
  343.        
  344.         # Configure container
  345.         configure_container "ovpn${i}" "$i"
  346.        
  347.         # Start container and wait for it to be ready
  348.         lxc-start -n "ovpn${i}"
  349.         sleep 30  # Give more time for container to initialize
  350.  
  351.     # Check container state
  352.     lxc-info -n "ovpn${i}" -s | grep -q "RUNNING" || handle_error 2 "Container ovpn${i} failed to start"
  353.  
  354.  
  355.     # Add this line here (for debugging):
  356.     lxc-attach -n "ovpn${i}" -- bash -c 'echo $RESOLV_CONF'
  357.  
  358.     # Check if resolv.conf exists
  359.     if [ ! -f "/var/lib/lxc/ovpn${i}/rootfs/etc/resolv.conf" ]; then
  360.         handle_error 2 "resolv.conf not found in container ovpn${i}"
  361.     fi
  362.        
  363.         # Set up DNS in running container
  364.         lxc-attach -n "ovpn${i}" -- bash -c '
  365.            mkdir -p /etc
  366.            touch /etc/resolv.conf
  367.            echo "nameserver 1.1.1.1" > /etc/resolv.conf
  368.            echo "nameserver 1.0.0.1" >> /etc/resolv.conf
  369.        '
  370.        
  371.         # Test network connectivity
  372.         lxc-attach -n "ovpn${i}" -- ping -c 1 8.8.8.8 || handle_error 2 "Container network setup failed"
  373.     done
  374.     echo
  375. }
  376.  
  377. configure_container() {
  378.     local container=$1
  379.     local index=$2
  380.     local base_ip="10.0.5"
  381.  
  382.     # Configure container networking
  383.     cat > "/var/lib/lxc/$container/config" << EOF
  384. lxc.net.0.type = veth
  385. lxc.net.0.link = lxcbr1
  386. lxc.net.0.flags = up
  387. lxc.net.0.ipv4.address = ${base_ip}.${index}/24
  388. lxc.net.0.ipv4.gateway = ${base_ip}.254
  389. lxc.net.0.name = eth0
  390. lxc.start.auto = 1
  391. lxc.uts.name = $container
  392.  
  393. # Common configuration
  394. lxc.include = /usr/share/lxc/config/ubuntu.common.conf
  395. lxc.arch = linux64
  396. lxc.rootfs.path = dir:/var/lib/lxc/$container/rootfs
  397.  
  398. # Make it privileged
  399. lxc.apparmor.profile = unconfined
  400. lxc.cgroup2.devices.allow = a
  401. lxc.mount.auto = proc sys cgroup
  402.  
  403. # TUN/TAP device
  404. lxc.mount.entry = /dev/net/tun /var/lib/lxc/$container/rootfs/dev/net/tun none bind,create=file
  405. EOF
  406.  
  407.     # Setup DNS in container
  408.     mkdir -p "/var/lib/lxc/$container/rootfs/etc"
  409.     cat > "/var/lib/lxc/$container/rootfs/etc/resolv.conf" << EOF
  410.     nameserver 1.1.1.1
  411.     nameserver 1.0.0.1
  412.     EOF
  413. }
  414.  
  415. setup_openvpn() {
  416.     local container=$1
  417.     local index=$2
  418.     local base_port=1194
  419.  
  420.     # Install OpenVPN and Easy-RSA
  421.     lxc-attach -n "$container" -- bash -c "apt-get update && DEBIAN_FRONTEND=noninteractive apt-get install -y openvpn easy-rsa net-tools"
  422.  
  423.  
  424.     # Create required directories
  425.     lxc-attach -n "$container" -- bash -c "mkdir -p /etc/openvpn/server"
  426.  
  427.     # Set up Easy-RSA and generate certificates
  428.     lxc-attach -n "$container" -- bash -c "
  429.         mkdir -p /etc/openvpn/easy-rsa
  430.         cp -r /usr/share/easy-rsa/* /etc/openvpn/easy-rsa/
  431.         cd /etc/openvpn/easy-rsa
  432.  
  433.         # Create vars file
  434.         cat > vars << EOF
  435. set_var EASYRSA_REQ_COUNTRY     \"${CERT_COUNTRY}\"
  436. set_var EASYRSA_REQ_PROVINCE    \"${CERT_PROVINCE}\"
  437. set_var EASYRSA_REQ_CITY        \"${CERT_CITY}\"
  438. set_var EASYRSA_REQ_ORG         \"${CERT_ORG}\"
  439. set_var EASYRSA_REQ_EMAIL       \"${CERT_EMAIL}\"
  440. set_var EASYRSA_REQ_OU          \"VPN Service\"
  441. set_var EASYRSA_REQ_CN         \"OpenVPN-Server-${index}\"
  442. set_var EASYRSA_BATCH           \"yes\"
  443. EOF
  444.  
  445.         # Initialize PKI and generate certificates
  446.         ./easyrsa init-pki
  447.         ./easyrsa --batch build-ca nopass
  448.         ./easyrsa --batch build-server-full server nopass
  449.         ./easyrsa gen-dh
  450.         openvpn --genkey secret ta.key
  451.  
  452.         # Copy files to OpenVPN directory
  453.         cp pki/ca.crt /etc/openvpn/server/
  454.         cp pki/issued/server.crt /etc/openvpn/server/
  455.         cp pki/private/server.key /etc/openvpn/server/
  456.         cp pki/dh.pem /etc/openvpn/server/
  457.         cp ta.key /etc/openvpn/server/
  458.     "
  459.    # Configure OpenVPN (Corrected part)
  460.    lxc-attach -n "$container" -- bash -c "cat > /etc/openvpn/server/server.conf << 'EOF'
  461. port $((base_port + index - 1))
  462. proto tcp
  463. dev tun
  464. topology subnet
  465. ca /etc/openvpn/server/ca.crt
  466. cert /etc/openvpn/server/server.crt
  467. key /etc/openvpn/server/server.key
  468. dh /etc/openvpn/server/dh.pem
  469. server 10.$((7 + index)).0.0 255.255.255.0
  470. push \"redirect-gateway def1 bypass-dhcp\"
  471. push \"dhcp-option DNS 1.1.1.1\"
  472. push \"dhcp-option DNS 1.0.0.1\"
  473. duplicate-cn
  474. keepalive 10 120
  475. tls-auth /etc/openvpn/server/ta.key 0
  476. cipher AES-256-GCM
  477. auth SHA256
  478. user nobody
  479. group nogroup
  480. persist-key
  481. persist-tun
  482. status openvpn-status.log
  483. verb 4
  484. log /var/log/openvpn.log
  485. EOF"
  486.  
  487.    # Set proper permissions
  488.    lxc-attach -n "$container" -- bash -c "
  489.         chmod 644 /etc/openvpn/server/ca.crt
  490.         chmod 644 /etc/openvpn/server/server.crt
  491.         chmod 600 /etc/openvpn/server/server.key
  492.         chmod 644 /etc/openvpn/server/dh.pem
  493.         chmod 600 /etc/openvpn/server/ta.key
  494.     "
  495.  
  496.    # Start OpenVPN service
  497.    lxc-attach -n "$container" -- systemctl enable openvpn-server@server
  498.    lxc-attach -n "$container" -- systemctl start openvpn-server@server
  499.  
  500.    # Wait a moment for the service to start
  501.    sleep 5
  502.  
  503.    # Verify service is running
  504.    lxc-attach -n "$container" -- systemctl status openvpn-server@server || handle_error 4 "OpenVPN service failed to start in $container"
  505. }
  506. setup_keepalived() {
  507.    echo "Configuring load balancer..."
  508.    local num_containers=$1
  509.    
  510.    cat > /etc/keepalived/keepalived.conf << EOF
  511. global_defs {
  512.    router_id LVS_MAIN
  513. }
  514.  
  515. virtual_server ${SERVER_IP} 1194 {
  516.    delay_loop 3
  517.    lb_algo rr
  518.    lb_kind NAT
  519.    protocol UDP
  520.    persistence_timeout 50
  521. EOF
  522.    
  523.    for i in $(seq 1 "$num_containers"); do
  524.        cat >> /etc/keepalived/keepalived.conf << EOF
  525.    
  526.    real_server 10.0.5.${i} $((1193 + i)) {
  527.        weight 1
  528.        UDP_CHECK {
  529.            connect_timeout 3
  530.            retry 3
  531.        }
  532.    }
  533. EOF
  534.    done
  535.    
  536.    echo "}" >> /etc/keepalived/keepalived.conf
  537. }
  538.  
  539. create_backup() {
  540.    local backup_dir="/opt/openvpn-lb/backups"
  541.    local config_dir="/etc/openvpn-lb"
  542.    local backup_file="$backup_dir/backup-$(date +%Y%m%d-%H%M%S).tar.gz"
  543.    
  544.    # Create necessary directories
  545.    mkdir -p "$backup_dir"
  546.    mkdir -p "$config_dir"
  547.    
  548.    echo "Creating backup..."
  549.    tar -czf "$backup_file" \
  550.        /etc/keepalived/keepalived.conf \
  551.        /var/lib/lxc/ovpn* \
  552.        2>/dev/null
  553.    
  554.    if [ $? -eq 0 ]; then
  555.        echo "Backup created: $backup_file"
  556.        return 0
  557.    else
  558.        handle_error 6 "Backup creation failed"
  559.        return 1
  560.    fi
  561. }
  562.  
  563. setup_auto_updates() {
  564.    cat > /usr/local/bin/openvpn-lb-update.sh << 'EOF'
  565. #!/bin/bash
  566. LOG_FILE="/var/log/openvpn-lb-updates.log"
  567. echo "Starting update at $(date)" >> "$LOG_FILE"
  568.  
  569. # Function to perform updates
  570. do_update() {
  571.    case $UPDATE_POLICY in
  572.        1) apt-get update && apt-get install -y --only-upgrade linux-firmware openssl ;;
  573.        2) apt-get update && apt-get upgrade -y ;;
  574.        3) apt-get update && apt-get upgrade -y
  575.           apt-get install -y --only-upgrade openvpn keepalived ;;
  576.        4) apt-get update && apt-get dist-upgrade -y ;;
  577.    esac
  578. }
  579.  
  580. # Perform update
  581. do_update >> "$LOG_FILE" 2>&1
  582.  
  583. # Restart services if needed
  584. if [ $? -eq 0 ]; then
  585.    systemctl restart keepalived
  586.    for i in $(seq 1 "$NUM_CONTAINERS"); do
  587.        lxc-attach -n "ovpn${i}" -- systemctl restart openvpn-server@server
  588.    done
  589. fi
  590. EOF
  591.    chmod +x /usr/local/bin/openvpn-lb-update.sh
  592.  
  593.    echo "0 3 * * * /usr/local/bin/openvpn-lb-update.sh" > /etc/cron.d/openvpn-lb-updates
  594. }
  595.  
  596. setup_performance_tuning() {
  597.    # Optimize sysctl settings
  598.    cat > /etc/sysctl.d/99-network-tuning.conf << 'EOF'
  599. # TCP settings
  600. net.ipv4.tcp_fin_timeout = 30
  601. net.ipv4.tcp_keepalive_time = 1200
  602. net.ipv4.tcp_max_syn_backlog = 4096
  603. net.ipv4.tcp_rmem = 4096 87380 16777216
  604. net.ipv4.tcp_wmem = 4096 87380 16777216
  605.  
  606. # UDP settings
  607. net.core.rmem_max = 16777216
  608. net.core.wmem_max = 16777216
  609. net.core.netdev_max_backlog = 5000
  610.  
  611. # Network interface settings
  612. net.core.somaxconn = 65535
  613. EOF
  614.    sysctl -p /etc/sysctl.d/99-network-tuning.conf
  615.  
  616.    # Optimize system limits
  617.    cat > /etc/security/limits.d/openvpn-lb.conf << 'EOF'
  618. * soft nofile 65535
  619. * hard nofile 65535
  620. * soft nproc 65535
  621. * hard nproc 65535
  622. EOF
  623. }
  624.  
  625. test_system_requirements() {
  626.    # Check if the system has at least 2 GB of RAM and 10 GB of free disk space.
  627.  
  628.    if [[ $(free -m | awk '/^Mem:/{print $2}') -lt 2048 ]]; then
  629.        return 1  # Not enough RAM
  630.    fi
  631.  
  632.    # Get disk space in GB, handling different units (G, M, K)
  633.    local disk_space=$(df -h / | awk '$NF=="/" {print $4}')
  634.    local disk_gb=$(echo "$disk_space" | sed 's/G$//;s/M$/\/1024/;s/K$/\/1024\/1024/')
  635.    disk_gb=$(echo "$disk_gb" | bc -l) # Calculate the value in GB
  636.  
  637.    if (( $(echo "$disk_gb < 10" | bc -l) )); then
  638.        return 1  # Not enough disk space
  639.    fi
  640.  
  641.    return 0  # System requirements met
  642. }
  643.  
  644. test_network_config() {
  645.    # Test bridge interface
  646.    ip link show lxcbr1 >/dev/null 2>&1 || return 1
  647.    
  648.    # Test NAT
  649.    iptables -t nat -C POSTROUTING -s 10.0.5.0/24 ! -d 10.0.5.0/24 -j MASQUERADE >/dev/null 2>&1 || return 1
  650.    
  651.    return 0
  652. }
  653.  
  654. test_container_setup() {
  655.    local containers_ok=true
  656.    
  657.    for i in $(seq 1 "$NUM_CONTAINERS"); do
  658.        lxc-info -n "ovpn${i}" -s | grep -q "RUNNING" || containers_ok=false
  659.    done
  660.    
  661.    $containers_ok
  662. }
  663.  
  664. run_tests() {
  665.    echo "Running system tests..."
  666.    local tests_passed=true
  667.  
  668.    # Test system requirements
  669.    if ! test_system_requirements; then
  670.        echo "System requirements test failed"
  671.        tests_passed=false
  672.    fi
  673.  
  674.    # Test network configuration
  675.    if ! test_network_config; then
  676.        echo "Network configuration test failed"
  677.        tests_passed=false
  678.    fi
  679.  
  680.    # Test container setup
  681.    if ! test_container_setup; then
  682.        echo "Container setup test failed"
  683.        tests_passed=false
  684.    fi
  685.  
  686.    $tests_passed
  687. }
  688.  
  689. show_status() {
  690.    clear
  691.    cat << "EOF"
  692. OpenVPN Load Balancer Status
  693. ===========================
  694. EOF
  695.    
  696.    echo "Load Balancer Status:"
  697.    systemctl status keepalived | grep Active
  698.    
  699.    echo -e "\nContainer Status:"
  700.    lxc-ls -f
  701.    
  702.    echo -e "\nConnection Statistics:"
  703.    ipvsadm -Ln --stats
  704.    
  705.    echo -e "\nLast 5 log entries:"
  706.    tail -n 5 "$LOG_FILE"
  707. }
  708.  
  709. # Main installation function
  710. install_openvpn_lb() {
  711.    clear
  712.    check_root
  713.    setup_logging
  714.    show_terms
  715.    check_apparmor_selinux
  716.    check_system
  717.    get_server_info
  718.    show_install_menu
  719.    
  720.    # Add certificate info collection here
  721.    if [ "$install_type" = "1" ]; then
  722.        echo "Using default certificate settings..."
  723.    else
  724.        get_certificate_info
  725.    fi
  726.  
  727.    # Start installation
  728.    install_dependencies
  729.    setup_networking
  730.    create_containers "$NUM_CONTAINERS"
  731.    
  732.    # Configure each container
  733.    for i in $(seq 1 "$NUM_CONTAINERS"); do
  734.        setup_openvpn "ovpn${i}" "$i"
  735.    done
  736.    
  737.    setup_keepalived "$NUM_CONTAINERS"
  738.    setup_performance_tuning
  739.    setup_auto_updates
  740.    
  741.    # Run tests
  742.    run_tests
  743.    
  744.    # Create initial backup
  745.    create_backup
  746.    
  747.    # Start services
  748.    systemctl restart keepalived
  749.    
  750.    # Final status check
  751.    show_status
  752.    
  753.    # Show completion message
  754.    clear
  755.    cat << "EOF"
  756. Installation Complete!
  757. =====================
  758. Your OpenVPN Load Balancer has been successfully installed.
  759.  
  760. Summary:
  761. - Containers created: ${NUM_CONTAINERS}
  762. - Load balancer: Active
  763. - Status: Running
  764.  
  765. Management:
  766. - Load balancer status: systemctl status keepalived
  767. - Container status: lxc-ls -f
  768. - Logs: /var/log/openvpn_lb_installer.log
  769.  
  770. Thank you for using ClaudePro LB!
  771. EOF
  772. }
  773.  
  774. # Start the installer
  775. install_openvpn_lb
Tags: OPVN
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement