15 Commits

Author SHA1 Message Date
Datong Sun
4dc9f867ed chore(release) add more cross compilation targets 2021-09-22 22:17:05 -07:00
Datong Sun
a54d1b3759 chore(phantun): update fake-tcp used to 0.1.1 2021-09-22 22:04:15 -07:00
Datong Sun
8371256f0b perf(fake-tcp) use cached tuples per dispatcher task to avoid RwLock
contentions. Use multi queue Tun. Upgraded tokio to 1.12.0.

This makes the entire Phantun forward process completely lock contention free
2021-09-23 12:59:49 +08:00
Datong Sun
04b0e97c1d perf(fake-tcp) faster checksum calculation
Before:
```
test packet::benchmarks::bench_build_tcp_packet_128  ... bench:         207 ns/iter (+/- 25)
test packet::benchmarks::bench_build_tcp_packet_1460 ... bench:         670 ns/iter (+/- 14)
test packet::benchmarks::bench_build_tcp_packet_512  ... bench:         334 ns/iter (+/- 21)
```

After:
```
test packet::benchmarks::bench_build_tcp_packet_128  ... bench:         206 ns/iter (+/- 9)
test packet::benchmarks::bench_build_tcp_packet_1460 ... bench:         259 ns/iter (+/- 16)
test packet::benchmarks::bench_build_tcp_packet_512  ... bench:         212 ns/iter (+/- 11)
```
2021-09-20 23:12:53 +08:00
Datong Sun
212f9b6f9d docs(readme) add iptables config guide 2021-09-20 04:15:55 -07:00
Datong Sun
9b644166a5 docs(readme) fixed typo 2021-09-20 04:09:12 -07:00
Datong Sun
e0eb0f03cd docs(readme) changed section header to be shorter 2021-09-19 03:59:27 -07:00
Datong Sun
9418096fe3 docs(readme) fix styling 2021-09-19 03:58:35 -07:00
Datong Sun
f70c466399 docs(readme) fix WireGuard section header format 2021-09-19 03:53:47 -07:00
Datong Sun
fb66286db3 docs(images) update diagram to include more descriptions 2021-09-19 03:46:19 -07:00
Datong Sun
d4d941971f ci(release) add aarch64 target 2021-09-19 03:32:05 -07:00
Datong Sun
62df34983f docs(readme) add future plans 2021-09-19 03:09:16 -07:00
Datong Sun
d2b8bbeaa8 docs(readme) add better styling for MAX_OF_16 2021-09-19 03:02:37 -07:00
Datong Sun
10468b48ce docs(readme) add WireGuard MTU calculation steps 2021-09-19 02:59:50 -07:00
Datong Sun
3405dd38ed docs(license) add license files to repository root 2021-09-19 02:40:43 -07:00
11 changed files with 506 additions and 89 deletions

View File

@@ -16,7 +16,12 @@ jobs:
matrix:
target:
- x86_64-unknown-linux-gnu
- i686-unknown-linux-gnu
- armv7-unknown-linux-gnueabihf
- arm-unknown-linux-gnueabihf
- aarch64-unknown-linux-gnu
- mips-unknown-linux-gnu
- mipsel-unknown-linux-gnu
steps:
- uses: actions/checkout@v2

201
LICENSE-APACHE Normal file
View File

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

27
LICENSE-MIT Normal file
View File

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

View File

