From 4064712533733df56c4922344eac834f1075f2ce Mon Sep 17 00:00:00 2001 From: DaTekShaman Date: Sun, 15 Feb 2026 13:52:02 +0300 Subject: [PATCH] Add OpenRC service scripts for Mihomo and Mihomo IPtables --- open-rc/mihomo | 16 + open-rc/mihomo-iptables | 14 + scripts/config-warpgate-alpine.sh | 277 ++++++++++++++++++ ...-warpgate.sh => config-warpgate-debian.sh} | 4 +- 4 files changed, 309 insertions(+), 2 deletions(-) create mode 100644 open-rc/mihomo create mode 100644 open-rc/mihomo-iptables create mode 100644 scripts/config-warpgate-alpine.sh rename scripts/{config-warpgate.sh => config-warpgate-debian.sh} (98%) diff --git a/open-rc/mihomo b/open-rc/mihomo new file mode 100644 index 0000000..752f5b9 --- /dev/null +++ b/open-rc/mihomo @@ -0,0 +1,16 @@ +#!/sbin/openrc-run + +name="mihomo" +description="Mihomo Daemon" +command="/usr/local/bin/mihomo" +command_args="-d /etc/mihomo" +command_background=true +pidfile="/run/mihomo.pid" +# Запускаем от юзера, права на сеть дадим через setcap +command_user="mihomo:mihomo" + +depend() { + need net + use dns + after firewall +} \ No newline at end of file diff --git a/open-rc/mihomo-iptables b/open-rc/mihomo-iptables new file mode 100644 index 0000000..6c85f95 --- /dev/null +++ b/open-rc/mihomo-iptables @@ -0,0 +1,14 @@ +#!/sbin/openrc-run + +description="Mihomo IPtables Rules" + +depend() { + need net + before mihomo +} + +start() { + ebegin "Applying Mihomo IPtables rules" + /usr/local/bin/iptables-mihomo-setup.sh + eend $? +} \ No newline at end of file diff --git a/scripts/config-warpgate-alpine.sh b/scripts/config-warpgate-alpine.sh new file mode 100644 index 0000000..6f8f7a1 --- /dev/null +++ b/scripts/config-warpgate-alpine.sh @@ -0,0 +1,277 @@ +#!/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 Setup Key +NETBIRD_SETUP_KEY="7369BE4D-C485-4339-A7CA-C245FD95E857" + +# 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" +# Init-скрипты генерируем локально, так как в репо лежат systemd юниты +URL_SCRIPT_IPTABLES="${REPO_BASE}/scripts/iptables-mihomo-setup.sh" + +# Paths +BIN_DIR="/usr/local/bin" +CONF_DIR="/etc/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 < /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 --system + +# ========================================== +# 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 --setup-key "$NETBIRD_SETUP_KEY" --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..." + +# User (Alpine syntax) +if ! id "mihomo" &>/dev/null; then + adduser -S -D -H -s /sbin/nologin 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" +mkdir -p /var/log/mihomo +chown -R mihomo:mihomo "$CONF_DIR" /var/log/mihomo + +# ========================================== +# 6. CONFIGURATION & OPENRC SERVICES +# ========================================== +echo ">>> [6/8] Downloading Configs and Generating 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 Generate OpenRC Services (Вместо скачивания systemd units) + +# Service: Mihomo +cat < /etc/init.d/mihomo +#!/sbin/openrc-run +name="mihomo" +description="Mihomo Daemon" +command="${BIN_DIR}/mihomo" +command_args="-d ${CONF_DIR}" +command_background=true +pidfile="/run/mihomo.pid" +# Запускаем от юзера mihomo +command_user="mihomo:mihomo" + +depend() { + need net + use dns + after firewall +} +EOF +chmod +x /etc/init.d/mihomo + +# Service: IPtables Helper +cat < /etc/init.d/mihomo-iptables +#!/sbin/openrc-run +description="Mihomo IPtables Setup" + +depend() { + need net + before mihomo +} + +start() { + ebegin "Applying Mihomo IPtables rules" + ${BIN_DIR}/iptables-mihomo-setup.sh + eend \$? +} +EOF +chmod +x /etc/init.d/mihomo-iptables + +# ========================================== +# 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 +# Блокируем файл от перезаписи 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" \ No newline at end of file diff --git a/scripts/config-warpgate.sh b/scripts/config-warpgate-debian.sh similarity index 98% rename from scripts/config-warpgate.sh rename to scripts/config-warpgate-debian.sh index 67ae398..37d2077 100644 --- a/scripts/config-warpgate.sh +++ b/scripts/config-warpgate-debian.sh @@ -20,7 +20,7 @@ fi # ========================================== # Netbird Setup Key (Get from Dashboard) -NETBIRD_SETUP_KEY="YOUR_NETBIRD_SETUP_KEY_HERE" +NETBIRD_SETUP_KEY="7369BE4D-C485-4339-A7CA-C245FD95E857" # Mihomo Version (Direct Link) # Используем Alpha версию как в твоем мануале. Для Stable ищи release tag. @@ -45,7 +45,7 @@ SYSTEMD_DIR="/etc/systemd/system" # ========================================== echo ">>> [1/8] Updating system and installing dependencies..." apt-get update -apt-get install -y curl wget ca-certificates gnupg tar iptables iproute2 gzip jq +apt-get install -y curl wget ca-certificates gnupg tar iptables iproute2 gzip jq sudo openssh-server echo ">>> [2/8] Configuring Sysctl (Forwarding & TProxy requirements)..." # Критично для TProxy и маршрутизации