Compare commits

..

No commits in common. "main" and "v0.1.0" have entirely different histories.
main ... v0.1.0

30 changed files with 440 additions and 2920 deletions

View File

@ -1,12 +0,0 @@
version: 2
updates:
- package-ecosystem: "github-actions"
directory: "/"
schedule:
interval: "daily"
- package-ecosystem: "cargo"
directory: "/"
schedule:
interval: "daily"

View File

@ -1,30 +0,0 @@
name: Docker image build
on:
push:
paths-ignore:
- '**.md'
jobs:
build:
runs-on: ubuntu-22.04
steps:
- name: Checkout
uses: actions/checkout@v4
- 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

View File

@ -16,18 +16,10 @@ jobs:
matrix:
target:
- x86_64-unknown-linux-gnu
- x86_64-unknown-linux-musl
- i686-unknown-linux-gnu
- i686-unknown-linux-musl
- armv7-unknown-linux-gnueabihf
- armv7-unknown-linux-musleabihf
- arm-unknown-linux-gnueabihf
- arm-unknown-linux-musleabihf
- aarch64-unknown-linux-gnu
- aarch64-unknown-linux-musl
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v2
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
@ -46,7 +38,7 @@ jobs:
zip phantun_${{ matrix.target }}.zip phantun_client phantun_server
- name: Upload Github Assets
uses: softprops/action-gh-release@v2
uses: softprops/action-gh-release@v1
with:
files: target/${{ matrix.target }}/release/*.zip
prerelease: ${{ contains(github.ref, '-') }}

View File

@ -11,10 +11,7 @@ jobs:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: actions-rs/toolchain@v1
with:
toolchain: stable
- uses: actions/checkout@v2
- name: Run lint
run: cargo clippy --verbose
- name: Build

1
.gitignore vendored
View File

@ -1 +1,2 @@
/target
Cargo.lock

1101
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -1,7 +1,5 @@
[workspace]
resolver = "2"
members = [
"fake-tcp",
"phantun",

View File

@ -1,201 +0,0 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
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.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -1,27 +0,0 @@
MIT License
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
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.

235
README.md
View File

@ -2,49 +2,35 @@
A lightweight and fast UDP to TCP obfuscator.
![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/dndx/phantun/rust.yml)
![docs.rs](https://img.shields.io/docsrs/fake-tcp)
Table of Contents
=================
* [Phantun](#phantun)
* [Latest release](#latest-release)
* [Overview](#overview)
* [Usage](#usage)
* [1. Enable Kernel IP forwarding](#1-enable-kernel-ip-forwarding)
* [2. Add required firewall rules](#2-add-required-firewall-rules)
* [Enable Kernel IP forwarding](#enable-kernel-ip-forwarding)
* [Add required firewall rules (using nftables as an example)](#add-required-firewall-rules-using-nftables-as-an-example)
* [Client](#client)
* [Using nftables](#using-nftables)
* [Using iptables](#using-iptables)
* [Server](#server)
* [Using nftables](#using-nftables)
* [Using iptables](#using-iptables)
* [3. Run Phantun binaries as non-root (Optional)](#3-run-phantun-binaries-as-non-root-optional)
* [4. Start Phantun daemon](#4-start-phantun-daemon)
* [Give Phantun binaries required capability to it can be run as non-root (Optional)](#give-phantun-binaries-required-capability-to-it-can-be-run-as-non-root-optional)
* [Start](#start)
* [Server](#server)
* [Client](#client)
* [MTU overhead](#mtu-overhead)
* [MTU calculation for WireGuard](#mtu-calculation-for-wireguard)
* [Version compatibility](#version-compatibility)
* [Documentations](#documentations)
* [Performance](#performance)
* [Future plans](#future-plans)
* [Compariation to udp2raw](#compariation-to-udp2raw)
* [License](#license)
# Latest release
[v0.7.0](https://github.com/dndx/phantun/releases/tag/v0.7.0)
# Overview
Phantun is a project that obfuscated UDP packets into TCP connections. It aims to
Phanton is a project that obfuscated UDP packets into TCP connections. It aims to
achieve maximum performance with minimum processing and encapsulation overhead.
It is commonly used in environments where UDP is blocked/throttled but TCP is allowed through.
Phantun simply converts a stream of UDP packets into obfuscated TCP stream packets. The TCP stack
Phanton simply converts a stream of UDP packets into obfuscated TCP stream packets. The TCP stack
used by Phantun is designed to pass through most L3/L4 stateful/stateless firewalls/NAT
devices. It will **not** be able to pass through L7 proxies.
However, the advantage of this approach is that none of the common UDP over TCP performance killer
@ -55,66 +41,22 @@ connection from the perspective of firewalls/NAT devices.
Phantun means Phantom TUN, as it is an obfuscator for UDP traffic that does just enough work
to make it pass through stateful firewall/NATs as TCP packets.
Phantun is written in 100% safe Rust. It has been optimized extensively to scale well on multi-core
systems and has no issue saturating all available CPU resources on a fast connection.
See the [Performance](#performance) section for benchmarking results.
![Phantun benchmark results](images/phantun-vs-udp2raw-benchmark-result.png)
![Traffic flow diagram](images/traffic-flow.png)
# Usage
For the example below, it is assumed that **Phantun Server** listens for incoming Phantun Client connections at
port `4567` (the `--local` option for server), and it forwards UDP packets to UDP server at `127.0.0.1:1234`
(the `--remote` option for server).
Phantun creates TUN interface for both the Client and Server. For Client, Phantun assigns itself the IP address
`192.168.200.2` and for Server, it assigns `192.168.201.2`. 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.
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` 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`/`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`/`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.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)
## 1. Enable Kernel IP forwarding
## Enable Kernel IP forwarding
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
## Add required firewall rules (using nftables as an example)
### Client
@ -123,10 +65,6 @@ one that can be used on the physical network. This can be done simply with masqu
Note: change `eth0` to whatever actual physical interface name is
[Back to TOC](#table-of-contents)
#### Using nftables
```
table inet nat {
chain postrouting {
@ -136,18 +74,6 @@ 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)
### Server
@ -155,34 +81,20 @@ ip6tables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
Server needs to DNAT the TCP listening port to Phantun's TUN interface address.
Note: change `eth0` to whatever actual physical interface name is and `4567` to
actual TCP port number used by Phantun server
[Back to TOC](#table-of-contents)
#### Using nftables
actual TCP port number used by Phanton server
```
table inet nat {
table ip nat {
chain prerouting {
type nat hook prerouting priority dstnat; policy accept;
iif eth0 tcp dport 4567 dnat ip to 192.168.201.2
iif eth0 tcp dport 4567 dnat ip6 to fcc9::2
iif eth0 tcp dport 4567 dnat to 192.168.201.2
}
}
```
[Back to TOC](#table-of-contents)
#### Using iptables
```
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)
## 3. Run Phantun binaries as non-root (Optional)
## Give Phantun binaries required capability to it can be run as non-root (Optional)
It is ill-advised to run network facing applications as root user. Phantun can be run fully
as non-root user with the `cap_net_admin` capability.
@ -195,11 +107,7 @@ sudo setcap cap_net_admin=+pe phantun_client
[Back to TOC](#table-of-contents)
## 4. Start Phantun daemon
**Note:** Run Phantun executable with `-h` option to see full detailed options.
[Back to TOC](#table-of-contents)
## Start
### Server
@ -210,16 +118,6 @@ rule specified above. `127.0.0.1:1234` is the UDP Server to connect to for new c
RUST_LOG=info /usr/local/bin/phantun_server --local 4567 --remote 127.0.0.1:1234
```
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
@ -231,70 +129,20 @@ the Phantun Server to connect.
RUST_LOG=info /usr/local/bin/phantun_client --local 127.0.0.1:1234 --remote 10.0.0.1:4567
```
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 (using IPv4 below as an example):
is the following:
**Standard UDP packet:** `20 byte IP header + 8 byte UDP header = 28 bytes`
Plain UDP packet: 20 byte IP header + 8 byte UDP header = 28 bytes
Phantun obfuscated UDP packet: 20 byte IP header + 20 byte TCP header = 40 bytes
**Obfuscated packet:** `20 byte IP header + 20 byte TCP header = 40 bytes`
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`. In other words, when using Phantun, the usable payload for
Phantun's additional overhead: 12 bytes. I 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.
![Packet header diagram](images/packet-headers.png)
[Back to TOC](#table-of-contents)
## MTU calculation for WireGuard
For people who use Phantun to tunnel [WireGuard®](https://www.wireguard.com) UDP packets, here are some guidelines on figuring
out the correct MTU to use for your WireGuard interface.
```
WireGuard MTU = Interface MTU - IPv4 header (20 bytes) - TCP header (20 bytes) - WireGuard overhead (32 bytes)
```
or
```
WireGuard MTU = Interface MTU - IPv6 header (40 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:
IPv4: `1500 - 20 - 20 - 32 = 1428 bytes`
IPv6: `1500 - 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 unexpected packet loss may occur and these issues are
generally very hard to troubleshoot.
[Back to TOC](#table-of-contents)
# Version compatibility
@ -304,47 +152,30 @@ of Server/Client of Phantun on both ends to ensure maximum compatibility.
[Back to TOC](#table-of-contents)
# Documentations
For users who wish to use `fake-tcp` library inside their own project, refer to the documentations for the library at:
[https://docs.rs/fake-tcp](https://docs.rs/fake-tcp).
[Back to TOC](#table-of-contents)
# Performance
Performance was tested on 2 AWS `t4g.xlarge` instances with 4 vCPUs and 5 Gb/s NIC over LAN. `nftables` was used to redirect
UDP stream of `iperf3` to go through the Phantun/udp2raw tunnel between two test instances and MTU has been tuned to avoid fragmentation.
Performance was tested on AWS t3.xlarge instance with 4 vCPUs and 5 Gb/s NIC. WireGuard was used
for tunneling TCP/UDP traffic between two test instances and MTU has been tuned to avoid fragmentation.
Phantun `v0.3.2` and `udp2raw_arm_asm_aes` `20200818.0` was used. These were the latest release of both projects as of Apr 2022.
Test command: `iperf3 -c <IP> -p <PORT> -R -u -l 1400 -b 1000m -t 30 -P 5`
| Mode | Send Speed | Receive Speed | Overall CPU Usage |
|---------------------------------------------------------------------------------|----------------|----------------|-----------------------------------------------------|
| Direct (1 stream) | 3.00 Gbits/sec | 2.37 Gbits/sec | 25% (1 core at 100%) |
| Phantun (1 stream) | 1.30 Gbits/sec | 1.20 Gbits/sec | 60% (1 core at 100%, 3 cores at 50%) |
| udp2raw (`cipher-mode=none` `auth-mode=none` `disable-anti-replay`) (1 stream) | 1.30 Gbits/sec | 715 Mbits/sec | 40% (1 core at 100%, 1 core at 50%, 2 cores idling) |
| Direct connection (5 streams) | 5.00 Gbits/sec | 3.64 Gbits/sec | 25% (1 core at 100%) |
| 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/).
| | WireGuard | WireGuard + Phantun | WireGuard + udp2raw (cipher-mode=none auth-mode=none disable-anti-replay) |
|-----------------|-------------|---------------------|---------------------------------------------------------------------------|
| iperf3 -c IP -R | 1.56 Gbit/s | 540 Mbit/s | 369 Mbit/s |
| iperf3 -c IP | 1.71 Gbit/s | 519 Mbit/s | 312 Mbit/s |
[Back to TOC](#table-of-contents)
# Future plans
* IPv6 support
* Load balancing a single UDP stream into multiple TCP streams
* Integration tests
* Auto insertion/removal of required firewall rules
* Iteration tests
[Back to TOC](#table-of-contents)
# Compariation to udp2raw
[udp2raw](https://github.com/wangyu-/udp2raw-tunnel) is another popular project by [@wangyu-](https://github.com/wangyu-)
that is very similar to what Phantun can do. In fact I took inspirations of Phantun from udp2raw. The biggest reason for
developing Phantun is because of lack of performance when running udp2raw (especially on multi-core systems such as Raspberry Pi).
developing Phanton is because of lack of performance when running udp2raw (especially on multi-core systems such as Raspberry Pi).
However, the goal is never to be as feature complete as udp2raw and only support the most common use cases. Most notably, UDP over ICMP
and UDP over UDP mode are not supported and there is no anti-replay nor encryption support. The benefit of this is much better
performance overall and less MTU overhead because lack of additional headers inside the TCP payload.
@ -358,17 +189,17 @@ Here is a quick overview of comparison between those two to help you choose:
| UDP over UDP obfuscation | ❌ | ✅ |
| Multi-threaded | ✅ | ❌ |
| Throughput | Better | Good |
| Layer 3 mode | TUN interface | Raw sockets + BPF |
| Raw IP mode | TUN interface | Raw sockets + BPF |
| Tunneling MTU overhead | 12 bytes | 44 bytes |
| Seprate TCP connections for each UDP connection | Client/Server | Server only |
| Anti-replay, encryption | ❌ | ✅ |
| IPv6 | ✅ | ✅ |
| IPv6 | Planned | ✅ |
[Back to TOC](#table-of-contents)
# License
Copyright 2021-2024 Datong Sun (dndx@idndx.com)
Copyright 2021 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

View File

@ -1,2 +0,0 @@
README.md
docker-compose.yml

View File

@ -1,33 +0,0 @@
#
# 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"]

View File

@ -1,11 +0,0 @@
# 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.

View File

@ -1,26 +0,0 @@
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

View File

@ -1,209 +0,0 @@
#!/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 "$@"

View File

@ -1,7 +1,7 @@
[package]
name = "fake-tcp"
version = "0.6.0"
edition = "2021"
version = "0.1.0"
edition = "2018"
authors = ["Datong Sun <dndx@idndx.com>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/dndx/phantun"
@ -10,16 +10,10 @@ description = """
A TUN interface based, user space, asynchronous and high performance TCP stack that allows
packet oriented tunneling with minimum overhead.
"""
[features]
benchmark = []
[dependencies]
bytes = "1"
pnet = "0"
tokio = { version = "1", features = ["full"] }
rand = { version = "0", features = ["small_rng"] }
log = "0"
internet-checksum = "0"
tokio-tun = "0"
flume = "0"
pnet = "0.28.0"
tokio-tun = "0.3.15"
tokio = { version = "1.11.0", features = ["full"] }
rand = { version = "0.8.4", features = ["small_rng"] }
log = "0.4"

View File

@ -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-2024 Datong Sun (dndx@idndx.com)
Copyright 2014-2021 The Rust Project Developers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2021-2024 Datong Sun (dndx@idndx.com)
Copyright (c) 2014-2021 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated

View File

@ -1,78 +1,34 @@
//! A minimum, userspace TCP based datagram stack
//!
//! # Overview
//!
//! `fake-tcp` is a reusable library that implements a minimum TCP stack in
//! user space using the Tun interface. It allows programs to send datagrams
//! as if they are part of a TCP connection. `fake-tcp` has been tested to
//! be able to pass through a variety of NAT and stateful firewalls while
//! fully preserves certain desirable behavior such as out of order delivery
//! and no congestion/flow controls.
//!
//! # Core Concepts
//!
//! The core of the `fake-tcp` crate compose of two structures. [`Stack`] and
//! [`Socket`].
//!
//! ## [`Stack`]
//!
//! [`Stack`] represents a virtual TCP stack that operates at
//! Layer 3. It is responsible for:
//!
//! * TCP active and passive open and handshake
//! * `RST` handling
//! * Interact with the Tun interface at Layer 3
//! * Distribute incoming datagrams to corresponding [`Socket`]
//!
//! ## [`Socket`]
//!
//! [`Socket`] represents a TCP connection. It registers the identifying
//! tuple `(src_ip, src_port, dest_ip, dest_port)` inside the [`Stack`] so
//! so that incoming packets can be distributed to the right [`Socket`] with
//! using a channel. It is also what the client should use for
//! sending/receiving datagrams.
//!
//! # Examples
//!
//! Please see [`client.rs`](https://github.com/dndx/phantun/blob/main/phantun/src/bin/client.rs)
//! and [`server.rs`](https://github.com/dndx/phantun/blob/main/phantun/src/bin/server.rs) files
//! from the `phantun` crate for how to use this library in client/server mode, respectively.
#![cfg_attr(feature = "benchmark", feature(test))]
pub mod packet;
use bytes::{Bytes, BytesMut};
use log::{error, info, trace, warn};
use log::{info, trace};
use packet::*;
use pnet::packet::{tcp, Packet};
use rand::prelude::*;
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
use std::sync::{
atomic::{AtomicU32, Ordering},
Arc, RwLock,
};
use tokio::sync::broadcast;
use tokio::sync::mpsc;
use tokio::time;
use std::net::{Ipv4Addr, SocketAddrV4};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, RwLock};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::mpsc::{self, Receiver, Sender};
use tokio::sync::watch;
use tokio::sync::Mutex as AsyncMutex;
use tokio::{io, time};
use tokio_tun::Tun;
const TIMEOUT: time::Duration = time::Duration::from_secs(1);
const RETRIES: usize = 6;
const MPMC_BUFFER_LEN: usize = 512;
const MPSC_BUFFER_LEN: usize = 128;
const MAX_UNACKED_LEN: u32 = 128 * 1024 * 1024; // 128MB
const MPSC_BUFFER_LEN: usize = 512;
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
struct AddrTuple {
local_addr: SocketAddr,
remote_addr: SocketAddr,
#[derive(Debug, Hash, Eq, PartialEq)]
pub struct AddrTuple {
local_addr: SocketAddrV4,
remote_addr: SocketAddrV4,
}
impl AddrTuple {
fn new(local_addr: SocketAddr, remote_addr: SocketAddr) -> AddrTuple {
fn new(local_addr: SocketAddrV4, remote_addr: SocketAddrV4) -> AddrTuple {
AddrTuple {
local_addr,
remote_addr,
@ -80,21 +36,21 @@ impl AddrTuple {
}
}
#[derive(Debug)]
struct Shared {
tuples: RwLock<HashMap<AddrTuple, flume::Sender<Bytes>>>,
tuples: RwLock<HashMap<AddrTuple, Arc<Sender<Bytes>>>>,
listening: RwLock<HashSet<u16>>,
tun: Vec<Arc<Tun>>,
ready: mpsc::Sender<Socket>,
tuples_purge: broadcast::Sender<AddrTuple>,
outgoing: Sender<Bytes>,
ready: Sender<Socket>,
}
pub struct Stack {
shared: Arc<Shared>,
local_ip: Ipv4Addr,
local_ip6: Option<Ipv6Addr>,
ready: mpsc::Receiver<Socket>,
ready: Receiver<Socket>,
}
#[derive(Debug)]
pub enum State {
Idle,
SynSent,
@ -102,141 +58,141 @@ pub enum State {
Established,
}
pub struct Socket {
shared: Arc<Shared>,
tun: Arc<Tun>,
incoming: flume::Receiver<Bytes>,
local_addr: SocketAddr,
remote_addr: SocketAddr,
seq: AtomicU32,
ack: AtomicU32,
last_ack: AtomicU32,
state: State,
#[derive(Debug)]
pub enum Mode {
Client,
Server,
}
#[derive(Debug)]
pub struct Socket {
mode: Mode,
shared: Arc<Shared>,
incoming: AsyncMutex<Receiver<Bytes>>,
local_addr: SocketAddrV4,
remote_addr: SocketAddrV4,
seq: AtomicU32,
ack: AtomicU32,
state: State,
closing_tx: watch::Sender<()>,
closing_rx: watch::Receiver<()>,
}
/// A socket that represents a unique TCP connection between a server and client.
///
/// The `Socket` object itself satisfies `Sync` and `Send`, which means it can
/// be safely called within an async future.
///
/// To close a TCP connection that is no longer needed, simply drop this object
/// out of scope.
impl Socket {
fn new(
mode: Mode,
shared: Arc<Shared>,
tun: Arc<Tun>,
local_addr: SocketAddr,
remote_addr: SocketAddr,
local_addr: SocketAddrV4,
remote_addr: SocketAddrV4,
ack: Option<u32>,
state: State,
) -> (Socket, flume::Sender<Bytes>) {
let (incoming_tx, incoming_rx) = flume::bounded(MPMC_BUFFER_LEN);
) -> (Socket, Sender<Bytes>) {
let (incoming_tx, incoming_rx) = mpsc::channel(MPSC_BUFFER_LEN);
let (closing_tx, closing_rx) = watch::channel(());
(
Socket {
mode,
shared,
tun,
incoming: incoming_rx,
incoming: AsyncMutex::new(incoming_rx),
local_addr,
remote_addr,
seq: AtomicU32::new(0),
ack: AtomicU32::new(ack.unwrap_or(0)),
last_ack: AtomicU32::new(ack.unwrap_or(0)),
state,
closing_tx,
closing_rx,
},
incoming_tx,
)
}
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);
fn build_tcp_packet(&self, flags: u16, payload: Option<&[u8]>) -> Bytes {
build_tcp_packet(
self.local_addr,
self.remote_addr,
self.seq.load(Ordering::Relaxed),
ack,
self.ack.load(Ordering::Relaxed),
flags,
payload,
)
}
/// Sends a datagram to the other end.
///
/// This method takes `&self`, and it can be called safely by multiple threads
/// at the same time.
///
/// A return of `None` means the Tun socket returned an error
/// and this socket must be closed.
pub async fn send(&self, payload: &[u8]) -> Option<()> {
let mut closing = self.closing_rx.clone();
match self.state {
State::Established => {
let buf = self.build_tcp_packet(tcp::TcpFlags::ACK, Some(payload));
self.seq.fetch_add(payload.len() as u32, Ordering::Relaxed);
self.tun.send(&buf).await.ok().and(Some(()))
self.seq.fetch_add(buf.len() as u32, Ordering::Relaxed);
tokio::select! {
res = self.shared.outgoing.send(buf) => {
res.unwrap();
Some(())
},
_ = closing.changed() => {
None
}
}
}
_ => unreachable!(),
}
}
/// Attempt to receive a datagram from the other end.
///
/// This method takes `&self`, and it can be called safely by multiple threads
/// at the same time.
///
/// A return of `None` means the TCP connection is broken
/// and this socket must be closed.
pub async fn recv(&self, buf: &mut [u8]) -> Option<usize> {
let mut closing = self.closing_rx.clone();
match self.state {
State::Established => {
self.incoming.recv_async().await.ok().and_then(|raw_buf| {
let (_v4_packet, tcp_packet) = parse_ip_packet(&raw_buf).unwrap();
let mut incoming = self.incoming.lock().await;
tokio::select! {
Some(raw_buf) = incoming.recv() => {
let (_v4_packet, tcp_packet) = parse_ipv4_packet(&raw_buf);
if (tcp_packet.get_flags() & tcp::TcpFlags::RST) != 0 {
info!("Connection {} reset by peer", self);
self.close();
return None;
}
let payload = tcp_packet.payload();
let new_ack = tcp_packet.get_sequence().wrapping_add(payload.len() as u32);
let last_ask = self.last_ack.load(Ordering::Relaxed);
self.ack.store(new_ack, Ordering::Relaxed);
if new_ack.overflowing_sub(last_ask).0 > MAX_UNACKED_LEN {
let buf = self.build_tcp_packet(tcp::TcpFlags::ACK, None);
if let Err(e) = self.tun.try_send(&buf) {
// This should not really happen as we have not sent anything for
// quite some time...
info!("Connection {} unable to send idling ACK back: {}", self, e)
}
}
self.ack
.store(tcp_packet.get_sequence().wrapping_add(1), Ordering::Relaxed);
buf[..payload.len()].copy_from_slice(payload);
Some(payload.len())
})
},
_ = closing.changed() => {
None
}
}
}
_ => unreachable!(),
}
}
pub fn close(&self) {
self.closing_tx.send(()).unwrap();
}
async fn accept(mut self) {
for _ in 0..RETRIES {
match self.state {
State::Idle => {
let buf = self.build_tcp_packet(tcp::TcpFlags::SYN | tcp::TcpFlags::ACK, None);
// ACK set by constructor
self.tun.send(&buf).await.unwrap();
self.shared.outgoing.send(buf).await.unwrap();
self.state = State::SynReceived;
info!("Sent SYN + ACK to client");
}
State::SynReceived => {
let res = time::timeout(TIMEOUT, self.incoming.recv_async()).await;
let res = time::timeout(TIMEOUT, self.incoming.lock().await.recv()).await;
if let Ok(buf) = res {
let buf = buf.unwrap();
let (_v4_packet, tcp_packet) = parse_ip_packet(&buf).unwrap();
let (_v4_packet, tcp_packet) = parse_ipv4_packet(&buf);
if (tcp_packet.get_flags() & tcp::TcpFlags::RST) != 0 {
return;
@ -252,9 +208,7 @@ impl Socket {
info!("Connection from {:?} established", self.remote_addr);
let ready = self.shared.ready.clone();
if let Err(e) = ready.send(self).await {
error!("Unable to send accepted socket to ready queue: {}", e);
}
ready.send(self).await.unwrap();
return;
}
} else {
@ -272,15 +226,15 @@ impl Socket {
match self.state {
State::Idle => {
let buf = self.build_tcp_packet(tcp::TcpFlags::SYN, None);
self.tun.send(&buf).await.unwrap();
self.shared.outgoing.send(buf).await.unwrap();
self.state = State::SynSent;
info!("Sent SYN to server");
}
State::SynSent => {
match time::timeout(TIMEOUT, self.incoming.recv_async()).await {
match time::timeout(TIMEOUT, self.incoming.lock().await.recv()).await {
Ok(buf) => {
let buf = buf.unwrap();
let (_v4_packet, tcp_packet) = parse_ip_packet(&buf).unwrap();
let (_v4_packet, tcp_packet) = parse_ipv4_packet(&buf);
if (tcp_packet.get_flags() & tcp::TcpFlags::RST) != 0 {
return None;
@ -297,7 +251,7 @@ impl Socket {
// send ACK to finish handshake
let buf = self.build_tcp_packet(tcp::TcpFlags::ACK, None);
self.tun.send(&buf).await.unwrap();
self.shared.outgoing.send(buf).await.unwrap();
self.state = State::Established;
@ -320,32 +274,24 @@ impl Socket {
}
impl Drop for Socket {
/// Drop the socket and close the TCP connection
fn drop(&mut self) {
let tuple = AddrTuple::new(self.local_addr, self.remote_addr);
// dissociates ourself from the dispatch map
assert!(self.shared.tuples.write().unwrap().remove(&tuple).is_some());
// purge cache
self.shared.tuples_purge.send(tuple).unwrap();
let buf = build_tcp_packet(
self.local_addr,
self.remote_addr,
self.seq.load(Ordering::Relaxed),
0,
tcp::TcpFlags::RST,
None,
);
if let Err(e) = self.tun.try_send(&buf) {
warn!("Unable to send RST to remote end: {}", e);
}
assert!(self
.shared
.tuples
.write()
.unwrap()
.remove(&AddrTuple::new(self.local_addr, self.remote_addr))
.is_some());
let buf = self.build_tcp_packet(tcp::TcpFlags::RST, None);
self.shared.outgoing.try_send(buf).unwrap();
self.close();
info!("Fake TCP connection to {} closed", self);
}
}
impl fmt::Display for Socket {
/// User-friendly string representation of the socket
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
@ -355,169 +301,97 @@ impl fmt::Display for Socket {
}
}
/// A userspace TCP state machine
impl Stack {
/// Create a new stack, `tun` is an array of [`Tun`](tokio_tun::Tun).
/// When more than one [`Tun`](tokio_tun::Tun) object is passed in, same amount
/// of reader will be spawned later. This allows user to utilize the performance
/// benefit of Multiqueue Tun support on machines with SMP.
pub fn new(tun: Vec<Tun>, local_ip: Ipv4Addr, local_ip6: Option<Ipv6Addr>) -> Stack {
let tun: Vec<Arc<Tun>> = tun.into_iter().map(Arc::new).collect();
pub fn new(tun: Tun) -> Stack {
let (outgoing_tx, outgoing_rx) = mpsc::channel(MPSC_BUFFER_LEN);
let (ready_tx, ready_rx) = mpsc::channel(MPSC_BUFFER_LEN);
let (tuples_purge_tx, _tuples_purge_rx) = broadcast::channel(16);
let shared = Arc::new(Shared {
tuples: RwLock::new(HashMap::new()),
tun: tun.clone(),
outgoing: outgoing_tx,
listening: RwLock::new(HashSet::new()),
ready: ready_tx,
tuples_purge: tuples_purge_tx.clone(),
});
let local_ip = tun.destination().unwrap();
for t in tun {
tokio::spawn(Stack::reader_task(
t,
shared.clone(),
tuples_purge_tx.subscribe(),
));
}
tokio::spawn(Stack::dispatch(tun, outgoing_rx, shared.clone()));
Stack {
shared,
local_ip,
local_ip6,
ready: ready_rx,
}
}
/// Listens for incoming connections on the given `port`.
pub fn listen(&mut self, port: u16) {
assert!(self.shared.listening.write().unwrap().insert(port));
}
/// Accepts an incoming connection.
pub async fn accept(&mut self) -> Socket {
self.ready.recv().await.unwrap()
}
/// 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_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,
);
pub async fn connect(&mut self, addr: SocketAddrV4) -> Option<Socket> {
let mut rng = SmallRng::from_entropy();
let local_port: u16 = rng.gen_range(1024..65535);
let local_addr = SocketAddrV4::new(self.local_ip, local_port);
let tuple = AddrTuple::new(local_addr, addr);
let mut sock;
{
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(
let (mut sock, incoming) = Socket::new(
Mode::Client,
self.shared.clone(),
self.shared.tun.choose(&mut rng).unwrap().clone(),
local_addr,
addr,
None,
State::Idle,
);
assert!(tuples.insert(tuple, incoming).is_none());
{
let mut tuples = self.shared.tuples.write().unwrap();
assert!(tuples.insert(tuple, Arc::new(incoming.clone())).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(
tun: Arc<Tun>,
shared: Arc<Shared>,
mut tuples_purge: broadcast::Receiver<AddrTuple>,
) {
let mut tuples: HashMap<AddrTuple, flume::Sender<Bytes>> = HashMap::new();
async fn dispatch(tun: Tun, mut outgoing: Receiver<Bytes>, shared: Arc<Shared>) {
let (mut tun_r, mut tun_w) = io::split(tun);
loop {
let mut buf = BytesMut::zeroed(MAX_PACKET_LEN);
let mut buf = BytesMut::with_capacity(MAX_PACKET_LEN);
tokio::select! {
size = tun.recv(&mut buf) => {
let size = size.unwrap();
buf.truncate(size);
buf = outgoing.recv() => {
let buf = buf.unwrap();
tun_w.write_all(&buf).await.unwrap();
},
s = tun_r.read_buf(&mut buf) => {
s.unwrap();
let buf = buf.freeze();
if buf[0] >> 4 != 4 {
// not an IPv4 packet
continue;
}
match parse_ip_packet(&buf) {
Some((ip_packet, tcp_packet)) => {
let local_addr =
SocketAddr::new(ip_packet.get_destination(), tcp_packet.get_destination());
let remote_addr = SocketAddr::new(ip_packet.get_source(), tcp_packet.get_source());
let (ip_packet, tcp_packet) = parse_ipv4_packet(&buf);
let local_addr = SocketAddrV4::new(ip_packet.get_destination(), tcp_packet.get_destination());
let remote_addr = SocketAddrV4::new(ip_packet.get_source(), tcp_packet.get_source());
let tuple = AddrTuple::new(local_addr, remote_addr);
if let Some(c) = tuples.get(&tuple) {
if c.send_async(buf).await.is_err() {
trace!("Cache hit, but receiver already closed, dropping packet");
}
continue;
// If not Ok, receiver has been closed and just fall through to the slow
// path below
} else {
trace!("Cache miss, checking the shared tuples table for connection");
let sender = {
let sender;
{
let tuples = shared.tuples.read().unwrap();
tuples.get(&tuple).cloned()
};
sender = tuples.get(&tuple).cloned();
}
if let Some(c) = sender {
trace!("Storing connection information into local tuples");
tuples.insert(tuple, c.clone());
c.send_async(buf).await.unwrap();
c.send(buf).await.unwrap();
continue;
}
}
if tcp_packet.get_flags() == tcp::TcpFlags::SYN
&& shared
.listening
.read()
.unwrap()
.contains(&tcp_packet.get_destination())
{
if tcp_packet.get_flags() == tcp::TcpFlags::SYN && shared.listening.read().unwrap().contains(&tcp_packet.get_destination()) {
// SYN seen on listening socket
if tcp_packet.get_sequence() == 0 {
let (sock, incoming) = Socket::new(
shared.clone(),
tun.clone(),
local_addr,
remote_addr,
Some(tcp_packet.get_sequence() + 1),
State::Idle,
);
assert!(shared
.tuples
.write()
.unwrap()
.insert(tuple, incoming)
.is_none());
let (sock, incoming) = Socket::new(Mode::Server, shared.clone(), local_addr, remote_addr, Some(tcp_packet.get_sequence() + 1), State::Idle);
assert!(shared.tuples.write().unwrap().insert(tuple, Arc::new(incoming)).is_none());
tokio::spawn(sock.accept());
} else {
trace!("Bad TCP SYN packet from {}, sending RST", remote_addr);
@ -525,11 +399,11 @@ impl Stack {
local_addr,
remote_addr,
0,
tcp_packet.get_sequence() + tcp_packet.payload().len() as u32 + 1, // +1 because of SYN flag set
tcp::TcpFlags::RST | tcp::TcpFlags::ACK,
tcp_packet.get_sequence() + 1,
tcp::TcpFlags::RST,
None,
);
shared.tun[0].try_send(&buf).unwrap();
shared.outgoing.try_send(buf).unwrap();
}
} else if (tcp_packet.get_flags() & tcp::TcpFlags::RST) == 0 {
info!("Unknown TCP packet from {}, sending RST", remote_addr);
@ -537,23 +411,13 @@ impl Stack {
local_addr,
remote_addr,
tcp_packet.get_acknowledgement(),
tcp_packet.get_sequence() + tcp_packet.payload().len() as u32,
tcp::TcpFlags::RST | tcp::TcpFlags::ACK,
0,
tcp::TcpFlags::RST,
None,
);
shared.tun[0].try_send(&buf).unwrap();
shared.outgoing.try_send(buf).unwrap();
}
}
None => {
continue;
}
}
},
tuple = tuples_purge.recv() => {
let tuple = tuple.unwrap();
tuples.remove(&tuple);
trace!("Removed cached tuple: {:?}", tuple);
}
}
}
}

View File

@ -1,84 +1,41 @@
use bytes::{Bytes, BytesMut};
use internet_checksum::Checksum;
use pnet::packet::Packet;
use pnet::packet::{ip, ipv4, ipv6, tcp};
use pnet::packet::{ip, ipv4, tcp};
use std::convert::TryInto;
use std::net::{IpAddr, SocketAddr};
use std::net::SocketAddrV4;
const IPV4_HEADER_LEN: usize = 20;
const IPV6_HEADER_LEN: usize = 40;
const TCP_HEADER_LEN: usize = 20;
pub const MAX_PACKET_LEN: usize = 1500;
pub enum IPPacket<'p> {
V4(ipv4::Ipv4Packet<'p>),
V6(ipv6::Ipv6Packet<'p>),
}
impl IPPacket<'_> {
pub fn get_source(&self) -> IpAddr {
match self {
IPPacket::V4(p) => IpAddr::V4(p.get_source()),
IPPacket::V6(p) => IpAddr::V6(p.get_source()),
}
}
pub fn get_destination(&self) -> IpAddr {
match self {
IPPacket::V4(p) => IpAddr::V4(p.get_destination()),
IPPacket::V6(p) => IpAddr::V6(p.get_destination()),
}
}
}
pub fn build_tcp_packet(
local_addr: SocketAddr,
remote_addr: SocketAddr,
local_addr: SocketAddrV4,
remote_addr: SocketAddrV4,
seq: u32,
ack: u32,
flags: u8,
flags: u16,
payload: Option<&[u8]>,
) -> Bytes {
let ip_header_len = match local_addr {
SocketAddr::V4(_) => IPV4_HEADER_LEN,
SocketAddr::V6(_) => IPV6_HEADER_LEN,
};
let wscale = (flags & tcp::TcpFlags::SYN) != 0;
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::zeroed(total_len);
let tcp_total_len = TCP_HEADER_LEN + if wscale {4} else {0} // nop + wscale
+ payload.map_or(0, |payload| payload.len());
let total_len = IPV4_HEADER_LEN + tcp_total_len;
let mut buf = BytesMut::with_capacity(total_len);
buf.resize(total_len, 0);
let mut ip_buf = buf.split_to(ip_header_len);
let mut v4_buf = buf.split_to(IPV4_HEADER_LEN);
let mut tcp_buf = buf.split_to(tcp_total_len);
assert_eq!(0, buf.len());
match (local_addr, remote_addr) {
(SocketAddr::V4(local), SocketAddr::V4(remote)) => {
let mut v4 = ipv4::MutableIpv4Packet::new(&mut ip_buf).unwrap();
let mut v4 = ipv4::MutableIpv4Packet::new(&mut v4_buf).unwrap();
v4.set_version(4);
v4.set_header_length(IPV4_HEADER_LEN as u8 / 4);
v4.set_next_level_protocol(ip::IpNextHeaderProtocols::Tcp);
v4.set_ttl(64);
v4.set_source(*local.ip());
v4.set_destination(*remote.ip());
v4.set_ttl(32);
v4.set_source(*local_addr.ip());
v4.set_destination(*remote_addr.ip());
v4.set_total_length(total_len.try_into().unwrap());
v4.set_flags(ipv4::Ipv4Flags::DontFragment);
let mut cksm = Checksum::new();
cksm.add_bytes(v4.packet());
v4.set_checksum(u16::from_be_bytes(cksm.checksum()));
}
(SocketAddr::V6(local), SocketAddr::V6(remote)) => {
let mut v6 = ipv6::MutableIpv6Packet::new(&mut ip_buf).unwrap();
v6.set_version(6);
v6.set_payload_length(tcp_total_len.try_into().unwrap());
v6.set_next_header(ip::IpNextHeaderProtocols::Tcp);
v6.set_hop_limit(64);
v6.set_source(*local.ip());
v6.set_destination(*remote.ip());
}
_ => unreachable!(),
};
v4.set_checksum(ipv4::checksum(&v4.to_immutable()));
let mut tcp = tcp::MutableTcpPacket::new(&mut tcp_buf).unwrap();
tcp.set_window(0xffff);
@ -97,112 +54,17 @@ pub fn build_tcp_packet(
tcp.set_payload(payload);
}
let mut cksm = Checksum::new();
let ip::IpNextHeaderProtocol(tcp_protocol) = ip::IpNextHeaderProtocols::Tcp;
let checksum = tcp::ipv4_checksum(&tcp.to_immutable(), local_addr.ip(), remote_addr.ip());
tcp.set_checksum(checksum);
match (local_addr, remote_addr) {
(SocketAddr::V4(local), SocketAddr::V4(remote)) => {
cksm.add_bytes(&local.ip().octets());
cksm.add_bytes(&remote.ip().octets());
v4_buf.unsplit(tcp_buf);
let mut pseudo = [0u8, tcp_protocol, 0, 0];
pseudo[2..].copy_from_slice(&(tcp_total_len as u16).to_be_bytes());
cksm.add_bytes(&pseudo);
}
(SocketAddr::V6(local), SocketAddr::V6(remote)) => {
cksm.add_bytes(&local.ip().octets());
cksm.add_bytes(&remote.ip().octets());
let mut pseudo = [0u8, 0, 0, 0, 0, 0, 0, tcp_protocol];
pseudo[0..4].copy_from_slice(&(tcp_total_len as u32).to_be_bytes());
cksm.add_bytes(&pseudo);
}
_ => unreachable!(),
};
cksm.add_bytes(tcp.packet());
tcp.set_checksum(u16::from_be_bytes(cksm.checksum()));
ip_buf.unsplit(tcp_buf);
ip_buf.freeze()
v4_buf.freeze()
}
pub fn parse_ip_packet(buf: &Bytes) -> Option<(IPPacket, tcp::TcpPacket)> {
if buf[0] >> 4 == 4 {
pub fn parse_ipv4_packet(buf: &Bytes) -> (ipv4::Ipv4Packet, tcp::TcpPacket) {
let v4 = ipv4::Ipv4Packet::new(buf).unwrap();
if v4.get_next_level_protocol() != ip::IpNextHeaderProtocols::Tcp {
return None;
}
let tcp = tcp::TcpPacket::new(&buf[IPV4_HEADER_LEN..]).unwrap();
Some((IPPacket::V4(v4), tcp))
} else if buf[0] >> 4 == 6 {
let v6 = ipv6::Ipv6Packet::new(buf).unwrap();
if v6.get_next_header() != ip::IpNextHeaderProtocols::Tcp {
return None;
}
let tcp = tcp::TcpPacket::new(&buf[IPV6_HEADER_LEN..]).unwrap();
Some((IPPacket::V6(v6), tcp))
} else {
None
}
}
#[cfg(all(test, feature = "benchmark"))]
mod benchmarks {
extern crate test;
use super::*;
use test::{black_box, Bencher};
#[bench]
fn bench_build_tcp_packet_1460(b: &mut Bencher) {
let local_addr = "127.0.0.1:1234".parse().unwrap();
let remote_addr = "127.0.0.2:1234".parse().unwrap();
let payload = black_box([123u8; 1460]);
b.iter(|| {
build_tcp_packet(
local_addr,
remote_addr,
123,
456,
tcp::TcpFlags::ACK,
Some(&payload),
)
});
}
#[bench]
fn bench_build_tcp_packet_512(b: &mut Bencher) {
let local_addr = "127.0.0.1:1234".parse().unwrap();
let remote_addr = "127.0.0.2:1234".parse().unwrap();
let payload = black_box([123u8; 512]);
b.iter(|| {
build_tcp_packet(
local_addr,
remote_addr,
123,
456,
tcp::TcpFlags::ACK,
Some(&payload),
)
});
}
#[bench]
fn bench_build_tcp_packet_128(b: &mut Bencher) {
let local_addr = "127.0.0.1:1234".parse().unwrap();
let remote_addr = "127.0.0.2:1234".parse().unwrap();
let payload = black_box([123u8; 128]);
b.iter(|| {
build_tcp_packet(
local_addr,
remote_addr,
123,
456,
tcp::TcpFlags::ACK,
Some(&payload),
)
});
}
(v4, tcp)
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 30 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 15 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 89 KiB

After

Width:  |  Height:  |  Size: 73 KiB

View File

@ -1,24 +1,20 @@
[package]
name = "phantun"
version = "0.7.0"
edition = "2021"
version = "0.1.0"
edition = "2018"
authors = ["Datong Sun <dndx@idndx.com>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/dndx/phantun"
readme = "README.md"
description = """
Transforms UDP stream into (fake) TCP streams that can go through
Layer 3 & Layer 4 (NAPT) firewalls/NATs.
Turns transforms UDP stream into (fake) TCP streams that can go through
Layer 4 firewalls.
"""
[dependencies]
clap = { version = "4", features = ["cargo"] }
socket2 = { version = "0", features = ["all"] }
fake-tcp = { path = "../fake-tcp", version = "0" }
tokio = { version = "1", features = ["full"] }
tokio-util = "0"
log = "0"
pretty_env_logger = "0"
tokio-tun = "0"
num_cpus = "1"
neli = "0"
nix = { version = "0", features = ["net"] }
clap = "2.33.3"
socket2 = { version = "0.4.2", features = ["all"] }
fake-tcp = "0.1.0"
tokio-tun = "0.3.15"
tokio = { version = "1.11.0", features = ["full"] }
log = "0.4"
pretty_env_logger = "0.4.0"

View File

@ -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-2024 Datong Sun (dndx@idndx.com)
Copyright 2014-2021 The Rust Project Developers
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

View File

@ -1,6 +1,6 @@
MIT License
Copyright (c) 2021-2024 Datong Sun (dndx@idndx.com)
Copyright (c) 2014-2021 The Rust Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated

View File

@ -1,181 +1,91 @@
use clap::{crate_version, Arg, ArgAction, Command};
use clap::{App, Arg};
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 std::collections::HashMap;
use std::fs;
use std::io;
use std::net::{Ipv4Addr, SocketAddr};
use std::convert::TryInto;
use std::net::{SocketAddr, SocketAddrV4};
use std::sync::Arc;
use tokio::sync::{Notify, RwLock};
use std::time::Duration;
use tokio::net::UdpSocket;
use tokio::sync::RwLock;
use tokio::time;
use tokio_tun::TunBuilder;
use tokio_util::sync::CancellationToken;
use phantun::UDP_TTL;
const UDP_TTL: Duration = Duration::from_secs(180);
fn new_udp_reuseport(addr: SocketAddrV4) -> UdpSocket {
let udp_sock = socket2::Socket::new(socket2::Domain::IPV4, socket2::Type::DGRAM, None).unwrap();
udp_sock.set_reuse_port(true).unwrap();
// from tokio-rs/mio/blob/master/src/sys/unix/net.rs
udp_sock.set_cloexec(true).unwrap();
udp_sock.set_nonblocking(true).unwrap();
udp_sock.bind(&socket2::SockAddr::from(addr)).unwrap();
let udp_sock: std::net::UdpSocket = udp_sock.into();
udp_sock.try_into().unwrap()
}
#[tokio::main]
async fn main() -> io::Result<()> {
async fn main() {
pretty_env_logger::init();
let matches = Command::new("Phantun Client")
.version(crate_version!())
.author("Datong Sun (github.com/dndx)")
let matches = App::new("Phantun Client")
.version("1.0")
.author("dndx@GitHub")
.arg(
Arg::new("local")
.short('l')
Arg::with_name("local")
.short("l")
.long("local")
.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\"")
.help("Sets the listening socket address")
.takes_value(true),
)
.arg(
Arg::new("remote")
.short('r')
Arg::with_name("remote")
.short("r")
.long("remote")
.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\"")
)
.arg(
Arg::new("tun")
.long("tun")
.required(false)
.value_name("tunX")
.help("Sets the Tun interface name, if absent, pick the next available name")
.default_value("")
)
.arg(
Arg::new("tun_local")
.long("tun-local")
.required(false)
.value_name("IP")
.help("Sets the Tun interface IPv4 local address (O/S's end)")
.default_value("192.168.200.1")
)
.arg(
Arg::new("tun_peer")
.long("tun-peer")
.required(false)
.value_name("IP")
.help("Sets the Tun interface IPv4 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("192.168.200.2")
)
.arg(
Arg::new("ipv4_only")
.long("ipv4-only")
.short('4')
.required(false)
.help("Only use IPv4 address when connecting to remote")
.action(ArgAction::SetTrue)
.conflicts_with_all(["tun_local6", "tun_peer6"]),
)
.arg(
Arg::new("tun_local6")
.long("tun-local6")
.required(false)
.value_name("IP")
.help("Sets the Tun interface IPv6 local address (O/S's end)")
.default_value("fcc8::1")
)
.arg(
Arg::new("tun_peer6")
.long("tun-peer6")
.required(false)
.value_name("IP")
.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("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")
.value_name("IP:PORT")
.help("Sets the connecting socket address")
.takes_value(true),
)
.get_matches();
let local_addr: SocketAddr = matches
.get_one::<String>("local")
let local_addr: SocketAddrV4 = matches
.value_of("local")
.unwrap()
.parse()
.expect("bad local address");
let ipv4_only = matches.get_flag("ipv4_only");
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())
.expect("unable to resolve remote host name");
info!("Remote address is: {}", remote_addr);
let tun_local: Ipv4Addr = matches
.get_one::<String>("tun_local")
let remote_addr: SocketAddrV4 = matches
.value_of("remote")
.unwrap()
.parse()
.expect("bad local address for Tun interface");
let tun_peer: Ipv4Addr = matches
.get_one::<String>("tun_peer")
.unwrap()
.parse()
.expect("bad peer address for Tun interface");
let (tun_local6, tun_peer6) = if matches.get_flag("ipv4_only") {
(None, None)
} else {
(
matches
.get_one::<String>("tun_local6")
.map(|v| v.parse().expect("bad local address for Tun interface")),
matches
.get_one::<String>("tun_peer6")
.map(|v| v.parse().expect("bad peer address for Tun interface")),
)
};
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);
.expect("bad remote address");
let tun = TunBuilder::new()
.name(tun_name) // if name is empty, then it is set by kernel.
.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)
.queues(num_cpus)
.build()
.address("192.168.200.1".parse().unwrap())
.destination("192.168.200.2".parse().unwrap())
.try_build()
.unwrap();
if remote_addr.is_ipv6() {
assign_ipv6_address(tun[0].name(), tun_local6.unwrap(), tun_peer6.unwrap());
}
info!("Created TUN device {}", tun[0].name());
info!("Created TUN device {}", tun.name());
let udp_sock = Arc::new(new_udp_reuseport(local_addr));
let connections = Arc::new(RwLock::new(HashMap::<SocketAddr, Arc<Socket>>::new()));
let connections = Arc::new(RwLock::new(HashMap::<SocketAddrV4, Arc<Socket>>::new()));
let mut stack = Stack::new(tun, tun_peer, tun_peer6);
let mut stack = Stack::new(tun);
let main_loop = tokio::spawn(async move {
let mut buf_r = [0u8; MAX_PACKET_LEN];
loop {
let (size, addr) = udp_sock.recv_from(&mut buf_r).await?;
tokio::select! {
Ok((size, SocketAddr::V4(addr))) = udp_sock.recv_from(&mut buf_r) => {
// 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
@ -193,38 +103,19 @@ 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
if sock.send(&buf_r[..size]).await.is_none() {
let res = sock.send(&buf_r[..size]).await;
if res.is_none() {
continue;
}
assert!(connections
.write()
.await
.insert(addr, sock.clone())
.is_none());
assert!(connections.write().await.insert(addr, sock.clone()).is_none());
debug!("inserted fake TCP socket into connection table");
let connections = connections.clone();
// spawn "fastpath" UDP socket and task, this will offload main task
// from forwarding UDP packets
let packet_received = Arc::new(Notify::new());
let quit = CancellationToken::new();
for i in 0..num_cpus {
let sock = sock.clone();
let quit = quit.clone();
let packet_received = packet_received.clone();
tokio::spawn(async move {
let mut buf_udp = [0u8; MAX_PACKET_LEN];
let mut buf_tcp = [0u8; MAX_PACKET_LEN];
@ -232,71 +123,43 @@ async fn main() -> io::Result<()> {
udp_sock.connect(addr).await.unwrap();
loop {
let read_timeout = time::sleep(UDP_TTL);
tokio::select! {
Ok(size) = udp_sock.recv(&mut buf_udp) => {
if sock.send(&buf_udp[..size]).await.is_none() {
connections.write().await.remove(&addr);
debug!("removed fake TCP socket from connections table");
quit.cancel();
return;
}
packet_received.notify_one();
},
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);
quit.cancel();
return;
}
udp_sock.send(&buf_tcp[..size]).await.unwrap();
}
},
None => {
connections.write().await.remove(&addr);
debug!("removed fake TCP socket from connections table");
quit.cancel();
return;
},
}
packet_received.notify_one();
},
_ = quit.cancelled() => {
debug!("worker {} terminated", i);
return;
},
};
}
});
}
let connections = connections.clone();
tokio::spawn(async move {
loop {
let read_timeout = time::sleep(UDP_TTL);
let packet_received_fut = packet_received.notified();
tokio::select! {
_ = read_timeout => {
info!("No traffic seen in the last {:?}, closing connection", UDP_TTL);
connections.write().await.remove(&addr);
debug!("removed fake TCP socket from connections table");
quit.cancel();
return;
}
};
}
});
},
_ = quit.cancelled() => {
connections.write().await.remove(&addr);
debug!("removed fake TCP socket from connections table");
return;
},
_ = packet_received_fut => {},
}
}
});
}
});
tokio::join!(main_loop).0.unwrap()
tokio::join!(main_loop).0.unwrap();
}

View File

@ -1,172 +1,63 @@
use clap::{crate_version, Arg, ArgAction, Command};
use clap::{App, Arg};
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;
use log::info;
use std::net::SocketAddrV4;
use tokio::net::UdpSocket;
use tokio::sync::Notify;
use tokio::time;
use tokio::time::{self, Duration};
use tokio_tun::TunBuilder;
use tokio_util::sync::CancellationToken;
use phantun::UDP_TTL;
const UDP_TTL: Duration = Duration::from_secs(180);
#[tokio::main]
async fn main() -> io::Result<()> {
async fn main() {
pretty_env_logger::init();
let matches = Command::new("Phantun Server")
.version(crate_version!())
.author("Datong Sun (github.com/dndx)")
let matches = App::new("Phantun Server")
.version("1.0")
.author("dndx@GitHub")
.arg(
Arg::new("local")
.short('l')
Arg::with_name("local")
.short("l")
.long("local")
.required(true)
.value_name("PORT")
.help("Sets the port where Phantun Server listens for incoming Phantun Client TCP connections")
.help("Sets the listening port")
.takes_value(true),
)
.arg(
Arg::new("remote")
.short('r')
Arg::with_name("remote")
.short("r")
.long("remote")
.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\"")
)
.arg(
Arg::new("tun")
.long("tun")
.required(false)
.value_name("tunX")
.help("Sets the Tun interface name, if absent, pick the next available name")
.default_value("")
)
.arg(
Arg::new("tun_local")
.long("tun-local")
.required(false)
.value_name("IP")
.help("Sets the Tun interface local address (O/S's end)")
.default_value("192.168.201.1")
)
.arg(
Arg::new("tun_peer")
.long("tun-peer")
.required(false)
.value_name("IP")
.help("Sets the Tun interface destination (peer) address (Phantun Server's end). \
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")
)
.arg(
Arg::new("ipv4_only")
.long("ipv4-only")
.short('4')
.required(false)
.help("Do not assign IPv6 addresses to Tun interface")
.action(ArgAction::SetTrue)
.conflicts_with_all(["tun_local6", "tun_peer6"]),
)
.arg(
Arg::new("tun_local6")
.long("tun-local6")
.required(false)
.value_name("IP")
.help("Sets the Tun interface IPv6 local address (O/S's end)")
.default_value("fcc9::1")
)
.arg(
Arg::new("tun_peer6")
.long("tun-peer6")
.required(false)
.value_name("IP")
.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("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")
.value_name("IP:PORT")
.help("Sets the connecting socket address")
.takes_value(true),
)
.get_matches();
let local_port: u16 = matches
.get_one::<String>("local")
.value_of("local")
.unwrap()
.parse()
.expect("bad local port");
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
.get_one::<String>("tun_local")
let remote_addr: SocketAddrV4 = matches
.value_of("remote")
.unwrap()
.parse()
.expect("bad local address for Tun interface");
let tun_peer: Ipv4Addr = matches
.get_one::<String>("tun_peer")
.unwrap()
.parse()
.expect("bad peer address for Tun interface");
let (tun_local6, tun_peer6) = if matches.get_flag("ipv4_only") {
(None, None)
} else {
(
matches
.get_one::<String>("tun_local6")
.map(|v| v.parse().expect("bad local address for Tun interface")),
matches
.get_one::<String>("tun_peer6")
.map(|v| v.parse().expect("bad peer address for Tun interface")),
)
};
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);
.expect("bad remote address");
let tun = TunBuilder::new()
.name(tun_name) // if name is empty, then it is set by kernel.
.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)
.queues(num_cpus)
.build()
.address("192.168.201.1".parse().unwrap())
.destination("192.168.201.2".parse().unwrap())
.try_build()
.unwrap();
if let (Some(tun_local6), Some(tun_peer6)) = (tun_local6, tun_peer6) {
assign_ipv6_address(tun[0].name(), tun_local6, tun_peer6);
}
info!("Created TUN device {}", tun[0].name());
//thread::sleep(time::Duration::from_secs(5));
let mut stack = Stack::new(tun, tun_local, tun_local6);
let mut stack = Stack::new(tun);
stack.listen(local_port);
info!("Listening on {}", local_port);
@ -175,93 +66,41 @@ async fn main() -> io::Result<()> {
let mut buf_tcp = [0u8; MAX_PACKET_LEN];
loop {
let sock = Arc::new(stack.accept().await);
let sock = 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();
let udp_sock = UdpSocket::bind(if remote_addr.is_ipv4() {
"0.0.0.0:0"
} else {
"[::]:0"
})
.await?;
let local_addr = udp_sock.local_addr()?;
drop(udp_sock);
for i in 0..num_cpus {
let sock = sock.clone();
let quit = quit.clone();
let packet_received = packet_received.clone();
let udp_sock = new_udp_reuseport(local_addr);
tokio::spawn(async move {
let udp_sock = UdpSocket::bind("0.0.0.0:0").await.unwrap();
udp_sock.connect(remote_addr).await.unwrap();
loop {
let read_timeout = time::sleep(UDP_TTL);
tokio::select! {
Ok(size) = udp_sock.recv(&mut buf_udp) => {
if sock.send(&buf_udp[..size]).await.is_none() {
quit.cancel();
return;
}
packet_received.notify_one();
},
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, remote_addr);
quit.cancel();
return;
}
udp_sock.send(&buf_tcp[..size]).await.unwrap();
}
},
None => {
quit.cancel();
return;
},
None => { return; },
}
packet_received.notify_one();
},
_ = quit.cancelled() => {
debug!("worker {} terminated", i);
_ = read_timeout => {
info!("No traffic seen in the last {:?}, closing connection", UDP_TTL);
return;
},
}
};
}
});
}
tokio::spawn(async move {
loop {
let read_timeout = time::sleep(UDP_TTL);
let packet_received_fut = packet_received.notified();
tokio::select! {
_ = read_timeout => {
info!("No traffic seen in the last {:?}, closing connection", UDP_TTL);
quit.cancel();
return;
},
_ = packet_received_fut => {},
}
}
});
}
});
tokio::join!(main_loop).0.unwrap()
tokio::join!(main_loop).0.unwrap();
}

View File

@ -1,5 +0,0 @@
use std::time::Duration;
pub mod utils;
pub const UDP_TTL: Duration = Duration::from_secs(180);

View File

@ -1,60 +0,0 @@
use neli::{
consts::{
nl::{NlmF, NlmFFlags},
rtnl::{Ifa, IfaFFlags, RtAddrFamily, Rtm},
socket::NlFamily,
},
nl::{NlPayload, Nlmsghdr},
rtnl::{Ifaddrmsg, Rtattr},
socket::NlSocketHandle,
types::RtBuffer,
};
use std::net::{Ipv6Addr, SocketAddr};
use tokio::net::UdpSocket;
pub fn new_udp_reuseport(local_addr: SocketAddr) -> UdpSocket {
let udp_sock = socket2::Socket::new(
if local_addr.is_ipv4() {
socket2::Domain::IPV4
} else {
socket2::Domain::IPV6
},
socket2::Type::DGRAM,
None,
)
.unwrap();
udp_sock.set_reuse_port(true).unwrap();
// from tokio-rs/mio/blob/master/src/sys/unix/net.rs
udp_sock.set_cloexec(true).unwrap();
udp_sock.set_nonblocking(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 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 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),
);
rtnl.send(nl_header).unwrap();
}