mirror of
https://github.com/dndx/phantun.git
synced 2025-09-16 04:04:29 +08:00
Compare commits
69 Commits
Author | SHA1 | Date | |
---|---|---|---|
|
d969f0cc5d | ||
|
19c9f2d9f2 | ||
|
1252affdad | ||
|
141c3477f9 | ||
|
d8dd3e65d1 | ||
|
66de44e32f | ||
|
2a37a2fc92 | ||
|
f5aac38969 | ||
|
118f20f74f | ||
|
6a424fd43c | ||
|
869c79422f | ||
|
201da45ee8 | ||
|
333c6dd059 | ||
|
62f0278c1a | ||
|
f436325d23 | ||
|
028a32d197 | ||
|
e452e40edd | ||
|
253ce54554 | ||
|
34d2350d1c | ||
|
6955a1eb4c | ||
|
e86c5c5c50 | ||
|
60f24d2563 | ||
|
8c7f4e98b3 | ||
|
90b93370ce | ||
|
792ee46ec4 | ||
|
f5cb4b1220 | ||
|
8a0ec729e2 | ||
|
78dd7c13b1 | ||
|
b58d58956b | ||
|
310bb17516 | ||
|
632132b75a | ||
|
48a0399f59 | ||
|
590a048b5b | ||
|
3fa8f86379 | ||
|
805bf80cd8 | ||
|
aec3bcdeda | ||
|
9b1d3c0124 | ||
|
6c42f02b28 | ||
|
ee0bce0a96 | ||
|
1f11d618e0 | ||
|
d7913c1407 | ||
|
ee7ee5d5f9 | ||
|
af3a9061a1 | ||
|
7c98012a67 | ||
|
b674268863 | ||
|
b40ca10cc1 | ||
|
30f0a1118b | ||
|
fd607bc72a | ||
|
939e4aa94e | ||
|
7bcfada87b | ||
|
fe18a49d40 | ||
|
b707c5bd12 | ||
|
6af7757456 | ||
|
f374ac8081 | ||
|
50346c1ba0 | ||
|
f649c79656 | ||
|
c91bda7e6a | ||
|
00a308a005 | ||
|
9ff691d063 | ||
|
b5e79653f0 | ||
|
f496a7919b | ||
|
bf6b9bc2ff | ||
|
47b9037968 | ||
|
c2341b6662 | ||
|
a3eff42453 | ||
|
87a42a1e23 | ||
|
851750b13d | ||
|
b89b683bb2 | ||
|
838cfa6738 |
15
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
15
.github/ISSUE_TEMPLATE/bug_report.md
vendored
Normal file
@@ -0,0 +1,15 @@
|
||||
---
|
||||
name: Bug report
|
||||
about: Create a report to help us improve
|
||||
title: ''
|
||||
labels: ''
|
||||
assignees: ''
|
||||
|
||||
---
|
||||
|
||||
**Describe the bug**
|
||||
A clear and concise description of what the bug is.
|
||||
|
||||
**Operating system**
|
||||
|
||||
**`tcpdump` between the server and client on Phantun's port**
|
30
.github/workflows/docker.yml
vendored
Normal file
30
.github/workflows/docker.yml
vendored
Normal file
@@ -0,0 +1,30 @@
|
||||
name: Docker image build
|
||||
|
||||
on:
|
||||
push:
|
||||
paths-ignore:
|
||||
- '**.md'
|
||||
|
||||
jobs:
|
||||
build:
|
||||
runs-on: ubuntu-22.04
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v5
|
||||
|
||||
- name: Setup QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
with:
|
||||
platforms: linux/amd64
|
||||
|
||||
- name: Setup Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
|
||||
- name: Build Docker Image
|
||||
uses: docker/build-push-action@v6
|
||||
with:
|
||||
context: .
|
||||
file: docker/Dockerfile
|
||||
tags: phantun
|
||||
platforms: linux/amd64
|
46
.github/workflows/release.yml
vendored
46
.github/workflows/release.yml
vendored
@@ -25,13 +25,9 @@ jobs:
|
||||
- arm-unknown-linux-musleabihf
|
||||
- aarch64-unknown-linux-gnu
|
||||
- aarch64-unknown-linux-musl
|
||||
- mips-unknown-linux-gnu
|
||||
- mips-unknown-linux-musl
|
||||
- mipsel-unknown-linux-gnu
|
||||
- mipsel-unknown-linux-musl
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
@@ -50,7 +46,45 @@ jobs:
|
||||
zip phantun_${{ matrix.target }}.zip phantun_client phantun_server
|
||||
|
||||
- name: Upload Github Assets
|
||||
uses: softprops/action-gh-release@v1
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: target/${{ matrix.target }}/release/*.zip
|
||||
prerelease: ${{ contains(github.ref, '-') }}
|
||||
update_existing: true
|
||||
|
||||
build-mips-nightly:
|
||||
runs-on: ubuntu-latest
|
||||
env:
|
||||
RUST_BACKTRACE: full
|
||||
strategy:
|
||||
matrix:
|
||||
target:
|
||||
- mips-unknown-linux-musl
|
||||
- mips64-unknown-linux-muslabi64
|
||||
- mipsel-unknown-linux-musl
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: nightly
|
||||
override: true
|
||||
components: rust-src
|
||||
- uses: actions-rs/cargo@v1
|
||||
with:
|
||||
use-cross: true
|
||||
command: build
|
||||
args: --release --target ${{ matrix.target }} -Z build-std
|
||||
- name: Rename artifacts and compress
|
||||
run: |
|
||||
cd target/${{ matrix.target }}/release
|
||||
mv client phantun_client
|
||||
mv server phantun_server
|
||||
zip phantun_${{ matrix.target }}_nightly.zip phantun_client phantun_server
|
||||
|
||||
- name: Upload Github Assets
|
||||
uses: softprops/action-gh-release@v2
|
||||
with:
|
||||
files: target/${{ matrix.target }}/release/*.zip
|
||||
prerelease: ${{ contains(github.ref, '-') }}
|
||||
update_existing: true
|
||||
|
2
.github/workflows/rust.yml
vendored
2
.github/workflows/rust.yml
vendored
@@ -11,7 +11,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v5
|
||||
- uses: actions-rs/toolchain@v1
|
||||
with:
|
||||
toolchain: stable
|
||||
|
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,2 +1 @@
|
||||
/target
|
||||
Cargo.lock
|
||||
|
1301
Cargo.lock
generated
Normal file
1301
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,11 @@
|
||||
[workspace]
|
||||
resolver = "3"
|
||||
|
||||
members = [
|
||||
"fake-tcp",
|
||||
"phantun",
|
||||
]
|
||||
|
||||
[workspace.dependencies]
|
||||
tokio = { version = "1", features = ["full"] }
|
||||
log = "0"
|
||||
|
@@ -186,7 +186,7 @@ APPENDIX: How to apply the Apache License to your work.
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2021-2022 Datong Sun (dndx@idndx.com)
|
||||
Copyright 2021-2024 Datong Sun (dndx@idndx.com)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-2022 Datong Sun (dndx@idndx.com)
|
||||
Copyright (c) 2021-2024 Datong Sun (dndx@idndx.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
|
88
README.md
88
README.md
@@ -2,7 +2,7 @@
|
||||
|
||||
A lightweight and fast UDP to TCP obfuscator.
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
Table of Contents
|
||||
@@ -35,7 +35,7 @@ Table of Contents
|
||||
|
||||
# Latest release
|
||||
|
||||
[v0.3.2](https://github.com/dndx/phantun/releases/tag/v0.3.2)
|
||||
[v0.7.0](https://github.com/dndx/phantun/releases/tag/v0.7.0)
|
||||
|
||||
# Overview
|
||||
|
||||
@@ -72,30 +72,32 @@ It is also assumed that **Phantun Client** listens for incoming UDP packets at
|
||||
`127.0.0.1:1234` (the `--local` option for client) and connects to Phantun Server at `10.0.0.1:4567`
|
||||
(the `--remote` option for client).
|
||||
|
||||
Phantun creates TUN interface for both the Client and Server. For Client, Phantun assigns itself the IP address
|
||||
`192.168.200.2` by default and for Server, it assigns `192.168.201.2` by default. Therefore, your Kernel must have
|
||||
`net.ipv4.ip_forward` enabled and setup appropriate iptables rules for NAT between your physical
|
||||
NIC address and Phantun's TUN interface address.
|
||||
Phantun creates TUN interface for both the Client and Server. For **Client**, Phantun assigns itself the IP address
|
||||
`192.168.200.2` and `fcc8::2` by default.
|
||||
For **Server**, it assigns `192.168.201.2` and `fcc9::2` by default. Therefore, your Kernel must have
|
||||
IPv4/IPv6 forwarding enabled and setup appropriate iptables/nftables rules for NAT between your physical
|
||||
NIC address and Phantun's Tun interface address.
|
||||
|
||||
You may customize the name of Tun interface created by Phantun and the assigned addresses. Please
|
||||
run the executable with `-h` options to see how to change them.
|
||||
|
||||
Another way to help understand this network topology (please see the diagram above for an illustration of this topology):
|
||||
|
||||
Phantun Client is like a machine with private IP address (`192.168.200.2`) behind a router.
|
||||
Phantun Client is like a machine with private IP address (`192.168.200.2`/`fcc8::2`) behind a router.
|
||||
In order for it to reach the Internet, you will need to SNAT the private IP address before it's traffic
|
||||
leaves the NIC.
|
||||
|
||||
Phantun Server is like a server with private IP address (`192.168.201.2`) behind a router.
|
||||
Phantun Server is like a server with private IP address (`192.168.201.2`/`fcc9::2`) behind a router.
|
||||
In order to access it from the Internet, you need to `DNAT` it's listening port on the router
|
||||
and change the destination IP address to where the server is listening for incoming connections.
|
||||
|
||||
In those cases, the machine/iptables running Phantun acts as the "router" that allows Phantun
|
||||
to communicate with outside using it's private IP addresses.
|
||||
|
||||
As of Phantun v0.2.2, IPv6 support for UDP endpoints has been added, however Fake TCP IPv6 support
|
||||
has not been finished yet. To specify an IPv6 address, use the following format: `[::1]:1234` with
|
||||
the command line options.
|
||||
As of Phantun v0.4.1, IPv6 is fully supported for both TCP and UDP sides.
|
||||
To specify an IPv6 address, use the following format: `[::1]:1234` with
|
||||
the command line options. Resolving AAAA record is also supported. Please run the program
|
||||
with `-h` to see detailed options on how to control the IPv6 behavior.
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
|
||||
@@ -103,6 +105,12 @@ the command line options.
|
||||
|
||||
Edit `/etc/sysctl.conf`, add `net.ipv4.ip_forward=1` and run `sudo sysctl -p /etc/sysctl.conf`.
|
||||
|
||||
<details>
|
||||
<summary>IPv6 specific config</summary>
|
||||
|
||||
`net.ipv6.conf.all.forwarding=1` will need to be set as well.
|
||||
</details>
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
|
||||
## 2. Add required firewall rules
|
||||
@@ -128,12 +136,16 @@ table inet nat {
|
||||
}
|
||||
```
|
||||
|
||||
Note: The above rule uses `inet` as the table family type, so it is compatible with
|
||||
both IPv4 and IPv6 usage.
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
|
||||
#### Using iptables
|
||||
|
||||
```
|
||||
iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
|
||||
ip6tables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
|
||||
```
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
@@ -150,10 +162,11 @@ actual TCP port number used by Phantun server
|
||||
#### Using nftables
|
||||
|
||||
```
|
||||
table ip nat {
|
||||
table inet nat {
|
||||
chain prerouting {
|
||||
type nat hook prerouting priority dstnat; policy accept;
|
||||
iif eth0 tcp dport 4567 dnat to 192.168.201.2
|
||||
iif eth0 tcp dport 4567 dnat ip to 192.168.201.2
|
||||
iif eth0 tcp dport 4567 dnat ip6 to fcc9::2
|
||||
}
|
||||
}
|
||||
```
|
||||
@@ -164,6 +177,7 @@ table ip nat {
|
||||
|
||||
```
|
||||
iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 4567 -j DNAT --to-destination 192.168.201.2
|
||||
ip6tables -t nat -A PREROUTING -p tcp -i eth0 --dport 4567 -j DNAT --to-destination fcc9::2
|
||||
```
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
@@ -202,6 +216,10 @@ Or use host name with `--remote`:
|
||||
RUST_LOG=info /usr/local/bin/phantun_server --local 4567 --remote example.com:1234
|
||||
```
|
||||
|
||||
Note: Server by default assigns both IPv4 and IPv6 private address to the Tun interface.
|
||||
If you do not wish to use IPv6, you can simply skip creating the IPv6 DNAT rule above and
|
||||
the presence of IPv6 address on the Tun interface should have no side effect to the server.
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
|
||||
### Client
|
||||
@@ -219,12 +237,22 @@ Or use host name with `--remote`:
|
||||
RUST_LOG=info /usr/local/bin/phantun_client --local 127.0.0.1:1234 --remote example.com:4567
|
||||
```
|
||||
|
||||
<details>
|
||||
<summary>IPv6 specific config</summary>
|
||||
|
||||
```
|
||||
RUST_LOG=info /usr/local/bin/phantun_client --local 127.0.0.1:1234 --remote [fdxx::1234]:4567
|
||||
```
|
||||
|
||||
Domain name with AAAA record is also supported.
|
||||
</details>
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
|
||||
# MTU overhead
|
||||
|
||||
Phantun aims to keep tunneling overhead to the minimum. The overhead compared to a plain UDP packet
|
||||
is the following:
|
||||
is the following (using IPv4 below as an example):
|
||||
|
||||
**Standard UDP packet:** `20 byte IP header + 8 byte UDP header = 28 bytes`
|
||||
|
||||
@@ -234,7 +262,7 @@ is the following:
|
||||
Note that Phantun does not add any additional header other than IP and TCP headers in order to pass through
|
||||
stateful packet inspection!
|
||||
|
||||
Phantun's additional overhead: `12 bytes`. I other words, when using Phantun, the usable payload for
|
||||
Phantun's additional overhead: `12 bytes`. In other words, when using Phantun, the usable payload for
|
||||
UDP packet is reduced by 12 bytes. This is the minimum overhead possible when doing such kind
|
||||
of obfuscation.
|
||||
|
||||
@@ -248,18 +276,31 @@ For people who use Phantun to tunnel [WireGuard®](https://www.wireguard.com) UD
|
||||
out the correct MTU to use for your WireGuard interface.
|
||||
|
||||
```
|
||||
WireGuard MTU = Interface MTU - IP header (20 bytes) - TCP header (20 bytes) - WireGuard overhead (32 bytes)
|
||||
WireGuard MTU = Link MTU - IPv4 header (20 bytes) - TCP header (20 bytes) - WireGuard overhead (32 bytes)
|
||||
```
|
||||
|
||||
For example, for a Ethernet interface with 1500 bytes MTU, the WireGuard interface MTU should be set as:
|
||||
or
|
||||
|
||||
```
|
||||
1500 - 20 - 20 - 32 = 1428 bytes
|
||||
WireGuard MTU = Link MTU - IPv6 header (40 bytes) - TCP header (20 bytes) - WireGuard overhead (32 bytes)
|
||||
```
|
||||
|
||||
For example, for a network link with 1500 bytes MTU, the WireGuard interface MTU should be set as:
|
||||
|
||||
**IPv4:** `1500 (link MTU) - 20 - 20 - 32 = 1428 bytes`
|
||||
|
||||
**IPv6:** `1500 (link MTU) - 40 - 20 - 32 = 1408 bytes`
|
||||
|
||||
The resulted Phantun TCP data packet will be 1500 bytes which does not exceed the
|
||||
interface MTU of 1500. Please note it is strongly recommended to use the same interface
|
||||
MTU for both ends of a WireGuard tunnel, or unexected packet loss may occur and these issues are
|
||||
interface MTU of 1500.
|
||||
|
||||
Please note **Phantun can not function correctly if
|
||||
the packet size exceeds that of the link MTU**, as Phantun do not perform any IP-fragmentation
|
||||
and reassymbly. For the same reason, Phantun always sets the `DF` (Don't Fragment) bit
|
||||
in the IP header to prevent intermidiate devices performing any fragmentation on the packet.
|
||||
|
||||
It is also *strongly recommended* to use the same interface
|
||||
MTU for both ends of a WireGuard tunnel, or unexpected packet loss may occur and these issues are
|
||||
generally very hard to troubleshoot.
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
@@ -296,11 +337,12 @@ Test command: `iperf3 -c <IP> -p <PORT> -R -u -l 1400 -b 1000m -t 30 -P 5`
|
||||
| Phantun (5 streams) | 5.00 Gbits/sec | 2.38 Gbits/sec | 95% (all cores utilized) |
|
||||
| udp2raw (`cipher-mode=none` `auth-mode=none` `disable-anti-replay`) (5 streams) | 5.00 Gbits/sec | 770 Mbits/sec | 50% (2 cores at 100%) |
|
||||
|
||||
Writeup on some of the techniques used in Phantun to achieve this performance result: [Writing Highly Efficient UDP Server in Rust](https://idndx.com/writing-highly-efficient-udp-server-in-rust/).
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
|
||||
# Future plans
|
||||
|
||||
* IPv6 support for fake-tcp
|
||||
* Load balancing a single UDP stream into multiple TCP streams
|
||||
* Integration tests
|
||||
* Auto insertion/removal of required firewall rules
|
||||
@@ -328,13 +370,13 @@ Here is a quick overview of comparison between those two to help you choose:
|
||||
| Tunneling MTU overhead | 12 bytes | 44 bytes |
|
||||
| Seprate TCP connections for each UDP connection | Client/Server | Server only |
|
||||
| Anti-replay, encryption | ❌ | ✅ |
|
||||
| IPv6 | UDP only | ✅ |
|
||||
| IPv6 | ✅ | ✅ |
|
||||
|
||||
[Back to TOC](#table-of-contents)
|
||||
|
||||
# License
|
||||
|
||||
Copyright 2021-2022 Datong Sun (dndx@idndx.com)
|
||||
Copyright 2021-2025 Datong Sun (dndx@idndx.com)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
|
||||
[https://www.apache.org/licenses/LICENSE-2.0](https://www.apache.org/licenses/LICENSE-2.0)> or the MIT license
|
||||
|
5
debian/cargo-checksum.json
vendored
Normal file
5
debian/cargo-checksum.json
vendored
Normal file
@@ -0,0 +1,5 @@
|
||||
[source.crates-io]
|
||||
replace-with = "vendored-sources"
|
||||
|
||||
[source.vendored-sources]
|
||||
directory = "vendor"
|
25
debian/changelog
vendored
Normal file
25
debian/changelog
vendored
Normal file
@@ -0,0 +1,25 @@
|
||||
phantun (0.7.0) UNRELEASED; urgency=medium
|
||||
|
||||
[ Datong Sun ]
|
||||
* fix(fake-tcp): when `connect()`-ing, attempt to get ephemeral port using algorithm similar to Linux (#162)
|
||||
* chore(deps): bump dependencies to latest
|
||||
* chore(cargo): bump `fake-tcp` version to `0.6.0` and `phantun` to `0.7.0`
|
||||
|
||||
[ dependabot[bot] ]
|
||||
* chore(deps): bump docker/build-push-action from 5 to 6
|
||||
* chore(release): remove MIPS targets due to being downgraded to Tier 3 support by Rust
|
||||
* docs(readme): latest release is now `v0.7.0`
|
||||
|
||||
[ Randy Li ]
|
||||
* phantun: change default tun address to link local
|
||||
* phantun: add client and server xor support
|
||||
* rpm: add selinux and rpm spec
|
||||
* deb: add debian files
|
||||
|
||||
-- Randy Li <ayaka@soulik.info> Wed, 11 Dec 2024 15:30:45 +0000
|
||||
|
||||
phantun (0.6.1-1) UNRELEASED; urgency=medium
|
||||
|
||||
* Initial release. (Closes: #nnnn) <nnnn is the bug number of your ITP>
|
||||
|
||||
-- Randy Li <ayaka@soulik.info> Wed, 06 Nov 2024 18:58:00 +0000
|
1
debian/compat
vendored
Normal file
1
debian/compat
vendored
Normal file
@@ -0,0 +1 @@
|
||||
10
|
19
debian/control
vendored
Normal file
19
debian/control
vendored
Normal file
@@ -0,0 +1,19 @@
|
||||
Source: phantun
|
||||
Section: net
|
||||
Priority: optional
|
||||
Maintainer: Randy Li <ayaka@soulik.info>
|
||||
Build-Depends: debhelper (>= 9), cargo, rustc
|
||||
Standards-Version: 4.5.0
|
||||
Homepage: <insert homepage here>
|
||||
|
||||
Package: phantun-client
|
||||
Architecture: any
|
||||
Depends: ${shlibs:Depends}, ${misc:Depends}
|
||||
Description: Phantun client
|
||||
Phantun client binary.
|
||||
|
||||
Package: phantun-server
|
||||
Architecture: any
|
||||
Depends: ${shlibs:Depends}, ${misc:Depends}
|
||||
Description: Phantun server
|
||||
Phantun server binary.
|
24
debian/copyright
vendored
Normal file
24
debian/copyright
vendored
Normal file
@@ -0,0 +1,24 @@
|
||||
Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
|
||||
Upstream-Name: phantun
|
||||
Source: https://github.com/hizukiayaka/phantun
|
||||
|
||||
Files: *
|
||||
Copyright: 2023, Randy Li <ayaka@soulik.info>
|
||||
License: MIT
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
.
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
.
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
6
debian/phantun-client-wrapper
vendored
Normal file
6
debian/phantun-client-wrapper
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
PID_FILE=$1
|
||||
shift 1
|
||||
mkdir -p /var/run/phantun
|
||||
/usr/libexec/phantun/phantun-client "$@" &
|
||||
echo $! > /var/run/phantun/${PID_FILE}
|
2
debian/phantun-client.install
vendored
Normal file
2
debian/phantun-client.install
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
usr/libexec/phantun/phantun-client
|
||||
usr/bin/phantun-client
|
6
debian/phantun-server-wrapper
vendored
Normal file
6
debian/phantun-server-wrapper
vendored
Normal file
@@ -0,0 +1,6 @@
|
||||
#!/bin/bash
|
||||
PID_FILE=$1
|
||||
shift 1
|
||||
mkdir -p /var/run/phantun
|
||||
/usr/libexec/phantun/phantun-server "$@" &
|
||||
echo $! > /var/run/phantun/${PID_FILE}
|
2
debian/phantun-server.install
vendored
Normal file
2
debian/phantun-server.install
vendored
Normal file
@@ -0,0 +1,2 @@
|
||||
usr/libexec/phantun/phantun-server
|
||||
usr/bin/phantun-server
|
35
debian/rules
vendored
Executable file
35
debian/rules
vendored
Executable file
@@ -0,0 +1,35 @@
|
||||
#!/usr/bin/make -f
|
||||
|
||||
%:
|
||||
dh $@ --buildsystem=cargo
|
||||
|
||||
override_dh_auto_install:
|
||||
# Define DESTDIR
|
||||
DESTDIR=$(CURDIR)/debian/phantun
|
||||
|
||||
# Install client binary
|
||||
install -D -m 0755 target/release/client debian/tmp/usr/libexec/phantun/phantun-client
|
||||
|
||||
# Install server binary
|
||||
install -D -m 0755 target/release/server debian/tmp/usr/libexec/phantun/phantun-server
|
||||
|
||||
# Create wrapper scripts
|
||||
install -D -m 0755 debian/phantun-client-wrapper debian/tmp/usr/bin/phantun-client
|
||||
|
||||
install -D -m 0755 debian/phantun-server-wrapper debian/tmp/usr/bin/phantun-server
|
||||
|
||||
chmod +x debian/tmp/usr/bin/phantun-client
|
||||
chmod +x debian/tmp/usr/bin/phantun-server
|
||||
|
||||
override_dh_auto_configure:
|
||||
cp ./debian/cargo-checksum.json ./.cargo-checksum.json
|
||||
|
||||
override_dh_auto_build:
|
||||
cargo build --release
|
||||
|
||||
override_dh_install:
|
||||
dh_install
|
||||
|
||||
override_dh_auto_test:
|
||||
# Disable the auto test step
|
||||
true
|
2
docker/.dockerignore
Normal file
2
docker/.dockerignore
Normal file
@@ -0,0 +1,2 @@
|
||||
README.md
|
||||
docker-compose.yml
|
33
docker/Dockerfile
Normal file
33
docker/Dockerfile
Normal file
@@ -0,0 +1,33 @@
|
||||
#
|
||||
# Dockerfile for phantun
|
||||
#
|
||||
|
||||
#
|
||||
# Build stage
|
||||
#
|
||||
FROM rust:latest AS builder
|
||||
|
||||
COPY . /phantun
|
||||
|
||||
RUN cd phantun \
|
||||
&& cargo build --release \
|
||||
&& strip target/release/server target/release/client \
|
||||
&& install target/release/server /usr/local/bin/phantun-server \
|
||||
&& install target/release/client /usr/local/bin/phantun-client \
|
||||
&& cd - \
|
||||
&& rm -r phantun
|
||||
|
||||
#
|
||||
# Runtime stage
|
||||
#
|
||||
FROM debian:latest
|
||||
|
||||
COPY --from=builder /usr/local/bin/phantun-server /usr/local/bin/
|
||||
COPY --from=builder /usr/local/bin/phantun-client /usr/local/bin/
|
||||
COPY docker/phantun.sh /usr/local/bin/
|
||||
|
||||
ENV USE_IPTABLES_NFT_BACKEND=0
|
||||
ENV RUST_LOG=INFO
|
||||
|
||||
ENTRYPOINT ["phantun.sh"]
|
||||
CMD ["phantun-server", "--help"]
|
11
docker/README.md
Normal file
11
docker/README.md
Normal file
@@ -0,0 +1,11 @@
|
||||
# phantun (docker)
|
||||
|
||||
## Build
|
||||
|
||||
```sh
|
||||
docker build -t phantun -f docker/Dockerfile .
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
It is recommended to use docker-compose, see [docker-compose.yml](docker-compose.yml) for details.
|
26
docker/docker-compose.yml
Normal file
26
docker/docker-compose.yml
Normal file
@@ -0,0 +1,26 @@
|
||||
version: '3.9'
|
||||
|
||||
services:
|
||||
phantun-server:
|
||||
image: phantun
|
||||
container_name: phantun-server
|
||||
restart: unless-stopped
|
||||
network_mode: host
|
||||
privileged: true
|
||||
environment:
|
||||
USE_IPTABLES_NFT_BACKEND: 0
|
||||
RUST_LOG: INFO
|
||||
command: >
|
||||
phantun-server --local 1985 --remote 127.0.0.1:1984 --ipv4-only
|
||||
|
||||
phantun-client:
|
||||
image: phantun
|
||||
container_name: phantun-client
|
||||
restart: unless-stopped
|
||||
network_mode: host
|
||||
privileged: true
|
||||
environment:
|
||||
USE_IPTABLES_NFT_BACKEND: 0
|
||||
RUST_LOG: INFO
|
||||
command: >
|
||||
phantun-client --local 127.0.0.1:1984 --remote 11.22.33.44:1985 --ipv4-only
|
209
docker/phantun.sh
Executable file
209
docker/phantun.sh
Executable file
@@ -0,0 +1,209 @@
|
||||
#!/bin/sh
|
||||
|
||||
# alias settings must be global, and must be defined before the function being called with the alias
|
||||
if [ "$USE_IPTABLES_NFT_BACKEND" = 1 ]; then
|
||||
alias iptables=iptables-nft
|
||||
alias iptables-save=iptables-nft-save
|
||||
alias ip6tables=ip6tables-nft
|
||||
alias ip6tables-save=ip6tables-nft-save
|
||||
fi
|
||||
|
||||
info() {
|
||||
local green='\e[0;32m'
|
||||
local clear='\e[0m'
|
||||
local time=$(date '+%Y-%m-%d %T')
|
||||
printf "${green}[${time}] [INFO]: ${clear}%s\n" "$*"
|
||||
}
|
||||
|
||||
warn() {
|
||||
local yellow='\e[1;33m'
|
||||
local clear='\e[0m'
|
||||
local time=$(date '+%Y-%m-%d %T')
|
||||
printf "${yellow}[${time}] [WARN]: ${clear}%s\n" "$*" >&2
|
||||
}
|
||||
|
||||
error() {
|
||||
local red='\e[0;31m'
|
||||
local clear='\e[0m'
|
||||
local time=$(date '+%Y-%m-%d %T')
|
||||
printf "${red}[${time}] [ERROR]: ${clear}%s\n" "$*" >&2
|
||||
}
|
||||
|
||||
_get_default_iface() {
|
||||
ip -4 route show default | awk -F 'dev' '{print $2}' | awk '{print $1}'
|
||||
}
|
||||
|
||||
_get_default6_iface() {
|
||||
ip -6 route show default | awk -F 'dev' '{print $2}' | awk '{print $1}'
|
||||
}
|
||||
|
||||
_get_addr_by_iface() {
|
||||
ip -4 addr show dev "$1" | grep -w "inet" | awk '{print $2}' | awk -F '/' '{print $1}' | head -1
|
||||
}
|
||||
|
||||
_get_addr6_by_iface() {
|
||||
ip -6 addr show dev "$1" | grep -w "inet6" | awk '{print $2}' | awk -F '/' '{print $1}' | head -1
|
||||
}
|
||||
|
||||
_check_rule_by_comment() {
|
||||
iptables-save | grep -q "$1"
|
||||
}
|
||||
|
||||
_check_rule6_by_comment() {
|
||||
ip6tables-save | grep -q "$1"
|
||||
}
|
||||
|
||||
_is_server_mode() {
|
||||
[ "$1" = "phantun-server" ]
|
||||
}
|
||||
|
||||
_is_ipv4_only() {
|
||||
case "$@" in
|
||||
*-4*|*--ipv4-only*)
|
||||
return 0
|
||||
;;
|
||||
*\ -4*|*\ --ipv4-only*)
|
||||
return 0
|
||||
;;
|
||||
esac
|
||||
return 1
|
||||
}
|
||||
|
||||
_get_tun_from_args() {
|
||||
local tun=$(echo "$@" | awk -F '--tun' '{print $2}' | awk '{print $1}')
|
||||
echo ${tun:=tun0}
|
||||
}
|
||||
|
||||
_get_peer_from_args() {
|
||||
local peer=$(echo "$@" | awk -F '--tun-peer' '{print $2}' | awk '{print $1}')
|
||||
_is_server_mode "$1" && echo ${peer:=192.168.201.2} || echo ${peer:=192.168.200.2}
|
||||
}
|
||||
|
||||
_get_peer6_from_args() {
|
||||
local peer=$(echo "$@" | awk -F '--tun-peer6' '{print $2}' | awk '{print $1}')
|
||||
_is_server_mode "$1" && echo ${peer:=fcc9::2} || echo ${peer:=fcc8::2}
|
||||
}
|
||||
|
||||
_get_port_from_args() {
|
||||
local value=$(echo "$@" | awk -F '-l|--local' '{print $2}' | awk '{print $1}')
|
||||
_is_server_mode "$1" && echo $value || echo $value | awk -F ':' '{print $2}'
|
||||
}
|
||||
|
||||
_iptables() {
|
||||
iptables -w 10 "$@"
|
||||
}
|
||||
|
||||
_ip6tables() {
|
||||
ip6tables -w 10 "$@"
|
||||
}
|
||||
|
||||
apply_sysctl() {
|
||||
info "apply sysctl: $(sysctl -w net.ipv4.ip_forward=1)"
|
||||
! _is_ipv4_only "$@" || return
|
||||
info "apply sysctl: $(sysctl -w net.ipv6.conf.all.forwarding=1)"
|
||||
}
|
||||
|
||||
apply_iptables() {
|
||||
local interface=$(_get_default_iface)
|
||||
local address=$(_get_addr_by_iface "${interface}")
|
||||
local tun=$(_get_tun_from_args "$@")
|
||||
local peer=$(_get_peer_from_args "$@")
|
||||
local port=$(_get_port_from_args "$@")
|
||||
local comment="phantun_${tun}_${port}"
|
||||
|
||||
if _check_rule_by_comment "${comment}"; then
|
||||
warn "iptables rules already exist, maybe needs to check."
|
||||
else
|
||||
_iptables -A FORWARD -i $tun -j ACCEPT -m comment --comment "${comment}" || error "iptables filter rule add failed."
|
||||
_iptables -A FORWARD -o $tun -j ACCEPT -m comment --comment "${comment}" || error "iptables filter rule add failed."
|
||||
if _is_server_mode "$1"; then
|
||||
info "iptables DNAT rule added: [${comment}]: ${interface} -> ${tun}, ${address} -> ${peer}"
|
||||
_iptables -t nat -A PREROUTING -p tcp -i $interface --dport $port -j DNAT --to-destination $peer \
|
||||
-m comment --comment "${comment}" || error "iptables DNAT rule add failed."
|
||||
else
|
||||
info "iptables SNAT rule added: [${comment}]: ${tun} -> ${interface}, ${peer} -> ${address}"
|
||||
_iptables -t nat -A POSTROUTING -s $peer -o $interface -j SNAT --to-source $address \
|
||||
-m comment --comment "${comment}" || error "iptables SNAT rule add failed."
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
apply_ip6tables() {
|
||||
! _is_ipv4_only "$@" || return
|
||||
|
||||
local interface=$(_get_default6_iface)
|
||||
local address=$(_get_addr6_by_iface "${interface}")
|
||||
local tun=$(_get_tun_from_args "$@")
|
||||
local peer=$(_get_peer6_from_args "$@")
|
||||
local port=$(_get_port_from_args "$@")
|
||||
local comment="phantun_${tun}_${port}"
|
||||
|
||||
if _check_rule6_by_comment "${comment}"; then
|
||||
warn "ip6tables rules already exist, maybe needs to check."
|
||||
else
|
||||
_ip6tables -A FORWARD -i $tun -j ACCEPT -m comment --comment "${comment}" || error "ip6tables filter rule add failed."
|
||||
_ip6tables -A FORWARD -o $tun -j ACCEPT -m comment --comment "${comment}" || error "ip6tables filter rule add failed."
|
||||
if _is_server_mode "$1"; then
|
||||
info "ip6tables DNAT rule added: [${comment}]: ${interface} -> ${tun}, ${address} -> ${peer}"
|
||||
_ip6tables -t nat -A PREROUTING -p tcp -i $interface --dport $port -j DNAT --to-destination $peer \
|
||||
-m comment --comment "${comment}" || error "ip6tables DNAT rule add failed."
|
||||
else
|
||||
info "ip6tables SNAT rule added: [${comment}]: ${tun} -> ${interface}, ${peer} -> ${address}"
|
||||
_ip6tables -t nat -A POSTROUTING -s $peer -o $interface -j SNAT --to-source $address \
|
||||
-m comment --comment "${comment}" || error "ip6tables SNAT rule add failed."
|
||||
fi
|
||||
fi
|
||||
}
|
||||
|
||||
stop_process() {
|
||||
kill $(pidof phantun-server phantun-client)
|
||||
info "terminate phantun process."
|
||||
}
|
||||
|
||||
revoke_iptables() {
|
||||
local tun=$(_get_tun_from_args "$@")
|
||||
local port=$(_get_port_from_args "$@")
|
||||
local comment="phantun_${tun}_${port}"
|
||||
|
||||
iptables-save -t filter | grep "${comment}" | while read rule; do
|
||||
_iptables -t filter ${rule/-A/-D} || error "iptables filter rule remove failed."
|
||||
done
|
||||
iptables-save -t nat | grep "${comment}" | while read rule; do
|
||||
_iptables -t nat ${rule/-A/-D} || error "iptables nat rule remove failed."
|
||||
done
|
||||
info "iptables rule: [${comment}] removed."
|
||||
}
|
||||
|
||||
revoke_ip6tables() {
|
||||
! _is_ipv4_only "$@" || return
|
||||
|
||||
local tun=$(_get_tun_from_args "$@")
|
||||
local port=$(_get_port_from_args "$@")
|
||||
local comment="phantun_${tun}_${port}"
|
||||
|
||||
ip6tables-save -t filter | grep "${comment}" | while read rule; do
|
||||
_ip6tables -t filter ${rule/-A/-D} || error "ip6tables filter rule remove failed."
|
||||
done
|
||||
ip6tables-save -t nat | grep "${comment}" | while read rule; do
|
||||
_ip6tables -t nat ${rule/-A/-D} || error "ip6tables nat rule remove failed."
|
||||
done
|
||||
info "ip6tables rule: [${comment}] removed."
|
||||
}
|
||||
|
||||
graceful_stop() {
|
||||
warn "caught SIGTERM or SIGINT signal, graceful stopping..."
|
||||
stop_process
|
||||
revoke_iptables "$@"
|
||||
revoke_ip6tables "$@"
|
||||
}
|
||||
|
||||
start_phantun() {
|
||||
trap 'graceful_stop "$@"' SIGTERM SIGINT
|
||||
apply_sysctl "$@"
|
||||
apply_iptables "$@"
|
||||
apply_ip6tables "$@"
|
||||
"$@" &
|
||||
wait
|
||||
}
|
||||
|
||||
start_phantun "$@"
|
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "fake-tcp"
|
||||
version = "0.4.0"
|
||||
edition = "2021"
|
||||
version = "0.7.0"
|
||||
edition = "2024"
|
||||
authors = ["Datong Sun <dndx@idndx.com>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/dndx/phantun"
|
||||
@@ -16,10 +16,10 @@ benchmark = []
|
||||
|
||||
[dependencies]
|
||||
bytes = "1"
|
||||
pnet = "0.29"
|
||||
tokio = { version = "1.14", features = ["full"] }
|
||||
rand = { version = "0.8", features = ["small_rng"] }
|
||||
log = "0.4"
|
||||
internet-checksum = "0.2"
|
||||
tokio-tun = "0.5"
|
||||
flume = "0.10"
|
||||
pnet = "0"
|
||||
rand = { version = "0", features = ["small_rng"] }
|
||||
internet-checksum = "0"
|
||||
tokio-tun = "0"
|
||||
flume = "0"
|
||||
tokio = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
@@ -186,7 +186,7 @@ APPENDIX: How to apply the Apache License to your work.
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2021-2022 Datong Sun (dndx@idndx.com)
|
||||
Copyright 2021-2024 Datong Sun (dndx@idndx.com)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-2022 Datong Sun (dndx@idndx.com)
|
||||
Copyright (c) 2021-2024 Datong Sun (dndx@idndx.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
|
@@ -50,8 +50,10 @@ use rand::prelude::*;
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::fmt;
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
use std::sync::{Arc, RwLock};
|
||||
use std::sync::{
|
||||
atomic::{AtomicU32, Ordering},
|
||||
Arc, RwLock,
|
||||
};
|
||||
use tokio::sync::broadcast;
|
||||
use tokio::sync::mpsc;
|
||||
use tokio::time;
|
||||
@@ -146,7 +148,7 @@ impl Socket {
|
||||
)
|
||||
}
|
||||
|
||||
fn build_tcp_packet(&self, flags: u16, payload: Option<&[u8]>) -> Bytes {
|
||||
fn build_tcp_packet(&self, flags: u8, payload: Option<&[u8]>) -> Bytes {
|
||||
let ack = self.ack.load(Ordering::Relaxed);
|
||||
self.last_ack.store(ack, Ordering::Relaxed);
|
||||
|
||||
@@ -400,32 +402,50 @@ impl Stack {
|
||||
/// Connects to the remote end. `None` returned means
|
||||
/// the connection attempt failed.
|
||||
pub async fn connect(&mut self, addr: SocketAddr) -> Option<Socket> {
|
||||
let mut rng = SmallRng::from_entropy();
|
||||
let local_port: u16 = rng.gen_range(1024..65535);
|
||||
let local_addr = SocketAddr::new(
|
||||
if addr.is_ipv4() {
|
||||
IpAddr::V4(self.local_ip)
|
||||
} else {
|
||||
IpAddr::V6(self.local_ip6.expect("IPv6 local address undefined"))
|
||||
},
|
||||
local_port,
|
||||
);
|
||||
let tuple = AddrTuple::new(local_addr, addr);
|
||||
let (mut sock, incoming) = Socket::new(
|
||||
self.shared.clone(),
|
||||
self.shared.tun.choose(&mut rng).unwrap().clone(),
|
||||
local_addr,
|
||||
addr,
|
||||
None,
|
||||
State::Idle,
|
||||
);
|
||||
let mut rng = SmallRng::from_os_rng();
|
||||
for local_port in rng.random_range(32768..=60999)..=60999 {
|
||||
let local_addr = SocketAddr::new(
|
||||
if addr.is_ipv4() {
|
||||
IpAddr::V4(self.local_ip)
|
||||
} else {
|
||||
IpAddr::V6(self.local_ip6.expect("IPv6 local address undefined"))
|
||||
},
|
||||
local_port,
|
||||
);
|
||||
let tuple = AddrTuple::new(local_addr, addr);
|
||||
let mut sock;
|
||||
|
||||
{
|
||||
let mut tuples = self.shared.tuples.write().unwrap();
|
||||
assert!(tuples.insert(tuple, incoming.clone()).is_none());
|
||||
{
|
||||
let mut tuples = self.shared.tuples.write().unwrap();
|
||||
if tuples.contains_key(&tuple) {
|
||||
trace!(
|
||||
"Fake TCP connection to {}, local port number {} already in use, trying another one",
|
||||
addr, local_port
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
let incoming;
|
||||
(sock, incoming) = Socket::new(
|
||||
self.shared.clone(),
|
||||
self.shared.tun.choose(&mut rng).unwrap().clone(),
|
||||
local_addr,
|
||||
addr,
|
||||
None,
|
||||
State::Idle,
|
||||
);
|
||||
|
||||
assert!(tuples.insert(tuple, incoming).is_none());
|
||||
}
|
||||
|
||||
return sock.connect().await.map(|_| sock);
|
||||
}
|
||||
|
||||
sock.connect().await.map(|_| sock)
|
||||
error!(
|
||||
"Fake TCP connection to {} failed, emphemeral port number exhausted",
|
||||
addr
|
||||
);
|
||||
None
|
||||
}
|
||||
|
||||
async fn reader_task(
|
||||
@@ -436,8 +456,7 @@ impl Stack {
|
||||
let mut tuples: HashMap<AddrTuple, flume::Sender<Bytes>> = HashMap::new();
|
||||
|
||||
loop {
|
||||
let mut buf = BytesMut::with_capacity(MAX_PACKET_LEN);
|
||||
buf.resize(MAX_PACKET_LEN, 0);
|
||||
let mut buf = BytesMut::zeroed(MAX_PACKET_LEN);
|
||||
|
||||
tokio::select! {
|
||||
size = tun.recv(&mut buf) => {
|
||||
|
@@ -15,7 +15,7 @@ pub enum IPPacket<'p> {
|
||||
V6(ipv6::Ipv6Packet<'p>),
|
||||
}
|
||||
|
||||
impl<'a> IPPacket<'a> {
|
||||
impl IPPacket<'_> {
|
||||
pub fn get_source(&self) -> IpAddr {
|
||||
match self {
|
||||
IPPacket::V4(p) => IpAddr::V4(p.get_source()),
|
||||
@@ -36,7 +36,7 @@ pub fn build_tcp_packet(
|
||||
remote_addr: SocketAddr,
|
||||
seq: u32,
|
||||
ack: u32,
|
||||
flags: u16,
|
||||
flags: u8,
|
||||
payload: Option<&[u8]>,
|
||||
) -> Bytes {
|
||||
let ip_header_len = match local_addr {
|
||||
@@ -47,8 +47,7 @@ pub fn build_tcp_packet(
|
||||
let tcp_header_len = TCP_HEADER_LEN + if wscale { 4 } else { 0 }; // nop + wscale
|
||||
let tcp_total_len = tcp_header_len + payload.map_or(0, |payload| payload.len());
|
||||
let total_len = ip_header_len + tcp_total_len;
|
||||
let mut buf = BytesMut::with_capacity(total_len);
|
||||
buf.resize(total_len, 0);
|
||||
let mut buf = BytesMut::zeroed(total_len);
|
||||
|
||||
let mut ip_buf = buf.split_to(ip_header_len);
|
||||
let mut tcp_buf = buf.split_to(tcp_total_len);
|
||||
@@ -128,7 +127,7 @@ pub fn build_tcp_packet(
|
||||
ip_buf.freeze()
|
||||
}
|
||||
|
||||
pub fn parse_ip_packet(buf: &Bytes) -> Option<(IPPacket, tcp::TcpPacket)> {
|
||||
pub fn parse_ip_packet(buf: &Bytes) -> Option<(IPPacket<'_>, tcp::TcpPacket<'_>)> {
|
||||
if buf[0] >> 4 == 4 {
|
||||
let v4 = ipv4::Ipv4Packet::new(buf).unwrap();
|
||||
if v4.get_next_level_protocol() != ip::IpNextHeaderProtocols::Tcp {
|
||||
|
@@ -1,7 +1,7 @@
|
||||
[package]
|
||||
name = "phantun"
|
||||
version = "0.4.0"
|
||||
edition = "2021"
|
||||
version = "0.8.0"
|
||||
edition = "2024"
|
||||
authors = ["Datong Sun <dndx@idndx.com>"]
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/dndx/phantun"
|
||||
@@ -11,14 +11,14 @@ Transforms UDP stream into (fake) TCP streams that can go through
|
||||
Layer 3 & Layer 4 (NAPT) firewalls/NATs.
|
||||
"""
|
||||
[dependencies]
|
||||
clap = { version = "3.0", features = ["cargo"] }
|
||||
socket2 = { version = "0.4", features = ["all"] }
|
||||
fake-tcp = { path = "../fake-tcp", version = "0.4" }
|
||||
tokio = { version = "1.14", features = ["full"] }
|
||||
tokio-util = "0.7"
|
||||
log = "0.4"
|
||||
pretty_env_logger = "0.4"
|
||||
tokio-tun = "0.5"
|
||||
num_cpus = "1.13"
|
||||
neli = "0.6"
|
||||
nix = "0.23"
|
||||
clap = { version = "4", features = ["cargo"] }
|
||||
socket2 = { version = "0", features = ["all"] }
|
||||
fake-tcp = { path = "../fake-tcp", version = "0" }
|
||||
tokio-util = "0"
|
||||
pretty_env_logger = "0"
|
||||
tokio-tun = "0"
|
||||
num_cpus = "1"
|
||||
neli = "0"
|
||||
nix = { version = "0", features = ["net", "uio", "socket"] }
|
||||
tokio = { workspace = true }
|
||||
log = { workspace = true }
|
||||
|
@@ -186,7 +186,7 @@ APPENDIX: How to apply the Apache License to your work.
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2021-2022 Datong Sun (dndx@idndx.com)
|
||||
Copyright 2021-2024 Datong Sun (dndx@idndx.com)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
|
@@ -1,6 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021-2022 Datong Sun (dndx@idndx.com)
|
||||
Copyright (c) 2021-2024 Datong Sun (dndx@idndx.com)
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
|
@@ -1,11 +1,12 @@
|
||||
use clap::{crate_version, Arg, Command};
|
||||
use clap::{crate_version, Arg, ArgAction, Command};
|
||||
use fake_tcp::packet::MAX_PACKET_LEN;
|
||||
use fake_tcp::{Socket, Stack};
|
||||
use log::{debug, error, info};
|
||||
use phantun::utils::{assign_ipv6_address, new_udp_reuseport};
|
||||
use phantun::utils::{assign_ipv6_address, new_udp_reuseport, udp_recv_pktinfo};
|
||||
use std::collections::HashMap;
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::net::{Ipv4Addr, SocketAddr};
|
||||
use std::net::{IpAddr, Ipv4Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
|
||||
use std::sync::Arc;
|
||||
use tokio::sync::{Notify, RwLock};
|
||||
use tokio::time;
|
||||
@@ -28,7 +29,6 @@ async fn main() -> io::Result<()> {
|
||||
.required(true)
|
||||
.value_name("IP:PORT")
|
||||
.help("Sets the IP and port where Phantun Client listens for incoming UDP datagrams, IPv6 address need to be specified as: \"[IPv6]:PORT\"")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("remote")
|
||||
@@ -37,7 +37,6 @@ async fn main() -> io::Result<()> {
|
||||
.required(true)
|
||||
.value_name("IP or HOST NAME:PORT")
|
||||
.help("Sets the address or host name and port where Phantun Client connects to Phantun Server, IPv6 address need to be specified as: \"[IPv6]:PORT\"")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun")
|
||||
@@ -46,7 +45,6 @@ async fn main() -> io::Result<()> {
|
||||
.value_name("tunX")
|
||||
.help("Sets the Tun interface name, if absent, pick the next available name")
|
||||
.default_value("")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun_local")
|
||||
@@ -55,7 +53,6 @@ async fn main() -> io::Result<()> {
|
||||
.value_name("IP")
|
||||
.help("Sets the Tun interface IPv4 local address (O/S's end)")
|
||||
.default_value("192.168.200.1")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun_peer")
|
||||
@@ -66,16 +63,15 @@ async fn main() -> io::Result<()> {
|
||||
You will need to setup SNAT/MASQUERADE rules on your Internet facing interface \
|
||||
in order for Phantun Client to connect to Phantun Server")
|
||||
.default_value("192.168.200.2")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("ipv4_only")
|
||||
.long("ipv4-only")
|
||||
.short('4')
|
||||
.required(false)
|
||||
.help("Do not assign IPv6 addresses to Tun interface")
|
||||
.takes_value(false)
|
||||
.conflicts_with_all(&["tun_local6", "tun_peer6"]),
|
||||
.help("Only use IPv4 address when connecting to remote")
|
||||
.action(ArgAction::SetTrue)
|
||||
.conflicts_with_all(["tun_local6", "tun_peer6"]),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun_local6")
|
||||
@@ -83,8 +79,7 @@ async fn main() -> io::Result<()> {
|
||||
.required(false)
|
||||
.value_name("IP")
|
||||
.help("Sets the Tun interface IPv6 local address (O/S's end)")
|
||||
.default_value("fec8::1")
|
||||
.takes_value(true),
|
||||
.default_value("fcc8::1")
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun_peer6")
|
||||
@@ -94,20 +89,29 @@ async fn main() -> io::Result<()> {
|
||||
.help("Sets the Tun interface IPv6 destination (peer) address (Phantun Client's end). \
|
||||
You will need to setup SNAT/MASQUERADE rules on your Internet facing interface \
|
||||
in order for Phantun Client to connect to Phantun Server")
|
||||
.default_value("fec8::2")
|
||||
.takes_value(true),
|
||||
.default_value("fcc8::2")
|
||||
)
|
||||
.arg(
|
||||
Arg::new("handshake_packet")
|
||||
.long("handshake-packet")
|
||||
.required(false)
|
||||
.value_name("PATH")
|
||||
.help("Specify a file, which, after TCP handshake, its content will be sent as the \
|
||||
first data packet to the server.\n\
|
||||
Note: ensure this file's size does not exceed the MTU of the outgoing interface. \
|
||||
The content is always sent out in a single packet and will not be further segmented")
|
||||
)
|
||||
.get_matches();
|
||||
|
||||
let local_addr: SocketAddr = matches
|
||||
.value_of("local")
|
||||
.get_one::<String>("local")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("bad local address");
|
||||
|
||||
let ipv4_only = matches.is_present("ipv4_only");
|
||||
let ipv4_only = matches.get_flag("ipv4_only");
|
||||
|
||||
let remote_addr = tokio::net::lookup_host(matches.value_of("remote").unwrap())
|
||||
let remote_addr = tokio::net::lookup_host(matches.get_one::<String>("remote").unwrap())
|
||||
.await
|
||||
.expect("bad remote address or host")
|
||||
.find(|addr| !ipv4_only || addr.is_ipv4())
|
||||
@@ -115,42 +119,45 @@ async fn main() -> io::Result<()> {
|
||||
info!("Remote address is: {}", remote_addr);
|
||||
|
||||
let tun_local: Ipv4Addr = matches
|
||||
.value_of("tun_local")
|
||||
.get_one::<String>("tun_local")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("bad local address for Tun interface");
|
||||
let tun_peer: Ipv4Addr = matches
|
||||
.value_of("tun_peer")
|
||||
.get_one::<String>("tun_peer")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("bad peer address for Tun interface");
|
||||
|
||||
let (tun_local6, tun_peer6) = if ipv4_only {
|
||||
let (tun_local6, tun_peer6) = if matches.get_flag("ipv4_only") {
|
||||
(None, None)
|
||||
} else {
|
||||
(
|
||||
matches
|
||||
.value_of("tun_local6")
|
||||
.get_one::<String>("tun_local6")
|
||||
.map(|v| v.parse().expect("bad local address for Tun interface")),
|
||||
matches
|
||||
.value_of("tun_peer6")
|
||||
.get_one::<String>("tun_peer6")
|
||||
.map(|v| v.parse().expect("bad peer address for Tun interface")),
|
||||
)
|
||||
};
|
||||
|
||||
let tun_name = matches.value_of("tun").unwrap();
|
||||
let tun_name = matches.get_one::<String>("tun").unwrap();
|
||||
let handshake_packet: Option<Vec<u8>> = matches
|
||||
.get_one::<String>("handshake_packet")
|
||||
.map(fs::read)
|
||||
.transpose()?;
|
||||
|
||||
let num_cpus = num_cpus::get();
|
||||
info!("{} cores available", num_cpus);
|
||||
|
||||
let tun = TunBuilder::new()
|
||||
.name(tun_name) // if name is empty, then it is set by kernel.
|
||||
.tap(false) // false (default): TUN, true: TAP.
|
||||
.packet_info(false) // false: IFF_NO_PI, default is true.
|
||||
.up() // or set it up manually using `sudo ip link set <tun-name> up`.
|
||||
.address(tun_local)
|
||||
.destination(tun_peer)
|
||||
.try_build_mq(num_cpus)
|
||||
.queues(num_cpus)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
if remote_addr.is_ipv6() {
|
||||
@@ -168,17 +175,17 @@ async fn main() -> io::Result<()> {
|
||||
let mut buf_r = [0u8; MAX_PACKET_LEN];
|
||||
|
||||
loop {
|
||||
let (size, addr) = udp_sock.recv_from(&mut buf_r).await?;
|
||||
let (size, udp_remote_addr, udp_local_addr) = udp_recv_pktinfo(&udp_sock, &mut buf_r).await?;
|
||||
// seen UDP packet to listening socket, this means:
|
||||
// 1. It is a new UDP connection, or
|
||||
// 2. It is some extra packets not filtered by more specific
|
||||
// connected UDP socket yet
|
||||
if let Some(sock) = connections.read().await.get(&addr) {
|
||||
if let Some(sock) = connections.read().await.get(&udp_remote_addr) {
|
||||
sock.send(&buf_r[..size]).await;
|
||||
continue;
|
||||
}
|
||||
|
||||
info!("New UDP client from {}", addr);
|
||||
info!("New UDP client from {}", udp_remote_addr);
|
||||
let sock = stack.connect(remote_addr).await;
|
||||
if sock.is_none() {
|
||||
error!("Unable to connect to remote {}", remote_addr);
|
||||
@@ -186,16 +193,24 @@ async fn main() -> io::Result<()> {
|
||||
}
|
||||
|
||||
let sock = Arc::new(sock.unwrap());
|
||||
if let Some(ref p) = handshake_packet {
|
||||
if sock.send(p).await.is_none() {
|
||||
error!("Failed to send handshake packet to remote, closing connection.");
|
||||
continue;
|
||||
}
|
||||
|
||||
debug!("Sent handshake packet to: {}", sock);
|
||||
}
|
||||
|
||||
// send first packet
|
||||
let res = sock.send(&buf_r[..size]).await;
|
||||
if res.is_none() {
|
||||
if sock.send(&buf_r[..size]).await.is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
assert!(connections
|
||||
.write()
|
||||
.await
|
||||
.insert(addr, sock.clone())
|
||||
.insert(udp_remote_addr, sock.clone())
|
||||
.is_none());
|
||||
debug!("inserted fake TCP socket into connection table");
|
||||
|
||||
@@ -213,8 +228,34 @@ async fn main() -> io::Result<()> {
|
||||
tokio::spawn(async move {
|
||||
let mut buf_udp = [0u8; MAX_PACKET_LEN];
|
||||
let mut buf_tcp = [0u8; MAX_PACKET_LEN];
|
||||
let udp_sock = new_udp_reuseport(local_addr);
|
||||
udp_sock.connect(addr).await.unwrap();
|
||||
// Always reply from the same address that the peer used to communicate with
|
||||
// us. This avoids a frequent problem with IPv6 privacy extensions when we
|
||||
// erroneously bind to wrong short-lived temporary address even if the peer
|
||||
// explicitly used a persistent address to communicate to us.
|
||||
//
|
||||
// To do so, first bind to (<incoming packet dst_ip>, <local addr port>), and then
|
||||
// connect to (<incoming packet src_ip>, <incoming packet src_port>).
|
||||
let bind_addr = match (udp_remote_addr, udp_local_addr) {
|
||||
(SocketAddr::V4(_), IpAddr::V4(udp_local_ipv4)) => {
|
||||
SocketAddr::V4(SocketAddrV4::new(
|
||||
udp_local_ipv4,
|
||||
local_addr.port(),
|
||||
))
|
||||
}
|
||||
(SocketAddr::V6(udp_remote_addr), IpAddr::V6(udp_local_ipv6)) => {
|
||||
SocketAddr::V6(SocketAddrV6::new(
|
||||
udp_local_ipv6,
|
||||
local_addr.port(),
|
||||
udp_remote_addr.flowinfo(),
|
||||
udp_remote_addr.scope_id(),
|
||||
))
|
||||
}
|
||||
(_, _) => {
|
||||
panic!("unexpected family combination for udp_remote_addr={udp_remote_addr} and udp_local_addr={udp_local_addr}");
|
||||
}
|
||||
};
|
||||
let udp_sock = new_udp_reuseport(bind_addr);
|
||||
udp_sock.connect(udp_remote_addr).await.unwrap();
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
@@ -230,13 +271,12 @@ async fn main() -> io::Result<()> {
|
||||
res = sock.recv(&mut buf_tcp) => {
|
||||
match res {
|
||||
Some(size) => {
|
||||
if size > 0 {
|
||||
if let Err(e) = udp_sock.send(&buf_tcp[..size]).await {
|
||||
error!("Unable to send UDP packet to {}: {}, closing connection", e, addr);
|
||||
if size > 0
|
||||
&& let Err(e) = udp_sock.send(&buf_tcp[..size]).await {
|
||||
error!("Unable to send UDP packet to {}: {}, closing connection", e, remote_addr);
|
||||
quit.cancel();
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
None => {
|
||||
debug!("removed fake TCP socket from connections table");
|
||||
@@ -265,14 +305,14 @@ async fn main() -> io::Result<()> {
|
||||
tokio::select! {
|
||||
_ = read_timeout => {
|
||||
info!("No traffic seen in the last {:?}, closing connection", UDP_TTL);
|
||||
connections.write().await.remove(&addr);
|
||||
connections.write().await.remove(&udp_remote_addr);
|
||||
debug!("removed fake TCP socket from connections table");
|
||||
|
||||
quit.cancel();
|
||||
return;
|
||||
},
|
||||
_ = quit.cancelled() => {
|
||||
connections.write().await.remove(&addr);
|
||||
connections.write().await.remove(&udp_remote_addr);
|
||||
debug!("removed fake TCP socket from connections table");
|
||||
return;
|
||||
},
|
||||
|
@@ -1,8 +1,9 @@
|
||||
use clap::{crate_version, Arg, Command};
|
||||
use clap::{crate_version, Arg, ArgAction, Command};
|
||||
use fake_tcp::packet::MAX_PACKET_LEN;
|
||||
use fake_tcp::Stack;
|
||||
use log::{debug, error, info};
|
||||
use phantun::utils::{assign_ipv6_address, new_udp_reuseport};
|
||||
use std::fs;
|
||||
use std::io;
|
||||
use std::net::Ipv4Addr;
|
||||
use std::sync::Arc;
|
||||
@@ -28,7 +29,6 @@ async fn main() -> io::Result<()> {
|
||||
.required(true)
|
||||
.value_name("PORT")
|
||||
.help("Sets the port where Phantun Server listens for incoming Phantun Client TCP connections")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("remote")
|
||||
@@ -37,7 +37,6 @@ async fn main() -> io::Result<()> {
|
||||
.required(true)
|
||||
.value_name("IP or HOST NAME:PORT")
|
||||
.help("Sets the address or host name and port where Phantun Server forwards UDP packets to, IPv6 address need to be specified as: \"[IPv6]:PORT\"")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun")
|
||||
@@ -46,7 +45,6 @@ async fn main() -> io::Result<()> {
|
||||
.value_name("tunX")
|
||||
.help("Sets the Tun interface name, if absent, pick the next available name")
|
||||
.default_value("")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun_local")
|
||||
@@ -55,7 +53,6 @@ async fn main() -> io::Result<()> {
|
||||
.value_name("IP")
|
||||
.help("Sets the Tun interface local address (O/S's end)")
|
||||
.default_value("192.168.201.1")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun_peer")
|
||||
@@ -66,7 +63,6 @@ async fn main() -> io::Result<()> {
|
||||
You will need to setup DNAT rules to this address in order for Phantun Server \
|
||||
to accept TCP traffic from Phantun Client")
|
||||
.default_value("192.168.201.2")
|
||||
.takes_value(true),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("ipv4_only")
|
||||
@@ -74,8 +70,8 @@ async fn main() -> io::Result<()> {
|
||||
.short('4')
|
||||
.required(false)
|
||||
.help("Do not assign IPv6 addresses to Tun interface")
|
||||
.takes_value(false)
|
||||
.conflicts_with_all(&["tun_local6", "tun_peer6"]),
|
||||
.action(ArgAction::SetTrue)
|
||||
.conflicts_with_all(["tun_local6", "tun_peer6"]),
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun_local6")
|
||||
@@ -83,8 +79,7 @@ async fn main() -> io::Result<()> {
|
||||
.required(false)
|
||||
.value_name("IP")
|
||||
.help("Sets the Tun interface IPv6 local address (O/S's end)")
|
||||
.default_value("fec9::1")
|
||||
.takes_value(true),
|
||||
.default_value("fcc9::1")
|
||||
)
|
||||
.arg(
|
||||
Arg::new("tun_peer6")
|
||||
@@ -94,61 +89,74 @@ async fn main() -> io::Result<()> {
|
||||
.help("Sets the Tun interface IPv6 destination (peer) address (Phantun Client's end). \
|
||||
You will need to setup SNAT/MASQUERADE rules on your Internet facing interface \
|
||||
in order for Phantun Client to connect to Phantun Server")
|
||||
.default_value("fec9::2")
|
||||
.takes_value(true),
|
||||
.default_value("fcc9::2")
|
||||
)
|
||||
.arg(
|
||||
Arg::new("handshake_packet")
|
||||
.long("handshake-packet")
|
||||
.required(false)
|
||||
.value_name("PATH")
|
||||
.help("Specify a file, which, after TCP handshake, its content will be sent as the \
|
||||
first data packet to the client.\n\
|
||||
Note: ensure this file's size does not exceed the MTU of the outgoing interface. \
|
||||
The content is always sent out in a single packet and will not be further segmented")
|
||||
)
|
||||
.get_matches();
|
||||
|
||||
let local_port: u16 = matches
|
||||
.value_of("local")
|
||||
.get_one::<String>("local")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("bad local port");
|
||||
|
||||
let remote_addr = tokio::net::lookup_host(matches.value_of("remote").unwrap())
|
||||
let remote_addr = tokio::net::lookup_host(matches.get_one::<String>("remote").unwrap())
|
||||
.await
|
||||
.expect("bad remote address or host")
|
||||
.next()
|
||||
.expect("unable to resolve remote host name");
|
||||
|
||||
info!("Remote address is: {}", remote_addr);
|
||||
|
||||
let tun_local: Ipv4Addr = matches
|
||||
.value_of("tun_local")
|
||||
.get_one::<String>("tun_local")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("bad local address for Tun interface");
|
||||
let tun_peer: Ipv4Addr = matches
|
||||
.value_of("tun_peer")
|
||||
.get_one::<String>("tun_peer")
|
||||
.unwrap()
|
||||
.parse()
|
||||
.expect("bad peer address for Tun interface");
|
||||
|
||||
let (tun_local6, tun_peer6) = if matches.is_present("ipv4_only") {
|
||||
let (tun_local6, tun_peer6) = if matches.get_flag("ipv4_only") {
|
||||
(None, None)
|
||||
} else {
|
||||
(
|
||||
matches
|
||||
.value_of("tun_local6")
|
||||
.get_one::<String>("tun_local6")
|
||||
.map(|v| v.parse().expect("bad local address for Tun interface")),
|
||||
matches
|
||||
.value_of("tun_peer6")
|
||||
.get_one::<String>("tun_peer6")
|
||||
.map(|v| v.parse().expect("bad peer address for Tun interface")),
|
||||
)
|
||||
};
|
||||
|
||||
let tun_name = matches.value_of("tun").unwrap();
|
||||
let tun_name = matches.get_one::<String>("tun").unwrap();
|
||||
let handshake_packet: Option<Vec<u8>> = matches
|
||||
.get_one::<String>("handshake_packet")
|
||||
.map(fs::read)
|
||||
.transpose()?;
|
||||
|
||||
let num_cpus = num_cpus::get();
|
||||
info!("{} cores available", num_cpus);
|
||||
|
||||
let tun = TunBuilder::new()
|
||||
.name(tun_name) // if name is empty, then it is set by kernel.
|
||||
.tap(false) // false (default): TUN, true: TAP.
|
||||
.packet_info(false) // false: IFF_NO_PI, default is true.
|
||||
.up() // or set it up manually using `sudo ip link set <tun-name> up`.
|
||||
.address(tun_local)
|
||||
.destination(tun_peer)
|
||||
.try_build_mq(num_cpus)
|
||||
.queues(num_cpus)
|
||||
.build()
|
||||
.unwrap();
|
||||
|
||||
if let (Some(tun_local6), Some(tun_peer6)) = (tun_local6, tun_peer6) {
|
||||
@@ -169,6 +177,14 @@ async fn main() -> io::Result<()> {
|
||||
loop {
|
||||
let sock = Arc::new(stack.accept().await);
|
||||
info!("New connection: {}", sock);
|
||||
if let Some(ref p) = handshake_packet {
|
||||
if sock.send(p).await.is_none() {
|
||||
error!("Failed to send handshake packet to remote, closing connection.");
|
||||
continue;
|
||||
}
|
||||
|
||||
debug!("Sent handshake packet to: {}", sock);
|
||||
}
|
||||
|
||||
let packet_received = Arc::new(Notify::new());
|
||||
let quit = CancellationToken::new();
|
||||
@@ -203,13 +219,12 @@ async fn main() -> io::Result<()> {
|
||||
res = sock.recv(&mut buf_tcp) => {
|
||||
match res {
|
||||
Some(size) => {
|
||||
if size > 0 {
|
||||
if let Err(e) = udp_sock.send(&buf_tcp[..size]).await {
|
||||
if size > 0
|
||||
&& let Err(e) = udp_sock.send(&buf_tcp[..size]).await {
|
||||
error!("Unable to send UDP packet to {}: {}, closing connection", e, remote_addr);
|
||||
quit.cancel();
|
||||
return;
|
||||
}
|
||||
}
|
||||
},
|
||||
None => {
|
||||
quit.cancel();
|
||||
|
@@ -1,15 +1,17 @@
|
||||
use neli::{
|
||||
consts::{
|
||||
nl::{NlmF, NlmFFlags},
|
||||
rtnl::{Ifa, IfaFFlags, RtAddrFamily, Rtm},
|
||||
nl::NlmF,
|
||||
rtnl::{Ifa, IfaF, RtAddrFamily, RtScope, Rtm},
|
||||
socket::NlFamily,
|
||||
},
|
||||
nl::{NlPayload, Nlmsghdr},
|
||||
rtnl::{Ifaddrmsg, Rtattr},
|
||||
socket::NlSocketHandle,
|
||||
nl::{NlPayload, NlmsghdrBuilder},
|
||||
rtnl::{IfaddrmsgBuilder, RtattrBuilder},
|
||||
socket::synchronous::NlSocketHandle,
|
||||
types::RtBuffer,
|
||||
utils::Groups,
|
||||
};
|
||||
use std::net::{Ipv6Addr, SocketAddr};
|
||||
use nix::sys::socket::{CmsgIterator, ControlMessageOwned, SockaddrLike as _};
|
||||
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
pub fn new_udp_reuseport(local_addr: SocketAddr) -> UdpSocket {
|
||||
@@ -27,34 +29,118 @@ pub fn new_udp_reuseport(local_addr: SocketAddr) -> UdpSocket {
|
||||
// from tokio-rs/mio/blob/master/src/sys/unix/net.rs
|
||||
udp_sock.set_cloexec(true).unwrap();
|
||||
udp_sock.set_nonblocking(true).unwrap();
|
||||
|
||||
// enable IP_PKTINFO/IPV6_PKTINFO delivery so we know the destination address of incoming
|
||||
// packets
|
||||
if local_addr.is_ipv4() {
|
||||
nix::sys::socket::setsockopt(&udp_sock, nix::sys::socket::sockopt::Ipv4PacketInfo, &true)
|
||||
.unwrap();
|
||||
} else {
|
||||
nix::sys::socket::setsockopt(
|
||||
&udp_sock,
|
||||
nix::sys::socket::sockopt::Ipv6RecvPacketInfo,
|
||||
&true,
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
udp_sock.bind(&socket2::SockAddr::from(local_addr)).unwrap();
|
||||
let udp_sock: std::net::UdpSocket = udp_sock.into();
|
||||
udp_sock.try_into().unwrap()
|
||||
}
|
||||
|
||||
pub async fn udp_recv_pktinfo(
|
||||
sock: &UdpSocket,
|
||||
buf: &mut [u8],
|
||||
) -> std::io::Result<(usize, std::net::SocketAddr, std::net::IpAddr)> {
|
||||
use std::os::unix::io::AsRawFd;
|
||||
use tokio::io::Interest;
|
||||
use nix::sys::socket::cmsg_space;
|
||||
|
||||
sock.async_io(Interest::READABLE, || {
|
||||
let control_buffer_size = std::cmp::max(
|
||||
cmsg_space::<nix::libc::in_pktinfo>(),
|
||||
cmsg_space::<nix::libc::in6_pktinfo>(),
|
||||
);
|
||||
let mut control_buffer = vec![0u8; control_buffer_size];
|
||||
let iov = &mut [std::io::IoSliceMut::new(buf)];
|
||||
let res = nix::sys::socket::recvmsg::<nix::sys::socket::SockaddrStorage>(
|
||||
sock.as_raw_fd(),
|
||||
iov,
|
||||
Some(&mut control_buffer),
|
||||
nix::sys::socket::MsgFlags::empty(),
|
||||
)?;
|
||||
|
||||
let src_addr = res.address.expect("missing source address");
|
||||
let src_addr: SocketAddr = {
|
||||
if let Some(inaddr) = src_addr.as_sockaddr_in() {
|
||||
SocketAddrV4::new(inaddr.ip(), inaddr.port()).into()
|
||||
} else if let Some(in6addr) = src_addr.as_sockaddr_in6() {
|
||||
SocketAddrV6::new(
|
||||
in6addr.ip(),
|
||||
in6addr.port(),
|
||||
in6addr.flowinfo(),
|
||||
in6addr.scope_id(),
|
||||
)
|
||||
.into()
|
||||
} else {
|
||||
panic!("unexpected source address family {:#?}", src_addr.family());
|
||||
}
|
||||
};
|
||||
|
||||
let dst_addr = dst_addr_from_cmsgs(res.cmsgs()?).expect("didn't receive pktinfo");
|
||||
|
||||
Ok((res.bytes, src_addr, dst_addr))
|
||||
})
|
||||
.await
|
||||
}
|
||||
|
||||
fn dst_addr_from_cmsgs(cmsgs: CmsgIterator) -> Option<IpAddr> {
|
||||
for cmsg in cmsgs {
|
||||
if let ControlMessageOwned::Ipv4PacketInfo(pktinfo) = cmsg {
|
||||
return Some(Ipv4Addr::from(pktinfo.ipi_addr.s_addr.to_ne_bytes()).into());
|
||||
}
|
||||
if let ControlMessageOwned::Ipv6PacketInfo(pktinfo) = cmsg {
|
||||
return Some(Ipv6Addr::from(pktinfo.ipi6_addr.s6_addr).into());
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn assign_ipv6_address(device_name: &str, local: Ipv6Addr, peer: Ipv6Addr) {
|
||||
let index = nix::net::if_::if_nametoindex(device_name).unwrap();
|
||||
|
||||
let mut rtnl = NlSocketHandle::connect(NlFamily::Route, None, &[]).unwrap();
|
||||
let rtnl = NlSocketHandle::connect(NlFamily::Route, None, Groups::empty()).unwrap();
|
||||
let mut rtattrs = RtBuffer::new();
|
||||
rtattrs.push(Rtattr::new(None, Ifa::Local, &local.octets()[..]).unwrap());
|
||||
rtattrs.push(Rtattr::new(None, Ifa::Address, &peer.octets()[..]).unwrap());
|
||||
|
||||
let ifaddrmsg = Ifaddrmsg {
|
||||
ifa_family: RtAddrFamily::Inet6,
|
||||
ifa_prefixlen: 128,
|
||||
ifa_flags: IfaFFlags::empty(),
|
||||
ifa_scope: 0,
|
||||
ifa_index: index as i32,
|
||||
rtattrs,
|
||||
};
|
||||
let nl_header = Nlmsghdr::new(
|
||||
None,
|
||||
Rtm::Newaddr,
|
||||
NlmFFlags::new(&[NlmF::Request]),
|
||||
None,
|
||||
None,
|
||||
NlPayload::Payload(ifaddrmsg),
|
||||
rtattrs.push(
|
||||
RtattrBuilder::default()
|
||||
.rta_type(Ifa::Local)
|
||||
.rta_payload(&local.octets()[..])
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
rtnl.send(nl_header).unwrap();
|
||||
rtattrs.push(
|
||||
RtattrBuilder::default()
|
||||
.rta_type(Ifa::Address)
|
||||
.rta_payload(&peer.octets()[..])
|
||||
.build()
|
||||
.unwrap(),
|
||||
);
|
||||
|
||||
let ifaddrmsg = IfaddrmsgBuilder::default()
|
||||
.ifa_family(RtAddrFamily::Inet6)
|
||||
.ifa_prefixlen(128)
|
||||
.ifa_flags(IfaF::empty())
|
||||
.ifa_scope(RtScope::Universe)
|
||||
.ifa_index(index)
|
||||
.rtattrs(rtattrs)
|
||||
.build()
|
||||
.unwrap();
|
||||
let nl_header = NlmsghdrBuilder::default()
|
||||
.nl_type(Rtm::Newaddr)
|
||||
.nl_flags(NlmF::REQUEST)
|
||||
.nl_payload(NlPayload::Payload(ifaddrmsg))
|
||||
.build()
|
||||
.unwrap();
|
||||
rtnl.send(&nl_header).unwrap();
|
||||
}
|
||||
|
128
rpm/phantun.spec
Normal file
128
rpm/phantun.spec
Normal file
@@ -0,0 +1,128 @@
|
||||
Name: phantun
|
||||
Version: 0.7.0
|
||||
Release: 2%{?dist}
|
||||
Summary: A lightweight and fast UDP to TCP obfuscator
|
||||
|
||||
License: Apache-2.0
|
||||
URL: https://github.com/dndx/phantun/tree/main
|
||||
Source0: %{name}-%{version}.tar.gz
|
||||
|
||||
BuildRequires: rust
|
||||
BuildRequires: cargo
|
||||
BuildRequires: selinux-policy-devel
|
||||
|
||||
%description
|
||||
Your project with client and server components.
|
||||
|
||||
%package client
|
||||
Summary: Client component of phantun
|
||||
Requires: (%{name}-selinux if selinux-policy-%{selinuxtype})
|
||||
|
||||
%description client
|
||||
Phantun Client is like a machine with private IP address
|
||||
(192.168.200.2/fcc8::2) behind a router. In order for it to reach
|
||||
the Internet, you will need to SNAT the private IP address
|
||||
before it's traffic leaves the NIC.
|
||||
|
||||
%package server
|
||||
Summary: Server component of phantun
|
||||
Requires: (%{name}-selinux if selinux-policy-%{selinuxtype})
|
||||
|
||||
%description server
|
||||
Phantun Server is like a server with private IP address
|
||||
(192.168.201.2/fcc9::2) behind a router. In order to access it from
|
||||
the Internet, you need to DNAT it's listening port on the router
|
||||
and change the destination IP address to where the server
|
||||
is listening for incoming connections.
|
||||
|
||||
%package selinux
|
||||
Summary: SELinux module for phantun
|
||||
%{?selinux_requires}
|
||||
%global modulename phantun
|
||||
%global selinuxtype targeted
|
||||
|
||||
%description selinux
|
||||
This package provides the SELinux policy module to ensure phantun
|
||||
runs properly under an environment with SELinux enabled.
|
||||
|
||||
%global debug_package %{nil}
|
||||
|
||||
%prep
|
||||
%setup -q
|
||||
|
||||
%build
|
||||
cargo build --release
|
||||
make -C selinux
|
||||
|
||||
%install
|
||||
# Install binaries
|
||||
install -D -m 0755 target/release/client %{buildroot}/usr/libexec/phantun/phantun-client
|
||||
install -D -m 0755 target/release/server %{buildroot}/usr/libexec/phantun/phantun-server
|
||||
|
||||
mkdir -p %{buildroot}/usr/bin
|
||||
# Create wrapper scripts
|
||||
echo '#!/bin/bash
|
||||
PID_FILE=$1
|
||||
shift 1
|
||||
mkdir -p /var/run/phantun
|
||||
/usr/libexec/phantun/phantun-client "$@" &
|
||||
echo $! > /var/run/phantun/${PID_FILE}' > %{buildroot}/usr/bin/phantun-client
|
||||
|
||||
echo '#!/bin/bash
|
||||
PID_FILE=$1
|
||||
shift 1
|
||||
mkdir -p /var/run/phantun
|
||||
/usr/libexec/phantun/phantun-server "$@" &
|
||||
echo $! > /var/run/phantun/${PID_FILE}' > %{buildroot}/usr/bin/phantun-server
|
||||
|
||||
# Make wrapper scripts executable
|
||||
chmod +x %{buildroot}/usr/bin/phantun-client
|
||||
chmod +x %{buildroot}/usr/bin/phantun-server
|
||||
|
||||
# SELinux
|
||||
install -d %{buildroot}%{_datadir}/selinux/packages/%{selinuxtype}
|
||||
install -m 0644 selinux/%{modulename}.pp.bz2 %{buildroot}%{_datadir}/selinux/packages/%{selinuxtype}
|
||||
|
||||
%pre selinux
|
||||
%selinux_relabel_pre -s %{selinuxtype}
|
||||
|
||||
%post selinux
|
||||
%selinux_modules_install -s %{selinuxtype} %{_datadir}/selinux/packages/%{selinuxtype}/%{modulename}.pp.bz2
|
||||
|
||||
%postun selinux
|
||||
if [ $1 -eq 0 ]; then
|
||||
%selinux_modules_uninstall -s %{selinuxtype} %{modulename}
|
||||
fi
|
||||
|
||||
%posttrans selinux
|
||||
%selinux_relabel_post -s %{selinuxtype}
|
||||
|
||||
%files client
|
||||
/usr/libexec/phantun/phantun-client
|
||||
/usr/bin/phantun-client
|
||||
|
||||
%files server
|
||||
/usr/libexec/phantun/phantun-server
|
||||
/usr/bin/phantun-server
|
||||
|
||||
%files selinux
|
||||
%{_datadir}/selinux/packages/%{selinuxtype}/%{modulename}.pp.bz2
|
||||
|
||||
%changelog
|
||||
* Wed Dec 11 2024 Randy Li <ayaka@soulik.info> - 0.7.0-2
|
||||
- chore(deps): update tokio-tun requirement from 0.9 to 0.11
|
||||
- chore(deps): update nix requirement from 0.27 to 0.28
|
||||
- chore(deps): bump softprops/action-gh-release from 1 to 2
|
||||
- chore(docs): update license year to 2024
|
||||
- docs(readme): update `README.md` to include incoming interface (`-i tun0`) in client NAT commands example (#163)
|
||||
- Revert "docs(readme): update `README.md` to include incoming interface (`-i t…"
|
||||
- fix(fake-tcp): when `connect()`-ing, attempt to get ephemeral port using algorithm similar to Linux (#162)
|
||||
- chore(deps): bump dependencies to latest
|
||||
- chore(cargo): bump `fake-tcp` version to `0.6.0` and `phantun` to `0.7.0`
|
||||
- chore(deps): bump docker/build-push-action from 5 to 6
|
||||
- chore(release): remove MIPS targets due to being downgraded to Tier 3 support by Rust
|
||||
- docs(readme): latest release is now `v0.7.0`
|
||||
|
||||
* Sat Oct 14 2023 Randy Li <ayaka@soulik.info> - 0.6.1-1
|
||||
- Initial package
|
||||
|
26
selinux/Makefile
Normal file
26
selinux/Makefile
Normal file
@@ -0,0 +1,26 @@
|
||||
TARGET?=phantun
|
||||
MODULES?=${TARGET:=.pp.bz2}
|
||||
SHAREDIR?=/usr/share
|
||||
|
||||
all: ${TARGET:=.pp.bz2}
|
||||
|
||||
%.pp.bz2: %.pp
|
||||
@echo Compressing $^ -\> $@
|
||||
bzip2 -9 $^
|
||||
|
||||
%.pp: %.te
|
||||
make -f ${SHAREDIR}/selinux/devel/Makefile $@
|
||||
|
||||
clean:
|
||||
rm -f *~ *.tc *.pp *.pp.bz2
|
||||
rm -rf tmp *.tar.gz
|
||||
|
||||
man: install-policy
|
||||
sepolicy manpage --path . --domain ${TARGET}_t
|
||||
|
||||
install-policy: all
|
||||
semodule -i ${TARGET}.pp.bz2
|
||||
|
||||
install: man
|
||||
install -D -m 644 ${TARGET}.pp.bz2 ${DESTDIR}${SHAREDIR}/selinux/packages/${TARGET}.pp.bz2
|
||||
install -D -m 644 ${TARGET}_selinux.8 ${DESTDIR}${SHAREDIR}/man/man8/
|
5
selinux/phantun.fc
Normal file
5
selinux/phantun.fc
Normal file
@@ -0,0 +1,5 @@
|
||||
/usr/libexec/phantun/phantun-client -- gen_context(system_u:object_r:phantun_client_exec_t,s0)
|
||||
/usr/libexec/phantun/phantun-server -- gen_context(system_u:object_r:phantun_server_exec_t,s0)
|
||||
/usr/bin/phantun-client -- gen_context(system_u:object_r:wireguard_exec_t,s0)
|
||||
/usr/bin/phantun-server -- gen_context(system_u:object_r:wireguard_exec_t,s0)
|
||||
/var/run/phantun(/.*)? gen_context(system_u:object_r:phantun_var_run_t,s0)
|
60
selinux/phantun.te
Normal file
60
selinux/phantun.te
Normal file
@@ -0,0 +1,60 @@
|
||||
policy_module(phantun, 1.0)
|
||||
|
||||
gen_require(`
|
||||
type wireguard_t;
|
||||
type wireguard_exec_t;
|
||||
class capability net_admin;
|
||||
class tun_socket { append bind connect create getattr getopt ioctl lock read relabelfrom relabelto setattr setopt shutdown write };
|
||||
class tcp_socket { name_bind listen accept connect };
|
||||
class udp_socket { name_bind };
|
||||
class file { getattr open read write create unlink execute };
|
||||
class process { transition };
|
||||
')
|
||||
|
||||
|
||||
# Define custom types
|
||||
type phantun_server_exec_t;
|
||||
type phantun_client_exec_t;
|
||||
type phantun_server_port_t;
|
||||
type phantun_client_port_t;
|
||||
type phantun_var_run_t;
|
||||
|
||||
# Allow the wrapper scripts to execute the phantun client and server binaries
|
||||
allow wireguard_exec_t phantun_client_exec_t:file { getattr open read execute };
|
||||
allow wireguard_exec_t phantun_server_exec_t:file { getattr open read execute };
|
||||
|
||||
# Allow the wrapper scripts to write to the PID file
|
||||
allow wireguard_exec_t phantun_var_run_t:file { getattr open read write create unlink };
|
||||
allow wireguard_t self:process transition;
|
||||
|
||||
####################################
|
||||
# Server
|
||||
#
|
||||
|
||||
# Allow wireguard_t to execute the server binary
|
||||
allow wireguard_t phantun_server_exec_t:file { getattr open read execute };
|
||||
|
||||
# Allow the server to create and manage tun devices
|
||||
allow phantun_server_exec_t self:tun_socket { append bind connect create getattr getopt ioctl lock read relabelfrom relabelto setattr setopt shutdown write };
|
||||
|
||||
# Allow the server to bind to the custom TCP port and listen for incoming connections
|
||||
allow phantun_server_exec_t phantun_server_port_t:tcp_socket { name_bind listen accept };
|
||||
|
||||
# Allow the server to use net_admin capability
|
||||
allow phantun_server_exec_t self:capability net_admin;
|
||||
|
||||
####################################
|
||||
# Client
|
||||
#
|
||||
|
||||
# Allow wireguard_t to execute the client binary
|
||||
allow wireguard_t phantun_client_exec_t:file { getattr open read execute };
|
||||
|
||||
# Allow the client to create and manage tun devices
|
||||
allow phantun_client_exec_t self:tun_socket { append bind connect create getattr getopt ioctl lock read relabelfrom relabelto setattr setopt shutdown write };
|
||||
|
||||
# Allow the client to bind to the custom UDP port
|
||||
#allow phantun_client_exec_t phantun_client_port_t:udp_socket { name_bind };
|
||||
|
||||
# Allow the client to use net_admin capability
|
||||
allow phantun_client_exec_t self:capability net_admin;
|
Reference in New Issue
Block a user