Files
nexus/wiki/concepts/内网穿透.md
2026-04-22 19:20:32 +08:00

123 lines
3.2 KiB
Markdown
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.
---
title: "内网穿透"
type: concept
aliases: [NAT穿透, 内网访问, 穿透技术]
tags: [network, tunneling, infrastructure]
---
# 内网穿透
## Definition
**内网穿透**NAT Traversal / Reverse Proxy Tunneling是一种使位于私有网络内网中的设备能够被公网访问的技术。家用网络设备通常位于 NAT网络地址转换后面无法直接接收公网连接内网穿透通过在公网服务器建立反向隧道来解决这一问题。
## Core Principle
传统正向代理:客户端 → 公网代理服务器 → 目标服务器
内网穿透(反向隧道):公网服务器 → 反向隧道 → 内网客户端
```
Internet
│ ← 发起连接(公网)
┌───────────────┐
│ VPS (公网) │
│ frps/Caddy │
└───────┬───────┘
│ ← 反向隧道建立
┌───────────────┐
│ 内网机器 (frpc) │
│ 192.168.x.x │
└───────────────┘
```
## Common Tools
| 工具 | 协议 | 特点 | 适用场景 |
|------|------|------|---------|
| **frp** | TCP/UDP/HTTP | 高性能、支持 Dashboard | 多服务穿透 |
| **ngrok** | TCP/HTTP | 简单易用、托管服务 | 临时测试 |
| **natapp** | TCP/HTTP | 国内服务 | 国内访问 |
| **花生壳** | TCP/HTTP | 老牌、商业化 | 企业用户 |
| **ZeroTier** | VPN | 虚拟局域网 | 远程办公 |
## frp 实现方案
### 架构组件
1. **frps (Server)**:部署在公网 VPS监听端口默认 7000
2. **frpc (Client)**:部署在内网机器,主动连接 frps
### 典型配置流程
1. VPS 安装 frps配置 systemd 服务
2. 内网机器安装 frpc配置连接参数
3. frpc 配置端口映射local_port → remote_port
4. Caddy/Nginx 在 VPS 做反向代理
### 映射示例
```ini
# frpc.ini
[nas]
type = tcp
local_ip = 127.0.0.1
local_port = 5000
remote_port = 15000
```
### 完整访问链路
```
用户浏览器 → https://nas.domain.com
阿里云 DNS → VPS 公网 IP
Caddy (443) → reverse_proxy 127.0.0.1:15000
frps 在 VPS :15000 监听
frp 隧道
frpc 在内网 :5000 监听
NAS Web UI
```
## Security Considerations
### 认证保护
- frps 配置 `token` 与 frpc 匹配
- Caddy 可添加 HTTP Basic Auth
- 使用非标准端口避免扫描
### 访问控制
```bash
# UFW 防火墙限制来源 IP
sudo ufw allow from <your_home_ip> to any port 60022 proto tcp
```
### SSH 安全
```bash
# 使用公钥认证,禁用密码
# 编辑 /etc/ssh/sshd_config
PasswordAuthentication no
PubkeyAuthentication yes
```
## Trade-offs
| 优势 | 劣势 |
|------|------|
| 无需公网 IP | 依赖 VPS 稳定性 |
| 支持任意 TCP/UDP 服务 | 增加延迟 |
| 可绑定独立域名 | 需要维护 frps/frpc |
| 成本低(月付几美元 VPS | 安全配置复杂 |
## Related Concepts
- [[frp]] — 实现内网穿透的工具
- [[反向代理]] — 内网穿透的上层组件
- [[TCP 隧道]] — 内网穿透的底层机制
- [[VPS]] — 内网穿透的公网中转站
- [[Let's Encrypt]] — 自动 HTTPS 证书
## References
- frp 官方文档: https://gofrp.org/docs/