2023-03-22 22:19:00 +08:00
|
|
|
use crate::error::Error;
|
2022-08-01 14:36:58 +00:00
|
|
|
use crate::virtdevice::VirtualTunDevice;
|
2022-08-16 16:18:25 +02:00
|
|
|
use log::{error, info};
|
2021-09-02 11:30:23 +02:00
|
|
|
use mio::event::Event;
|
2022-08-01 14:36:58 +00:00
|
|
|
use mio::net::TcpStream;
|
2021-09-02 11:30:23 +02:00
|
|
|
use mio::unix::SourceFd;
|
2022-08-01 14:36:58 +00:00
|
|
|
use mio::{Events, Interest, Poll, Token};
|
2023-03-20 15:34:41 +01:00
|
|
|
use smoltcp::iface::{Config, Interface, SocketHandle, SocketSet};
|
2021-09-02 11:30:23 +02:00
|
|
|
use smoltcp::phy::{Device, Medium, RxToken, TunTapInterface, TxToken};
|
2023-03-20 17:56:54 +01:00
|
|
|
use smoltcp::socket::tcp;
|
2021-09-02 11:30:23 +02:00
|
|
|
use smoltcp::time::Instant;
|
2023-03-20 17:56:54 +01:00
|
|
|
use smoltcp::wire::{
|
|
|
|
IpAddress, IpCidr, Ipv4Address, Ipv4Packet, Ipv6Address, Ipv6Packet, TcpPacket, UdpPacket,
|
|
|
|
};
|
|
|
|
use std::collections::HashMap;
|
2022-08-01 14:36:58 +00:00
|
|
|
use std::convert::From;
|
2023-03-22 19:11:28 +01:00
|
|
|
use std::fmt::{Display, Formatter};
|
2022-08-01 14:36:58 +00:00
|
|
|
use std::io::{Read, Write};
|
2021-09-02 21:02:17 +02:00
|
|
|
use std::net::Shutdown::Both;
|
2022-08-01 14:36:58 +00:00
|
|
|
use std::net::{IpAddr, Shutdown, SocketAddr};
|
|
|
|
use std::os::unix::io::AsRawFd;
|
2023-03-23 16:31:33 +08:00
|
|
|
use std::rc::Rc;
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2023-03-22 19:11:28 +01:00
|
|
|
#[derive(Hash, Clone, Eq, PartialEq)]
|
|
|
|
pub enum DestinationHost {
|
|
|
|
Address(IpAddr),
|
|
|
|
Hostname(String),
|
|
|
|
}
|
|
|
|
|
|
|
|
impl ToString for DestinationHost {
|
|
|
|
fn to_string(&self) -> String {
|
|
|
|
match self {
|
|
|
|
DestinationHost::Address(addr) => addr.to_string(),
|
|
|
|
DestinationHost::Hostname(name) => name.clone(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Hash, Clone, Eq, PartialEq)]
|
|
|
|
pub(crate) struct Destination {
|
|
|
|
pub(crate) host: DestinationHost,
|
|
|
|
pub(crate) port: u16,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<Destination> for SocketAddr {
|
|
|
|
fn from(value: Destination) -> Self {
|
|
|
|
SocketAddr::new(
|
|
|
|
match value.host {
|
|
|
|
DestinationHost::Address(addr) => addr,
|
|
|
|
DestinationHost::Hostname(_) => {
|
|
|
|
panic!("Failed to convert hostname destination into socket address")
|
|
|
|
}
|
|
|
|
},
|
|
|
|
value.port,
|
|
|
|
)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl From<SocketAddr> for Destination {
|
|
|
|
fn from(addr: SocketAddr) -> Self {
|
|
|
|
Self {
|
|
|
|
host: DestinationHost::Address(addr.ip()),
|
|
|
|
port: addr.port(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Display for Destination {
|
|
|
|
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
|
|
|
|
write!(f, "{}:{}", self.host.to_string(), self.port)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Hash, Clone, Eq, PartialEq)]
|
|
|
|
pub(crate) struct Connection {
|
|
|
|
pub(crate) src: std::net::SocketAddr,
|
|
|
|
pub(crate) dst: Destination,
|
|
|
|
pub(crate) proto: u8,
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
2021-09-02 21:02:17 +02:00
|
|
|
impl std::fmt::Display for Connection {
|
|
|
|
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
|
|
|
|
write!(f, "{} -> {}", self.src, self.dst)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-02 11:30:23 +02:00
|
|
|
#[derive(Eq, PartialEq, Debug)]
|
|
|
|
pub(crate) enum IncomingDirection {
|
|
|
|
FromServer,
|
2022-08-01 14:36:58 +00:00
|
|
|
FromClient,
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[derive(Eq, PartialEq, Debug)]
|
|
|
|
pub(crate) enum OutgoingDirection {
|
|
|
|
ToServer,
|
2022-08-01 14:36:58 +00:00
|
|
|
ToClient,
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
#[allow(dead_code)]
|
|
|
|
pub(crate) enum ConnectionEvent<'a> {
|
|
|
|
NewConnection(&'a Connection),
|
2022-08-01 14:36:58 +00:00
|
|
|
ConnectionClosed(&'a Connection),
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) struct DataEvent<'a, T> {
|
|
|
|
pub(crate) direction: T,
|
2022-08-01 14:36:58 +00:00
|
|
|
pub(crate) buffer: &'a [u8],
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) type IncomingDataEvent<'a> = DataEvent<'a, IncomingDirection>;
|
|
|
|
pub(crate) type OutgoingDataEvent<'a> = DataEvent<'a, OutgoingDirection>;
|
|
|
|
|
2022-08-01 14:36:58 +00:00
|
|
|
fn get_transport_info(
|
|
|
|
proto: u8,
|
|
|
|
transport_offset: usize,
|
|
|
|
packet: &[u8],
|
|
|
|
) -> Option<((u16, u16), bool, usize, usize)> {
|
2021-09-02 11:30:23 +02:00
|
|
|
if proto == smoltcp::wire::IpProtocol::Udp.into() {
|
|
|
|
match UdpPacket::new_checked(packet) {
|
2022-08-01 14:36:58 +00:00
|
|
|
Ok(result) => Some((
|
|
|
|
(result.src_port(), result.dst_port()),
|
|
|
|
false,
|
|
|
|
transport_offset + 8,
|
|
|
|
packet.len() - 8,
|
|
|
|
)),
|
|
|
|
Err(_) => None,
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
} else if proto == smoltcp::wire::IpProtocol::Tcp.into() {
|
|
|
|
match TcpPacket::new_checked(packet) {
|
2022-08-01 14:36:58 +00:00
|
|
|
Ok(result) => Some((
|
|
|
|
(result.src_port(), result.dst_port()),
|
|
|
|
result.syn() && !result.ack(),
|
|
|
|
transport_offset + result.header_len() as usize,
|
|
|
|
packet.len(),
|
|
|
|
)),
|
|
|
|
Err(_) => None,
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
2022-08-01 14:36:58 +00:00
|
|
|
} else {
|
2021-09-02 11:30:23 +02:00
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn connection_tuple(frame: &[u8]) -> Option<(Connection, bool, usize, usize)> {
|
2022-08-01 14:36:58 +00:00
|
|
|
if let Ok(packet) = Ipv4Packet::new_checked(frame) {
|
2023-03-20 15:34:41 +01:00
|
|
|
let proto: u8 = packet.next_header().into();
|
2022-08-01 14:36:58 +00:00
|
|
|
|
|
|
|
let mut a: [u8; 4] = Default::default();
|
|
|
|
a.copy_from_slice(packet.src_addr().as_bytes());
|
|
|
|
let src_addr = IpAddr::from(a);
|
|
|
|
a.copy_from_slice(packet.dst_addr().as_bytes());
|
|
|
|
let dst_addr = IpAddr::from(a);
|
|
|
|
|
|
|
|
if let Some((ports, first_packet, payload_offset, payload_size)) = get_transport_info(
|
|
|
|
proto,
|
|
|
|
packet.header_len().into(),
|
|
|
|
&frame[packet.header_len().into()..],
|
|
|
|
) {
|
|
|
|
let connection = Connection {
|
|
|
|
src: SocketAddr::new(src_addr, ports.0),
|
2023-03-22 19:11:28 +01:00
|
|
|
dst: SocketAddr::new(dst_addr, ports.1).into(),
|
2022-08-01 14:36:58 +00:00
|
|
|
proto,
|
|
|
|
};
|
|
|
|
return Some((connection, first_packet, payload_offset, payload_size));
|
|
|
|
} else {
|
|
|
|
return None;
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
match Ipv6Packet::new_checked(frame) {
|
|
|
|
Ok(packet) => {
|
|
|
|
// TODO: Support extension headers.
|
2022-08-01 14:36:58 +00:00
|
|
|
let proto: u8 = packet.next_header().into();
|
2021-09-02 11:30:23 +02:00
|
|
|
|
|
|
|
let mut a: [u8; 16] = Default::default();
|
|
|
|
a.copy_from_slice(packet.src_addr().as_bytes());
|
|
|
|
let src_addr = IpAddr::from(a);
|
|
|
|
a.copy_from_slice(packet.dst_addr().as_bytes());
|
|
|
|
let dst_addr = IpAddr::from(a);
|
|
|
|
|
2022-08-01 14:36:58 +00:00
|
|
|
if let Some((ports, first_packet, payload_offset, payload_size)) =
|
|
|
|
get_transport_info(proto, packet.header_len(), &frame[packet.header_len()..])
|
|
|
|
{
|
2021-09-02 11:30:23 +02:00
|
|
|
let connection = Connection {
|
|
|
|
src: SocketAddr::new(src_addr, ports.0),
|
2023-03-22 19:11:28 +01:00
|
|
|
dst: SocketAddr::new(dst_addr, ports.1).into(),
|
2022-08-01 14:36:58 +00:00
|
|
|
proto,
|
2021-09-02 11:30:23 +02:00
|
|
|
};
|
|
|
|
Some((connection, first_packet, payload_offset, payload_size))
|
|
|
|
} else {
|
|
|
|
None
|
|
|
|
}
|
|
|
|
}
|
2022-08-01 14:36:58 +00:00
|
|
|
_ => None,
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
struct ConnectionState {
|
|
|
|
smoltcp_handle: SocketHandle,
|
|
|
|
mio_stream: TcpStream,
|
2021-09-02 22:36:47 +02:00
|
|
|
token: Token,
|
2023-03-23 16:31:33 +08:00
|
|
|
handler: Box<dyn TcpProxy>,
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
2023-03-22 13:18:07 +01:00
|
|
|
#[derive(Default, Clone, Debug)]
|
2023-03-22 01:02:27 +01:00
|
|
|
pub struct Credentials {
|
|
|
|
pub(crate) username: Vec<u8>,
|
|
|
|
pub(crate) password: Vec<u8>,
|
|
|
|
}
|
|
|
|
|
|
|
|
impl Credentials {
|
2023-03-22 12:18:41 +01:00
|
|
|
pub fn new(username: &str, password: &str) -> Self {
|
2023-03-22 01:02:27 +01:00
|
|
|
Self {
|
|
|
|
username: username.as_bytes().to_vec(),
|
|
|
|
password: password.as_bytes().to_vec(),
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2021-09-02 11:30:23 +02:00
|
|
|
pub(crate) trait TcpProxy {
|
2023-03-22 22:19:00 +08:00
|
|
|
fn push_data(&mut self, event: IncomingDataEvent<'_>) -> Result<(), Error>;
|
2021-09-02 11:30:23 +02:00
|
|
|
fn consume_data(&mut self, dir: OutgoingDirection, size: usize);
|
|
|
|
fn peek_data(&mut self, dir: OutgoingDirection) -> OutgoingDataEvent;
|
2021-09-02 21:02:17 +02:00
|
|
|
fn connection_established(&self) -> bool;
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
pub(crate) trait ConnectionManager {
|
|
|
|
fn handles_connection(&self, connection: &Connection) -> bool;
|
2023-03-22 01:02:27 +01:00
|
|
|
fn new_connection(
|
|
|
|
&self,
|
|
|
|
connection: &Connection,
|
2023-03-23 16:31:33 +08:00
|
|
|
manager: Rc<dyn ConnectionManager>,
|
|
|
|
) -> Option<Box<dyn TcpProxy>>;
|
2023-03-21 01:08:44 +01:00
|
|
|
fn close_connection(&self, connection: &Connection);
|
2021-09-02 11:30:23 +02:00
|
|
|
fn get_server(&self) -> SocketAddr;
|
2023-03-22 12:18:41 +01:00
|
|
|
fn get_credentials(&self) -> &Option<Credentials>;
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
2023-03-23 16:31:33 +08:00
|
|
|
const TCP_TOKEN: Token = Token(0);
|
|
|
|
const UDP_TOKEN: Token = Token(1);
|
|
|
|
|
2021-09-02 11:30:23 +02:00
|
|
|
pub(crate) struct TunToProxy<'a> {
|
|
|
|
tun: TunTapInterface,
|
|
|
|
poll: Poll,
|
2023-03-20 15:34:41 +01:00
|
|
|
iface: Interface,
|
2021-09-02 11:30:23 +02:00
|
|
|
connections: HashMap<Connection, ConnectionState>,
|
2023-03-23 16:31:33 +08:00
|
|
|
connection_managers: Vec<Rc<dyn ConnectionManager>>,
|
2021-09-02 11:30:23 +02:00
|
|
|
next_token: usize,
|
|
|
|
token_to_connection: HashMap<Token, Connection>,
|
2023-03-20 15:34:41 +01:00
|
|
|
sockets: SocketSet<'a>,
|
|
|
|
device: VirtualTunDevice,
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
impl<'a> TunToProxy<'a> {
|
|
|
|
pub(crate) fn new(interface: &str) -> Self {
|
|
|
|
let tun = TunTapInterface::new(interface, Medium::Ip).unwrap();
|
|
|
|
let poll = Poll::new().unwrap();
|
2022-08-01 14:36:58 +00:00
|
|
|
poll.registry()
|
|
|
|
.register(
|
|
|
|
&mut SourceFd(&tun.as_raw_fd()),
|
2023-03-23 16:31:33 +08:00
|
|
|
TCP_TOKEN,
|
2022-08-01 14:36:58 +00:00
|
|
|
Interest::READABLE,
|
|
|
|
)
|
|
|
|
.unwrap();
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2023-03-20 15:34:41 +01:00
|
|
|
let config = Config::new();
|
|
|
|
let mut virt = VirtualTunDevice::new(tun.capabilities());
|
|
|
|
let mut iface = Interface::new(config, &mut virt);
|
|
|
|
iface.update_ip_addrs(|ip_addrs| {
|
2023-03-20 17:56:54 +01:00
|
|
|
ip_addrs
|
|
|
|
.push(IpCidr::new(IpAddress::v4(0, 0, 0, 1), 0))
|
|
|
|
.unwrap();
|
|
|
|
ip_addrs
|
|
|
|
.push(IpCidr::new(IpAddress::v6(0, 0, 0, 0, 0, 0, 0, 1), 0))
|
|
|
|
.unwrap()
|
2023-03-20 15:34:41 +01:00
|
|
|
});
|
2023-03-20 17:56:54 +01:00
|
|
|
iface
|
|
|
|
.routes_mut()
|
|
|
|
.add_default_ipv4_route(Ipv4Address::new(0, 0, 0, 1))
|
|
|
|
.unwrap();
|
|
|
|
iface
|
|
|
|
.routes_mut()
|
|
|
|
.add_default_ipv6_route(Ipv6Address::new(0, 0, 0, 0, 0, 0, 0, 1))
|
|
|
|
.unwrap();
|
2023-03-20 15:34:41 +01:00
|
|
|
iface.set_any_ip(true);
|
2021-09-02 11:30:23 +02:00
|
|
|
|
|
|
|
Self {
|
|
|
|
tun,
|
|
|
|
poll,
|
|
|
|
iface,
|
|
|
|
connections: Default::default(),
|
|
|
|
next_token: 2,
|
|
|
|
token_to_connection: Default::default(),
|
2022-08-01 14:36:58 +00:00
|
|
|
connection_managers: Default::default(),
|
2023-03-20 15:34:41 +01:00
|
|
|
sockets: SocketSet::new([]),
|
|
|
|
device: virt,
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-03-23 16:31:33 +08:00
|
|
|
pub(crate) fn add_connection_manager(&mut self, manager: Rc<dyn ConnectionManager>) {
|
2021-09-02 11:30:23 +02:00
|
|
|
self.connection_managers.push(manager);
|
|
|
|
}
|
|
|
|
|
|
|
|
fn expect_smoltcp_send(&mut self) {
|
2023-03-20 17:56:54 +01:00
|
|
|
self.iface
|
|
|
|
.poll(Instant::now(), &mut self.device, &mut self.sockets);
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2023-03-20 15:34:41 +01:00
|
|
|
while let Some(vec) = self.device.exfiltrate_packet() {
|
2021-09-02 11:30:23 +02:00
|
|
|
let slice = vec.as_slice();
|
|
|
|
|
|
|
|
// TODO: Actual write. Replace.
|
2022-08-01 14:36:58 +00:00
|
|
|
self.tun
|
2023-03-20 15:34:41 +01:00
|
|
|
.transmit(Instant::now())
|
2022-08-01 14:36:58 +00:00
|
|
|
.unwrap()
|
2023-03-20 15:34:41 +01:00
|
|
|
.consume(slice.len(), |buf| {
|
2022-08-01 14:36:58 +00:00
|
|
|
buf[..].clone_from_slice(slice);
|
2023-03-20 15:34:41 +01:00
|
|
|
});
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn remove_connection(&mut self, connection: &Connection) {
|
|
|
|
let mut connection_state = self.connections.remove(connection).unwrap();
|
|
|
|
self.token_to_connection.remove(&connection_state.token);
|
2022-08-01 14:36:58 +00:00
|
|
|
self.poll
|
|
|
|
.registry()
|
|
|
|
.deregister(&mut connection_state.mio_stream)
|
|
|
|
.unwrap();
|
2022-08-16 16:18:25 +02:00
|
|
|
info!("CLOSE {}", connection);
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
2023-03-23 16:31:33 +08:00
|
|
|
fn get_connection_manager(&self, connection: &Connection) -> Option<Rc<dyn ConnectionManager>> {
|
2021-09-02 11:30:23 +02:00
|
|
|
for manager in self.connection_managers.iter() {
|
|
|
|
if manager.handles_connection(connection) {
|
2023-03-22 01:02:27 +01:00
|
|
|
return Some(manager.clone());
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
None
|
|
|
|
}
|
|
|
|
|
|
|
|
fn tunsocket_read_and_forward(&mut self, connection: &Connection) {
|
2022-08-01 14:36:58 +00:00
|
|
|
if let Some(state) = self.connections.get_mut(connection) {
|
2021-09-02 11:30:23 +02:00
|
|
|
let closed = {
|
2023-03-20 15:34:41 +01:00
|
|
|
// let socket = self.iface.get_socket::<TcpSocket>(state.smoltcp_handle);
|
|
|
|
let socket = self.sockets.get_mut::<tcp::Socket>(state.smoltcp_handle);
|
2021-09-02 21:02:17 +02:00
|
|
|
let mut error = Ok(());
|
|
|
|
while socket.can_recv() && error.is_ok() {
|
2022-08-01 14:36:58 +00:00
|
|
|
socket
|
|
|
|
.recv(|data| {
|
|
|
|
let event = IncomingDataEvent {
|
|
|
|
direction: IncomingDirection::FromClient,
|
|
|
|
buffer: data,
|
|
|
|
};
|
|
|
|
error = state.handler.push_data(event);
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2022-08-01 14:36:58 +00:00
|
|
|
(data.len(), ())
|
|
|
|
})
|
|
|
|
.unwrap();
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
|
2022-08-01 14:36:58 +00:00
|
|
|
match error {
|
2023-03-20 15:34:41 +01:00
|
|
|
Ok(_) => socket.state() == smoltcp::socket::tcp::State::CloseWait,
|
2022-08-01 14:36:58 +00:00
|
|
|
Err(e) => {
|
2023-03-22 22:19:00 +08:00
|
|
|
log::error!("{e}");
|
2022-08-01 14:36:58 +00:00
|
|
|
true
|
|
|
|
}
|
2021-09-02 21:02:17 +02:00
|
|
|
}
|
2021-09-02 11:30:23 +02:00
|
|
|
};
|
|
|
|
|
|
|
|
if closed {
|
2022-08-01 14:36:58 +00:00
|
|
|
let connection_state = self.connections.get_mut(connection).unwrap();
|
|
|
|
connection_state
|
|
|
|
.mio_stream
|
|
|
|
.shutdown(Shutdown::Both)
|
|
|
|
.unwrap();
|
|
|
|
self.remove_connection(connection);
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn receive_tun(&mut self, frame: &mut [u8]) {
|
2022-08-01 14:36:58 +00:00
|
|
|
if let Some((connection, first_packet, _payload_offset, _payload_size)) =
|
|
|
|
connection_tuple(frame)
|
|
|
|
{
|
2021-09-02 11:30:23 +02:00
|
|
|
if connection.proto == smoltcp::wire::IpProtocol::Tcp.into() {
|
|
|
|
let cm = self.get_connection_manager(&connection);
|
2022-08-01 14:36:58 +00:00
|
|
|
if cm.is_none() {
|
2021-09-02 11:30:23 +02:00
|
|
|
return;
|
|
|
|
}
|
|
|
|
let server = cm.unwrap().get_server();
|
|
|
|
if first_packet {
|
2021-09-02 22:36:47 +02:00
|
|
|
for manager in self.connection_managers.iter_mut() {
|
2023-03-22 01:02:27 +01:00
|
|
|
if let Some(handler) = manager.new_connection(&connection, manager.clone())
|
|
|
|
{
|
2023-03-20 15:34:41 +01:00
|
|
|
let mut socket = smoltcp::socket::tcp::Socket::new(
|
|
|
|
smoltcp::socket::tcp::SocketBuffer::new(vec![0; 4096]),
|
|
|
|
smoltcp::socket::tcp::SocketBuffer::new(vec![0; 4096]),
|
2022-08-01 14:36:58 +00:00
|
|
|
);
|
2021-09-02 22:36:47 +02:00
|
|
|
socket.set_ack_delay(None);
|
2023-03-22 19:11:28 +01:00
|
|
|
let dst = connection.dst.clone();
|
|
|
|
socket
|
|
|
|
.listen(<Destination as Into<SocketAddr>>::into(dst))
|
|
|
|
.unwrap();
|
2023-03-20 15:34:41 +01:00
|
|
|
let handle = self.sockets.add(socket);
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2022-08-01 14:36:58 +00:00
|
|
|
let client = TcpStream::connect(server).unwrap();
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2021-09-02 22:36:47 +02:00
|
|
|
let token = Token(self.next_token);
|
|
|
|
self.next_token += 1;
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2021-09-02 22:36:47 +02:00
|
|
|
let mut state = ConnectionState {
|
|
|
|
smoltcp_handle: handle,
|
|
|
|
mio_stream: client,
|
|
|
|
token,
|
2022-08-01 14:36:58 +00:00
|
|
|
handler,
|
2021-09-02 22:36:47 +02:00
|
|
|
};
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2023-03-22 19:11:28 +01:00
|
|
|
self.token_to_connection.insert(token, connection.clone());
|
2022-08-01 14:36:58 +00:00
|
|
|
self.poll
|
|
|
|
.registry()
|
|
|
|
.register(
|
|
|
|
&mut state.mio_stream,
|
|
|
|
token,
|
|
|
|
Interest::READABLE | Interest::WRITABLE,
|
|
|
|
)
|
|
|
|
.unwrap();
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2023-03-22 19:11:28 +01:00
|
|
|
self.connections.insert(connection.clone(), state);
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2022-08-16 16:18:25 +02:00
|
|
|
info!("CONNECT {}", connection,);
|
2021-09-02 11:30:23 +02:00
|
|
|
break;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
} else if !self.connections.contains_key(&connection) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
|
|
|
|
// Inject the packet to advance the smoltcp socket state
|
2023-03-20 15:34:41 +01:00
|
|
|
self.device.inject_packet(frame);
|
2021-09-02 11:30:23 +02:00
|
|
|
|
|
|
|
// Having advanced the socket state, we expect the socket to ACK
|
|
|
|
// Exfiltrate the response packets generated by the socket and inject them
|
|
|
|
// into the tunnel interface.
|
|
|
|
self.expect_smoltcp_send();
|
|
|
|
|
|
|
|
// Read from the smoltcp socket and push the data to the connection handler.
|
|
|
|
self.tunsocket_read_and_forward(&connection);
|
|
|
|
|
|
|
|
// The connection handler builds up the connection or encapsulates the data.
|
|
|
|
// Therefore, we now expect it to write data to the server.
|
|
|
|
self.write_to_server(&connection);
|
2022-08-01 14:36:58 +00:00
|
|
|
} else if connection.proto == smoltcp::wire::IpProtocol::Udp.into() {
|
2022-08-17 00:04:08 +02:00
|
|
|
// UDP is not yet supported
|
|
|
|
/*if _payload_offset > frame.len() || _payload_offset + _payload_offset > frame.len() {
|
2021-09-02 11:30:23 +02:00
|
|
|
return;
|
|
|
|
}
|
2022-08-17 00:04:08 +02:00
|
|
|
let payload = &frame[_payload_offset.._payload_offset + _payload_size];
|
|
|
|
self.virtual_dns.add_query(payload);*/
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn write_to_server(&mut self, connection: &Connection) {
|
2022-08-01 14:36:58 +00:00
|
|
|
if let Some(state) = self.connections.get_mut(connection) {
|
2021-09-02 22:36:47 +02:00
|
|
|
let event = state.handler.peek_data(OutgoingDirection::ToServer);
|
2022-08-01 14:36:58 +00:00
|
|
|
if event.buffer.is_empty() {
|
2021-09-02 11:30:23 +02:00
|
|
|
return;
|
|
|
|
}
|
2021-09-02 22:36:47 +02:00
|
|
|
let result = state.mio_stream.write(event.buffer);
|
2021-09-02 11:30:23 +02:00
|
|
|
match result {
|
|
|
|
Ok(consumed) => {
|
2022-08-01 14:36:58 +00:00
|
|
|
state
|
|
|
|
.handler
|
|
|
|
.consume_data(OutgoingDirection::ToServer, consumed);
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
2022-08-01 14:36:58 +00:00
|
|
|
Err(error) if error.kind() != std::io::ErrorKind::WouldBlock => {
|
2021-09-02 11:30:23 +02:00
|
|
|
panic!("Error: {:?}", error);
|
|
|
|
}
|
|
|
|
_ => {
|
|
|
|
// println!("{:?}", result);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn write_to_client(&mut self, connection: &Connection) {
|
2022-08-01 14:36:58 +00:00
|
|
|
if let Some(state) = self.connections.get_mut(connection) {
|
2021-09-02 22:36:47 +02:00
|
|
|
let event = state.handler.peek_data(OutgoingDirection::ToClient);
|
2023-03-20 15:34:41 +01:00
|
|
|
let socket = self.sockets.get_mut::<tcp::Socket>(state.smoltcp_handle);
|
2021-09-02 11:30:23 +02:00
|
|
|
if socket.may_send() {
|
|
|
|
let consumed = socket.send_slice(event.buffer).unwrap();
|
2022-08-01 14:36:58 +00:00
|
|
|
state
|
|
|
|
.handler
|
|
|
|
.consume_data(OutgoingDirection::ToClient, consumed);
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn tun_event(&mut self, event: &Event) {
|
|
|
|
if event.is_readable() {
|
2023-03-20 15:34:41 +01:00
|
|
|
while let Some((rx_token, _)) = self.tun.receive(Instant::now()) {
|
|
|
|
rx_token.consume(|frame| {
|
2021-09-02 11:30:23 +02:00
|
|
|
self.receive_tun(frame);
|
2023-03-20 15:34:41 +01:00
|
|
|
});
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
fn mio_socket_event(&mut self, event: &Event) {
|
2022-12-10 21:29:57 +01:00
|
|
|
if let Some(conn_ref) = self.token_to_connection.get(&event.token()) {
|
2023-03-22 19:11:28 +01:00
|
|
|
let connection = conn_ref.clone();
|
2022-12-10 21:29:57 +01:00
|
|
|
if event.is_readable() {
|
|
|
|
{
|
|
|
|
let state = self.connections.get_mut(&connection).unwrap();
|
|
|
|
|
|
|
|
let mut buf = [0u8; 4096];
|
|
|
|
let read_result = state.mio_stream.read(&mut buf);
|
2023-03-19 14:27:01 +08:00
|
|
|
let read = if let Ok(read_result) = read_result {
|
|
|
|
read_result
|
|
|
|
} else {
|
2022-12-10 21:29:57 +01:00
|
|
|
error!("READ from proxy: {}", read_result.as_ref().err().unwrap());
|
|
|
|
0
|
|
|
|
};
|
|
|
|
|
|
|
|
if read == 0 {
|
|
|
|
{
|
2023-03-20 15:34:41 +01:00
|
|
|
let socket = self.sockets.get_mut::<tcp::Socket>(
|
2022-12-10 21:29:57 +01:00
|
|
|
self.connections.get(&connection).unwrap().smoltcp_handle,
|
|
|
|
);
|
|
|
|
socket.close();
|
|
|
|
}
|
|
|
|
self.expect_smoltcp_send();
|
|
|
|
self.remove_connection(&connection.clone());
|
|
|
|
return;
|
2021-09-02 21:02:17 +02:00
|
|
|
}
|
|
|
|
|
2022-12-10 21:29:57 +01:00
|
|
|
let event = IncomingDataEvent {
|
|
|
|
direction: IncomingDirection::FromServer,
|
|
|
|
buffer: &buf[0..read],
|
|
|
|
};
|
|
|
|
if let Err(error) = state.handler.push_data(event) {
|
|
|
|
state.mio_stream.shutdown(Both).unwrap();
|
|
|
|
{
|
2023-03-20 15:34:41 +01:00
|
|
|
let socket = self.sockets.get_mut::<tcp::Socket>(
|
2022-12-10 21:29:57 +01:00
|
|
|
self.connections.get(&connection).unwrap().smoltcp_handle,
|
|
|
|
);
|
|
|
|
socket.close();
|
|
|
|
}
|
|
|
|
self.expect_smoltcp_send();
|
2023-03-22 22:19:00 +08:00
|
|
|
log::error! {"{error}"};
|
2022-12-10 21:29:57 +01:00
|
|
|
self.remove_connection(&connection.clone());
|
|
|
|
return;
|
2021-09-02 21:02:17 +02:00
|
|
|
}
|
|
|
|
}
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2022-12-10 21:29:57 +01:00
|
|
|
// We have read from the proxy server and pushed the data to the connection handler.
|
|
|
|
// Thus, expect data to be processed (e.g. decapsulated) and forwarded to the client.
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2022-12-10 21:29:57 +01:00
|
|
|
//self.expect_smoltcp_send();
|
|
|
|
self.write_to_client(&connection);
|
|
|
|
self.expect_smoltcp_send();
|
|
|
|
}
|
|
|
|
if event.is_writable() {
|
|
|
|
self.write_to_server(&connection);
|
|
|
|
}
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2022-08-01 14:36:58 +00:00
|
|
|
fn udp_event(&mut self, _event: &Event) {}
|
2021-09-02 11:30:23 +02:00
|
|
|
|
2023-03-23 16:31:33 +08:00
|
|
|
pub(crate) fn run(&mut self) -> Result<(), Error> {
|
2021-09-02 11:30:23 +02:00
|
|
|
let mut events = Events::with_capacity(1024);
|
|
|
|
|
|
|
|
loop {
|
2023-03-23 16:31:33 +08:00
|
|
|
self.poll.poll(&mut events, None)?;
|
2021-09-02 11:30:23 +02:00
|
|
|
for event in events.iter() {
|
2023-03-23 16:31:33 +08:00
|
|
|
match event.token() {
|
|
|
|
TCP_TOKEN => self.tun_event(event),
|
|
|
|
UDP_TOKEN => self.udp_event(event),
|
|
|
|
_ => self.mio_socket_event(event),
|
2021-09-02 11:30:23 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
2022-08-01 14:36:58 +00:00
|
|
|
}
|