Files
clash-rules/scripts/config-warpgate-alpine.sh

277 lines
9.7 KiB
Bash
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#!/bin/bash
set -euo pipefail
# ==========================================
# 0. USER INTERACTION
# ==========================================
echo "-----------------------------------------------------"
echo "🔐 USER SETUP"
echo "-----------------------------------------------------"
# В Alpine bash может не быть установлен изначально, но мы добавим его в зависимостях.
# Если скрипт запускается через sh, read -sp работает, но проверим.
echo "Enter password for new user 'supervisor':"
stty -echo
read SUPERVISOR_PASS
stty echo
echo
if [ -z "$SUPERVISOR_PASS" ]; then
echo "❌ Password cannot be empty."
exit 1
fi
# ==========================================
# 1. CONFIGURATION
# ==========================================
# Netbird
NETBIRD_SETUP_KEY="7369BE4D-C485-4339-A7CA-C245FD95E857"
NETBIRD_MANAGEMENT_URL="https://webway.shamanlanding.org:443"
# Mihomo Version (Alpha)
MIHOMO_URL="https://github.com/vernesong/mihomo/releases/download/Prerelease-Alpha/mihomo-linux-amd64-alpha-smart-ec7f445.gz"
# Remote Resources
REPO_BASE="https://gitea.shamanlanding.org/DaTekShaman/clash-rules/raw/branch/main"
URL_CONFIG_MIHOMO="${REPO_BASE}/config-clash/cadian/cadian.current.yaml"
URL_SCRIPT_IPTABLES="${REPO_BASE}/scripts/iptables-mihomo-setup.sh"
URL_INIT_MIHOMO="${REPO_BASE}/init-scripts/openrc/mihomo"
URL_INIT_IPTABLES="${REPO_BASE}/init-scripts/openrc/mihomo-iptables"
# Paths
BIN_DIR="/usr/local/bin"
CONF_DIR="/etc/mihomo"
LOG_DIR="/var/log/mihomo"
INIT_DIR="/etc/init.d"
# ==========================================
# 2. SYSTEM PREP & DEPENDENCIES
# ==========================================
echo ">>> [1/8] Updating system and installing dependencies..."
# Включаем community репозитории (обычно там лежит gcompat и прочее)
sed -i 's/^#//g' /etc/apk/repositories
apk update
apk add bash curl wget ca-certificates tar iptables ip6tables jq coreutils libcap bind-tools nano openrc openssh sudo shadow
# Для совместимости AdGuard VPN (если потребуется glibc)
apk add gcompat libgcc || true
echo ">>> [2/8] Configuring Sysctl (Forwarding)..."
# OpenRC читает /etc/sysctl.d/*.conf
cat <<EOF > /etc/sysctl.d/99-warpgate.conf
net.ipv4.ip_forward=1
net.ipv6.conf.all.forwarding=1
net.ipv4.conf.all.rp_filter=0
net.ipv4.conf.default.rp_filter=0
net.ipv4.conf.wt0.rp_filter=0
EOF
sysctl -p /etc/sysctl.d/99-warpgate.conf
# ==========================================
# 3. NETBIRD INSTALLATION
# ==========================================
echo ">>> [3/8] Checking Netbird..."
if ! command -v netbird &> /dev/null; then
echo "Installing Netbird..."
curl -fsSL https://pkgs.netbird.io/install.sh | sh
fi
echo ">>> Connecting Netbird..."
# Проверяем статус. Если не подключен — подключаем.
if ! netbird status | grep -q "Connected"; then
if [ -n "$NETBIRD_SETUP_KEY" ] && [ "$NETBIRD_SETUP_KEY" != "YOUR_NETBIRD_SETUP_KEY_HERE" ]; then
netbird up --management-url "$NETBIRD_MANAGEMENT_URL" https://webway.shamanlanding.org:443 --setup-key "$NETBIRD_SETUP_KEY" --disable-dns --allow-server-ssh --enable-ssh-root
else
echo "WARNING: Netbird Setup Key not set. Run manual setup later."
fi
else
echo "Netbird is already connected."
fi
# Добавляем в автозагрузку OpenRC
if [ -f /etc/init.d/netbird ]; then
rc-update add netbird default
fi
# ==========================================
# 4. ADGUARD VPN CLI
# ==========================================
echo ">>> [4/8] Checking AdGuard VPN CLI..."
if ! command -v adguardvpn-cli &> /dev/null; then
echo "Installing AdGuard VPN CLI..."
# Используем проверенный в диагностике метод
curl -fsSL https://raw.githubusercontent.com/AdguardTeam/AdGuardVPNCLI/master/scripts/release/install.sh | sh -s -- -v
fi
# Преднастройка
adguardvpn-cli config set-mode socks
adguardvpn-cli config set-socks-host 0.0.0.0
adguardvpn-cli config set-tun-routing-mode none
# ==========================================
# 5. MIHOMO INSTALLATION
# ==========================================
echo ">>> [5/8] Installing Mihomo..."
# Создаем группу, если нет
if ! grep -q "^mihomo:" /etc/group; then
addgroup -S mihomo
fi
# Создаем пользователя и добавляем в группу (-G mihomo)
if ! id "mihomo" &>/dev/null; then
adduser -S -D -H -s /sbin/nologin -G mihomo mihomo
fi
# Binary
if [ ! -f "${BIN_DIR}/mihomo" ]; then
echo "Downloading Mihomo binary..."
# Используем временное имя, чтобы не конфликтовать
wget -qO /tmp/mihomo.gz "$MIHOMO_URL"
gzip -d /tmp/mihomo.gz
mv /tmp/mihomo "${BIN_DIR}/mihomo"
chmod +x "${BIN_DIR}/mihomo"
else
echo "Mihomo binary already exists."
fi
# Capabilities (Вместо Systemd AmbientCapabilities)
# Даем права на биндинг портов <1024 и управление сетью
setcap 'cap_net_admin,cap_net_bind_service,cap_net_raw+ep' "${BIN_DIR}/mihomo"
# Directories
mkdir -p "$CONF_DIR"
chown -R mihomo:mihomo "$CONF_DIR"
mkdir -p "$LOG_DIR"
chown -R mihomo:mihomo "$LOG_DIR"
# ==========================================
# 6. CONFIGURATION & OPENRC SERVICES
# ==========================================
echo ">>> [6/8] Downloading Configs and Services..."
# 6.1 Mihomo Config
if [ ! -f "${CONF_DIR}/config.yaml" ]; then
echo "Fetching Config: $URL_CONFIG_MIHOMO"
wget -qO "${CONF_DIR}/config.yaml" "$URL_CONFIG_MIHOMO"
chown mihomo:mihomo "${CONF_DIR}/config.yaml"
else
echo "Config exists, skipping download."
fi
# 6.2 Iptables Setup Script
echo "Fetching Script: $URL_SCRIPT_IPTABLES"
wget -qO "${BIN_DIR}/iptables-mihomo-setup.sh" "$URL_SCRIPT_IPTABLES"
chmod +x "${BIN_DIR}/iptables-mihomo-setup.sh"
# 6.3 Config Validation
echo "Validating Mihomo Configuration..."
if ! "${BIN_DIR}/mihomo" -t -d "$CONF_DIR"; then
echo "❌ ERROR: Mihomo configuration test failed!"
echo "Please inspect: ${CONF_DIR}/config.yaml"
exit 1
else
echo "✅ Configuration test passed."
fi
# 6.4 Download OpenRC Services
echo "Fetching OpenRC Init Scripts..."
# Service: Mihomo
if [ ! -f "${INIT_DIR}/mihomo" ]; then
echo "Downloading Service: $URL_INIT_MIHOMO"
wget -qO "${INIT_DIR}/mihomo" "$URL_INIT_MIHOMO"
chmod +x "${INIT_DIR}/mihomo"
else
echo "Service 'mihomo' already exists."
fi
# Service: IPtables Helper
if [ ! -f "${INIT_DIR}/mihomo-iptables" ]; then
echo "Downloading Service: $URL_INIT_IPTABLES"
wget -qO "${INIT_DIR}/mihomo-iptables" "$URL_INIT_IPTABLES"
chmod +x "${INIT_DIR}/mihomo-iptables"
else
echo "Service 'mihomo-iptables' already exists."
fi
# 6.5 Enable Services (rc-update)
# Добавляем в автозагрузку (default runlevel)
echo "Enabling services..."
rc-update add mihomo-iptables default
rc-update add mihomo default
# ==========================================
# 7. USER & SSH SETUP
# ==========================================
echo ">>> [7/8] Configuring User and SSH..."
# 7.1 Create Supervisor
if ! id "supervisor" &>/dev/null; then
# Alpine: adduser создает группу с именем юзера
adduser -D -s /bin/bash supervisor
# Устанавливаем пароль
echo "supervisor:${SUPERVISOR_PASS}" | chpasswd
# Настройка sudo (группа wheel)
# Убедимся, что wheel раскомментирована в sudoers
sed -i 's/^# %wheel ALL=(ALL:ALL) ALL/%wheel ALL=(ALL:ALL) ALL/' /etc/sudoers
# Добавляем юзера в wheel
addgroup supervisor wheel
echo "✅ User 'supervisor' created and added to wheel group."
else
echo "User 'supervisor' already exists."
fi
# 7.2 Configure SSHD
# Проверяем, установлен ли sshd (openssh)
if [ ! -f /etc/ssh/sshd_config ]; then
apk add openssh
rc-update add sshd default
fi
# Разрешаем вход по паролю, запрещаем рута
sed -i 's/^#PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config
sed -i 's/^PasswordAuthentication.*/PasswordAuthentication yes/' /etc/ssh/sshd_config
sed -i 's/^#PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
sed -i 's/^PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config
# Перезапуск SSH
if rc-service sshd status | grep -q "started"; then
rc-service sshd restart
else
rc-service sshd start
fi
echo "✅ SSH configured."
# ==========================================
# 8. DNS & FINALIZATION
# ==========================================
echo ">>> [8/8] Locking DNS & Enabling Services..."
# В Alpine нет systemd-resolved. Просто пишем в resolv.conf
# Убираем immutable атрибут, если он был (на всякий случай)
chattr -i /etc/resolv.conf 2>/dev/null || true
echo "nameserver 127.0.0.1" > /etc/resolv.conf
mkdir -p /etc/udhcpc
echo 'RESOLV_CONF="no"' > /etc/udhcpc/udhcpc.conf
touch /etc/.pve-ignore.resolv.conf
# Блокируем файл от перезаписи DHCP клиентом
chattr +i /etc/resolv.conf 2>/dev/null || true
# (chattr в Alpine требует e2fsprogs-extra, если не установлен - пропустим)
# Включаем сервисы
rc-update add mihomo-iptables default
rc-update add mihomo default
echo "-----------------------------------------------------"
echo "✅ INSTALLATION COMPLETE"
echo "-----------------------------------------------------"
echo "Next Steps:"
echo "1. Login to AdGuard: 'adguardvpn-cli login'"
echo "2. Start services:"
echo " rc-service mihomo-iptables start"
echo " rc-service mihomo start"
echo "3. Check logs: 'cat /var/log/mihomo/...' or check process status"