- name
- 3x-ui-setup
- description
- Complete VPN server setup from scratch. Takes a fresh VPS (IP + root + password from hosting provider) through full server hardening and 3x-ui (Xray proxy panel) installation with VLESS Reality or VLESS TLS. Guides user through connecting via Hiddify client. Use when user mentions v2ray, xray, vless, 3x-ui, proxy server, vpn server, or wants to set up encrypted proxy access on a VPS. Designed for beginners — hand-holds through every step.
- allowed-tools
- Bash,Read,Write,Edit
# VPN Server Setup (3x-ui)
Complete setup: fresh VPS from provider → secured server → working VPN with Hiddify client.
## Workflow Overview
```
ЧАСТЬ 1: Настройка сервера
Fresh VPS (IP + root + password)
→ Determine execution mode (remote or local)
→ Generate SSH key / setup access
→ Connect as root
→ Update system
→ Create non-root user + sudo
→ Install SSH key
→ TEST new user login (critical!)
→ Firewall (ufw)
→ Kernel hardening
→ Time sync + packages
→ Configure local ~/.ssh/config
→ ✅ Server secured
ЧАСТЬ 2: Установка VPN (3x-ui)
→ Install 3x-ui panel
→ Enable BBR (TCP optimization)
→ Disable ICMP (stealth)
→ Reality: scanner → create inbound → get link
→ Install Hiddify client
→ Verify connection
→ Generate guide file (credentials + instructions)
→ Install fail2ban + lock SSH (after key verified)
→ ✅ VPN working
```
---
# PART 1: Server Hardening
Secure a fresh server from provider credentials to production-ready state.
## Step 0: Collect Information
First, determine **execution mode**:
**Где запущен Claude Code?**
- **На локальном компьютере** (Remote mode) -- настраиваем удалённый сервер через SSH
- **На самом сервере** (Local mode) -- настраиваем этот же сервер напрямую
### Remote Mode -- ASK the user for:
1. **Server IP** -- from provider email
2. **Root password** -- from provider email
3. **Desired username** -- for the new non-root account
4. **Server nickname** -- for SSH config (e.g., `myserver`, `vpn1`)
5. **Has domain?** -- if unsure, recommend "no" (Reality path, simpler)
6. **Domain name** (if yes to #5) -- must already point to server IP
### Local Mode -- ASK the user for:
1. **Desired username** -- for the new non-root account
2. **Server nickname** -- for future SSH access from user's computer (e.g., `myserver`, `vpn1`)
3. **Has domain?** -- if unsure, recommend "no" (Reality path, simpler)
4. **Domain name** (if yes to #3) -- must already point to server IP
In Local mode, get server IP automatically:
```bash
curl -4 -s ifconfig.me
```
If user pastes the full provider email, extract the data from it.
**Recommend Reality (no domain) for beginners.** Explain:
- Reality: works without domain, free, simpler setup, great performance
- TLS: needs domain purchase (~$10/year), more traditional, allows fallback site
## Execution Modes
All commands in this skill are written for **Remote mode** (via SSH).
For **Local mode**, adapt as follows:
| Step | Remote Mode (default) | Local Mode |
|------|----------------------|------------|
| Step 1 | Generate SSH key on LOCAL machine | **SKIP** -- user creates key on laptop later (Step 22) |
| Step 2 | `ssh root@{SERVER_IP}` | Already on server. If not root: `sudo su -` |
| Steps 3-4 | Run on server via root SSH | Run directly (already on server) |
| Step 5 | Install local public key on server | **SKIP** -- user sends .pub via SCP later (Step 22) |
| Step 6 | SSH test from LOCAL: `ssh -i ... user@IP` | Switch user: `su - {username}`, then `sudo whoami` |
| Step 7 | **SKIP** -- lockdown deferred to Step 22 | **SKIP** -- lockdown deferred to Step 22 |
| Steps 8-11 | `sudo` on server via SSH | `sudo` directly (no SSH prefix) |
| Step 12 | Write `~/.ssh/config` on LOCAL | **SKIP** -- user does this from guide file (Step 22) |
| Step 13 | Verify via `ssh {nickname}` | Run audit directly, **skip SSH lockdown checks** |
| Part 2 | `ssh {nickname} "sudo ..."` | `sudo ...` directly (no SSH prefix) |
| Step 17A | Scanner via `ssh {nickname} '...'` | Scanner runs directly (no SSH wrapper) -- see Step 17A for both commands |
| Panel access | Via SSH tunnel | Direct: `https://127.0.0.1:{panel_port}/{web_base_path}` |
| Step 22 | Generate guide + fail2ban + lock SSH | Generate guide → SCP download → SSH key setup → fail2ban + lock SSH |
**IMPORTANT:** In both modes, the end result is the same -- user has SSH key access to the server from their local computer via `ssh {nickname}`, password auth disabled, root login disabled.
## Step 1: Generate SSH Key (LOCAL)
Run on the user's LOCAL machine BEFORE connecting to the server:
```bash
ssh-keygen -t ed25519 -C "{username}@{nickname}" -f ~/.ssh/{nickname}_key -N ""
```
Save the public key content for later:
```bash
cat ~/.ssh/{nickname}_key.pub
```
## Step 2: First Connection as Root
```bash
ssh root@{SERVER_IP}
```
### Handling forced password change
Many providers force a password change on first login. Signs:
- Prompt: "You are required to change your password immediately"
- Prompt: "Current password:" followed by "New password:"
- Prompt: "WARNING: Your password has expired"
If this happens:
1. Enter the current (provider) password
2. Enter a new strong temporary password (this is temporary -- SSH keys will replace it)
3. You may be disconnected -- reconnect with the new password
**If connection drops after password change -- this is normal.** Reconnect:
```bash
ssh root@{SERVER_IP}
```
## Step 3: System Update (as root on server)
```bash
apt update && DEBIAN_FRONTEND=noninteractive NEEDRESTART_MODE=a apt upgrade -y
```
## Step 4: Create Non-Root User
```bash
useradd -m -s /bin/bash {username}
echo "{username}:{GENERATE_STRONG_PASSWORD}" | chpasswd
usermod -aG sudo {username}
```
Generate a strong random password. Tell the user to save it (needed for sudo). Then:
```bash
# Verify
groups {username}
```
## Step 5: Install SSH Key for New User
```bash
mkdir -p /home/{username}/.ssh
echo "{PUBLIC_KEY_CONTENT}" > /home/{username}/.ssh/authorized_keys
chmod 700 /home/{username}/.ssh
chmod 600 /home/{username}/.ssh/authorized_keys
chown -R {username}:{username} /home/{username}/.ssh
```
## Step 6: TEST New User Login -- CRITICAL CHECKPOINT
**DO NOT proceed without successful test!**
Open a NEW connection (keep root session alive):
```bash
ssh -i ~/.ssh/{nickname}_key {username}@{SERVER_IP}
```
Verify sudo works:
```bash
sudo whoami
# Must output: root
```
**If this fails** -- debug permissions, do NOT disable root login:
```bash
# Check on server as root:
ls -la /home/{username}/.ssh/
cat /home/{username}/.ssh/authorized_keys
# Fix ownership:
chown -R {username}:{username} /home/{username}/.ssh
```
## Step 7: Lock Down SSH — DEFERRED
**Оба режима: ПРОПУСКАЕМ.** Блокировка SSH и установка fail2ban выполняются в самом конце (Step 22), после того как SSH-ключ проверен. Это предотвращает случайную блокировку доступа во время настройки.
## Step 8: Firewall
```bash
sudo apt install -y ufw
sudo ufw default deny incoming
sudo ufw default allow outgoing
sudo ufw allow ssh
sudo ufw allow 80/tcp
sudo ufw allow 443/tcp
sudo ufw --force enable
sudo ufw status
```
## Step 9: fail2ban — DEFERRED
**Пропущен.** fail2ban устанавливается в конце настройки (Step 22) вместе с блокировкой SSH, чтобы не заблокировать пользователя во время настройки.
## Step 10: Kernel Hardening
```bash
sudo tee /etc/sysctl.d/99-security.conf << 'EOF'
net.ipv4.conf.all.rp_filter = 1
net.ipv4.conf.default.rp_filter = 1
net.ipv4.conf.all.accept_redirects = 0
net.ipv4.conf.default.accept_redirects = 0
net.ipv4.conf.all.send_redirects = 0
net.ipv4.conf.default.send_redirects = 0
net.ipv4.tcp_syncookies = 1
net.ipv4.conf.all.log_martians = 1
net.ipv4.conf.default.log_martians = 1
net.ipv4.icmp_echo_ignore_broadcasts = 1
net.ipv4.conf.all.accept_source_route = 0
net.ipv4.conf.default.accept_source_route = 0
EOF
sudo sysctl -p /etc/sysctl.d/99-security.conf
```
## Step 11: Time Sync + Base Packages
```bash
sudo apt install -y chrony curl wget unzip net-tools
sudo systemctl enable chrony
```
## Step 12: Configure Local SSH Config
On the user's LOCAL machine:
```bash
cat >> ~/.ssh/config << 'EOF'
Host {nickname}
HostName {SERVER_IP}
User {username}
IdentityFile ~/.ssh/{nickname}_key
IdentitiesOnly yes
EOF
```
Tell user: **Теперь подключайся командой `ssh {nickname}` -- без пароля и IP.**
## Step 13: Final Verification
Connect as new user and run quick audit:
```bash
ssh {nickname}
# Then on server:
sudo ufw status
sudo sysctl net.ipv4.conf.all.rp_filter
```
Expected: ufw active, rp_filter = 1.
**Note:** SSH lockdown и fail2ban проверяются в конце (Step 22) после подтверждения работы SSH-ключа.
**Часть 1 завершена. Базовая настройка сервера готова. Переходим к установке VPN.**
---
# PART 2: VPN Installation (3x-ui)
All commands from here use `ssh {nickname}` -- the shortcut configured in Part 1.
## Step 14: Install 3x-ui
3x-ui install script requires root. Run with sudo:
```bash
ssh {nickname} "curl -Ls https://raw.githubusercontent.com/mhsanaei/3x-ui/master/install.sh -o /tmp/3x-ui-install.sh && echo 'n' | sudo bash /tmp/3x-ui-install.sh"
```
The `echo 'n'` answers "no" to port customization prompt -- a random port and credentials will be generated.
**Note:** Do NOT use `sudo bash <(curl ...)` -- process substitution does not work with sudo (file descriptors are not inherited).
**IMPORTANT:** Capture the output! It contains:
- Generated **username**
- Generated **password**
- Panel **port**
- Panel **web base path**
Extract and save these values. Show them to the user:
```
Данные панели 3x-ui (СОХРАНИ!):
Username: {panel_username}
Password: {panel_password}
Port: {panel_port}
Path: {web_base_path}
URL: https://127.0.0.1:{panel_port}/{web_base_path} (через SSH-туннель)
```
Verify 3x-ui is running:
```bash
ssh {nickname} "sudo x-ui status"
```
If not running: `ssh {nickname} "sudo x-ui start"`
**Panel port is NOT opened in firewall intentionally** -- access panel only via SSH tunnel for security.
## Step 14b: Enable BBR
BBR (Bottleneck Bandwidth and RTT) dramatically improves TCP throughput, especially on lossy links -- critical for VPN performance.
```bash
ssh {nickname} 'current=$(sysctl -n net.ipv4.tcp_congestion_control); echo "Current: $current"; if [ "$current" != "bbr" ]; then echo "net.core.default_qdisc=fq" | sudo tee -a /etc/sysctl.conf && echo "net.ipv4.tcp_congestion_control=bbr" | sudo tee -a /etc/sysctl.conf && sudo sysctl -p && echo "BBR enabled"; else echo "BBR already active"; fi'
```
Verify:
```bash
ssh {nickname} "sysctl net.ipv4.tcp_congestion_control net.core.default_qdisc"
```
Expected: `net.ipv4.tcp_congestion_control = bbr`, `net.core.default_qdisc = fq`.
## Step 15: Disable ICMP (Stealth)
Makes server invisible to ping scans:
```bash
ssh {nickname} "sudo sed -i 's/-A ufw-before-input -p icmp --icmp-type echo-request -j ACCEPT/-A ufw-before-input -p icmp --icmp-type echo-request -j DROP/' /etc/ufw/before.rules && sudo sed -i 's/-A ufw-before-forward -p icmp --icmp-type echo-request -j ACCEPT/-A ufw-before-forward -p icmp --icmp-type echo-request -j DROP/' /etc/ufw/before.rules && sudo ufw reload"
```
Verify:
```bash
ping -c 2 -W 2 {SERVER_IP}
```
Expected: no response (timeout).
## Step 16: Branch -- Reality or TLS
### Path A: VLESS Reality (NO domain needed) -- RECOMMENDED
Go to Step 17A.
### Path B: VLESS TLS (domain required)
Go to `references/vless-tls.md`.
## Step 17A: Find Best SNI with Reality Scanner
Scan the server's **/24 subnet** to find real websites on neighboring IPs that support **TLS 1.3, H2 (HTTP/2), and X25519** -- the exact stack Reality needs to mimic a genuine TLS handshake. The found domain becomes the masquerade target (SNI/dest), making VPN traffic indistinguishable from regular HTTPS to a neighboring site on the same hosting.
**Why subnet scanning matters:**
- Reality reproduces a real TLS 1.3 handshake with the dest server -- the dest **must** support TLS 1.3 + H2 + X25519, or Reality won't work
- RealiTLScanner (from the XTLS project) checks exactly this -- it only outputs servers compatible with Reality
- DPI sees the SNI in TLS ClientHello and can probe the IP to verify the domain actually lives there
- Popular domains (microsoft.com, google.com) are often on CDN IPs far from the VPS -- active probing catches this
- A small unknown site on a neighboring IP (e.g., `shop.finn-auto.fi`) is ideal -- nobody filters it, and it's in the same subnet
- **Do NOT manually pick an SNI** without the scanner -- a random domain may not support TLS 1.3 or may be on a different IP range
Download and run Reality Scanner against the /24 subnet:
**Remote mode** (Claude Code on user's laptop):
```bash
在 GitHub 查看