196 lines
6.8 KiB
Bash
196 lines
6.8 KiB
Bash
#!/usr/bin/env bash
|
||
# =====================================================================
|
||
# Установка и настройка L2TP/IPsec VPN-сервера на Ubuntu 24.04
|
||
# Создаёт пользователя vpn1 с паролем "dfgdfgdg34"
|
||
# Запускать от root: sudo bash setup-l2tp-vpn.sh
|
||
# =====================================================================
|
||
set -euo pipefail
|
||
|
||
# ---------- Параметры (правьте при необходимости) --------------------
|
||
VPN_USER="vpn1"
|
||
VPN_PASS='dfgdfgdg34'
|
||
VPN_PSK="ChangeMe_PSK_$(tr -dc A-Za-z0-9 </dev/urandom | head -c 12 || true)"
|
||
VPN_NET="10.10.10" # подсеть для VPN-клиентов
|
||
SERVER_LOCAL_IP="${VPN_NET}.1"
|
||
CLIENT_IP_RANGE="${VPN_NET}.10-${VPN_NET}.250"
|
||
DNS1="1.1.1.1"
|
||
DNS2="8.8.8.8"
|
||
# ---------------------------------------------------------------------
|
||
|
||
if [[ $EUID -ne 0 ]]; then
|
||
echo "Запустите скрипт от root (sudo)." >&2
|
||
exit 1
|
||
fi
|
||
|
||
# Внешний интерфейс с маршрутом по умолчанию
|
||
NET_IFACE="$(ip -4 route show default | awk '/default/ {print $5; exit}')"
|
||
if [[ -z "$NET_IFACE" ]]; then
|
||
echo "Не удалось определить внешний интерфейс." >&2
|
||
exit 1
|
||
fi
|
||
echo "[*] Внешний интерфейс: $NET_IFACE"
|
||
|
||
# ---------- Установка пакетов ----------------------------------------
|
||
export DEBIAN_FRONTEND=noninteractive
|
||
|
||
# Чтобы iptables-persistent не задавал вопросов при установке
|
||
echo "iptables-persistent iptables-persistent/autosave_v4 boolean true" | debconf-set-selections
|
||
echo "iptables-persistent iptables-persistent/autosave_v6 boolean true" | debconf-set-selections
|
||
|
||
apt-get update
|
||
apt-get install -y \
|
||
strongswan strongswan-pki libcharon-extauth-plugins libcharon-extra-plugins \
|
||
xl2tpd ppp \
|
||
iptables iptables-persistent \
|
||
curl
|
||
|
||
# ---------- /etc/ipsec.conf ------------------------------------------
|
||
cat > /etc/ipsec.conf <<EOF
|
||
config setup
|
||
charondebug="ike 1, knl 1, cfg 0"
|
||
uniqueids=no
|
||
|
||
conn L2TP-PSK
|
||
authby=secret
|
||
pfs=no
|
||
auto=add
|
||
keyingtries=3
|
||
rekey=no
|
||
ikelifetime=8h
|
||
keylife=1h
|
||
type=transport
|
||
left=%any
|
||
leftprotoport=17/1701
|
||
right=%any
|
||
rightprotoport=17/%any
|
||
ike=aes256-sha256-modp2048,aes256-sha1-modp1024,aes128-sha1-modp1024,3des-sha1-modp1024!
|
||
esp=aes256-sha256,aes256-sha1,aes128-sha1,3des-sha1!
|
||
dpddelay=10
|
||
dpdtimeout=20
|
||
dpdaction=clear
|
||
EOF
|
||
|
||
# ---------- /etc/ipsec.secrets ---------------------------------------
|
||
cat > /etc/ipsec.secrets <<EOF
|
||
%any %any : PSK "$VPN_PSK"
|
||
EOF
|
||
chmod 600 /etc/ipsec.secrets
|
||
|
||
# ---------- /etc/xl2tpd/xl2tpd.conf ----------------------------------
|
||
cat > /etc/xl2tpd/xl2tpd.conf <<EOF
|
||
[global]
|
||
ipsec saref = yes
|
||
port = 1701
|
||
|
||
[lns default]
|
||
ip range = $CLIENT_IP_RANGE
|
||
local ip = $SERVER_LOCAL_IP
|
||
require chap = yes
|
||
refuse pap = yes
|
||
require authentication = yes
|
||
name = L2TPVPN
|
||
ppp debug = no
|
||
pppoptfile = /etc/ppp/options.xl2tpd
|
||
length bit = yes
|
||
EOF
|
||
|
||
# ---------- /etc/ppp/options.xl2tpd ----------------------------------
|
||
cat > /etc/ppp/options.xl2tpd <<EOF
|
||
require-mschap-v2
|
||
ms-dns $DNS1
|
||
ms-dns $DNS2
|
||
asyncmap 0
|
||
auth
|
||
crtscts
|
||
lock
|
||
hide-password
|
||
modem
|
||
name l2tpd
|
||
proxyarp
|
||
lcp-echo-interval 30
|
||
lcp-echo-failure 4
|
||
mtu 1410
|
||
mru 1410
|
||
nodefaultroute
|
||
EOF
|
||
|
||
# ---------- Пользователь VPN -----------------------------------------
|
||
# Удаляем прошлую запись с тем же логином (если запускали повторно) и добавляем заново
|
||
touch /etc/ppp/chap-secrets
|
||
sed -i "/^\"\?${VPN_USER}\"\?[[:space:]]\+l2tpd[[:space:]]/d" /etc/ppp/chap-secrets
|
||
cat >> /etc/ppp/chap-secrets <<EOF
|
||
# client server secret IP addresses
|
||
"$VPN_USER" l2tpd "$VPN_PASS" *
|
||
EOF
|
||
chmod 600 /etc/ppp/chap-secrets
|
||
|
||
# ---------- sysctl: форвардинг и т.д. --------------------------------
|
||
cat > /etc/sysctl.d/60-l2tp-vpn.conf <<EOF
|
||
net.ipv4.ip_forward = 1
|
||
net.ipv4.conf.all.accept_redirects = 0
|
||
net.ipv4.conf.all.send_redirects = 0
|
||
net.ipv4.conf.default.rp_filter = 0
|
||
net.ipv4.conf.default.accept_source_route = 0
|
||
net.ipv4.conf.all.rp_filter = 0
|
||
net.ipv4.icmp_ignore_bogus_error_responses = 1
|
||
EOF
|
||
sysctl --system >/dev/null
|
||
|
||
# ---------- iptables / NAT -------------------------------------------
|
||
# Чистим прошлые правила скрипта (идемпотентность)
|
||
iptables -t nat -C POSTROUTING -s "${VPN_NET}.0/24" -o "$NET_IFACE" -j MASQUERADE 2>/dev/null \
|
||
&& iptables -t nat -D POSTROUTING -s "${VPN_NET}.0/24" -o "$NET_IFACE" -j MASQUERADE
|
||
|
||
iptables -t nat -A POSTROUTING -s "${VPN_NET}.0/24" -o "$NET_IFACE" -j MASQUERADE
|
||
iptables -A INPUT -p udp --dport 500 -j ACCEPT
|
||
iptables -A INPUT -p udp --dport 4500 -j ACCEPT
|
||
iptables -A INPUT -p udp --dport 1701 -j ACCEPT
|
||
iptables -A INPUT -p esp -j ACCEPT
|
||
iptables -A FORWARD -s "${VPN_NET}.0/24" -j ACCEPT
|
||
iptables -A FORWARD -d "${VPN_NET}.0/24" -j ACCEPT
|
||
# Чиним MSS, чтобы не было проблем с большими пакетами
|
||
iptables -t mangle -A FORWARD -p tcp --tcp-flags SYN,RST SYN -s "${VPN_NET}.0/24" \
|
||
-j TCPMSS --clamp-mss-to-pmtu
|
||
|
||
# Сохраняем правила между перезагрузками
|
||
netfilter-persistent save
|
||
|
||
# ---------- Фикс xl2tpd на Ubuntu 24.04 ------------------------------
|
||
# В пакете unit объявлен Type=forking с ожиданием PID-файла, но xl2tpd
|
||
# 1.3.18 его не пишет — systemd убивает процесс по таймауту.
|
||
# Переводим в Type=simple и запускаем xl2tpd в форграунде (-D).
|
||
mkdir -p /etc/systemd/system/xl2tpd.service.d
|
||
cat > /etc/systemd/system/xl2tpd.service.d/override.conf <<EOF
|
||
[Service]
|
||
Type=simple
|
||
PIDFile=
|
||
ExecStart=
|
||
ExecStart=/usr/sbin/xl2tpd -D -c /etc/xl2tpd/xl2tpd.conf
|
||
RuntimeDirectory=xl2tpd
|
||
RuntimeDirectoryMode=0755
|
||
EOF
|
||
systemctl daemon-reload
|
||
|
||
# ---------- Запуск служб ---------------------------------------------
|
||
# В Ubuntu 24.04 unit называется strongswan-starter
|
||
systemctl enable strongswan-starter xl2tpd
|
||
systemctl restart strongswan-starter
|
||
systemctl restart xl2tpd
|
||
|
||
# ---------- Итог -----------------------------------------------------
|
||
PUBLIC_IP="$(curl -fsS4 https://ifconfig.me 2>/dev/null || hostname -I | awk '{print $1}')"
|
||
|
||
cat <<EOF
|
||
|
||
=========================================================
|
||
L2TP/IPsec VPN-сервер настроен.
|
||
---------------------------------------------------------
|
||
Адрес сервера : $PUBLIC_IP
|
||
PSK (общий) : $VPN_PSK
|
||
Логин : $VPN_USER
|
||
Пароль : $VPN_PASS
|
||
Тип VPN : L2TP/IPsec PSK (MS-CHAPv2)
|
||
Открытые порты: UDP 500, 4500, 1701 + ESP
|
||
Подсеть VPN : ${VPN_NET}.0/24
|
||
=========================================================
|
||
EOF
|