Files
nexus/wiki/concepts/TCP隧道.md

113 lines
3.3 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: "TCP 隧道"
type: concept
aliases: [TCP Tunnel, TCP端口转发, TCP代理]
tags: [network, tunneling, protocol]
---
# TCP 隧道
## Definition
**TCP 隧道**是通过在两个端点之间建立虚拟连接,将本地 TCP 端口的流量透明传输到远程端点的技术。TCP 隧道是构建 VPN、反向代理和内网穿透的基础机制之一。
## How It Works
```
┌─────────────┐ ┌─────────────┐
│ 本地机器 │ │ VPS │
│ │ │ │
│ 应用 → :22 │ ──── TCP 隧道 ──── → │ :60022 ← ──│──── 外部 SSH 客户端
│ │ (frp/nc/socat) │ │
└─────────────┘ └─────────────┘
```
## TCP vs HTTP/HTTPS 隧道
| 特性 | TCP 隧道 | HTTP/HTTPS 隧道 |
|------|----------|----------------|
| **协议** | 任意 TCP | HTTP/HTTPS |
| **应用层解析** | ❌ 不解析 | ✅ 可解析 |
| **WebSocket** | ❌ 不支持 | ✅ 支持 |
| **使用场景** | SSH、数据库、任意 TCP | Web 服务 |
| **Caddy 支持** | ❌ 不支持 | ✅ 支持 |
## frp TCP 映射
### 配置示例
```ini
# frpc.ini
[ssh]
type = tcp
local_ip = 127.0.0.1
local_port = 22
remote_port = 60022
```
### 访问链路
```
外部 SSH 客户端
ssh -p 60022 user@vps-ip
VPS :60022 (frps 监听)
frp 隧道
内网机器 :22
本地 SSH 服务
```
## Common Tools for TCP Tunneling
| 工具 | 特点 | 使用场景 |
|------|------|---------|
| **frp** | 高性能、支持 Dashboard | 内网穿透 |
| **socat** | 简单单次转发 | 临时调试 |
| **netcat (nc)** | 基础端口转发 | 快速测试 |
| **ssh -L** | SSH 内置隧道 | 临时访问 |
| **stunnel** | SSL 隧道加密 | 安全转发 |
## SSH 原生隧道 (替代方案)
### 临时隧道
```bash
# 本地端口转发:访问远程内网服务
ssh -L 8080:internal:80 user@vps
# 远程端口转发:暴露本地服务到公网
ssh -R 60022:localhost:22 user@vps
```
### 持久化问题
SSH 隧道在网络中断后不会自动重连,生产环境推荐使用 frp。
## Security Considerations
### TCP 隧道注意事项
1. **不经过 HTTP 代理**TCP 流量不被 Caddy/Nginx 解析
2. **直接暴露端口**SSH 22 端口不宜直接暴露,使用非标准端口
3. **IP 白名单**:防火墙限制来源 IP
4. **公钥认证**:禁用密码登录
### 建议配置
```bash
# VPS 防火墙:只允许特定 IP
sudo ufw allow from <home_ip> to any port 60022 proto tcp
# SSH 配置:禁用密码
sudo nano /etc/ssh/sshd_config
PasswordAuthentication no
PubkeyAuthentication yes
```
## Related Concepts
- [[内网穿透]] — TCP 隧道的典型应用场景
- [[frp]] — 实现 TCP 隧道的工具
- [[反向代理]] — HTTP/HTTPS 层面的代理(与 TCP 层互补)
- [[VPS]] — TCP 隧道的公网端点
## References
- frp TCP: https://gofrp.org/docs/features/common-address-types/#tcp
- SSH Tunneling: https://www.ssh.com/academy/ssh/tunneling