├── .gitignore ├── Cargo.toml ├── src ├── linux.rs ├── commands.rs ├── options.rs ├── firewall.rs ├── main.rs ├── command.rs ├── firewall │ ├── nat.rs │ └── tproxy.rs ├── client.rs └── network.rs ├── .vscode └── settings.json ├── README.md ├── Cargo.lock └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "sshuttle_rust" 3 | version = "0.1.0" 4 | edition = "2021" 5 | 6 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 7 | 8 | [dependencies] 9 | nix = { features = ["socket", "net"], git = "https://github.com/nix-rust/nix" } 10 | clap = { version = "3.2.12", features = ["derive"] } 11 | regex = "1" 12 | dns-lookup = "1.0.8" 13 | log = "0.4.0" 14 | env_logger = "0.9.0" 15 | tokio = { version = "1.20.0", features = ["full"] } 16 | fast-socks5 = "0.8.0" 17 | ctrlc = "3.2.2" 18 | libc = "0.2.126" 19 | thiserror = "1.0.0" 20 | futures = "0.3.21" 21 | -------------------------------------------------------------------------------- /src/linux.rs: -------------------------------------------------------------------------------- 1 | use crate::{command::Line, commands::Commands, network::Family}; 2 | 3 | impl Commands { 4 | pub fn ipt(&mut self, family: Family, table: &str, extra: &[&str]) { 5 | let cmd = match family { 6 | Family::Ipv4 => "iptables", 7 | Family::Ipv6 => "ip6tables", 8 | } 9 | .to_string(); 10 | 11 | let mut args = vec!["-w", "-t", table]; 12 | args.extend(extra); 13 | 14 | self.push(Line::new(cmd, args)); 15 | } 16 | 17 | pub fn ipt_ignore_errors(&mut self, family: Family, table: &str, extra: &[&str]) { 18 | let cmd = match family { 19 | Family::Ipv4 => "iptables", 20 | Family::Ipv6 => "ip6tables", 21 | } 22 | .to_string(); 23 | 24 | let mut args = vec!["-w", "-t", table]; 25 | args.extend(extra); 26 | 27 | self.push_ignore_errors(Line::new(cmd, args)); 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /.vscode/settings.json: -------------------------------------------------------------------------------- 1 | { 2 | "cSpell.words": [ 3 | "addrinfo", 4 | "addrtype", 5 | "cmsg", 6 | "cmsgs", 7 | "dport", 8 | "Errno", 9 | "familys", 10 | "fconfig", 11 | "fport", 12 | "getaddrinfo", 13 | "getsockopt", 14 | "INET", 15 | "IPPROTO", 16 | "IPPROTO_IP", 17 | "libc", 18 | "lport", 19 | "noncommercially", 20 | "PREROUTING", 21 | "recvmesg", 22 | "recvmsg", 23 | "RECVORIGDSTADDR", 24 | "reprs", 25 | "rustfmt", 26 | "setsocketopt", 27 | "setsockopt", 28 | "sockaddr", 29 | "sockopt", 30 | "socksstream", 31 | "socktype", 32 | "sshuttle", 33 | "Stdio", 34 | "subnetport", 35 | "SWIDTHS", 36 | "tcpstream", 37 | "thiserror", 38 | "tmark", 39 | "TPROXY", 40 | "transproxy" 41 | ] 42 | } -------------------------------------------------------------------------------- /src/commands.rs: -------------------------------------------------------------------------------- 1 | use std::slice::Iter; 2 | 3 | use crate::command::{Error, ErrorKind, Line}; 4 | 5 | #[derive(Debug)] 6 | pub struct Command { 7 | pub line: Line, 8 | pub ignore_errors: bool, 9 | } 10 | 11 | #[derive(Debug, Default)] 12 | pub struct Commands(Vec); 13 | 14 | impl Commands { 15 | pub fn new() -> Self { 16 | Self::default() 17 | } 18 | 19 | pub async fn run_all(&self) -> Result<(), Error> { 20 | for cmd in &self.0 { 21 | if let Err(err) = cmd.line.run().await { 22 | if let ErrorKind::BadExitCode { .. } = err.kind { 23 | if cmd.ignore_errors { 24 | log::info!("Ignoring error: {}", err); 25 | } else { 26 | return Err(err); 27 | } 28 | } else { 29 | return Err(err); 30 | } 31 | } 32 | } 33 | Ok(()) 34 | } 35 | 36 | #[allow(dead_code)] 37 | pub fn len(&self) -> usize { 38 | self.0.len() 39 | } 40 | 41 | #[allow(dead_code)] 42 | pub fn iter(&self) -> Iter { 43 | self.0.iter() 44 | } 45 | 46 | pub fn push(&mut self, line: Line) { 47 | self.0.push(Command { 48 | line, 49 | ignore_errors: false, 50 | }); 51 | } 52 | 53 | pub fn push_ignore_errors(&mut self, line: Line) { 54 | self.0.push(Command { 55 | line, 56 | ignore_errors: true, 57 | }); 58 | } 59 | } 60 | 61 | // impl Index for Commands { 62 | // type Output = Command; 63 | // fn index(&self, index: usize) -> &Command { 64 | // &self.0[index] 65 | // } 66 | // } 67 | -------------------------------------------------------------------------------- /src/options.rs: -------------------------------------------------------------------------------- 1 | use clap::Parser; 2 | use std::{error::Error, fmt::Display, net::SocketAddr}; 3 | 4 | use crate::network::Subnets; 5 | 6 | #[derive(Debug)] 7 | pub struct ParseError { 8 | message: String, 9 | } 10 | 11 | impl Display for ParseError { 12 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 13 | write!(f, "{}", self.message) 14 | } 15 | } 16 | 17 | // impl Debug for ParseError {} 18 | impl Error for ParseError {} 19 | 20 | #[derive(Clone, clap::ArgEnum, Debug, Copy)] 21 | pub enum FirewallType { 22 | Nat, 23 | #[clap(name = "tproxy")] 24 | TProxy, 25 | } 26 | 27 | /// Simple program to greet a person 28 | #[derive(Parser, Debug)] 29 | #[clap(author, version, about, long_about = None)] 30 | pub struct Options { 31 | /// ssh hostname (and optional username and password) of remote server. 32 | /// 33 | /// [USERNAME[:PASSWORD]@]ADDR[:PORT] 34 | #[clap(short, long, value_parser)] 35 | pub remote: Option, 36 | 37 | /// Transproxy to this ip address and port number. 38 | /// 39 | /// Maybe used twice, once for IPv4 and once for IPv6. 40 | #[clap(short, long, value_parser)] 41 | pub listen: Vec, 42 | 43 | /// Capture and forward traffic to these subnets (whitespace separated). 44 | /// 45 | /// IP/MASK[:PORT[-PORT]]... 46 | pub include: Vec, 47 | 48 | /// Exclude this subnet (can be used more than once). 49 | #[clap(short, long)] 50 | pub exclude: Vec, 51 | 52 | /// Connect to this socks server. 53 | /// 54 | /// If --remote is used then this value will be passed to ssh using -D. 55 | #[clap(short, long, default_value = "127.0.0.1:1080")] 56 | pub socks: SocketAddr, 57 | 58 | /// What kind of firewall to use. 59 | #[clap(short, long, arg_enum, default_value_t = FirewallType::Nat)] 60 | pub firewall: FirewallType, 61 | } 62 | 63 | pub fn parse() -> Options { 64 | Options::parse() 65 | } 66 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # sshuttle-rust 2 | 3 | ## About 4 | 5 | sshuttle-rust is a a rewrite of sshuttle, with the following features: 6 | 7 | * It is written in rust, not Python. 8 | * It talks to ssh using the "ssh -D" socks support, as a result it does not require any additional code on server. 9 | * It should be considered alpha quality. While it works, there are many missing features. 10 | 11 | Features that are implemented: 12 | 13 | * IPv4 and IPv6. 14 | * TCP support. 15 | * socks5 support. 16 | * nat firewall support. 17 | * TPROXY firewall support. 18 | 19 | Missing features include, but not limited to: 20 | 21 | * Other firewalls, such as OSX support (should be easy to add, just not been a priority). 22 | * UDP support (see below). 23 | * DNS support (see below). 24 | * Daemon support. 25 | 26 | Known bugs: 27 | 28 | * After starting process, initial connections will be rejected because ssh hasn't started yet. 29 | * Some servers may support running remote programs, but might disallow -D port forwarding. 30 | * Shutdown of run_client code could be a bit cleaner. 31 | * Probably many others. 32 | 33 | ## Usage 34 | 35 | ```sh 36 | sudo RUST_LOG=trace SSH_AUTH_SOCK="$SSH_AUTH_SOCK" sshuttle_rust --remote user@host.example.org --listen 127.0.0.1:1021 --listen '[::1]:1022' 0.0.0.0/0:443 '[::/0]:443' 37 | ``` 38 | 39 | This will create a ssh connection to "use@host.example.org" using "-D" and forward all connections to port 443. By default ssh is configured with `-D 127.0.0.1:1080`, the socks address can be changed with the `--socks` option. 40 | 41 | If you omit the `--remote` option it will not start ssh, but try to connect to an existing socks server at the address given by the `--socks` option. 42 | 43 | Alternative, possibly better usage: 44 | 45 | ```sh 46 | ssh -D1080 -N user@host.example.org 47 | sudo RUST_LOG=trace SSH_AUTH_SOCK="$SSH_AUTH_SOCK" sshuttle_rust --socks 127.0.0.1:1080 --listen 127.0.0.1:1021 --listen '[::1]:1022' 0.0.0.0/0:443 '[::/0]:443' 48 | ``` 49 | 50 | ## UDP/DNS notes 51 | 52 | Unfortunately Socks5 support for UDP involves sending UDP packets to a specified UDP port on the server. 53 | Plus openssh does not have UDP support on its socks server, and does not allow forwarding of UDP packets. 54 | 55 | These limitations mean it is not practical to implement a UDP solution that forwards packets over UDP, so 56 | as I result this has not been implemented. 57 | 58 | In the future, if anybody wanted to write the code, we could: 59 | 60 | * Implement server side code, similar to the Python sshuttle. 61 | * Implement a UDP DNS proxy that forwards all DNS requests using TCP. 62 | -------------------------------------------------------------------------------- /src/firewall.rs: -------------------------------------------------------------------------------- 1 | use std::{net::SocketAddr, os::unix::prelude::AsRawFd}; 2 | 3 | use nix::{ 4 | errno::Errno, 5 | libc::{sockaddr, sockaddr_in, sockaddr_in6}, 6 | sys::socket::{ 7 | getsockopt, 8 | sockopt::{Ip6tOriginalDst, OriginalDst}, 9 | SockaddrIn, SockaddrIn6, SockaddrLike, 10 | }, 11 | }; 12 | use thiserror::Error; 13 | use tokio::net::{TcpListener, TcpStream, UdpSocket}; 14 | 15 | use crate::{ 16 | commands::Commands, 17 | network::{Family, SubnetsFamily, SubnetsV6}, 18 | network::{ListenerAddr, SubnetsV4}, 19 | }; 20 | 21 | pub mod nat; 22 | pub mod tproxy; 23 | 24 | #[derive(Error, Debug)] 25 | pub enum FirewallError { 26 | #[error("Errno error `{0}`")] 27 | Errno(#[from] Errno), 28 | 29 | #[error("IO Error `{0}`")] 30 | Io(#[from] std::io::Error), 31 | 32 | #[error("Not supported `{0}`")] 33 | NotSupported(String), 34 | 35 | #[error("Cannot get destination address")] 36 | CannotGetDstAddress, 37 | } 38 | 39 | fn get_dst_addr_sockopt(s: &TcpStream) -> Result { 40 | let addr = match s.local_addr()? { 41 | SocketAddr::V4(_) => { 42 | let a = getsockopt(s.as_raw_fd(), OriginalDst)?; 43 | raw_to_socket_addr_v4(a) 44 | } 45 | SocketAddr::V6(_) => { 46 | let a = getsockopt(s.as_raw_fd(), Ip6tOriginalDst)?; 47 | raw_to_socket_addr_v6(a) 48 | } 49 | }; 50 | addr.ok_or(FirewallError::CannotGetDstAddress) 51 | } 52 | 53 | fn raw_to_socket_addr_v4(a: sockaddr_in) -> Option { 54 | let a_ptr: *const sockaddr = std::ptr::addr_of!(a).cast(); 55 | let addr = unsafe { SockaddrIn::from_raw(a_ptr, None) }; 56 | addr.map(|a| SocketAddr::V4(a.into())) 57 | } 58 | 59 | fn raw_to_socket_addr_v6(a: sockaddr_in6) -> Option { 60 | let a_ptr: *const sockaddr = std::ptr::addr_of!(a).cast(); 61 | let addr = unsafe { SockaddrIn6::from_raw(a_ptr, None) }; 62 | addr.map(|a| SocketAddr::V6(a.into())) 63 | } 64 | 65 | pub trait Firewall { 66 | fn setup_tcp_listener(&self, _l: &TcpListener) -> Result<(), FirewallError> { 67 | Ok(()) 68 | } 69 | 70 | fn setup_udp_socket(&self, _l: &UdpSocket) -> Result<(), FirewallError> { 71 | Ok(()) 72 | } 73 | 74 | fn get_dst_addr(&self, s: &TcpStream) -> Result { 75 | get_dst_addr_sockopt(s) 76 | } 77 | 78 | fn setup_firewall(&self, config: &FirewallConfig) -> Result; 79 | fn restore_firewall(&self, config: &FirewallConfig) -> Result; 80 | } 81 | 82 | pub struct FirewallSubnetConfig { 83 | pub enable: bool, 84 | pub listener: ListenerAddr, 85 | pub includes: T, 86 | pub excludes: T, 87 | } 88 | 89 | impl FirewallSubnetConfig { 90 | pub fn family(&self) -> Family { 91 | self.includes.family() 92 | } 93 | } 94 | 95 | pub enum FirewallListenerConfig { 96 | Ipv4(FirewallSubnetConfig), 97 | Ipv6(FirewallSubnetConfig), 98 | } 99 | 100 | #[derive(Default)] 101 | pub struct FirewallConfig { 102 | pub filter_from_user: Option, 103 | pub listeners: Vec, 104 | } 105 | -------------------------------------------------------------------------------- /src/main.rs: -------------------------------------------------------------------------------- 1 | // #![warn(missing_docs)] 2 | #![deny(clippy::pedantic)] 3 | #![deny(clippy::nursery)] 4 | #![deny(clippy::unwrap_used)] 5 | #![deny(clippy::expect_used)] 6 | #![allow(clippy::module_name_repetitions)] 7 | #![allow(clippy::use_self)] 8 | #![allow(clippy::unused_self)] 9 | 10 | use std::{error::Error, fmt::Display, process::ExitCode}; 11 | 12 | mod network; 13 | 14 | mod client; 15 | use client::Config; 16 | use network::{ListenerAddr, Subnets}; 17 | 18 | mod options; 19 | 20 | mod command; 21 | mod commands; 22 | 23 | mod firewall; 24 | 25 | mod linux; 26 | 27 | #[derive(Clone, Debug)] 28 | pub struct ConfigError { 29 | message: String, 30 | } 31 | 32 | impl Display for ConfigError { 33 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 34 | write!(f, "{}", self.message) 35 | } 36 | } 37 | 38 | // impl Debug for ParseError {} 39 | impl Error for ConfigError {} 40 | 41 | fn options_to_config(opt: &options::Options) -> Result { 42 | let includes = { 43 | let mut includes = Vec::new(); 44 | for list1 in &opt.include { 45 | let inner_list = &list1.0; 46 | includes.extend(inner_list.iter().cloned()); 47 | } 48 | Subnets::new(includes) 49 | }; 50 | 51 | let excludes = { 52 | let mut excludes = Vec::new(); 53 | for list2 in &opt.exclude { 54 | let inner_list = &list2.0; 55 | excludes.extend(inner_list.iter().cloned()); 56 | } 57 | Subnets::new(excludes) 58 | }; 59 | 60 | if opt.include.is_empty() { 61 | return Err(ConfigError { 62 | message: "No subnets specified".to_string(), 63 | }); 64 | } 65 | 66 | let num_ipv4_listen = opt.listen.iter().filter(|l| l.is_ipv4()).count(); 67 | if num_ipv4_listen > 1 { 68 | return Err(ConfigError { 69 | message: "Multiple IPv4 listeners specified".to_string(), 70 | }); 71 | } 72 | 73 | let num_ipv6_listen = opt.listen.iter().filter(|l| l.is_ipv6()).count(); 74 | if num_ipv6_listen > 1 { 75 | return Err(ConfigError { 76 | message: "Multiple IPv6 listeners specified".to_string(), 77 | }); 78 | } 79 | 80 | if num_ipv4_listen == 0 && num_ipv6_listen == 0 { 81 | return Err(ConfigError { 82 | message: "No IPv4 or IPv6 listeners specified".to_string(), 83 | }); 84 | } 85 | 86 | let ipv4_includes = includes.count_ipv4(); 87 | let ipv4_excludes = excludes.count_ipv4(); 88 | let ipv6_includes = includes.count_ipv6(); 89 | let ipv6_excludes = excludes.count_ipv6(); 90 | 91 | if (ipv4_includes > 0 || ipv4_excludes > 0) && num_ipv4_listen == 0 { 92 | return Err(ConfigError { 93 | message: "IPv4 subnets supplied but not enabled".to_string(), 94 | }); 95 | } 96 | 97 | if (ipv6_includes > 0 || ipv6_excludes > 0) && num_ipv6_listen == 0 { 98 | return Err(ConfigError { 99 | message: "IPv6 subnets supplied but not enabled".to_string(), 100 | }); 101 | } 102 | 103 | let remote = opt.remote.clone(); 104 | 105 | let listen = { 106 | let mut listen = Vec::new(); 107 | 108 | opt.listen 109 | .iter() 110 | .map(|l| ListenerAddr { 111 | addr: *l, 112 | protocol: network::Protocol::Tcp, 113 | }) 114 | .for_each(|l| listen.push(l)); 115 | 116 | listen 117 | }; 118 | 119 | let config = Config { 120 | includes, 121 | excludes, 122 | remote, 123 | listen, 124 | socks_addr: opt.socks, 125 | firewall: opt.firewall, 126 | }; 127 | 128 | Ok(config) 129 | } 130 | 131 | async fn run_client() -> Result<(), Box> { 132 | let opt = options::parse(); 133 | let config = options_to_config(&opt)?; 134 | client::main(&config).await?; 135 | Ok(()) 136 | } 137 | 138 | #[tokio::main] 139 | async fn main() -> ExitCode { 140 | env_logger::init(); 141 | 142 | match run_client().await { 143 | Ok(()) => { 144 | log::info!("Exiting normally"); 145 | ExitCode::SUCCESS 146 | } 147 | Err(err) => { 148 | log::error!("Exiting with error: {}", err); 149 | ExitCode::FAILURE 150 | } 151 | } 152 | } 153 | -------------------------------------------------------------------------------- /src/command.rs: -------------------------------------------------------------------------------- 1 | //! Run a binary executable 2 | //! 3 | //! This will run a Unix command, and keep track of stdout, stderr, and any errors. 4 | 5 | use log::info; 6 | use std::{ 7 | error, 8 | fmt::Display, 9 | process::{Output, Stdio}, 10 | result, 11 | str::{self, Utf8Error}, 12 | time::{Duration, Instant}, 13 | }; 14 | use tokio::{io, process::Command}; 15 | 16 | pub fn duration_string(duration: &Duration) -> String { 17 | let seconds = duration.as_secs() % 60; 18 | let minutes = (duration.as_secs() / 60) % 60; 19 | let hours = (duration.as_secs() / 60) / 60; 20 | format!("{hours:02}:{minutes:02}:{seconds:02}") 21 | } 22 | 23 | #[derive(Debug)] 24 | pub struct Success { 25 | pub cmd: Line, 26 | pub stdout: String, 27 | pub stderr: String, 28 | pub duration: Duration, 29 | } 30 | 31 | impl Success { 32 | #[allow(clippy::unused_self)] 33 | pub fn result_line(&self) -> String { 34 | "Command was successful".to_string() 35 | } 36 | } 37 | 38 | impl Display for Success { 39 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 40 | let summary = self.result_line(); 41 | 42 | f.write_str("result: ")?; 43 | f.write_str(&summary)?; 44 | f.write_str("\n")?; 45 | 46 | f.write_str("command: ")?; 47 | f.write_str(&self.cmd.to_string())?; 48 | f.write_str("\n")?; 49 | 50 | f.write_str("duration: ")?; 51 | f.write_str(&duration_string(&self.duration))?; 52 | f.write_str("\n")?; 53 | 54 | f.write_str("stdout:\n")?; 55 | f.write_str(&self.stdout)?; 56 | f.write_str("\n")?; 57 | 58 | f.write_str("stderr:\n")?; 59 | f.write_str(&self.stderr)?; 60 | f.write_str("\n")?; 61 | 62 | Ok(()) 63 | } 64 | } 65 | 66 | #[derive(Debug)] 67 | pub struct Error { 68 | pub cmd: Line, 69 | pub stdout: String, 70 | pub stderr: String, 71 | pub duration: Duration, 72 | pub exit_code: i32, 73 | pub kind: ErrorKind, 74 | } 75 | 76 | #[derive(Debug)] 77 | pub enum ErrorKind { 78 | BadExitCode, 79 | FailedToStart { err: std::io::Error }, 80 | Utf8Error { err: Utf8Error }, 81 | } 82 | 83 | impl From for ErrorKind { 84 | fn from(err: Utf8Error) -> Self { 85 | Self::Utf8Error { err } 86 | } 87 | } 88 | 89 | impl Error { 90 | pub fn result_line(&self) -> String { 91 | match &self.kind { 92 | ErrorKind::BadExitCode {} => format!("Bad Exit code {}", self.exit_code), 93 | ErrorKind::FailedToStart { err } => format!("Failed to start: {err}"), 94 | ErrorKind::Utf8Error { err } => format!("UTF-8 error: {err}"), 95 | } 96 | } 97 | } 98 | 99 | impl Display for Error { 100 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 101 | let summary = self.result_line(); 102 | 103 | f.write_str("result: ")?; 104 | f.write_str(&summary)?; 105 | f.write_str("\n")?; 106 | 107 | f.write_str("command: ")?; 108 | f.write_str(&self.cmd.to_string())?; 109 | f.write_str("\n")?; 110 | 111 | f.write_str("duration: ")?; 112 | f.write_str(&duration_string(&self.duration))?; 113 | f.write_str("\n")?; 114 | 115 | f.write_str("stdout:\n")?; 116 | f.write_str(&self.stdout)?; 117 | f.write_str("\n")?; 118 | 119 | f.write_str("stderr:\n")?; 120 | f.write_str(&self.stderr)?; 121 | f.write_str("\n")?; 122 | 123 | Ok(()) 124 | } 125 | } 126 | 127 | impl error::Error for Error {} 128 | 129 | pub type Result = result::Result; 130 | 131 | #[derive(Clone, Eq, PartialEq)] 132 | pub struct Line(pub String, pub Vec); 133 | 134 | fn get_exit_code(output: &result::Result) -> i32 { 135 | output 136 | .as_ref() 137 | .map_or(-1, |output| output.status.code().unwrap_or(-1)) 138 | } 139 | 140 | fn get_stdin_out( 141 | output: &result::Result, 142 | ) -> result::Result<(String, String), ErrorKind> { 143 | if let Ok(output) = &output { 144 | let stdin = str::from_utf8(&output.stdout)?; 145 | let stderr = str::from_utf8(&output.stderr)?; 146 | Ok((stdin.to_string(), stderr.to_string())) 147 | } else { 148 | Ok((String::new(), String::new())) 149 | } 150 | } 151 | 152 | impl Line { 153 | pub fn new(cmd: impl Into, args: impl IntoIterator>) -> Self { 154 | let cmd = cmd.into(); 155 | let args = args.into_iter().map(std::convert::Into::into).collect(); 156 | Self(cmd, args) 157 | } 158 | 159 | pub async fn run(&self) -> Result { 160 | let start = Instant::now(); 161 | info!("Running command: {self}"); 162 | 163 | let Self(cmd, args) = &self; 164 | let output = Command::new(cmd) 165 | .args(args) 166 | .stdin(Stdio::null()) 167 | .stdout(Stdio::piped()) 168 | .stderr(Stdio::piped()) 169 | .output() 170 | .await; 171 | 172 | let exit_code = get_exit_code(&output); 173 | let duration = start.elapsed(); 174 | 175 | let (stdout, stderr) = match get_stdin_out(&output) { 176 | Ok(output) => output, 177 | Err(err) => { 178 | return Err(Error { 179 | cmd: self.clone(), 180 | stdout: String::new(), 181 | stderr: String::new(), 182 | exit_code, 183 | duration, 184 | kind: err, 185 | }) 186 | } 187 | }; 188 | 189 | let kind = match output { 190 | Err(err) => Err(ErrorKind::FailedToStart { err }), 191 | Ok(output) => { 192 | if output.status.success() { 193 | Ok(()) 194 | } else { 195 | Err(ErrorKind::BadExitCode {}) 196 | } 197 | } 198 | }; 199 | 200 | match kind { 201 | Ok(()) => Ok(Success { 202 | cmd: self.clone(), 203 | stdout, 204 | stderr, 205 | duration, 206 | }), 207 | Err(kind) => Err(Error { 208 | cmd: self.clone(), 209 | stdout, 210 | stderr, 211 | exit_code, 212 | duration, 213 | kind, 214 | }), 215 | } 216 | } 217 | } 218 | 219 | impl Display for Line { 220 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 221 | write!(f, "{}", self.0)?; 222 | for arg in &self.1 { 223 | write!(f, " {arg}")?; 224 | } 225 | Ok(()) 226 | } 227 | } 228 | 229 | impl std::fmt::Debug for Line { 230 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { 231 | write!(f, "CommandLine(\"{}", self.0)?; 232 | for arg in &self.1 { 233 | write!(f, " {arg}")?; 234 | } 235 | write!(f, "\")")?; 236 | Ok(()) 237 | } 238 | } 239 | -------------------------------------------------------------------------------- /src/firewall/nat.rs: -------------------------------------------------------------------------------- 1 | use crate::network::Ports; 2 | use crate::network::Protocol; 3 | use crate::network::SubnetFamily; 4 | use crate::network::SubnetsFamily; 5 | 6 | use super::{Commands, Firewall, FirewallConfig, FirewallError, FirewallSubnetConfig}; 7 | 8 | pub struct NatFirewall {} 9 | 10 | impl NatFirewall { 11 | pub const fn new() -> Self { 12 | NatFirewall {} 13 | } 14 | 15 | #[rustfmt::skip] 16 | fn setup_family( 17 | &self, 18 | config: &FirewallConfig, 19 | subnet_config: &FirewallSubnetConfig, 20 | commands: &mut Commands, 21 | ) -> Result<(), FirewallError> { 22 | if !matches!(subnet_config.listener.protocol, Protocol::Tcp) { 23 | return Err(FirewallError::NotSupported( 24 | "Only TCP is supported for NAT".to_string()), 25 | ); 26 | } 27 | 28 | let port = subnet_config.listener.port().to_string(); 29 | let chain = format!("sshuttle-{port}"); 30 | let family = subnet_config.family(); 31 | 32 | macro_rules! ipt { 33 | ( $( $e:expr),* ) => { 34 | let v = vec![ $( $e ),* ]; 35 | commands.ipt(family, "nat", &v); 36 | }; 37 | } 38 | 39 | macro_rules! ipt_vec { 40 | ( $e:expr ) => { 41 | let v = $e; 42 | commands.ipt(family, "nat", &v); 43 | }; 44 | } 45 | 46 | macro_rules! ipm { 47 | ( $( $e:expr),* ) => { 48 | let v = vec![ $( $e ),* ]; 49 | commands.ipt(family, "mangle", &v); 50 | }; 51 | } 52 | 53 | ipt!("-N", &chain); 54 | ipt!("-F", &chain); 55 | 56 | if let Some(user) = &config.filter_from_user { 57 | ipm!("-I", "OUTPUT", "1", "-m", "owner", "--uid-owner", user, "-j", "MARK", "set-mark", &port); 58 | 59 | ipt!("-I", "OUTPUT", "1", "-m", "mark", "--mark", &port, "-j", &chain); 60 | ipt!("-I", "PREROUTING", "1", "-m", "mark","--mark", &port, "-j", &chain); 61 | } else { 62 | ipt!("-I", "OUTPUT", "1", "-j", &chain); 63 | ipt!("-I", "PREROUTING", "1", "-j", &chain); 64 | } 65 | 66 | ipt!("-A", &chain, "-j", "RETURN", "-m", "addrtype", "--dst-type", "LOCAL"); 67 | 68 | for subnet in subnet_config.excludes.iter() { 69 | let subnet_str = subnet.subnet_str(); 70 | let ports: Vec = match subnet.ports() { 71 | Ports::Single(port) => vec!["--dport".to_string(), port.to_string()], 72 | Ports::Range(first, last) => vec!["--dport".to_string(), format!("{first}:{last}")], 73 | Ports::None => vec![], 74 | }; 75 | let mut ports = ports.iter().map(std::string::String::as_str).collect(); 76 | let mut cmd = vec!["-A", &chain, "-j", "RETURN", "--dest", &subnet_str, "-p", "tcp"]; 77 | cmd.append(&mut ports); 78 | ipt_vec!(cmd); 79 | } 80 | 81 | for subnet in subnet_config.includes.iter() { 82 | let subnet_str = subnet.subnet_str(); 83 | let ports: Vec = match subnet.ports() { 84 | Ports::Single(port) => vec!["--dport".to_string(), port.to_string()], 85 | Ports::Range(first, last) => vec!["--dport".to_string(), format!("{first}:{last}")], 86 | Ports::None => vec![], 87 | }; 88 | let mut ports = ports.iter().map(std::string::String::as_str).collect(); 89 | let mut cmd = vec!["-A", &chain, "-j", "REDIRECT", "--dest", &subnet_str, "-p", "tcp"]; 90 | cmd.append(&mut ports); 91 | cmd.append(&mut vec!["--to-ports", &port]); 92 | ipt_vec!(cmd); 93 | } 94 | 95 | Ok(()) 96 | } 97 | 98 | #[rustfmt::skip] 99 | fn restore_family( 100 | &self, 101 | config: &FirewallConfig, 102 | subnet_config: &FirewallSubnetConfig, 103 | commands: &mut Commands, 104 | ) -> Result<(), FirewallError> { 105 | if !matches!(subnet_config.listener.protocol, Protocol::Tcp) { 106 | return Err(FirewallError::NotSupported( 107 | "Only TCP is supported for NAT".to_string()), 108 | ); 109 | } 110 | 111 | let port = subnet_config.listener.port().to_string(); 112 | let chain = format!("sshuttle-{port}"); 113 | let family = subnet_config.family(); 114 | 115 | macro_rules! ipt { 116 | ( $( $e:expr),* ) => { 117 | let v = vec![ $( $e ),* ]; 118 | commands.ipt_ignore_errors(family, "nat", &v); 119 | }; 120 | } 121 | 122 | macro_rules! ipm { 123 | ( $( $e:expr),* ) => { 124 | let v = vec![ $( $e ),* ]; 125 | commands.ipt_ignore_errors(family, "mangle", &v); 126 | }; 127 | } 128 | 129 | if let Some(user) = &config.filter_from_user { 130 | ipm!("-D", "OUTPUT", "-m", "owner", "--uid-owner", user, "-j", "MARK", "--set-mark", &port); 131 | ipt!("-D", "OUTPUT", "-m", "mark", "--mark", &port, "-j", &chain); 132 | ipt!("-D", "PREROUTING", "1", "-m", "mark","--mark", &port, "-j", &chain); 133 | } else { 134 | ipt!("-D", "OUTPUT", "-j", &chain); 135 | ipt!("-D", "PREROUTING", "-j", &chain); 136 | } 137 | 138 | ipt!("-F", &chain); 139 | ipt!("-X", &chain); 140 | Ok(()) 141 | } 142 | } 143 | 144 | impl Firewall for NatFirewall { 145 | fn setup_firewall(&self, config: &FirewallConfig) -> Result { 146 | let mut commands: Commands = self.restore_firewall(config)?; 147 | 148 | for family in &config.listeners { 149 | match family { 150 | super::FirewallListenerConfig::Ipv4(ip) => { 151 | self.setup_family(config, ip, &mut commands)?; 152 | } 153 | super::FirewallListenerConfig::Ipv6(ip) => { 154 | self.setup_family(config, ip, &mut commands)?; 155 | } 156 | } 157 | } 158 | 159 | Ok(commands) 160 | } 161 | fn restore_firewall(&self, config: &FirewallConfig) -> Result { 162 | let mut commands: Commands = Commands::new(); 163 | 164 | for family in &config.listeners { 165 | match family { 166 | super::FirewallListenerConfig::Ipv4(ip) => { 167 | self.restore_family(config, ip, &mut commands)?; 168 | } 169 | super::FirewallListenerConfig::Ipv6(ip) => { 170 | self.restore_family(config, ip, &mut commands)?; 171 | } 172 | } 173 | } 174 | 175 | Ok(commands) 176 | } 177 | } 178 | 179 | #[allow(clippy::unwrap_used)] 180 | #[cfg(test)] 181 | mod tests { 182 | use crate::{ 183 | command::Line, 184 | network::{ListenerAddr, SubnetsV4, SubnetsV6}, 185 | }; 186 | 187 | use super::*; 188 | 189 | #[test] 190 | fn test_setup_family_v4() { 191 | let firewall = NatFirewall::new(); 192 | let ipv4_family = FirewallSubnetConfig { 193 | enable: true, 194 | listener: ListenerAddr { 195 | protocol: Protocol::Tcp, 196 | addr: "127.0.0.1:1024".parse().unwrap(), 197 | }, 198 | includes: "1.2.3.0/24:8000-9000".parse::().unwrap(), 199 | excludes: "1.2.3.66:8080".parse::().unwrap(), 200 | }; 201 | let config = FirewallConfig { 202 | filter_from_user: None, 203 | listeners: vec![], 204 | }; 205 | 206 | let expected_ipv4: [&str; 7] = [ 207 | "iptables -w -t nat -N sshuttle-1024", 208 | "iptables -w -t nat -F sshuttle-1024", 209 | "iptables -w -t nat -I OUTPUT 1 -j sshuttle-1024", 210 | "iptables -w -t nat -I PREROUTING 1 -j sshuttle-1024", 211 | "iptables -w -t nat -A sshuttle-1024 -j RETURN -m addrtype --dst-type LOCAL", 212 | "iptables -w -t nat -A sshuttle-1024 -j RETURN --dest 1.2.3.66/32 -p tcp --dport 8080", 213 | "iptables -w -t nat -A sshuttle-1024 -j REDIRECT --dest 1.2.3.0/24 -p tcp --dport 8000:9000 --to-ports 1024", 214 | ]; 215 | 216 | let mut commands = Commands::default(); 217 | firewall 218 | .setup_family(&config, &ipv4_family, &mut commands) 219 | .unwrap(); 220 | assert_eq!(commands.len(), expected_ipv4.len()); 221 | for (command, expected_line) in commands.iter().zip(expected_ipv4.iter()) { 222 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 223 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 224 | assert_eq!(command.line, expected_command); 225 | } 226 | } 227 | 228 | #[test] 229 | fn test_setup_family_v6() { 230 | let firewall = NatFirewall::new(); 231 | let ipv6_family = FirewallSubnetConfig { 232 | enable: true, 233 | listener: ListenerAddr { 234 | protocol: Protocol::Tcp, 235 | addr: "127.0.0.1:1024".parse().unwrap(), 236 | }, 237 | includes: "2404:6800:4004:80c::/64".parse::().unwrap(), 238 | excludes: "[2404:6800:4004:80c::101f]:80".parse().unwrap(), 239 | }; 240 | let config = FirewallConfig { 241 | filter_from_user: None, 242 | listeners: vec![], 243 | }; 244 | let expected_ipv6: [&str; 7] = [ 245 | "ip6tables -w -t nat -N sshuttle-1024", 246 | "ip6tables -w -t nat -F sshuttle-1024", 247 | "ip6tables -w -t nat -I OUTPUT 1 -j sshuttle-1024", 248 | "ip6tables -w -t nat -I PREROUTING 1 -j sshuttle-1024", 249 | "ip6tables -w -t nat -A sshuttle-1024 -j RETURN -m addrtype --dst-type LOCAL", 250 | "ip6tables -w -t nat -A sshuttle-1024 -j RETURN --dest 2404:6800:4004:80c::101f/128 -p tcp --dport 80", 251 | "ip6tables -w -t nat -A sshuttle-1024 -j REDIRECT --dest 2404:6800:4004:80c::/64 -p tcp --to-ports 1024", 252 | ]; 253 | 254 | let mut commands = Commands::default(); 255 | firewall 256 | .setup_family(&config, &ipv6_family, &mut commands) 257 | .unwrap(); 258 | assert_eq!(commands.len(), expected_ipv6.len()); 259 | for (command, expected_line) in commands.iter().zip(expected_ipv6.iter()) { 260 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 261 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 262 | assert_eq!(command.line, expected_command); 263 | } 264 | } 265 | 266 | #[test] 267 | fn test_restore_family_v4() { 268 | let firewall = NatFirewall::new(); 269 | let ipv4_family = FirewallSubnetConfig { 270 | enable: true, 271 | listener: ListenerAddr { 272 | protocol: Protocol::Tcp, 273 | addr: "127.0.0.1:1024".parse().unwrap(), 274 | }, 275 | includes: "1.2.3.0/32".parse::().unwrap(), 276 | excludes: "1.2.3.66".parse::().unwrap(), 277 | }; 278 | let config = FirewallConfig { 279 | filter_from_user: None, 280 | listeners: vec![], 281 | }; 282 | 283 | let expected_ipv4: [&str; 4] = [ 284 | "iptables -w -t nat -D OUTPUT -j sshuttle-1024", 285 | "iptables -w -t nat -D PREROUTING -j sshuttle-1024", 286 | "iptables -w -t nat -F sshuttle-1024", 287 | "iptables -w -t nat -X sshuttle-1024", 288 | ]; 289 | 290 | let mut commands = Commands::default(); 291 | firewall 292 | .restore_family(&config, &ipv4_family, &mut commands) 293 | .unwrap(); 294 | assert_eq!(commands.len(), expected_ipv4.len()); 295 | for (command, expected_line) in commands.iter().zip(expected_ipv4.iter()) { 296 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 297 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 298 | assert_eq!(command.line, expected_command); 299 | } 300 | } 301 | 302 | #[test] 303 | fn test_restore_family_v6() { 304 | let firewall = NatFirewall::new(); 305 | let ipv6_family = FirewallSubnetConfig { 306 | enable: true, 307 | listener: ListenerAddr { 308 | protocol: Protocol::Tcp, 309 | addr: "127.0.0.1:1024".parse().unwrap(), 310 | }, 311 | includes: "2404:6800:4004:80c::/64".parse::().unwrap(), 312 | excludes: "[2404:6800:4004:80c::101f]:80".parse().unwrap(), 313 | }; 314 | let config = FirewallConfig { 315 | filter_from_user: None, 316 | listeners: vec![], 317 | }; 318 | let expected_ipv6: [&str; 4] = [ 319 | "ip6tables -w -t nat -D OUTPUT -j sshuttle-1024", 320 | "ip6tables -w -t nat -D PREROUTING -j sshuttle-1024", 321 | "ip6tables -w -t nat -F sshuttle-1024", 322 | "ip6tables -w -t nat -X sshuttle-1024", 323 | ]; 324 | 325 | let mut commands = Commands::default(); 326 | firewall 327 | .restore_family(&config, &ipv6_family, &mut commands) 328 | .unwrap(); 329 | assert_eq!(commands.len(), expected_ipv6.len()); 330 | for (command, expected_line) in commands.iter().zip(expected_ipv6.iter()) { 331 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 332 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 333 | assert_eq!(command.line, expected_command); 334 | } 335 | } 336 | } 337 | -------------------------------------------------------------------------------- /src/client.rs: -------------------------------------------------------------------------------- 1 | use std::net::IpAddr; 2 | use std::net::SocketAddr; 3 | use std::sync::Arc; 4 | use std::time::Duration; 5 | 6 | use fast_socks5::client::Socks5Stream; 7 | use fast_socks5::SocksError; 8 | 9 | use nix::errno::Errno; 10 | use thiserror::Error; 11 | use tokio::io::copy_bidirectional; 12 | use tokio::net::{TcpListener, TcpStream}; 13 | use tokio::select; 14 | use tokio::sync::mpsc; 15 | use tokio::task::JoinError; 16 | use tokio::time::sleep; 17 | use tokio::{process::Command, spawn, task::JoinHandle}; 18 | 19 | use crate::command::Error; 20 | use crate::firewall::{ 21 | Firewall, FirewallConfig, FirewallError, FirewallListenerConfig, FirewallSubnetConfig, 22 | }; 23 | use crate::network::{ListenerAddr, Subnets}; 24 | use crate::options::FirewallType; 25 | 26 | pub struct Config { 27 | pub includes: Subnets, 28 | pub excludes: Subnets, 29 | pub remote: Option, 30 | pub listen: Vec, 31 | pub socks_addr: SocketAddr, 32 | pub firewall: FirewallType, 33 | } 34 | 35 | #[derive(Error, Debug)] 36 | pub enum ClientError { 37 | #[error("Firewall Error `{0}`")] 38 | Firewall(#[from] FirewallError), 39 | 40 | #[error("Join Error `{0}`")] 41 | Join(#[from] JoinError), 42 | 43 | #[error("Command Error `{0}`")] 44 | Command(#[from] Error), 45 | 46 | #[error("IO Error `{0}`")] 47 | Io(#[from] std::io::Error), 48 | 49 | #[error("Errno error `{0}`")] 50 | Errno(#[from] Errno), 51 | 52 | #[error("Socks5 Error `{0}`")] 53 | Socks5(#[from] SocksError), 54 | 55 | #[error("Error setting up Ctrl-C handler `{0}`")] 56 | CtrlC(#[from] ctrlc::Error), 57 | } 58 | 59 | pub async fn main(config: &Config) -> Result<(), ClientError> { 60 | let (control_tx, control_rx) = mpsc::channel(1); 61 | 62 | let tx_clone = control_tx.clone(); 63 | ctrlc::set_handler(move || { 64 | #[allow(clippy::expect_used)] 65 | tx_clone 66 | .blocking_send(Message::Shutdown) 67 | .expect("Could not send signal on channel."); 68 | })?; 69 | 70 | let firewall_config = get_firewall_config(config); 71 | let firewall = get_firewall(config); 72 | let setup_commands = firewall.setup_firewall(&firewall_config)?; 73 | let shutdown_commands = firewall.restore_firewall(&firewall_config)?; 74 | 75 | log::info!("Setting up firewall {:#?}", setup_commands); 76 | setup_commands.run_all().await?; 77 | 78 | log::debug!("run_everything"); 79 | let client_result = run_everything(config, firewall, control_tx, control_rx).await; 80 | if let Err(err) = &client_result { 81 | log::error!("run_everything error: {err}"); 82 | } else { 83 | log::debug!("run_everything exited normally"); 84 | } 85 | 86 | log::info!("Restoring firewall{:#?}", shutdown_commands); 87 | let shutdown_result = shutdown_commands.run_all().await; 88 | if let Err(err) = &shutdown_result { 89 | log::error!("Error restoring firewall: {err}"); 90 | } else { 91 | log::debug!("Restored firewall"); 92 | } 93 | 94 | client_result?; 95 | shutdown_result?; 96 | Ok(()) 97 | } 98 | 99 | async fn run_everything( 100 | config: &Config, 101 | firewall: Box, 102 | control_tx: mpsc::Sender, 103 | mut control_rx: mpsc::Receiver, 104 | ) -> Result<(), ClientError> { 105 | let client = run_client(config, firewall); 106 | 107 | if let Some(remote) = &config.remote { 108 | // ssh shutdown sequence with ssh: 109 | // ctrlc handler sends signal to control_tx. 110 | // ssh handler receives event from control_rx. 111 | // ssh handler kills ssh. 112 | // ssh_handle completes, and the select finishes. 113 | // we return. 114 | let c = run_ssh(config, remote.to_string(), control_rx).await?; 115 | let ssh_handle = c.handle; 116 | 117 | tokio::pin!(ssh_handle); 118 | tokio::pin!(client); 119 | 120 | select! { 121 | res = &mut ssh_handle => { 122 | log::info!("ssh_handle finished"); 123 | res??; 124 | }, 125 | res = &mut client => { 126 | log::info!("client finished"); 127 | res?; 128 | }, 129 | else => { 130 | log::info!("everything finished"); 131 | } 132 | } 133 | 134 | // We don't care if the message fails, probably because ssh already exited. 135 | _ = control_tx.send(Message::Shutdown).await; 136 | } else { 137 | // ssh shutdown sequence without ssh: 138 | // ctrlc handler sends signal to control_tx. 139 | // the select finishes. 140 | // we return. 141 | select! { 142 | res = client => { 143 | log::info!("client finished"); 144 | res?; 145 | }, 146 | Some(_) = control_rx.recv() => { 147 | log::info!("control_rx shutdown requested"); 148 | } 149 | } 150 | } 151 | 152 | Ok(()) 153 | } 154 | 155 | // async fn read_tcpstream( 156 | // stream: &mut TcpStream, 157 | // buf: &mut [u8], 158 | // shutdown: bool, 159 | // ) -> Option> { 160 | // if shutdown { 161 | // None 162 | // } else { 163 | // Some(stream.read(buf).await) 164 | // } 165 | // } 166 | 167 | // async fn read_socksstream( 168 | // stream: &mut Socks5Stream, 169 | // buf: &mut [u8], 170 | // shutdown: bool, 171 | // ) -> Option> { 172 | // if shutdown { 173 | // None 174 | // } else { 175 | // Some(stream.read(buf).await) 176 | // } 177 | // } 178 | 179 | // async fn write(stream: &mut Option, buf: &[u8]) -> Option> { 180 | // if let Some(s) = stream { 181 | // Some(s.write_all(buf).await) 182 | // } else { 183 | // None 184 | // } 185 | // } 186 | 187 | fn get_firewall(config: &Config) -> Box { 188 | match config.firewall { 189 | FirewallType::Nat => Box::new(crate::firewall::nat::NatFirewall::new()), 190 | FirewallType::TProxy => Box::new(crate::firewall::tproxy::TProxyFirewall::new()), 191 | } 192 | } 193 | 194 | fn get_firewall_config(config: &Config) -> FirewallConfig { 195 | let familys = config 196 | .listen 197 | .iter() 198 | .map(|addr| match addr.ip() { 199 | IpAddr::V4(_) => FirewallListenerConfig::Ipv4(FirewallSubnetConfig { 200 | enable: true, 201 | listener: addr.clone(), 202 | includes: config.includes.ipv4(), 203 | excludes: config.excludes.ipv4(), 204 | }), 205 | IpAddr::V6(_) => FirewallListenerConfig::Ipv6(FirewallSubnetConfig { 206 | enable: true, 207 | listener: addr.clone(), 208 | includes: config.includes.ipv6(), 209 | excludes: config.excludes.ipv6(), 210 | }), 211 | }) 212 | .collect(); 213 | FirewallConfig { 214 | filter_from_user: None, 215 | listeners: familys, 216 | } 217 | } 218 | 219 | #[derive(Debug, Clone)] 220 | enum Message { 221 | Shutdown, 222 | } 223 | 224 | struct Task { 225 | // tx: mpsc::Sender, 226 | handle: JoinHandle>, 227 | } 228 | 229 | async fn run_ssh( 230 | config: &Config, 231 | remote: String, 232 | mut rx: mpsc::Receiver, 233 | ) -> Result { 234 | let socks = config.socks_addr; 235 | 236 | let handle: JoinHandle> = spawn(async move { 237 | let args = vec![ 238 | "-D".to_string(), 239 | socks.to_string(), 240 | "-N".to_string(), 241 | remote, 242 | ]; 243 | 244 | let mut child = Command::new("ssh").args(args).spawn()?; 245 | 246 | tokio::select! { 247 | msg = rx.recv() => { 248 | log::info!("ssh shutdown requested, killing child ssh: {msg:?}"); 249 | child.kill().await?; 250 | Ok(()) 251 | } 252 | status = child.wait() => { 253 | match status { 254 | Ok(rc) => { 255 | if rc.success() { 256 | log::error!("ssh exited with rc: {rc}"); 257 | Ok(()) 258 | } else { 259 | log::info!("ssh exited with rc: {rc}"); 260 | Err(std::io::Error::new(std::io::ErrorKind::Other, "ssh failed")) 261 | } 262 | } 263 | Err(err) => { 264 | log::error!("ssh wait failed: {err}"); 265 | Err(err) 266 | } 267 | } 268 | } 269 | } 270 | }); 271 | 272 | Ok(Task { handle }) 273 | } 274 | 275 | async fn run_client( 276 | config: &Config, 277 | firewall: Box, 278 | ) -> Result { 279 | let socks_addr = config.socks_addr; 280 | let listen = config.listen.clone(); 281 | 282 | let firewall: Arc = Arc::from(firewall); 283 | for l_addr in listen { 284 | match l_addr.protocol { 285 | crate::network::Protocol::Tcp => listen_tcp(&firewall, l_addr, socks_addr).await?, 286 | crate::network::Protocol::Udp => {} 287 | } 288 | } 289 | 290 | loop { 291 | sleep(Duration::from_secs(60)).await; 292 | } 293 | } 294 | 295 | async fn listen_tcp( 296 | firewall: &Arc, 297 | l_addr: ListenerAddr, 298 | socks_addr: SocketAddr, 299 | ) -> Result<(), ClientError> { 300 | let firewall = Arc::clone(firewall); 301 | let listener = TcpListener::bind(l_addr.addr).await?; 302 | firewall.setup_tcp_listener(&listener)?; 303 | 304 | let _handle: JoinHandle> = tokio::spawn(async move { 305 | loop { 306 | let firewall = Arc::clone(&firewall); 307 | let socket = match listener.accept().await { 308 | Ok((socket, _)) => socket, 309 | Err(err) => break Err(err.into()), 310 | }; 311 | let l_addr = l_addr.clone(); 312 | tokio::spawn(async move { 313 | handle_tcp_client(socket, &l_addr, socks_addr, firewall) 314 | .await 315 | .map_err(|err| { 316 | log::error!("handle_tcp_client failed: {err}"); 317 | err 318 | }) 319 | .ok(); 320 | }); 321 | } 322 | }); 323 | Ok(()) 324 | } 325 | 326 | async fn handle_tcp_client( 327 | socket: TcpStream, 328 | l_addr: &ListenerAddr, 329 | socks_addr: SocketAddr, 330 | firewall: Arc, 331 | ) -> Result<(), ClientError> { 332 | let mut local = socket; 333 | let local_addr = local.peer_addr()?; 334 | log::debug!("new connection from: {}", local_addr); 335 | 336 | let remote_addr = firewall.get_dst_addr(&local)?; 337 | log::info!("{l_addr} got connection from {local_addr} to {remote_addr}"); 338 | 339 | let (addr_str, port) = { 340 | let addr = remote_addr.ip().to_string(); 341 | let port = remote_addr.port(); 342 | (addr, port) 343 | }; 344 | 345 | let mut remote_config = fast_socks5::client::Config::default(); 346 | remote_config.set_skip_auth(false); 347 | let mut remote = Socks5Stream::connect(socks_addr, addr_str, port, remote_config).await?; 348 | 349 | let result = copy_bidirectional(&mut local, &mut remote).await; 350 | // let result = my_bidirectional_copy(&mut local, &mut remote).await; 351 | 352 | log::debug!("copy_bidirectional result: {:?}", result); 353 | 354 | Ok(()) 355 | } 356 | 357 | // async fn my_bidirectional_copy( 358 | // local: &mut TcpStream, 359 | // remote: &mut Socks5Stream, 360 | // ) -> Result<(), ClientError> { 361 | // let mut local_buf = [0; 1024]; 362 | // let mut remote_buf = [0; 1024]; 363 | // let remote_shutdown: bool = false; 364 | // let mut local_shutdown: bool = false; 365 | 366 | // println!("start loop"); 367 | // loop { 368 | // println!("start select"); 369 | // select! { 370 | // Some(res) = read_tcpstream(local, &mut local_buf, local_shutdown) => { 371 | // println!("local read"); 372 | // match res { 373 | // Ok(0) => { 374 | // println!("local shutdown request"); 375 | // remote.shutdown().await.unwrap(); 376 | // local_shutdown = true; 377 | // } 378 | // Ok(n) => { 379 | // println!("local read -> remote write: {}", n); 380 | // remote.write_all(&local_buf[..n]).await.unwrap(); 381 | // } 382 | // Err(err) => { 383 | // println!("local read failed: {}", err); 384 | // remote.shutdown().await.unwrap(); 385 | // break; 386 | // } 387 | // } 388 | // } 389 | // Some(res) = read_socksstream(remote, &mut remote_buf, remote_shutdown) => { 390 | // println!("remote read {:?}", res); 391 | // match res { 392 | // Ok(0) => { 393 | // println!("remote shutdown request"); 394 | // let _ = local.shutdown().await.map_err(|err| {log::warn!("local shutdown failed {err}"); err}); // remote_shutdown = true; 395 | // break; 396 | // } 397 | // Ok(n) => { 398 | // println!("remote read -> local write: {} {}", n, remote_shutdown); 399 | // println!("{:?}", &remote_buf[..n]); 400 | // local.write_all(&remote_buf[..n]).await.unwrap(); 401 | // } 402 | // Err(err) => { 403 | // println!("remote read failed: {}", err); 404 | // local.shutdown().await.unwrap(); 405 | // break; 406 | // } 407 | // } 408 | // } 409 | // else => { 410 | // print!("else Shutdown"); 411 | // break; 412 | // } 413 | // } 414 | // println!("end select"); 415 | // } 416 | // println!("end loop"); 417 | 418 | // Ok(()) 419 | // } 420 | -------------------------------------------------------------------------------- /src/network.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | fmt::{Display, Formatter}, 3 | net::IpAddr, 4 | net::Ipv6Addr, 5 | net::{Ipv4Addr, SocketAddr}, 6 | str::FromStr, 7 | }; 8 | 9 | use dns_lookup::getaddrinfo; 10 | use regex::Match; 11 | use thiserror::Error; 12 | 13 | #[derive(Clone, Copy, Debug, Eq, PartialEq)] 14 | pub enum Family { 15 | Ipv4, 16 | Ipv6, 17 | } 18 | 19 | // fn parse_family(family: i32) -> Result { 20 | // match family { 21 | // IPV6 => Ok(Family::Ipv6), 22 | // IPV4 => Ok(Family::Ipv4), 23 | // _ => Err(NetworkError { 24 | // message: format!("Invalid family {}", family), 25 | // }), 26 | // } 27 | // } 28 | 29 | // const IPV6: i32 = 10; 30 | // const IPV4: i32 = 2; 31 | const STREAM: i32 = 1; 32 | 33 | #[derive(Error, Debug)] 34 | pub enum NetworkParseError { 35 | #[error("Input Error `{0}`")] 36 | InputError(String), 37 | 38 | #[error("IO Error `{0}`")] 39 | Io(#[from] std::io::Error), 40 | 41 | #[error("Regular Expression Error `{0}`")] 42 | Regex(#[from] regex::Error), 43 | } 44 | 45 | #[derive(Debug, Copy, Clone, Eq, PartialEq)] 46 | pub enum Ports { 47 | None, 48 | Single(u16), 49 | Range(u16, u16), 50 | } 51 | 52 | #[derive(Debug, Clone)] 53 | pub struct Subnet { 54 | pub address: IpAddr, 55 | pub cidr: u8, 56 | pub ports: Ports, 57 | } 58 | 59 | pub trait SubnetFamily { 60 | fn subnet_str(&self) -> String; 61 | fn ports(&self) -> Ports; 62 | } 63 | 64 | #[derive(Debug, Clone)] 65 | pub struct SubnetV4 { 66 | pub address: Ipv4Addr, 67 | pub cidr: u8, 68 | pub ports: Ports, 69 | } 70 | 71 | impl SubnetFamily for SubnetV4 { 72 | fn subnet_str(&self) -> String { 73 | format!("{}/{}", self.address, self.cidr) 74 | } 75 | fn ports(&self) -> Ports { 76 | self.ports 77 | } 78 | } 79 | 80 | #[derive(Debug, Clone)] 81 | pub struct SubnetV6 { 82 | pub address: Ipv6Addr, 83 | pub cidr: u8, 84 | pub ports: Ports, 85 | } 86 | 87 | impl SubnetFamily for SubnetV6 { 88 | fn subnet_str(&self) -> String { 89 | format!("{}/{}", self.address, self.cidr) 90 | } 91 | fn ports(&self) -> Ports { 92 | self.ports 93 | } 94 | } 95 | 96 | fn parse_int(s: Match) -> Result { 97 | s.as_str().parse::().map_err(|_| { 98 | NetworkParseError::InputError(format!("Could not parse '{}' as an integer", s.as_str())) 99 | }) 100 | } 101 | 102 | #[derive(Debug)] 103 | pub struct Subnets(pub Vec); 104 | 105 | #[derive(Debug, Default)] 106 | pub struct SubnetsV4(pub Vec); 107 | 108 | impl SubnetsV4 { 109 | pub fn len(&self) -> usize { 110 | self.0.len() 111 | } 112 | } 113 | 114 | #[derive(Debug, Default)] 115 | pub struct SubnetsV6(pub Vec); 116 | 117 | impl SubnetsV6 { 118 | pub fn len(&self) -> usize { 119 | self.0.len() 120 | } 121 | } 122 | 123 | impl Subnets { 124 | pub fn new(subnets: Vec) -> Self { 125 | Subnets(subnets) 126 | } 127 | 128 | pub fn ipv4(&self) -> SubnetsV4 { 129 | let subnets: Vec = self 130 | .0 131 | .iter() 132 | .filter_map(|s| match s.address { 133 | IpAddr::V4(ip) => Some(SubnetV4 { 134 | address: ip, 135 | cidr: s.cidr, 136 | ports: s.ports, 137 | }), 138 | IpAddr::V6(_) => None, 139 | }) 140 | .collect(); 141 | SubnetsV4(subnets) 142 | } 143 | 144 | pub fn ipv6(&self) -> SubnetsV6 { 145 | let subnets: Vec = self 146 | .0 147 | .iter() 148 | .filter_map(|s| match s.address { 149 | IpAddr::V6(ip) => Some(SubnetV6 { 150 | address: ip, 151 | cidr: s.cidr, 152 | ports: s.ports, 153 | }), 154 | IpAddr::V4(_) => None, 155 | }) 156 | .collect(); 157 | SubnetsV6(subnets) 158 | } 159 | 160 | pub fn count_ipv4(&self) -> usize { 161 | self.ipv4().len() 162 | } 163 | pub fn count_ipv6(&self) -> usize { 164 | self.ipv6().len() 165 | } 166 | #[allow(dead_code)] 167 | pub fn len(&self) -> usize { 168 | self.0.len() 169 | } 170 | } 171 | 172 | impl FromStr for Subnets { 173 | type Err = NetworkParseError; 174 | 175 | fn from_str(s: &str) -> Result { 176 | let rx = if s.matches(':').count() > 1 { 177 | r"^(?:\[?(?:\*\.)?([\w:]+)(?:/(\d+))?]?)(?::(\d+)(?:-(\d+))?)?$" 178 | } else { 179 | r"^((?:\*\.)?[\w\.\-]+)(?:/(\d+))?(?::(\d+)(?:-(\d+))?)?$" 180 | }; 181 | 182 | let re = regex::Regex::new(rx)?; 183 | let caps = re 184 | .captures(s) 185 | .ok_or_else(|| NetworkParseError::InputError(format!("Invalid subnet format: {s}")))?; 186 | 187 | let host = caps[1].to_string(); 188 | let cidr = caps.get(2).map(parse_int).transpose()?; 189 | let first_port = caps.get(3).map(parse_int).transpose()?; 190 | let last_port = caps.get(4).map(parse_int).transpose()?; 191 | 192 | let addrinfo: Result, std::io::Error> = 193 | getaddrinfo(Some(host.as_str()), None, None) 194 | .map_err(|err| { 195 | NetworkParseError::InputError(format!("Invalid hostname {host}: {err:?}")) 196 | })? 197 | .filter(|a| a.as_ref().map_or(true, |b| b.socktype == STREAM)) 198 | .collect(); 199 | let addrinfo = addrinfo?; 200 | 201 | if let Some(cidr) = cidr { 202 | let addr_v6: Vec<_> = addrinfo.iter().filter(|a| a.sockaddr.is_ipv4()).collect(); 203 | let addr_v4: Vec<_> = addrinfo.iter().filter(|a| a.sockaddr.is_ipv6()).collect(); 204 | 205 | if !addr_v6.is_empty() && !addr_v4.is_empty() { 206 | return Err(NetworkParseError::InputError(format!( 207 | "{host} has IPv4 and IPv6 addresses, so the mask \ 208 | of /{cidr} is not supported. Specify the IP \ 209 | addresses directly if you wish to specify \ 210 | a mask." 211 | ))); 212 | } 213 | 214 | if addr_v6.len() > 1 || addr_v4.len() > 1 { 215 | println!( 216 | "WARNING: {host} has multiple IP addresses. The \ 217 | mask of /{cidr} is applied to all of the addresses." 218 | ); 219 | } 220 | } 221 | 222 | let rv: Vec = addrinfo 223 | .iter() 224 | .map(|a| { 225 | let max_cidr = match a.sockaddr { 226 | std::net::SocketAddr::V4(_) => 32, 227 | std::net::SocketAddr::V6(_) => 128, 228 | }; 229 | 230 | let cidr_to_use = cidr.map_or(max_cidr, |cidr| cidr); 231 | 232 | if cidr_to_use > max_cidr { 233 | return Err(NetworkParseError::InputError(format!( 234 | "Invalid CIDR mask: {cidr_to_use}. Valid CIDR masks \ 235 | are between 0 and {max_cidr}." 236 | ))); 237 | }; 238 | 239 | let ports = match (first_port, last_port) { 240 | (None, None) => Ports::None, 241 | (None, Some(port)) | (Some(port), None) => Ports::Single(port), 242 | (Some(first), Some(last)) => Ports::Range(first, last), 243 | }; 244 | 245 | Ok(Subnet { 246 | address: a.sockaddr.ip(), 247 | cidr: cidr_to_use, 248 | ports, 249 | }) 250 | }) 251 | .collect::>()?; 252 | 253 | Ok(Subnets(rv)) 254 | } 255 | } 256 | 257 | pub trait SubnetsFamily { 258 | type Subnet: SubnetFamily; 259 | fn family(&self) -> Family; 260 | fn iter(&self) -> std::slice::Iter; 261 | } 262 | 263 | impl SubnetsFamily for SubnetsV4 { 264 | type Subnet = SubnetV4; 265 | 266 | fn family(&self) -> Family { 267 | Family::Ipv4 268 | } 269 | fn iter(&self) -> std::slice::Iter { 270 | self.0.iter() 271 | } 272 | } 273 | 274 | impl FromStr for SubnetsV4 { 275 | type Err = NetworkParseError; 276 | 277 | fn from_str(s: &str) -> Result { 278 | let subnets: Result, NetworkParseError> = Subnets::from_str(s)? 279 | .0 280 | .iter() 281 | .map(|s| match s.address { 282 | IpAddr::V4(ip) => Ok(SubnetV4 { 283 | address: ip, 284 | cidr: s.cidr, 285 | ports: s.ports, 286 | }), 287 | IpAddr::V6(_) => Err(NetworkParseError::InputError(format!( 288 | "Invalid family, expected IPv4: {s:?}" 289 | ))), 290 | }) 291 | .collect(); 292 | 293 | Ok(SubnetsV4(subnets?)) 294 | } 295 | } 296 | 297 | impl SubnetsFamily for SubnetsV6 { 298 | type Subnet = SubnetV6; 299 | 300 | fn family(&self) -> Family { 301 | Family::Ipv6 302 | } 303 | 304 | fn iter(&self) -> std::slice::Iter { 305 | self.0.iter() 306 | } 307 | } 308 | 309 | impl FromStr for SubnetsV6 { 310 | type Err = NetworkParseError; 311 | 312 | fn from_str(s: &str) -> Result { 313 | let subnets: Result, NetworkParseError> = Subnets::from_str(s)? 314 | .0 315 | .iter() 316 | .map(|s| match s.address { 317 | IpAddr::V6(ip) => Ok(SubnetV6 { 318 | address: ip, 319 | cidr: s.cidr, 320 | ports: s.ports, 321 | }), 322 | IpAddr::V4(_) => Err(NetworkParseError::InputError(format!( 323 | "Invalid family, expected IPv6: {s:?}" 324 | ))), 325 | }) 326 | .collect(); 327 | 328 | Ok(SubnetsV6(subnets?)) 329 | } 330 | } 331 | 332 | #[derive(Clone, Copy)] 333 | pub enum Protocol { 334 | Tcp, 335 | #[allow(dead_code)] 336 | Udp, 337 | } 338 | 339 | #[derive(Clone)] 340 | pub struct ListenerAddr { 341 | pub protocol: Protocol, 342 | pub addr: SocketAddr, 343 | } 344 | 345 | impl ListenerAddr { 346 | pub fn ip(&self) -> IpAddr { 347 | self.addr.ip() 348 | } 349 | pub fn port(&self) -> u16 { 350 | self.addr.port() 351 | } 352 | } 353 | 354 | impl Display for ListenerAddr { 355 | fn fmt(&self, f: &mut Formatter) -> std::fmt::Result { 356 | write!(f, "{}", self.addr)?; 357 | match self.protocol { 358 | Protocol::Tcp => write!(f, "/tcp"), 359 | Protocol::Udp => write!(f, "/udp"), 360 | } 361 | } 362 | } 363 | 364 | #[allow(clippy::unwrap_used)] 365 | #[cfg(test)] 366 | mod tests { 367 | use super::*; 368 | 369 | use regex::Regex; 370 | 371 | #[test] 372 | fn test_parse_int() { 373 | let re = Regex::new("(.*)").unwrap(); 374 | let caps = re.captures("123").unwrap().get(1).unwrap(); 375 | assert_eq!(parse_int::(caps).unwrap(), 123); 376 | 377 | let re = Regex::new("(.*)").unwrap(); 378 | let caps = re.captures("").unwrap().get(1).unwrap(); 379 | assert!(matches!(parse_int::(caps), Err(_))); 380 | 381 | let re = Regex::new("(.*)").unwrap(); 382 | let caps = re.captures("FOOD").unwrap().get(1).unwrap(); 383 | assert!(matches!(parse_int::(caps), Err(_))); 384 | } 385 | 386 | const IP4_REPRS: [(&str, &str); 7] = [ 387 | ("0.0.0.0", "0.0.0.0"), 388 | ("255.255.255.255", "255.255.255.255"), 389 | ("10.0", "10.0.0.0"), 390 | ("184.172.10.74", "184.172.10.74"), 391 | ("3098282570", "184.172.10.74"), 392 | ("0xb8.0xac.0x0a.0x4a", "184.172.10.74"), 393 | ("0270.0254.0012.0112", "184.172.10.74"), 394 | ]; 395 | 396 | const IP4_SWIDTHS: [u8; 5] = [1, 8, 22, 27, 32]; 397 | 398 | #[test] 399 | fn test_parse_subnetport_ip4() { 400 | for (s, ip4) in IP4_REPRS { 401 | let subnets = Subnets::from_str(s).unwrap(); 402 | assert_eq!(subnets.0.len(), 1); 403 | assert!(matches!(subnets.0[0].address, IpAddr::V4(_))); 404 | assert_eq!(subnets.0[0].address.to_string(), ip4.to_string()); 405 | assert_eq!(subnets.0[0].cidr, 32); 406 | assert_eq!(subnets.0[0].ports, Ports::None); 407 | } 408 | 409 | let s = "10.256.0.0"; 410 | let subnets = Subnets::from_str(s); 411 | assert!(matches!(subnets, Err(_))); 412 | } 413 | 414 | #[test] 415 | fn test_parse_subnetport_ip4_with_mask() { 416 | for (s, ip4) in IP4_REPRS { 417 | for width in IP4_SWIDTHS { 418 | let s = format!("{s}/{width}"); 419 | let subnets = Subnets::from_str(&s).unwrap(); 420 | assert_eq!(subnets.0.len(), 1); 421 | assert!(matches!(subnets.0[0].address, IpAddr::V4(_))); 422 | assert_eq!(subnets.0[0].address.to_string(), ip4.to_string()); 423 | assert_eq!(subnets.0[0].cidr, width); 424 | assert_eq!(subnets.0[0].ports, Ports::None); 425 | } 426 | } 427 | 428 | let s = "10.256.0.0"; 429 | let subnets = Subnets::from_str(s); 430 | assert!(matches!(subnets, Err(_))); 431 | } 432 | 433 | #[test] 434 | fn test_parse_subnetport_ip4_with_port() { 435 | for (s, ip4) in IP4_REPRS { 436 | let s = format!("{s}:80"); 437 | let subnets = Subnets::from_str(&s).unwrap(); 438 | assert_eq!(subnets.0.len(), 1); 439 | assert!(matches!(subnets.0[0].address, IpAddr::V4(_))); 440 | assert_eq!(subnets.0[0].address.to_string(), ip4.to_string()); 441 | assert_eq!(subnets.0[0].cidr, 32); 442 | assert_eq!(subnets.0[0].ports, Ports::Single(80)); 443 | } 444 | 445 | for (s, ip4) in IP4_REPRS { 446 | let s = format!("{s}:80-90"); 447 | let subnets = Subnets::from_str(&s).unwrap(); 448 | assert_eq!(subnets.0.len(), 1); 449 | assert!(matches!(subnets.0[0].address, IpAddr::V4(_))); 450 | assert_eq!(subnets.0[0].address.to_string(), ip4.to_string()); 451 | assert_eq!(subnets.0[0].cidr, 32); 452 | assert_eq!(subnets.0[0].ports, Ports::Range(80, 90)); 453 | } 454 | } 455 | 456 | #[test] 457 | fn test_parse_subnetport_ip4_with_port_and_mask() { 458 | for (s, ip4) in IP4_REPRS { 459 | let s = format!("{s}/32:80"); 460 | let subnets = Subnets::from_str(&s).unwrap(); 461 | assert_eq!(subnets.0.len(), 1); 462 | assert!(matches!(subnets.0[0].address, IpAddr::V4(_))); 463 | assert_eq!(subnets.0[0].address.to_string(), ip4.to_string()); 464 | assert_eq!(subnets.0[0].cidr, 32); 465 | assert_eq!(subnets.0[0].ports, Ports::Single(80)); 466 | } 467 | 468 | for (s, ip4) in IP4_REPRS { 469 | let s = format!("{s}/16:80-90"); 470 | let subnets = Subnets::from_str(&s).unwrap(); 471 | assert_eq!(subnets.0.len(), 1); 472 | assert!(matches!(subnets.0[0].address, IpAddr::V4(_))); 473 | assert_eq!(subnets.0[0].address.to_string(), ip4.to_string()); 474 | assert_eq!(subnets.0[0].cidr, 16); 475 | assert_eq!(subnets.0[0].ports, Ports::Range(80, 90)); 476 | } 477 | } 478 | 479 | const IP6_REPRS: [(&str, &str); 4] = [ 480 | ("::", "::"), 481 | ("::1", "::1"), 482 | ("fc00::", "fc00::"), 483 | ("2a01:7e00:e000:188::1", "2a01:7e00:e000:188::1"), 484 | ]; 485 | 486 | const IP6_SWIDTHS: [u8; 5] = [48, 64, 96, 115, 128]; 487 | 488 | #[test] 489 | fn test_parse_subnetport_ip6() { 490 | for (s, ip6) in IP6_REPRS { 491 | let subnets = Subnets::from_str(s).unwrap(); 492 | assert_eq!(subnets.0.len(), 1); 493 | assert!(matches!(subnets.0[0].address, IpAddr::V6(_))); 494 | assert_eq!(subnets.0[0].address.to_string(), ip6.to_string()); 495 | assert_eq!(subnets.0[0].cidr, 128); 496 | assert_eq!(subnets.0[0].ports, Ports::None); 497 | } 498 | } 499 | 500 | #[test] 501 | fn test_parse_subnetport_ip6_with_mask() { 502 | for (s, ip6) in IP6_REPRS { 503 | for width in IP6_SWIDTHS { 504 | let s = format!("{s}/{width}"); 505 | let subnets = Subnets::from_str(&s).unwrap(); 506 | assert_eq!(subnets.0.len(), 1); 507 | assert!(matches!(subnets.0[0].address, IpAddr::V6(_))); 508 | assert_eq!(subnets.0[0].address.to_string(), ip6.to_string()); 509 | assert_eq!(subnets.0[0].cidr, width); 510 | assert_eq!(subnets.0[0].ports, Ports::None); 511 | } 512 | } 513 | 514 | let s = "10.256.0.0"; 515 | let subnets = Subnets::from_str(s); 516 | assert!(matches!(subnets, Err(_))); 517 | } 518 | 519 | #[test] 520 | fn test_parse_subnetport_ip6_with_port() { 521 | for (s, ip6) in IP6_REPRS { 522 | let s = format!("[{s}]:80"); 523 | let subnets = Subnets::from_str(&s).unwrap(); 524 | assert_eq!(subnets.0.len(), 1); 525 | assert!(matches!(subnets.0[0].address, IpAddr::V6(_))); 526 | assert_eq!(subnets.0[0].address.to_string(), ip6.to_string()); 527 | assert_eq!(subnets.0[0].cidr, 128); 528 | assert_eq!(subnets.0[0].ports, Ports::Single(80)); 529 | } 530 | 531 | for (s, ip6) in IP6_REPRS { 532 | let s = format!("[{s}]:80-90"); 533 | let subnets = Subnets::from_str(&s).unwrap(); 534 | assert_eq!(subnets.0.len(), 1); 535 | assert!(matches!(subnets.0[0].address, IpAddr::V6(_))); 536 | assert_eq!(subnets.0[0].address.to_string(), ip6.to_string()); 537 | assert_eq!(subnets.0[0].cidr, 128); 538 | assert_eq!(subnets.0[0].ports, Ports::Range(80, 90)); 539 | } 540 | } 541 | 542 | #[test] 543 | fn test_parse_subnetport_ip6_with_port_and_mask() { 544 | for (s, ip6) in IP6_REPRS { 545 | let s = format!("[{s}/128]:80"); 546 | let subnets = Subnets::from_str(&s).unwrap(); 547 | assert_eq!(subnets.0.len(), 1); 548 | assert!(matches!(subnets.0[0].address, IpAddr::V6(_))); 549 | assert_eq!(subnets.0[0].address.to_string(), ip6.to_string()); 550 | assert_eq!(subnets.0[0].cidr, 128); 551 | assert_eq!(subnets.0[0].ports, Ports::Single(80)); 552 | } 553 | 554 | for (s, ip6) in IP6_REPRS { 555 | let s = format!("[{s}/16]:80-90"); 556 | let subnets = Subnets::from_str(&s).unwrap(); 557 | assert_eq!(subnets.0.len(), 1); 558 | assert!(matches!(subnets.0[0].address, IpAddr::V6(_))); 559 | assert_eq!(subnets.0[0].address.to_string(), ip6.to_string()); 560 | assert_eq!(subnets.0[0].cidr, 16); 561 | assert_eq!(subnets.0[0].ports, Ports::Range(80, 90)); 562 | } 563 | } 564 | } 565 | -------------------------------------------------------------------------------- /Cargo.lock: -------------------------------------------------------------------------------- 1 | # This file is automatically @generated by Cargo. 2 | # It is not intended for manual editing. 3 | version = 3 4 | 5 | [[package]] 6 | name = "aho-corasick" 7 | version = "0.7.20" 8 | source = "registry+https://github.com/rust-lang/crates.io-index" 9 | checksum = "cc936419f96fa211c1b9166887b38e5e40b19958e5b895be7c1f93adec7071ac" 10 | dependencies = [ 11 | "memchr", 12 | ] 13 | 14 | [[package]] 15 | name = "anyhow" 16 | version = "1.0.69" 17 | source = "registry+https://github.com/rust-lang/crates.io-index" 18 | checksum = "224afbd727c3d6e4b90103ece64b8d1b67fbb1973b1046c2281eed3f3803f800" 19 | 20 | [[package]] 21 | name = "atty" 22 | version = "0.2.14" 23 | source = "registry+https://github.com/rust-lang/crates.io-index" 24 | checksum = "d9b39be18770d11421cdb1b9947a45dd3f37e93092cbf377614828a319d5fee8" 25 | dependencies = [ 26 | "hermit-abi 0.1.19", 27 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 28 | "winapi", 29 | ] 30 | 31 | [[package]] 32 | name = "autocfg" 33 | version = "1.1.0" 34 | source = "registry+https://github.com/rust-lang/crates.io-index" 35 | checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa" 36 | 37 | [[package]] 38 | name = "bitflags" 39 | version = "1.3.2" 40 | source = "registry+https://github.com/rust-lang/crates.io-index" 41 | checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" 42 | 43 | [[package]] 44 | name = "bytes" 45 | version = "1.4.0" 46 | source = "registry+https://github.com/rust-lang/crates.io-index" 47 | checksum = "89b2fd2a0dcf38d7971e2194b6b6eebab45ae01067456a7fd93d5547a61b70be" 48 | 49 | [[package]] 50 | name = "cfg-if" 51 | version = "1.0.0" 52 | source = "registry+https://github.com/rust-lang/crates.io-index" 53 | checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" 54 | 55 | [[package]] 56 | name = "clap" 57 | version = "3.2.23" 58 | source = "registry+https://github.com/rust-lang/crates.io-index" 59 | checksum = "71655c45cb9845d3270c9d6df84ebe72b4dad3c2ba3f7023ad47c144e4e473a5" 60 | dependencies = [ 61 | "atty", 62 | "bitflags", 63 | "clap_derive", 64 | "clap_lex", 65 | "indexmap", 66 | "once_cell", 67 | "strsim", 68 | "termcolor", 69 | "textwrap", 70 | ] 71 | 72 | [[package]] 73 | name = "clap_derive" 74 | version = "3.2.18" 75 | source = "registry+https://github.com/rust-lang/crates.io-index" 76 | checksum = "ea0c8bce528c4be4da13ea6fead8965e95b6073585a2f05204bd8f4119f82a65" 77 | dependencies = [ 78 | "heck", 79 | "proc-macro-error", 80 | "proc-macro2", 81 | "quote", 82 | "syn", 83 | ] 84 | 85 | [[package]] 86 | name = "clap_lex" 87 | version = "0.2.4" 88 | source = "registry+https://github.com/rust-lang/crates.io-index" 89 | checksum = "2850f2f5a82cbf437dd5af4d49848fbdfc27c157c3d010345776f952765261c5" 90 | dependencies = [ 91 | "os_str_bytes", 92 | ] 93 | 94 | [[package]] 95 | name = "ctrlc" 96 | version = "3.2.5" 97 | source = "registry+https://github.com/rust-lang/crates.io-index" 98 | checksum = "bbcf33c2a618cbe41ee43ae6e9f2e48368cd9f9db2896f10167d8d762679f639" 99 | dependencies = [ 100 | "nix 0.26.2", 101 | "windows-sys 0.45.0", 102 | ] 103 | 104 | [[package]] 105 | name = "dns-lookup" 106 | version = "1.0.8" 107 | source = "registry+https://github.com/rust-lang/crates.io-index" 108 | checksum = "53ecafc952c4528d9b51a458d1a8904b81783feff9fde08ab6ed2545ff396872" 109 | dependencies = [ 110 | "cfg-if", 111 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 112 | "socket2", 113 | "winapi", 114 | ] 115 | 116 | [[package]] 117 | name = "env_logger" 118 | version = "0.9.3" 119 | source = "registry+https://github.com/rust-lang/crates.io-index" 120 | checksum = "a12e6657c4c97ebab115a42dcee77225f7f482cdd841cf7088c657a42e9e00e7" 121 | dependencies = [ 122 | "atty", 123 | "humantime", 124 | "log", 125 | "regex", 126 | "termcolor", 127 | ] 128 | 129 | [[package]] 130 | name = "fast-socks5" 131 | version = "0.8.1" 132 | source = "registry+https://github.com/rust-lang/crates.io-index" 133 | checksum = "d2687b5a6108f18ba8621e0e618a3be1dcc2768632dad24b7cea1f87975375a9" 134 | dependencies = [ 135 | "anyhow", 136 | "log", 137 | "thiserror", 138 | "tokio", 139 | "tokio-stream", 140 | ] 141 | 142 | [[package]] 143 | name = "futures" 144 | version = "0.3.26" 145 | source = "registry+https://github.com/rust-lang/crates.io-index" 146 | checksum = "13e2792b0ff0340399d58445b88fd9770e3489eff258a4cbc1523418f12abf84" 147 | dependencies = [ 148 | "futures-channel", 149 | "futures-core", 150 | "futures-executor", 151 | "futures-io", 152 | "futures-sink", 153 | "futures-task", 154 | "futures-util", 155 | ] 156 | 157 | [[package]] 158 | name = "futures-channel" 159 | version = "0.3.26" 160 | source = "registry+https://github.com/rust-lang/crates.io-index" 161 | checksum = "2e5317663a9089767a1ec00a487df42e0ca174b61b4483213ac24448e4664df5" 162 | dependencies = [ 163 | "futures-core", 164 | "futures-sink", 165 | ] 166 | 167 | [[package]] 168 | name = "futures-core" 169 | version = "0.3.26" 170 | source = "registry+https://github.com/rust-lang/crates.io-index" 171 | checksum = "ec90ff4d0fe1f57d600049061dc6bb68ed03c7d2fbd697274c41805dcb3f8608" 172 | 173 | [[package]] 174 | name = "futures-executor" 175 | version = "0.3.26" 176 | source = "registry+https://github.com/rust-lang/crates.io-index" 177 | checksum = "e8de0a35a6ab97ec8869e32a2473f4b1324459e14c29275d14b10cb1fd19b50e" 178 | dependencies = [ 179 | "futures-core", 180 | "futures-task", 181 | "futures-util", 182 | ] 183 | 184 | [[package]] 185 | name = "futures-io" 186 | version = "0.3.26" 187 | source = "registry+https://github.com/rust-lang/crates.io-index" 188 | checksum = "bfb8371b6fb2aeb2d280374607aeabfc99d95c72edfe51692e42d3d7f0d08531" 189 | 190 | [[package]] 191 | name = "futures-macro" 192 | version = "0.3.26" 193 | source = "registry+https://github.com/rust-lang/crates.io-index" 194 | checksum = "95a73af87da33b5acf53acfebdc339fe592ecf5357ac7c0a7734ab9d8c876a70" 195 | dependencies = [ 196 | "proc-macro2", 197 | "quote", 198 | "syn", 199 | ] 200 | 201 | [[package]] 202 | name = "futures-sink" 203 | version = "0.3.26" 204 | source = "registry+https://github.com/rust-lang/crates.io-index" 205 | checksum = "f310820bb3e8cfd46c80db4d7fb8353e15dfff853a127158425f31e0be6c8364" 206 | 207 | [[package]] 208 | name = "futures-task" 209 | version = "0.3.26" 210 | source = "registry+https://github.com/rust-lang/crates.io-index" 211 | checksum = "dcf79a1bf610b10f42aea489289c5a2c478a786509693b80cd39c44ccd936366" 212 | 213 | [[package]] 214 | name = "futures-util" 215 | version = "0.3.26" 216 | source = "registry+https://github.com/rust-lang/crates.io-index" 217 | checksum = "9c1d6de3acfef38d2be4b1f543f553131788603495be83da675e180c8d6b7bd1" 218 | dependencies = [ 219 | "futures-channel", 220 | "futures-core", 221 | "futures-io", 222 | "futures-macro", 223 | "futures-sink", 224 | "futures-task", 225 | "memchr", 226 | "pin-project-lite", 227 | "pin-utils", 228 | "slab", 229 | ] 230 | 231 | [[package]] 232 | name = "hashbrown" 233 | version = "0.12.3" 234 | source = "registry+https://github.com/rust-lang/crates.io-index" 235 | checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888" 236 | 237 | [[package]] 238 | name = "heck" 239 | version = "0.4.1" 240 | source = "registry+https://github.com/rust-lang/crates.io-index" 241 | checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" 242 | 243 | [[package]] 244 | name = "hermit-abi" 245 | version = "0.1.19" 246 | source = "registry+https://github.com/rust-lang/crates.io-index" 247 | checksum = "62b467343b94ba476dcb2500d242dadbb39557df889310ac77c5d99100aaac33" 248 | dependencies = [ 249 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 250 | ] 251 | 252 | [[package]] 253 | name = "hermit-abi" 254 | version = "0.2.6" 255 | source = "registry+https://github.com/rust-lang/crates.io-index" 256 | checksum = "ee512640fe35acbfb4bb779db6f0d80704c2cacfa2e39b601ef3e3f47d1ae4c7" 257 | dependencies = [ 258 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 259 | ] 260 | 261 | [[package]] 262 | name = "humantime" 263 | version = "2.1.0" 264 | source = "registry+https://github.com/rust-lang/crates.io-index" 265 | checksum = "9a3a5bfb195931eeb336b2a7b4d761daec841b97f947d34394601737a7bba5e4" 266 | 267 | [[package]] 268 | name = "indexmap" 269 | version = "1.9.2" 270 | source = "registry+https://github.com/rust-lang/crates.io-index" 271 | checksum = "1885e79c1fc4b10f0e172c475f458b7f7b93061064d98c3293e98c5ba0c8b399" 272 | dependencies = [ 273 | "autocfg", 274 | "hashbrown", 275 | ] 276 | 277 | [[package]] 278 | name = "libc" 279 | version = "0.2.139" 280 | source = "registry+https://github.com/rust-lang/crates.io-index" 281 | checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79" 282 | 283 | [[package]] 284 | name = "libc" 285 | version = "0.2.139" 286 | source = "git+https://github.com/rust-lang/libc?rev=44cc30c6b68427d3628926868758d35fe561bbe6#44cc30c6b68427d3628926868758d35fe561bbe6" 287 | 288 | [[package]] 289 | name = "lock_api" 290 | version = "0.4.9" 291 | source = "registry+https://github.com/rust-lang/crates.io-index" 292 | checksum = "435011366fe56583b16cf956f9df0095b405b82d76425bc8981c0e22e60ec4df" 293 | dependencies = [ 294 | "autocfg", 295 | "scopeguard", 296 | ] 297 | 298 | [[package]] 299 | name = "log" 300 | version = "0.4.17" 301 | source = "registry+https://github.com/rust-lang/crates.io-index" 302 | checksum = "abb12e687cfb44aa40f41fc3978ef76448f9b6038cad6aef4259d3c095a2382e" 303 | dependencies = [ 304 | "cfg-if", 305 | ] 306 | 307 | [[package]] 308 | name = "memchr" 309 | version = "2.5.0" 310 | source = "registry+https://github.com/rust-lang/crates.io-index" 311 | checksum = "2dffe52ecf27772e601905b7522cb4ef790d2cc203488bbd0e2fe85fcb74566d" 312 | 313 | [[package]] 314 | name = "memoffset" 315 | version = "0.8.0" 316 | source = "registry+https://github.com/rust-lang/crates.io-index" 317 | checksum = "d61c719bcfbcf5d62b3a09efa6088de8c54bc0bfcd3ea7ae39fcc186108b8de1" 318 | dependencies = [ 319 | "autocfg", 320 | ] 321 | 322 | [[package]] 323 | name = "mio" 324 | version = "0.8.6" 325 | source = "registry+https://github.com/rust-lang/crates.io-index" 326 | checksum = "5b9d9a46eff5b4ff64b45a9e316a6d1e0bc719ef429cbec4dc630684212bfdf9" 327 | dependencies = [ 328 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 329 | "log", 330 | "wasi", 331 | "windows-sys 0.45.0", 332 | ] 333 | 334 | [[package]] 335 | name = "nix" 336 | version = "0.26.1" 337 | source = "git+https://github.com/nix-rust/nix#b2318f98d31ff96bcd8f85910766a48638c16622" 338 | dependencies = [ 339 | "bitflags", 340 | "cfg-if", 341 | "libc 0.2.139 (git+https://github.com/rust-lang/libc?rev=44cc30c6b68427d3628926868758d35fe561bbe6)", 342 | "memoffset", 343 | "pin-utils", 344 | "static_assertions", 345 | ] 346 | 347 | [[package]] 348 | name = "nix" 349 | version = "0.26.2" 350 | source = "registry+https://github.com/rust-lang/crates.io-index" 351 | checksum = "bfdda3d196821d6af13126e40375cdf7da646a96114af134d5f417a9a1dc8e1a" 352 | dependencies = [ 353 | "bitflags", 354 | "cfg-if", 355 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 356 | "static_assertions", 357 | ] 358 | 359 | [[package]] 360 | name = "num_cpus" 361 | version = "1.15.0" 362 | source = "registry+https://github.com/rust-lang/crates.io-index" 363 | checksum = "0fac9e2da13b5eb447a6ce3d392f23a29d8694bff781bf03a16cd9ac8697593b" 364 | dependencies = [ 365 | "hermit-abi 0.2.6", 366 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 367 | ] 368 | 369 | [[package]] 370 | name = "once_cell" 371 | version = "1.17.1" 372 | source = "registry+https://github.com/rust-lang/crates.io-index" 373 | checksum = "b7e5500299e16ebb147ae15a00a942af264cf3688f47923b8fc2cd5858f23ad3" 374 | 375 | [[package]] 376 | name = "os_str_bytes" 377 | version = "6.4.1" 378 | source = "registry+https://github.com/rust-lang/crates.io-index" 379 | checksum = "9b7820b9daea5457c9f21c69448905d723fbd21136ccf521748f23fd49e723ee" 380 | 381 | [[package]] 382 | name = "parking_lot" 383 | version = "0.12.1" 384 | source = "registry+https://github.com/rust-lang/crates.io-index" 385 | checksum = "3742b2c103b9f06bc9fff0a37ff4912935851bee6d36f3c02bcc755bcfec228f" 386 | dependencies = [ 387 | "lock_api", 388 | "parking_lot_core", 389 | ] 390 | 391 | [[package]] 392 | name = "parking_lot_core" 393 | version = "0.9.7" 394 | source = "registry+https://github.com/rust-lang/crates.io-index" 395 | checksum = "9069cbb9f99e3a5083476ccb29ceb1de18b9118cafa53e90c9551235de2b9521" 396 | dependencies = [ 397 | "cfg-if", 398 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 399 | "redox_syscall", 400 | "smallvec", 401 | "windows-sys 0.45.0", 402 | ] 403 | 404 | [[package]] 405 | name = "pin-project-lite" 406 | version = "0.2.9" 407 | source = "registry+https://github.com/rust-lang/crates.io-index" 408 | checksum = "e0a7ae3ac2f1173085d398531c705756c94a4c56843785df85a60c1a0afac116" 409 | 410 | [[package]] 411 | name = "pin-utils" 412 | version = "0.1.0" 413 | source = "registry+https://github.com/rust-lang/crates.io-index" 414 | checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" 415 | 416 | [[package]] 417 | name = "proc-macro-error" 418 | version = "1.0.4" 419 | source = "registry+https://github.com/rust-lang/crates.io-index" 420 | checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" 421 | dependencies = [ 422 | "proc-macro-error-attr", 423 | "proc-macro2", 424 | "quote", 425 | "syn", 426 | "version_check", 427 | ] 428 | 429 | [[package]] 430 | name = "proc-macro-error-attr" 431 | version = "1.0.4" 432 | source = "registry+https://github.com/rust-lang/crates.io-index" 433 | checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" 434 | dependencies = [ 435 | "proc-macro2", 436 | "quote", 437 | "version_check", 438 | ] 439 | 440 | [[package]] 441 | name = "proc-macro2" 442 | version = "1.0.51" 443 | source = "registry+https://github.com/rust-lang/crates.io-index" 444 | checksum = "5d727cae5b39d21da60fa540906919ad737832fe0b1c165da3a34d6548c849d6" 445 | dependencies = [ 446 | "unicode-ident", 447 | ] 448 | 449 | [[package]] 450 | name = "quote" 451 | version = "1.0.23" 452 | source = "registry+https://github.com/rust-lang/crates.io-index" 453 | checksum = "8856d8364d252a14d474036ea1358d63c9e6965c8e5c1885c18f73d70bff9c7b" 454 | dependencies = [ 455 | "proc-macro2", 456 | ] 457 | 458 | [[package]] 459 | name = "redox_syscall" 460 | version = "0.2.16" 461 | source = "registry+https://github.com/rust-lang/crates.io-index" 462 | checksum = "fb5a58c1855b4b6819d59012155603f0b22ad30cad752600aadfcb695265519a" 463 | dependencies = [ 464 | "bitflags", 465 | ] 466 | 467 | [[package]] 468 | name = "regex" 469 | version = "1.7.1" 470 | source = "registry+https://github.com/rust-lang/crates.io-index" 471 | checksum = "48aaa5748ba571fb95cd2c85c09f629215d3a6ece942baa100950af03a34f733" 472 | dependencies = [ 473 | "aho-corasick", 474 | "memchr", 475 | "regex-syntax", 476 | ] 477 | 478 | [[package]] 479 | name = "regex-syntax" 480 | version = "0.6.28" 481 | source = "registry+https://github.com/rust-lang/crates.io-index" 482 | checksum = "456c603be3e8d448b072f410900c09faf164fbce2d480456f50eea6e25f9c848" 483 | 484 | [[package]] 485 | name = "scopeguard" 486 | version = "1.1.0" 487 | source = "registry+https://github.com/rust-lang/crates.io-index" 488 | checksum = "d29ab0c6d3fc0ee92fe66e2d99f700eab17a8d57d1c1d3b748380fb20baa78cd" 489 | 490 | [[package]] 491 | name = "signal-hook-registry" 492 | version = "1.4.1" 493 | source = "registry+https://github.com/rust-lang/crates.io-index" 494 | checksum = "d8229b473baa5980ac72ef434c4415e70c4b5e71b423043adb4ba059f89c99a1" 495 | dependencies = [ 496 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 497 | ] 498 | 499 | [[package]] 500 | name = "slab" 501 | version = "0.4.8" 502 | source = "registry+https://github.com/rust-lang/crates.io-index" 503 | checksum = "6528351c9bc8ab22353f9d776db39a20288e8d6c37ef8cfe3317cf875eecfc2d" 504 | dependencies = [ 505 | "autocfg", 506 | ] 507 | 508 | [[package]] 509 | name = "smallvec" 510 | version = "1.10.0" 511 | source = "registry+https://github.com/rust-lang/crates.io-index" 512 | checksum = "a507befe795404456341dfab10cef66ead4c041f62b8b11bbb92bffe5d0953e0" 513 | 514 | [[package]] 515 | name = "socket2" 516 | version = "0.4.7" 517 | source = "registry+https://github.com/rust-lang/crates.io-index" 518 | checksum = "02e2d2db9033d13a1567121ddd7a095ee144db4e1ca1b1bda3419bc0da294ebd" 519 | dependencies = [ 520 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 521 | "winapi", 522 | ] 523 | 524 | [[package]] 525 | name = "sshuttle_rust" 526 | version = "0.1.0" 527 | dependencies = [ 528 | "clap", 529 | "ctrlc", 530 | "dns-lookup", 531 | "env_logger", 532 | "fast-socks5", 533 | "futures", 534 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 535 | "log", 536 | "nix 0.26.1", 537 | "regex", 538 | "thiserror", 539 | "tokio", 540 | ] 541 | 542 | [[package]] 543 | name = "static_assertions" 544 | version = "1.1.0" 545 | source = "registry+https://github.com/rust-lang/crates.io-index" 546 | checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" 547 | 548 | [[package]] 549 | name = "strsim" 550 | version = "0.10.0" 551 | source = "registry+https://github.com/rust-lang/crates.io-index" 552 | checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623" 553 | 554 | [[package]] 555 | name = "syn" 556 | version = "1.0.109" 557 | source = "registry+https://github.com/rust-lang/crates.io-index" 558 | checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" 559 | dependencies = [ 560 | "proc-macro2", 561 | "quote", 562 | "unicode-ident", 563 | ] 564 | 565 | [[package]] 566 | name = "termcolor" 567 | version = "1.2.0" 568 | source = "registry+https://github.com/rust-lang/crates.io-index" 569 | checksum = "be55cf8942feac5c765c2c993422806843c9a9a45d4d5c407ad6dd2ea95eb9b6" 570 | dependencies = [ 571 | "winapi-util", 572 | ] 573 | 574 | [[package]] 575 | name = "textwrap" 576 | version = "0.16.0" 577 | source = "registry+https://github.com/rust-lang/crates.io-index" 578 | checksum = "222a222a5bfe1bba4a77b45ec488a741b3cb8872e5e499451fd7d0129c9c7c3d" 579 | 580 | [[package]] 581 | name = "thiserror" 582 | version = "1.0.38" 583 | source = "registry+https://github.com/rust-lang/crates.io-index" 584 | checksum = "6a9cd18aa97d5c45c6603caea1da6628790b37f7a34b6ca89522331c5180fed0" 585 | dependencies = [ 586 | "thiserror-impl", 587 | ] 588 | 589 | [[package]] 590 | name = "thiserror-impl" 591 | version = "1.0.38" 592 | source = "registry+https://github.com/rust-lang/crates.io-index" 593 | checksum = "1fb327af4685e4d03fa8cbcf1716380da910eeb2bb8be417e7f9fd3fb164f36f" 594 | dependencies = [ 595 | "proc-macro2", 596 | "quote", 597 | "syn", 598 | ] 599 | 600 | [[package]] 601 | name = "tokio" 602 | version = "1.25.0" 603 | source = "registry+https://github.com/rust-lang/crates.io-index" 604 | checksum = "c8e00990ebabbe4c14c08aca901caed183ecd5c09562a12c824bb53d3c3fd3af" 605 | dependencies = [ 606 | "autocfg", 607 | "bytes", 608 | "libc 0.2.139 (registry+https://github.com/rust-lang/crates.io-index)", 609 | "memchr", 610 | "mio", 611 | "num_cpus", 612 | "parking_lot", 613 | "pin-project-lite", 614 | "signal-hook-registry", 615 | "socket2", 616 | "tokio-macros", 617 | "windows-sys 0.42.0", 618 | ] 619 | 620 | [[package]] 621 | name = "tokio-macros" 622 | version = "1.8.2" 623 | source = "registry+https://github.com/rust-lang/crates.io-index" 624 | checksum = "d266c00fde287f55d3f1c3e96c500c362a2b8c695076ec180f27918820bc6df8" 625 | dependencies = [ 626 | "proc-macro2", 627 | "quote", 628 | "syn", 629 | ] 630 | 631 | [[package]] 632 | name = "tokio-stream" 633 | version = "0.1.12" 634 | source = "registry+https://github.com/rust-lang/crates.io-index" 635 | checksum = "8fb52b74f05dbf495a8fba459fdc331812b96aa086d9eb78101fa0d4569c3313" 636 | dependencies = [ 637 | "futures-core", 638 | "pin-project-lite", 639 | "tokio", 640 | ] 641 | 642 | [[package]] 643 | name = "unicode-ident" 644 | version = "1.0.6" 645 | source = "registry+https://github.com/rust-lang/crates.io-index" 646 | checksum = "84a22b9f218b40614adcb3f4ff08b703773ad44fa9423e4e0d346d5db86e4ebc" 647 | 648 | [[package]] 649 | name = "version_check" 650 | version = "0.9.4" 651 | source = "registry+https://github.com/rust-lang/crates.io-index" 652 | checksum = "49874b5167b65d7193b8aba1567f5c7d93d001cafc34600cee003eda787e483f" 653 | 654 | [[package]] 655 | name = "wasi" 656 | version = "0.11.0+wasi-snapshot-preview1" 657 | source = "registry+https://github.com/rust-lang/crates.io-index" 658 | checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" 659 | 660 | [[package]] 661 | name = "winapi" 662 | version = "0.3.9" 663 | source = "registry+https://github.com/rust-lang/crates.io-index" 664 | checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" 665 | dependencies = [ 666 | "winapi-i686-pc-windows-gnu", 667 | "winapi-x86_64-pc-windows-gnu", 668 | ] 669 | 670 | [[package]] 671 | name = "winapi-i686-pc-windows-gnu" 672 | version = "0.4.0" 673 | source = "registry+https://github.com/rust-lang/crates.io-index" 674 | checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" 675 | 676 | [[package]] 677 | name = "winapi-util" 678 | version = "0.1.5" 679 | source = "registry+https://github.com/rust-lang/crates.io-index" 680 | checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" 681 | dependencies = [ 682 | "winapi", 683 | ] 684 | 685 | [[package]] 686 | name = "winapi-x86_64-pc-windows-gnu" 687 | version = "0.4.0" 688 | source = "registry+https://github.com/rust-lang/crates.io-index" 689 | checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" 690 | 691 | [[package]] 692 | name = "windows-sys" 693 | version = "0.42.0" 694 | source = "registry+https://github.com/rust-lang/crates.io-index" 695 | checksum = "5a3e1820f08b8513f676f7ab6c1f99ff312fb97b553d30ff4dd86f9f15728aa7" 696 | dependencies = [ 697 | "windows_aarch64_gnullvm", 698 | "windows_aarch64_msvc", 699 | "windows_i686_gnu", 700 | "windows_i686_msvc", 701 | "windows_x86_64_gnu", 702 | "windows_x86_64_gnullvm", 703 | "windows_x86_64_msvc", 704 | ] 705 | 706 | [[package]] 707 | name = "windows-sys" 708 | version = "0.45.0" 709 | source = "registry+https://github.com/rust-lang/crates.io-index" 710 | checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" 711 | dependencies = [ 712 | "windows-targets", 713 | ] 714 | 715 | [[package]] 716 | name = "windows-targets" 717 | version = "0.42.1" 718 | source = "registry+https://github.com/rust-lang/crates.io-index" 719 | checksum = "8e2522491fbfcd58cc84d47aeb2958948c4b8982e9a2d8a2a35bbaed431390e7" 720 | dependencies = [ 721 | "windows_aarch64_gnullvm", 722 | "windows_aarch64_msvc", 723 | "windows_i686_gnu", 724 | "windows_i686_msvc", 725 | "windows_x86_64_gnu", 726 | "windows_x86_64_gnullvm", 727 | "windows_x86_64_msvc", 728 | ] 729 | 730 | [[package]] 731 | name = "windows_aarch64_gnullvm" 732 | version = "0.42.1" 733 | source = "registry+https://github.com/rust-lang/crates.io-index" 734 | checksum = "8c9864e83243fdec7fc9c5444389dcbbfd258f745e7853198f365e3c4968a608" 735 | 736 | [[package]] 737 | name = "windows_aarch64_msvc" 738 | version = "0.42.1" 739 | source = "registry+https://github.com/rust-lang/crates.io-index" 740 | checksum = "4c8b1b673ffc16c47a9ff48570a9d85e25d265735c503681332589af6253c6c7" 741 | 742 | [[package]] 743 | name = "windows_i686_gnu" 744 | version = "0.42.1" 745 | source = "registry+https://github.com/rust-lang/crates.io-index" 746 | checksum = "de3887528ad530ba7bdbb1faa8275ec7a1155a45ffa57c37993960277145d640" 747 | 748 | [[package]] 749 | name = "windows_i686_msvc" 750 | version = "0.42.1" 751 | source = "registry+https://github.com/rust-lang/crates.io-index" 752 | checksum = "bf4d1122317eddd6ff351aa852118a2418ad4214e6613a50e0191f7004372605" 753 | 754 | [[package]] 755 | name = "windows_x86_64_gnu" 756 | version = "0.42.1" 757 | source = "registry+https://github.com/rust-lang/crates.io-index" 758 | checksum = "c1040f221285e17ebccbc2591ffdc2d44ee1f9186324dd3e84e99ac68d699c45" 759 | 760 | [[package]] 761 | name = "windows_x86_64_gnullvm" 762 | version = "0.42.1" 763 | source = "registry+https://github.com/rust-lang/crates.io-index" 764 | checksum = "628bfdf232daa22b0d64fdb62b09fcc36bb01f05a3939e20ab73aaf9470d0463" 765 | 766 | [[package]] 767 | name = "windows_x86_64_msvc" 768 | version = "0.42.1" 769 | source = "registry+https://github.com/rust-lang/crates.io-index" 770 | checksum = "447660ad36a13288b1db4d4248e857b510e8c3a225c822ba4fb748c0aafecffd" 771 | -------------------------------------------------------------------------------- /src/firewall/tproxy.rs: -------------------------------------------------------------------------------- 1 | use std::net::SocketAddr; 2 | use std::os::unix::prelude::AsRawFd; 3 | 4 | use nix::sys::socket::setsockopt; 5 | use nix::sys::socket::sockopt::IpTransparent; 6 | use tokio::net::TcpListener; 7 | use tokio::net::TcpStream; 8 | use tokio::net::UdpSocket; 9 | 10 | use crate::network::ListenerAddr; 11 | use crate::network::Ports; 12 | use crate::network::Protocol; 13 | use crate::network::SubnetFamily; 14 | use crate::network::SubnetsFamily; 15 | 16 | use super::{Commands, Firewall, FirewallConfig, FirewallError, FirewallSubnetConfig}; 17 | 18 | pub struct TProxyFirewall {} 19 | 20 | fn chain_name(listener: &ListenerAddr, name: &str) -> String { 21 | match listener.protocol { 22 | Protocol::Tcp => format!("sshuttle-{}-tcp-{}", name, listener.port()), 23 | Protocol::Udp => format!("sshuttle-{}-udp-{}", name, listener.port()), 24 | } 25 | } 26 | 27 | impl TProxyFirewall { 28 | pub const fn new() -> Self { 29 | TProxyFirewall {} 30 | } 31 | 32 | #[rustfmt::skip] 33 | fn setup_family( 34 | &self, 35 | config: &FirewallConfig, 36 | subnet_config: &FirewallSubnetConfig, 37 | commands: &mut Commands, 38 | ) { 39 | let port = subnet_config.listener.port().to_string(); 40 | let protocol = match subnet_config.listener.protocol { 41 | Protocol::Tcp => "tcp", 42 | Protocol::Udp => "udp", 43 | }; 44 | let mark_chain = chain_name(&subnet_config.listener, "m"); 45 | let tproxy_chain = chain_name(&subnet_config.listener, "t"); 46 | let divert_chain = chain_name(&subnet_config.listener, "d"); 47 | let family = subnet_config.family(); 48 | // FIXME 49 | let tmark = "0x01"; 50 | 51 | macro_rules! ipm { 52 | ( $( $e:expr),* ) => { 53 | let v = vec![ $( $e ),* ]; 54 | commands.ipt(family, "mangle", &v); 55 | }; 56 | } 57 | 58 | macro_rules! ipm_vec { 59 | ( $e:expr ) => { 60 | let v = $e; 61 | commands.ipt(family, "mangle", &v); 62 | }; 63 | } 64 | 65 | ipm!("-N", &mark_chain); 66 | ipm!("-F", &mark_chain); 67 | ipm!("-N", &divert_chain); 68 | ipm!("-F", &divert_chain); 69 | ipm!("-N", &tproxy_chain); 70 | ipm!("-F", &tproxy_chain); 71 | 72 | if let Some(user) = &config.filter_from_user { 73 | ipm!("-I", "OUTPUT", "1", "-m", "owner", "--uid-owner", user, "-j", "MARK", "set-mark", &port); 74 | 75 | ipm!("-I", "OUTPUT", "1", "-m", "mark", "--mark", &port, "-j", &mark_chain); 76 | ipm!("-I", "PREROUTING", "1", "-m", "mark","--mark", &port, "-j", &tproxy_chain); 77 | } else { 78 | ipm!("-I", "OUTPUT", "1", "-j", &mark_chain); 79 | ipm!("-I", "PREROUTING", "1", "-j", &tproxy_chain); 80 | } 81 | 82 | ipm!("-A", &mark_chain, "-j", "RETURN", "-m", "addrtype", "--dst-type", "LOCAL", "-m", protocol, "-p", protocol); 83 | ipm!("-A", &tproxy_chain, "-j", "RETURN", "-m", "addrtype", "--dst-type", "LOCAL", "-m", protocol, "-p", protocol); 84 | 85 | ipm!("-A", &divert_chain, "-j", "MARK", "--set-mark", tmark); 86 | ipm!("-A", &divert_chain, "-j", "ACCEPT"); 87 | ipm!("-A", &tproxy_chain, "-m", "socket", "-j", &divert_chain, "-m", protocol, "-p", protocol); 88 | 89 | for subnet in subnet_config.excludes.iter() { 90 | let subnet_str = subnet.subnet_str(); 91 | let ports: Vec = match subnet.ports() { 92 | Ports::Single(port) => vec!["--dport".to_string(), port.to_string()], 93 | Ports::Range(first, last) => vec!["--dport".to_string(), format!("{first}:{last}")], 94 | Ports::None => vec![], 95 | }; 96 | let ports: Vec<_> = ports.iter().map(String::as_str).collect(); 97 | 98 | { 99 | let mut cmd = vec!["-A", &mark_chain, "-j", "RETURN", "--dest", &subnet_str, "-m", protocol, "-p", protocol]; 100 | cmd.extend(ports.iter()); 101 | ipm_vec!(cmd); 102 | } 103 | 104 | { 105 | let mut cmd = vec!["-A", &tproxy_chain, "-j", "RETURN", "--dest", &subnet_str, "-m", protocol, "-p", protocol]; 106 | cmd.extend(ports.iter()); 107 | ipm_vec!(cmd); 108 | } 109 | } 110 | 111 | for subnet in subnet_config.includes.iter() { 112 | let subnet_str = subnet.subnet_str(); 113 | let ports: Vec = match subnet.ports() { 114 | Ports::Single(port) => vec!["--dport".to_string(), port.to_string()], 115 | Ports::Range(first, last) => vec!["--dport".to_string(), format!("{first}:{last}")], 116 | Ports::None => vec![], 117 | }; 118 | let ports: Vec<_> = ports.iter().map(String::as_str).collect(); 119 | 120 | { 121 | let mut cmd = vec!["-A", &mark_chain, "-j", "MARK", "--set-mark", tmark, "--dest", &subnet_str, "-m", protocol, "-p", protocol]; 122 | cmd.extend(ports.iter()); 123 | ipm_vec!(cmd); 124 | } 125 | 126 | { 127 | let mut cmd = vec!["-A", &tproxy_chain, "-j", "TPROXY", "--tproxy-mark", tmark, "--dest", &subnet_str, "-m", protocol, "-p", protocol, "--on-port", &port]; 128 | cmd.extend(ports.iter()); 129 | ipm_vec!(cmd); 130 | } 131 | } 132 | } 133 | 134 | #[rustfmt::skip] 135 | fn restore_family( 136 | &self, 137 | config: &FirewallConfig, 138 | subnet_config: &FirewallSubnetConfig, 139 | commands: &mut Commands, 140 | ) { 141 | let port = subnet_config.listener.port().to_string(); 142 | let mark_chain = chain_name(&subnet_config.listener, "m"); 143 | let tproxy_chain = chain_name(&subnet_config.listener, "t"); 144 | let divert_chain = chain_name(&subnet_config.listener, "d"); 145 | let family = subnet_config.family(); 146 | 147 | 148 | macro_rules! ipm { 149 | ( $( $e:expr),* ) => { 150 | let v = vec![ $( $e ),* ]; 151 | commands.ipt_ignore_errors(family, "mangle", &v); 152 | }; 153 | } 154 | 155 | if let Some(user) = &config.filter_from_user { 156 | ipm!("-D", "OUTPUT", "-m", "owner", "--uid-owner", user, "-j", "MARK", "--set-mark", &port); 157 | ipm!("-D", "OUTPUT", "-m", "mark", "--mark", &port, "-j", &mark_chain); 158 | ipm!("-D", "PREROUTING", "1", "-m", "mark", "--mark", &port, "-j", &tproxy_chain); 159 | } else { 160 | ipm!("-D", "OUTPUT", "-j", &mark_chain); 161 | ipm!("-D", "PREROUTING", "-j", &tproxy_chain); 162 | } 163 | 164 | ipm!("-F", &mark_chain); 165 | ipm!("-X", &mark_chain); 166 | 167 | ipm!("-F", &tproxy_chain); 168 | ipm!("-X", &tproxy_chain); 169 | 170 | ipm!("-F", &divert_chain); 171 | ipm!("-X", &divert_chain); 172 | } 173 | } 174 | 175 | impl Firewall for TProxyFirewall { 176 | fn setup_tcp_listener(&self, l: &TcpListener) -> Result<(), FirewallError> { 177 | setsockopt(l.as_raw_fd(), IpTransparent, &true)?; 178 | 179 | Ok(()) 180 | } 181 | 182 | fn setup_udp_socket(&self, l: &UdpSocket) -> Result<(), FirewallError> { 183 | let fd = l.as_raw_fd(); 184 | setsockopt(fd, IpTransparent, &true)?; 185 | 186 | let value = 1u8; 187 | let value_ptr: *const libc::c_void = std::ptr::addr_of!(value).cast::(); 188 | 189 | match l.local_addr()? { 190 | SocketAddr::V4(_) => unsafe { 191 | #[allow(clippy::cast_possible_truncation)] 192 | libc::setsockopt( 193 | fd, 194 | libc::IPPROTO_IP, 195 | libc::IP_RECVORIGDSTADDR, 196 | value_ptr, 197 | std::mem::size_of::() as u32, 198 | ) 199 | }, 200 | SocketAddr::V6(_) => unsafe { 201 | #[allow(clippy::cast_possible_truncation)] 202 | libc::setsockopt( 203 | fd, 204 | libc::IPPROTO_IPV6, 205 | libc::IPV6_RECVORIGDSTADDR, 206 | value_ptr, 207 | std::mem::size_of::() as u32, 208 | ) 209 | }, 210 | }; 211 | 212 | Ok(()) 213 | } 214 | 215 | fn get_dst_addr(&self, s: &TcpStream) -> Result { 216 | Ok(s.local_addr()?) 217 | } 218 | 219 | fn setup_firewall(&self, config: &FirewallConfig) -> Result { 220 | let mut commands: Commands = self.restore_firewall(config)?; 221 | 222 | for family in &config.listeners { 223 | match family { 224 | super::FirewallListenerConfig::Ipv4(ip) => { 225 | self.setup_family(config, ip, &mut commands); 226 | } 227 | super::FirewallListenerConfig::Ipv6(ip) => { 228 | self.setup_family(config, ip, &mut commands); 229 | } 230 | } 231 | } 232 | 233 | Ok(commands) 234 | } 235 | fn restore_firewall(&self, config: &FirewallConfig) -> Result { 236 | let mut commands: Commands = Commands::new(); 237 | 238 | for family in &config.listeners { 239 | match family { 240 | super::FirewallListenerConfig::Ipv4(ip) => { 241 | self.restore_family(config, ip, &mut commands); 242 | } 243 | super::FirewallListenerConfig::Ipv6(ip) => { 244 | self.restore_family(config, ip, &mut commands); 245 | } 246 | } 247 | } 248 | 249 | Ok(commands) 250 | } 251 | } 252 | 253 | #[allow(clippy::unwrap_used)] 254 | #[cfg(test)] 255 | mod tests { 256 | use crate::{ 257 | command::Line, 258 | network::{SubnetsV4, SubnetsV6}, 259 | }; 260 | 261 | use super::*; 262 | 263 | #[test] 264 | fn test_setup_family_v4_tcp() { 265 | let firewall = TProxyFirewall::new(); 266 | let ipv4_family = FirewallSubnetConfig { 267 | enable: true, 268 | listener: ListenerAddr { 269 | protocol: Protocol::Tcp, 270 | addr: "127.0.0.1:1024".parse().unwrap(), 271 | }, 272 | includes: "1.2.3.0/24:8000-9000".parse::().unwrap(), 273 | excludes: "1.2.3.66:8080".parse::().unwrap(), 274 | }; 275 | let config = FirewallConfig { 276 | filter_from_user: None, 277 | listeners: vec![], 278 | }; 279 | 280 | let expected_ipv4: [&str; 17] = [ 281 | "iptables -w -t mangle -N sshuttle-m-tcp-1024", 282 | "iptables -w -t mangle -F sshuttle-m-tcp-1024", 283 | "iptables -w -t mangle -N sshuttle-d-tcp-1024", 284 | "iptables -w -t mangle -F sshuttle-d-tcp-1024", 285 | "iptables -w -t mangle -N sshuttle-t-tcp-1024", 286 | "iptables -w -t mangle -F sshuttle-t-tcp-1024", 287 | "iptables -w -t mangle -I OUTPUT 1 -j sshuttle-m-tcp-1024", 288 | "iptables -w -t mangle -I PREROUTING 1 -j sshuttle-t-tcp-1024", 289 | "iptables -w -t mangle -A sshuttle-m-tcp-1024 -j RETURN -m addrtype --dst-type LOCAL -m tcp -p tcp", 290 | "iptables -w -t mangle -A sshuttle-t-tcp-1024 -j RETURN -m addrtype --dst-type LOCAL -m tcp -p tcp", 291 | "iptables -w -t mangle -A sshuttle-d-tcp-1024 -j MARK --set-mark 0x01", 292 | "iptables -w -t mangle -A sshuttle-d-tcp-1024 -j ACCEPT", 293 | "iptables -w -t mangle -A sshuttle-t-tcp-1024 -m socket -j sshuttle-d-tcp-1024 -m tcp -p tcp", 294 | "iptables -w -t mangle -A sshuttle-m-tcp-1024 -j RETURN --dest 1.2.3.66/32 -m tcp -p tcp --dport 8080", 295 | "iptables -w -t mangle -A sshuttle-t-tcp-1024 -j RETURN --dest 1.2.3.66/32 -m tcp -p tcp --dport 8080", 296 | "iptables -w -t mangle -A sshuttle-m-tcp-1024 -j MARK --set-mark 0x01 --dest 1.2.3.0/24 -m tcp -p tcp --dport 8000:9000", 297 | "iptables -w -t mangle -A sshuttle-t-tcp-1024 -j TPROXY --tproxy-mark 0x01 --dest 1.2.3.0/24 -m tcp -p tcp --on-port 1024 --dport 8000:9000", 298 | ]; 299 | 300 | let mut commands = Commands::default(); 301 | firewall.setup_family(&config, &ipv4_family, &mut commands); 302 | assert_eq!(commands.len(), expected_ipv4.len()); 303 | for (command, expected_line) in commands.iter().zip(expected_ipv4.iter()) { 304 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 305 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 306 | assert_eq!(command.line, expected_command); 307 | } 308 | } 309 | 310 | #[test] 311 | fn test_setup_family_v6_tcp() { 312 | let firewall = TProxyFirewall::new(); 313 | let ipv6_family = FirewallSubnetConfig { 314 | enable: true, 315 | listener: ListenerAddr { 316 | protocol: Protocol::Tcp, 317 | addr: "127.0.0.1:1024".parse().unwrap(), 318 | }, 319 | includes: "[2404:6800:4004:80c::/64]:8000-9000" 320 | .parse::() 321 | .unwrap(), 322 | excludes: "[2404:6800:4004:80c::101f]:8080".parse().unwrap(), 323 | }; 324 | let config = FirewallConfig { 325 | filter_from_user: None, 326 | listeners: vec![], 327 | }; 328 | let expected_ipv6: [&str; 17] = [ 329 | "ip6tables -w -t mangle -N sshuttle-m-tcp-1024", 330 | "ip6tables -w -t mangle -F sshuttle-m-tcp-1024", 331 | "ip6tables -w -t mangle -N sshuttle-d-tcp-1024", 332 | "ip6tables -w -t mangle -F sshuttle-d-tcp-1024", 333 | "ip6tables -w -t mangle -N sshuttle-t-tcp-1024", 334 | "ip6tables -w -t mangle -F sshuttle-t-tcp-1024", 335 | "ip6tables -w -t mangle -I OUTPUT 1 -j sshuttle-m-tcp-1024", 336 | "ip6tables -w -t mangle -I PREROUTING 1 -j sshuttle-t-tcp-1024", 337 | "ip6tables -w -t mangle -A sshuttle-m-tcp-1024 -j RETURN -m addrtype --dst-type LOCAL -m tcp -p tcp", 338 | "ip6tables -w -t mangle -A sshuttle-t-tcp-1024 -j RETURN -m addrtype --dst-type LOCAL -m tcp -p tcp", 339 | "ip6tables -w -t mangle -A sshuttle-d-tcp-1024 -j MARK --set-mark 0x01", 340 | "ip6tables -w -t mangle -A sshuttle-d-tcp-1024 -j ACCEPT", 341 | "ip6tables -w -t mangle -A sshuttle-t-tcp-1024 -m socket -j sshuttle-d-tcp-1024 -m tcp -p tcp", 342 | "ip6tables -w -t mangle -A sshuttle-m-tcp-1024 -j RETURN --dest 2404:6800:4004:80c::101f/128 -m tcp -p tcp --dport 8080", 343 | "ip6tables -w -t mangle -A sshuttle-t-tcp-1024 -j RETURN --dest 2404:6800:4004:80c::101f/128 -m tcp -p tcp --dport 8080", 344 | "ip6tables -w -t mangle -A sshuttle-m-tcp-1024 -j MARK --set-mark 0x01 --dest 2404:6800:4004:80c::/64 -m tcp -p tcp --dport 8000:9000", 345 | "ip6tables -w -t mangle -A sshuttle-t-tcp-1024 -j TPROXY --tproxy-mark 0x01 --dest 2404:6800:4004:80c::/64 -m tcp -p tcp --on-port 1024 --dport 8000:9000", 346 | ]; 347 | let mut commands = Commands::default(); 348 | firewall.setup_family(&config, &ipv6_family, &mut commands); 349 | assert_eq!(commands.len(), expected_ipv6.len()); 350 | for (command, expected_line) in commands.iter().zip(expected_ipv6.iter()) { 351 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 352 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 353 | assert_eq!(command.line, expected_command); 354 | } 355 | } 356 | 357 | #[test] 358 | fn test_restore_family_v4_tcp() { 359 | let firewall = TProxyFirewall::new(); 360 | let ipv4_family = FirewallSubnetConfig { 361 | enable: true, 362 | listener: ListenerAddr { 363 | protocol: Protocol::Tcp, 364 | addr: "127.0.0.1:1024".parse().unwrap(), 365 | }, 366 | includes: "1.2.3.0/32".parse::().unwrap(), 367 | excludes: "1.2.3.66".parse::().unwrap(), 368 | }; 369 | let config = FirewallConfig { 370 | filter_from_user: None, 371 | listeners: vec![], 372 | }; 373 | 374 | let expected_ipv4: [&str; 8] = [ 375 | "iptables -w -t mangle -D OUTPUT -j sshuttle-m-tcp-1024", 376 | "iptables -w -t mangle -D PREROUTING -j sshuttle-t-tcp-1024", 377 | "iptables -w -t mangle -F sshuttle-m-tcp-1024", 378 | "iptables -w -t mangle -X sshuttle-m-tcp-1024", 379 | "iptables -w -t mangle -F sshuttle-t-tcp-1024", 380 | "iptables -w -t mangle -X sshuttle-t-tcp-1024", 381 | "iptables -w -t mangle -F sshuttle-d-tcp-1024", 382 | "iptables -w -t mangle -X sshuttle-d-tcp-1024", 383 | ]; 384 | 385 | let mut commands = Commands::default(); 386 | firewall.restore_family(&config, &ipv4_family, &mut commands); 387 | assert_eq!(commands.len(), expected_ipv4.len()); 388 | for (command, expected_line) in commands.iter().zip(expected_ipv4.iter()) { 389 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 390 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 391 | assert_eq!(command.line, expected_command); 392 | } 393 | } 394 | 395 | #[test] 396 | fn test_restore_family_v6_tcp() { 397 | let firewall = TProxyFirewall::new(); 398 | let ipv6_family = FirewallSubnetConfig { 399 | enable: true, 400 | listener: ListenerAddr { 401 | protocol: Protocol::Tcp, 402 | addr: "127.0.0.1:1024".parse().unwrap(), 403 | }, 404 | includes: "2404:6800:4004:80c::/64".parse::().unwrap(), 405 | excludes: "[2404:6800:4004:80c::101f]:80".parse().unwrap(), 406 | }; 407 | let config = FirewallConfig { 408 | filter_from_user: None, 409 | listeners: vec![], 410 | }; 411 | let expected_ipv6: [&str; 8] = [ 412 | "ip6tables -w -t mangle -D OUTPUT -j sshuttle-m-tcp-1024", 413 | "ip6tables -w -t mangle -D PREROUTING -j sshuttle-t-tcp-1024", 414 | "ip6tables -w -t mangle -F sshuttle-m-tcp-1024", 415 | "ip6tables -w -t mangle -X sshuttle-m-tcp-1024", 416 | "ip6tables -w -t mangle -F sshuttle-t-tcp-1024", 417 | "ip6tables -w -t mangle -X sshuttle-t-tcp-1024", 418 | "ip6tables -w -t mangle -F sshuttle-d-tcp-1024", 419 | "ip6tables -w -t mangle -X sshuttle-d-tcp-1024", 420 | ]; 421 | 422 | let mut commands = Commands::default(); 423 | firewall.restore_family(&config, &ipv6_family, &mut commands); 424 | assert_eq!(commands.len(), expected_ipv6.len()); 425 | for (command, expected_line) in commands.iter().zip(expected_ipv6.iter()) { 426 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 427 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 428 | assert_eq!(command.line, expected_command); 429 | } 430 | } 431 | 432 | #[test] 433 | fn test_setup_family_v4_udp() { 434 | let firewall = TProxyFirewall::new(); 435 | let ipv4_family = FirewallSubnetConfig { 436 | enable: true, 437 | listener: ListenerAddr { 438 | protocol: Protocol::Udp, 439 | addr: "127.0.0.1:1024".parse().unwrap(), 440 | }, 441 | includes: "1.2.3.0/24:8000-9000".parse::().unwrap(), 442 | excludes: "1.2.3.66:8080".parse::().unwrap(), 443 | }; 444 | let config = FirewallConfig { 445 | filter_from_user: None, 446 | listeners: vec![], 447 | }; 448 | 449 | let expected_ipv4: [&str; 17] = [ 450 | "iptables -w -t mangle -N sshuttle-m-udp-1024", 451 | "iptables -w -t mangle -F sshuttle-m-udp-1024", 452 | "iptables -w -t mangle -N sshuttle-d-udp-1024", 453 | "iptables -w -t mangle -F sshuttle-d-udp-1024", 454 | "iptables -w -t mangle -N sshuttle-t-udp-1024", 455 | "iptables -w -t mangle -F sshuttle-t-udp-1024", 456 | "iptables -w -t mangle -I OUTPUT 1 -j sshuttle-m-udp-1024", 457 | "iptables -w -t mangle -I PREROUTING 1 -j sshuttle-t-udp-1024", 458 | "iptables -w -t mangle -A sshuttle-m-udp-1024 -j RETURN -m addrtype --dst-type LOCAL -m udp -p udp", 459 | "iptables -w -t mangle -A sshuttle-t-udp-1024 -j RETURN -m addrtype --dst-type LOCAL -m udp -p udp", 460 | "iptables -w -t mangle -A sshuttle-d-udp-1024 -j MARK --set-mark 0x01", 461 | "iptables -w -t mangle -A sshuttle-d-udp-1024 -j ACCEPT", 462 | "iptables -w -t mangle -A sshuttle-t-udp-1024 -m socket -j sshuttle-d-udp-1024 -m udp -p udp", 463 | "iptables -w -t mangle -A sshuttle-m-udp-1024 -j RETURN --dest 1.2.3.66/32 -m udp -p udp --dport 8080", 464 | "iptables -w -t mangle -A sshuttle-t-udp-1024 -j RETURN --dest 1.2.3.66/32 -m udp -p udp --dport 8080", 465 | "iptables -w -t mangle -A sshuttle-m-udp-1024 -j MARK --set-mark 0x01 --dest 1.2.3.0/24 -m udp -p udp --dport 8000:9000", 466 | "iptables -w -t mangle -A sshuttle-t-udp-1024 -j TPROXY --tproxy-mark 0x01 --dest 1.2.3.0/24 -m udp -p udp --on-port 1024 --dport 8000:9000", 467 | ]; 468 | 469 | let mut commands = Commands::default(); 470 | firewall.setup_family(&config, &ipv4_family, &mut commands); 471 | assert_eq!(commands.len(), expected_ipv4.len()); 472 | for (command, expected_line) in commands.iter().zip(expected_ipv4.iter()) { 473 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 474 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 475 | assert_eq!(command.line, expected_command); 476 | } 477 | } 478 | 479 | #[test] 480 | fn test_setup_family_v6_udp() { 481 | let firewall = TProxyFirewall::new(); 482 | let ipv6_family = FirewallSubnetConfig { 483 | enable: true, 484 | listener: ListenerAddr { 485 | protocol: Protocol::Udp, 486 | addr: "127.0.0.1:1024".parse().unwrap(), 487 | }, 488 | includes: "[2404:6800:4004:80c::/64]:8000-9000" 489 | .parse::() 490 | .unwrap(), 491 | excludes: "[2404:6800:4004:80c::101f]:8080".parse().unwrap(), 492 | }; 493 | let config = FirewallConfig { 494 | filter_from_user: None, 495 | listeners: vec![], 496 | }; 497 | let expected_ipv6: [&str; 17] = [ 498 | "ip6tables -w -t mangle -N sshuttle-m-udp-1024", 499 | "ip6tables -w -t mangle -F sshuttle-m-udp-1024", 500 | "ip6tables -w -t mangle -N sshuttle-d-udp-1024", 501 | "ip6tables -w -t mangle -F sshuttle-d-udp-1024", 502 | "ip6tables -w -t mangle -N sshuttle-t-udp-1024", 503 | "ip6tables -w -t mangle -F sshuttle-t-udp-1024", 504 | "ip6tables -w -t mangle -I OUTPUT 1 -j sshuttle-m-udp-1024", 505 | "ip6tables -w -t mangle -I PREROUTING 1 -j sshuttle-t-udp-1024", 506 | "ip6tables -w -t mangle -A sshuttle-m-udp-1024 -j RETURN -m addrtype --dst-type LOCAL -m udp -p udp", 507 | "ip6tables -w -t mangle -A sshuttle-t-udp-1024 -j RETURN -m addrtype --dst-type LOCAL -m udp -p udp", 508 | "ip6tables -w -t mangle -A sshuttle-d-udp-1024 -j MARK --set-mark 0x01", 509 | "ip6tables -w -t mangle -A sshuttle-d-udp-1024 -j ACCEPT", 510 | "ip6tables -w -t mangle -A sshuttle-t-udp-1024 -m socket -j sshuttle-d-udp-1024 -m udp -p udp", 511 | "ip6tables -w -t mangle -A sshuttle-m-udp-1024 -j RETURN --dest 2404:6800:4004:80c::101f/128 -m udp -p udp --dport 8080", 512 | "ip6tables -w -t mangle -A sshuttle-t-udp-1024 -j RETURN --dest 2404:6800:4004:80c::101f/128 -m udp -p udp --dport 8080", 513 | "ip6tables -w -t mangle -A sshuttle-m-udp-1024 -j MARK --set-mark 0x01 --dest 2404:6800:4004:80c::/64 -m udp -p udp --dport 8000:9000", 514 | "ip6tables -w -t mangle -A sshuttle-t-udp-1024 -j TPROXY --tproxy-mark 0x01 --dest 2404:6800:4004:80c::/64 -m udp -p udp --on-port 1024 --dport 8000:9000", 515 | ]; 516 | let mut commands = Commands::default(); 517 | firewall.setup_family(&config, &ipv6_family, &mut commands); 518 | assert_eq!(commands.len(), expected_ipv6.len()); 519 | for (command, expected_line) in commands.iter().zip(expected_ipv6.iter()) { 520 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 521 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 522 | assert_eq!(command.line, expected_command); 523 | } 524 | } 525 | 526 | #[test] 527 | fn test_restore_family_v4_udp() { 528 | let firewall = TProxyFirewall::new(); 529 | let ipv4_family = FirewallSubnetConfig { 530 | enable: true, 531 | listener: ListenerAddr { 532 | protocol: Protocol::Udp, 533 | addr: "127.0.0.1:1024".parse().unwrap(), 534 | }, 535 | includes: "1.2.3.0/32".parse::().unwrap(), 536 | excludes: "1.2.3.66".parse::().unwrap(), 537 | }; 538 | let config = FirewallConfig { 539 | filter_from_user: None, 540 | listeners: vec![], 541 | }; 542 | 543 | let expected_ipv4: [&str; 8] = [ 544 | "iptables -w -t mangle -D OUTPUT -j sshuttle-m-udp-1024", 545 | "iptables -w -t mangle -D PREROUTING -j sshuttle-t-udp-1024", 546 | "iptables -w -t mangle -F sshuttle-m-udp-1024", 547 | "iptables -w -t mangle -X sshuttle-m-udp-1024", 548 | "iptables -w -t mangle -F sshuttle-t-udp-1024", 549 | "iptables -w -t mangle -X sshuttle-t-udp-1024", 550 | "iptables -w -t mangle -F sshuttle-d-udp-1024", 551 | "iptables -w -t mangle -X sshuttle-d-udp-1024", 552 | ]; 553 | 554 | let mut commands = Commands::default(); 555 | firewall.restore_family(&config, &ipv4_family, &mut commands); 556 | assert_eq!(commands.len(), expected_ipv4.len()); 557 | for (command, expected_line) in commands.iter().zip(expected_ipv4.iter()) { 558 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 559 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 560 | assert_eq!(command.line, expected_command); 561 | } 562 | } 563 | 564 | #[test] 565 | fn test_restore_family_v6_udp() { 566 | let firewall = TProxyFirewall::new(); 567 | let ipv6_family = FirewallSubnetConfig { 568 | enable: true, 569 | listener: ListenerAddr { 570 | protocol: Protocol::Udp, 571 | addr: "127.0.0.1:1024".parse().unwrap(), 572 | }, 573 | includes: "2404:6800:4004:80c::/64".parse::().unwrap(), 574 | excludes: "[2404:6800:4004:80c::101f]:80".parse().unwrap(), 575 | }; 576 | let config = FirewallConfig { 577 | filter_from_user: None, 578 | listeners: vec![], 579 | }; 580 | let expected_ipv6: [&str; 8] = [ 581 | "ip6tables -w -t mangle -D OUTPUT -j sshuttle-m-udp-1024", 582 | "ip6tables -w -t mangle -D PREROUTING -j sshuttle-t-udp-1024", 583 | "ip6tables -w -t mangle -F sshuttle-m-udp-1024", 584 | "ip6tables -w -t mangle -X sshuttle-m-udp-1024", 585 | "ip6tables -w -t mangle -F sshuttle-t-udp-1024", 586 | "ip6tables -w -t mangle -X sshuttle-t-udp-1024", 587 | "ip6tables -w -t mangle -F sshuttle-d-udp-1024", 588 | "ip6tables -w -t mangle -X sshuttle-d-udp-1024", 589 | ]; 590 | 591 | let mut commands = Commands::default(); 592 | firewall.restore_family(&config, &ipv6_family, &mut commands); 593 | assert_eq!(commands.len(), expected_ipv6.len()); 594 | for (command, expected_line) in commands.iter().zip(expected_ipv6.iter()) { 595 | let split: Vec = expected_line.split(' ').map(ToOwned::to_owned).collect(); 596 | let expected_command = Line(split[0].clone(), split[1..].to_vec()); 597 | assert_eq!(command.line, expected_command); 598 | } 599 | } 600 | } 601 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------