@@ -6,23 +6,33 @@ Table of Contents
=================
* [Phantun](#phantun)
* [Latest release](#latest-release)
* [Overview](#overview)
* [Usage](#usage)
* [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)
* [1. Enable Kernel IP forwarding](#1-enable-kernel-ip-forwarding)
* [2. Add required firewall rules](#2-add-required-firewall-rules)
* [Client](#client)
* [Using nftables](#using-nftables)
* [Using iptables](#using-iptables)
* [Server](#server)
* [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)
* [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)
* [Server](#server)
* [Client](#client)
* [MTU overhead](#mtu-overhead)
* [MTU calculation for WireGuard](#mtu-calculation-for-wireguard)
* [Version compatibility](#version-compatibility)
* [Performance](#performance)
* [Future plans](#future-plans)
* [Compariation to udp2raw](#compariation-to-udp2raw)
* [License](#license)
# Latest release
[v0.1.0](https://github.com/dndx/phantun/releases/tag/v0.1.0)
# Overview
Phanton is a project that obfuscated UDP packets into TCP connections. It aims to
@@ -50,13 +60,16 @@ Phantun creates TUN interface for both the Client and Server. For Client, Phantu
`net.ipv4.ip_forward` enabled and setup appropriate iptables rules for NAT between your physical
NIC address and Phantun's TUN interface address.
## Enable Kernel IP forwarding
[Back to TOC](#table-of-contents)
## 1. Enable Kernel IP forwarding
Edit `/etc/sysctl.conf`, add `net.ipv4.ip_forward=1` and run `sudo sysctl -p /etc/sysctl.conf`.
[Back to TOC](#table-of-contents)
## Add required firewall rules (using nftables as an example)
## 2. Add required firewall rules
### Client
@@ -65,6 +78,10 @@ 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 {
@@ -76,6 +93,14 @@ table inet nat {
[Back to TOC](#table-of-contents)
#### Using iptables
```
iptables -t nat -A POSTROUTING -i tun0 -o eth0 -j MASQUERADE
```
[Back to TOC](#table-of-contents)
### Server
Server needs to DNAT the TCP listening port to Phantun's TUN interface address.
@@ -83,6 +108,10 @@ 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 Phanton server
[Back to TOC](#table-of-contents)
#### Using nftables
```
table ip nat {
chain prerouting {
@@ -94,7 +123,15 @@ table ip nat {
[Back to TOC](#table-of-contents)
## Give Phantun binaries required capability to it can be run as non-root (Optional)
#### Using iptables
```
iptables -t nat -A PREROUTING -p tcp -i eth0 --dport 4567 -j DNAT --to-destination 192.168.201.2
```
[Back to TOC](#table-of-contents)
## 3. Run Phantun binaries 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.
@@ -107,7 +144,7 @@ sudo setcap cap_net_admin=+pe phantun_client
[Back to TOC](#table-of-contents)
## Start
## 4. Start Phantun daemon
### Server
@@ -136,15 +173,41 @@ RUST_LOG=info /usr/local/bin/phantun_client --local 127.0.0.1:1234 --remote 10.0
Phantun aims to keep tunneling overhead to the minimum. The overhead compared to a plain UDP packet
is the following:
Plain UDP packet: 20 byte IP header + 8 byte UDP header = 28 bytes
Standard 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
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
UDP packet is reduced by 12 bytes. This is the minimum overhead possible when doing such kind
of obfuscation.
[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 = `MAX_OF_16`(Interface MTU - IP header (20 bytes) - TCP header (20 bytes) - WireGuard overhead (32 bytes))
Where:
`MAX_OF_16` takes an input integer and calculates the maximum multiple of 16 not exceeding the input. This
is needed because WireGuard will always pad it's payloads to multiple of 16 bytes.
For example, for a Ethernet interface with 1500 bytes MTU, the WireGuard interface MTU should be set as:
`MAX_OF_16`(1500 - 20 - 20 - 32) = 1424 bytes
The resulted Phantun TCP data packet will be 1424 + 20 + 20 + 32 = 1496 bytes which does not exceed the
interface MTU of 1500.
[Back to TOC](#table-of-contents)
# Version compatibility
While the TCP stack is fairly stable, the general expectation is that you should run same minor versions
@@ -168,7 +231,8 @@ for tunneling TCP/UDP traffic between two test instances and MTU has been tuned
* IPv6 support
* Load balancing a single UDP stream into multiple TCP streams
* Iteration tests
* Integration tests
* Auto insertion/removal of required firewall rules
[Back to TOC](#table-of-contents)

View File

@@ -1,6 +1,6 @@
[package]
name = "fake-tcp"
version = "0.1.0"
version = "0.1.1"
edition = "2018"
authors = ["Datong Sun <dndx@idndx.com>"]
license = "MIT OR Apache-2.0"
@@ -10,10 +10,15 @@ 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.28.0"
tokio-tun = "0.3.15"
tokio = { version = "1.11.0", features = ["full"] }
tokio = { version = "1.12.0", features = ["full"] }
rand = { version = "0.8.4", features = ["small_rng"] }
log = "0.4"
internet-checksum = "0.2.0"
dndx-fork-tokio-tun = "0.3.16"

View File

@@ -1,7 +1,10 @@
#![cfg_attr(feature = "benchmark", feature(test))]
pub mod packet;
extern crate dndx_fork_tokio_tun as tokio_tun;
use bytes::{Bytes, BytesMut};
use log::{info, trace};
use log::{error, info, trace, warn};
use packet::*;
use pnet::packet::{tcp, Packet};
use rand::prelude::*;
@@ -10,18 +13,18 @@ use std::fmt;
use std::net::{Ipv4Addr, SocketAddrV4};
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Arc, RwLock};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::sync::broadcast;
use tokio::sync::mpsc::{self, Receiver, Sender};
use tokio::sync::watch;
use tokio::sync::Mutex as AsyncMutex;
use tokio::{io, time};
use tokio::time;
use tokio_tun::Tun;
const TIMEOUT: time::Duration = time::Duration::from_secs(1);
const RETRIES: usize = 6;
const MPSC_BUFFER_LEN: usize = 512;
#[derive(Debug, Hash, Eq, PartialEq)]
#[derive(Hash, Eq, PartialEq, Clone, Debug)]
pub struct AddrTuple {
local_addr: SocketAddrV4,
remote_addr: SocketAddrV4,
@@ -36,12 +39,12 @@ impl AddrTuple {
}
}
#[derive(Debug)]
struct Shared {
tuples: RwLock<HashMap<AddrTuple, Arc<Sender<Bytes>>>>,
tuples: RwLock<HashMap<AddrTuple, Sender<Bytes>>>,
listening: RwLock<HashSet<u16>>,
outgoing: Sender<Bytes>,
tun: Vec<Arc<Tun>>,
ready: Sender<Socket>,
tuples_purge: broadcast::Sender<AddrTuple>,
}
pub struct Stack {
@@ -50,7 +53,6 @@ pub struct Stack {
ready: Receiver<Socket>,
}
#[derive(Debug)]
pub enum State {
Idle,
SynSent,
@@ -58,16 +60,9 @@ pub enum State {
Established,
}
#[derive(Debug)]
pub enum Mode {
Client,
Server,
}
#[derive(Debug)]
pub struct Socket {
mode: Mode,
shared: Arc<Shared>,
tun: Arc<Tun>,
incoming: AsyncMutex<Receiver<Bytes>>,
local_addr: SocketAddrV4,
remote_addr: SocketAddrV4,
@@ -80,8 +75,8 @@ pub struct Socket {
impl Socket {
fn new(
mode: Mode,
shared: Arc<Shared>,
tun: Arc<Tun>,
local_addr: SocketAddrV4,
remote_addr: SocketAddrV4,
ack: Option<u32>,
@@ -92,8 +87,8 @@ impl Socket {
(
Socket {
mode,
shared,
tun,
incoming: AsyncMutex::new(incoming_rx),
local_addr,
remote_addr,
@@ -124,10 +119,10 @@ impl Socket {
match self.state {
State::Established => {
let buf = self.build_tcp_packet(tcp::TcpFlags::ACK, Some(payload));
self.seq.fetch_add(buf.len() as u32, Ordering::Relaxed);
self.seq.fetch_add(payload.len() as u32, Ordering::Relaxed);
tokio::select! {
res = self.shared.outgoing.send(buf) => {
res = self.tun.send(&buf) => {
res.unwrap();
Some(())
},
@@ -184,7 +179,7 @@ impl Socket {
State::Idle => {
let buf = self.build_tcp_packet(tcp::TcpFlags::SYN | tcp::TcpFlags::ACK, None);
// ACK set by constructor
self.shared.outgoing.send(buf).await.unwrap();
self.tun.send(&buf).await.unwrap();
self.state = State::SynReceived;
info!("Sent SYN + ACK to client");
}
@@ -208,7 +203,9 @@ impl Socket {
info!("Connection from {:?} established", self.remote_addr);
let ready = self.shared.ready.clone();
ready.send(self).await.unwrap();
if let Err(e) = ready.send(self).await {
error!("Unable to send accepted socket to ready queue: {}", e);
}
return;
}
} else {
@@ -226,7 +223,7 @@ impl Socket {
match self.state {
State::Idle => {
let buf = self.build_tcp_packet(tcp::TcpFlags::SYN, None);
self.shared.outgoing.send(buf).await.unwrap();
self.tun.send(&buf).await.unwrap();
self.state = State::SynSent;
info!("Sent SYN to server");
}
@@ -251,7 +248,7 @@ impl Socket {
// send ACK to finish handshake
let buf = self.build_tcp_packet(tcp::TcpFlags::ACK, None);
self.shared.outgoing.send(buf).await.unwrap();
self.tun.send(&buf).await.unwrap();
self.state = State::Established;
@@ -275,17 +272,16 @@ impl Socket {
impl Drop for Socket {
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(&AddrTuple::new(self.local_addr, self.remote_addr))
.is_some());
assert!(self.shared.tuples.write().unwrap().remove(&tuple).is_some());
// purge cache
self.shared.tuples_purge.send(tuple).unwrap();
let buf = self.build_tcp_packet(tcp::TcpFlags::RST, None);
self.shared.outgoing.try_send(buf).unwrap();
if let Err(e) = self.tun.try_send(&buf) {
warn!("Unable to send RST to remote end: {}", e);
}
self.close();
info!("Fake TCP connection to {} closed", self);
}
@@ -302,18 +298,27 @@ impl fmt::Display for Socket {
}
impl Stack {
pub fn new(tun: Tun) -> Stack {
let (outgoing_tx, outgoing_rx) = mpsc::channel(MPSC_BUFFER_LEN);
pub fn new(tun: Vec<Tun>) -> Stack {
let tun: Vec<Arc<Tun>> = tun.into_iter().map(Arc::new).collect();
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()),
outgoing: outgoing_tx,
tun: tun.clone(),
listening: RwLock::new(HashSet::new()),
ready: ready_tx,
tuples_purge: tuples_purge_tx.clone(),
});
let local_ip = tun.destination().unwrap();
let local_ip = tun[0].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,
@@ -335,8 +340,8 @@ impl Stack {
let local_addr = SocketAddrV4::new(self.local_ip, local_port);
let tuple = AddrTuple::new(local_addr, addr);
let (mut sock, incoming) = Socket::new(
Mode::Client,
self.shared.clone(),
self.shared.tun.choose(&mut rng).unwrap().clone(),
local_addr,
addr,
None,
@@ -345,53 +350,83 @@ impl Stack {
{
let mut tuples = self.shared.tuples.write().unwrap();
assert!(tuples.insert(tuple, Arc::new(incoming.clone())).is_none());
assert!(tuples.insert(tuple, incoming.clone()).is_none());
}
sock.connect().await.map(|_| sock)
}
async fn dispatch(tun: Tun, mut outgoing: Receiver<Bytes>, shared: Arc<Shared>) {
let (mut tun_r, mut tun_w) = io::split(tun);
async fn reader_task(
tun: Arc<Tun>,
shared: Arc<Shared>,
mut tuples_purge: broadcast::Receiver<AddrTuple>,
) {
let mut tuples: HashMap<AddrTuple, Sender<Bytes>> = HashMap::new();
loop {
let mut buf = BytesMut::with_capacity(MAX_PACKET_LEN);
buf.resize(MAX_PACKET_LEN, 0);
tokio::select! {
buf = outgoing.recv() => {
let buf = buf.unwrap();
tun_w.write_all(&buf).await.unwrap();
},
s = tun_r.read_buf(&mut buf) => {
s.unwrap();
size = tun.recv(&mut buf) => {
let size = size.unwrap();
buf.truncate(size);
let buf = buf.freeze();
if buf[0] >> 4 != 4 {
// not an IPv4 packet
continue;
}
let (ip_packet, tcp_packet) = parse_ipv4_packet(&buf);
let local_addr = SocketAddrV4::new(ip_packet.get_destination(), tcp_packet.get_destination());
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);
let sender;
{
let tuples = shared.tuples.read().unwrap();
sender = tuples.get(&tuple).cloned();
}
if let Some(c) = sender {
if let Some(c) = tuples.get(&tuple) {
c.send(buf).await.unwrap();
continue;
} else {
trace!("Cache miss, checking the shared tuples table for connection");
let sender;
{
let tuples = shared.tuples.read().unwrap();
sender = tuples.get(&tuple).cloned();
}
if let Some(c) = sender {
trace!("Storing connection information into local tuples");
tuples.insert(tuple, c.clone());
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(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());
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());
tokio::spawn(sock.accept());
} else {
trace!("Bad TCP SYN packet from {}, sending RST", remote_addr);
@@ -403,7 +438,7 @@ impl Stack {
tcp::TcpFlags::RST,
None,
);
shared.outgoing.try_send(buf).unwrap();
shared.tun[0].try_send(&buf).unwrap();
}
} else if (tcp_packet.get_flags() & tcp::TcpFlags::RST) == 0 {
info!("Unknown TCP packet from {}, sending RST", remote_addr);
@@ -415,8 +450,13 @@ impl Stack {
tcp::TcpFlags::RST,
None,
);
shared.outgoing.try_send(buf).unwrap();
shared.tun[0].try_send(&buf).unwrap();
}
},
tuple = tuples_purge.recv() => {
let tuple = tuple.unwrap();
tuples.remove(&tuple);
trace!("Removed cached tuple");
}
}
}

View File

@@ -1,4 +1,6 @@
use bytes::{Bytes, BytesMut};
use internet_checksum::Checksum;
use pnet::packet::Packet;
use pnet::packet::{ip, ipv4, tcp};
use std::convert::TryInto;
use std::net::SocketAddrV4;
@@ -16,8 +18,8 @@ pub fn build_tcp_packet(
payload: Option<&[u8]>,
) -> Bytes {
let wscale = (flags & tcp::TcpFlags::SYN) != 0;
let tcp_total_len = TCP_HEADER_LEN + if wscale {4} else {0} // nop + wscale
+ payload.map_or(0, |payload| payload.len());
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 = IPV4_HEADER_LEN + tcp_total_len;
let mut buf = BytesMut::with_capacity(total_len);
buf.resize(total_len, 0);
@@ -35,7 +37,9 @@ pub fn build_tcp_packet(
v4.set_destination(*remote_addr.ip());
v4.set_total_length(total_len.try_into().unwrap());
v4.set_flags(ipv4::Ipv4Flags::DontFragment);
v4.set_checksum(ipv4::checksum(&v4.to_immutable()));
let mut cksm = Checksum::new();
cksm.add_bytes(v4.packet());
v4.set_checksum(u16::from_be_bytes(cksm.checksum()));
let mut tcp = tcp::MutableTcpPacket::new(&mut tcp_buf).unwrap();
tcp.set_window(0xffff);
@@ -54,11 +58,17 @@ pub fn build_tcp_packet(
tcp.set_payload(payload);
}
let checksum = tcp::ipv4_checksum(&tcp.to_immutable(), local_addr.ip(), remote_addr.ip());
tcp.set_checksum(checksum);
let mut cksm = Checksum::new();
cksm.add_bytes(&local_addr.ip().octets());
cksm.add_bytes(&remote_addr.ip().octets());
let ip::IpNextHeaderProtocol(tcp_protocol) = ip::IpNextHeaderProtocols::Tcp;
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);
cksm.add_bytes(tcp.packet());
tcp.set_checksum(u16::from_be_bytes(cksm.checksum()));
v4_buf.unsplit(tcp_buf);
v4_buf.freeze()
}
@@ -68,3 +78,61 @@ pub fn parse_ipv4_packet(buf: &Bytes) -> (ipv4::Ipv4Packet, tcp::TcpPacket) {
(v4, tcp)
}
#[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),
)
});
}
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 73 KiB

After

Width:  |  Height:  |  Size: 82 KiB

View File

@@ -1,20 +1,21 @@
[package]
name = "phantun"
version = "0.1.0"
version = "0.1.1"
edition = "2018"
authors = ["Datong Sun <dndx@idndx.com>"]
license = "MIT OR Apache-2.0"
repository = "https://github.com/dndx/phantun"
readme = "README.md"
description = """
Turns transforms UDP stream into (fake) TCP streams that can go through
Layer 4 firewalls.
Transforms UDP stream into (fake) TCP streams that can go through
Layer 3 & Layer 4 (NAPT) firewalls/NATs.
"""
[dependencies]
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"] }
fake-tcp = "0.1.1"
tokio = { version = "1.12.0", features = ["full"] }
log = "0.4"
pretty_env_logger = "0.4.0"
dndx-fork-tokio-tun = "0.3.16"
num_cpus = "1.13.0"

View File

@@ -1,3 +1,5 @@
extern crate dndx_fork_tokio_tun as tokio_tun;
use clap::{App, Arg};
use fake_tcp::packet::MAX_PACKET_LEN;
use fake_tcp::{Socket, Stack};
@@ -70,10 +72,10 @@ async fn main() {
.up() // or set it up manually using `sudo ip link set <tun-name> up`.
.address("192.168.200.1".parse().unwrap())
.destination("192.168.200.2".parse().unwrap())
.try_build()
.try_build_mq(num_cpus::get())
.unwrap();
info!("Created TUN device {}", tun.name());
info!("Created TUN device {}", tun[0].name());
let udp_sock = Arc::new(new_udp_reuseport(local_addr));
let connections = Arc::new(RwLock::new(HashMap::<SocketAddrV4, Arc<Socket>>::new()));

View File

@@ -1,3 +1,5 @@
extern crate dndx_fork_tokio_tun as tokio_tun;
use clap::{App, Arg};
use fake_tcp::packet::MAX_PACKET_LEN;
use fake_tcp::Stack;
@@ -53,9 +55,11 @@ async fn main() {
.up() // or set it up manually using `sudo ip link set <tun-name> up`.
.address("192.168.201.1".parse().unwrap())
.destination("192.168.201.2".parse().unwrap())
.try_build()
.try_build_mq(num_cpus::get())
.unwrap();
info!("Created TUN device {}", tun[0].name());
//thread::sleep(time::Duration::from_secs(5));
let mut stack = Stack::new(tun);
stack.listen(local_port);