Fixed a number of warnings

This commit is contained in:
Conrad Kramer 2023-12-17 19:40:19 -08:00
parent 76278809ea
commit 104f8215ba
28 changed files with 144 additions and 199 deletions

12
Cargo.lock generated
View file

@ -121,17 +121,6 @@ dependencies = [
"pin-project-lite",
]
[[package]]
name = "async-trait"
version = "0.1.74"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a66537f1bb974b254c98ed142ff995236e81b9d0fe4db0575f46612cb15eb0f9"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.39",
]
[[package]]
name = "autocfg"
version = "1.1.0"
@ -253,7 +242,6 @@ dependencies = [
"aead",
"anyhow",
"async-channel",
"async-trait",
"base64",
"blake2",
"caps",

View file

@ -36,7 +36,6 @@ base64 = "0.21.4"
fehler = "1.0.0"
ip_network_table = "0.2.0"
ip_network = "0.4.0"
async-trait = "0.1.74"
async-channel = "2.1.1"
schemars = "0.8"
futures = "0.3.28"

View file

@ -41,10 +41,6 @@ impl DaemonInstance {
}
}
pub fn set_tun_interface(&mut self, tun_interface: Arc<RwLock<TunInterface>>) {
self.tun_interface = Some(tun_interface);
}
async fn proc_command(&mut self, command: DaemonCommand) -> Result<DaemonResponseData> {
info!("Daemon got command: {:?}", command);
match command {

View file

@ -1,52 +1,24 @@
use std::net::ToSocketAddrs;
use std::{
net::{IpAddr, Ipv4Addr, SocketAddr},
sync::Arc,
};
use std::sync::Arc;
mod command;
mod instance;
mod net;
mod response;
use anyhow::{anyhow, Error, Result};
use base64::{engine::general_purpose, Engine as _};
use anyhow::Result;
pub use command::{DaemonCommand, DaemonStartOptions};
use fehler::throws;
use instance::DaemonInstance;
use ip_network::{IpNetwork, Ipv4Network};
#[cfg(target_vendor = "apple")]
pub use net::start_srv;
pub use net::DaemonClient;
pub use response::{DaemonResponse, DaemonResponseData, ServerInfo};
use tokio::sync::RwLock;
use crate::wireguard::Config;
use crate::{
daemon::net::listen,
wireguard::{Interface, Peer, PublicKey, StaticSecret},
wireguard::{Config, Interface},
};
#[throws]
fn parse_key(string: &str) -> [u8; 32] {
let value = general_purpose::STANDARD.decode(string)?;
let mut key = [0u8; 32];
key.copy_from_slice(&value[..]);
key
}
#[throws]
fn parse_secret_key(string: &str) -> StaticSecret {
let key = parse_key(string)?;
StaticSecret::from(key)
}
#[throws]
fn parse_public_key(string: &str) -> PublicKey {
let key = parse_key(string)?;
PublicKey::from(key)
}
pub async fn daemon_main() -> Result<()> {
let (commands_tx, commands_rx) = async_channel::unbounded();
let (response_tx, response_rx) = async_channel::unbounded();
@ -73,6 +45,7 @@ pub async fn daemon_main() -> Result<()> {
}
});
tokio::try_join!(inst_job, listen_job).map(|_| ());
Ok(())
tokio::try_join!(inst_job, listen_job)
.map(|_| ())
.map_err(|e| e.into())
}

View file

@ -23,8 +23,8 @@ pub extern "C" fn start_srv() {
Ok(..) => {
info!("Server successfully started");
break
},
Err(e) => error!("Could not connect to server: {}", e)
}
Err(e) => error!("Could not connect to server: {}", e),
}
}
});

View file

@ -1,7 +1,9 @@
use std::os::fd::IntoRawFd;
use anyhow::Result;
use super::*;
use crate::daemon::DaemonResponse;
use anyhow::Result;
use std::os::fd::IntoRawFd;
pub async fn listen(
cmd_tx: async_channel::Sender<DaemonCommand>,

View file

@ -6,16 +6,16 @@ use std::{
},
path::{Path, PathBuf},
};
use tracing::info;
use crate::daemon::{DaemonCommand, DaemonResponse, DaemonResponseData};
use anyhow::{anyhow, Result};
use tokio::{
io::{AsyncBufReadExt, AsyncWriteExt, BufReader},
net::{UnixListener, UnixStream},
};
use tracing::debug;
use tracing::{debug, info};
use super::*;
use crate::daemon::{DaemonCommand, DaemonResponse, DaemonResponseData};
#[cfg(not(target_vendor = "apple"))]
const UNIX_SOCKET_PATH: &str = "/run/burrow.sock";
@ -36,7 +36,7 @@ fn fetch_socket_path() -> Option<PathBuf> {
for path in tries {
let path = PathBuf::from(path);
if path.exists() {
return Some(path);
return Some(path)
}
}
None

View file

@ -1,5 +1,6 @@
use super::*;
use anyhow::Result;
use super::*;
use crate::daemon::DaemonResponse;
pub async fn listen(

View file

@ -1,7 +1,6 @@
use schemars::JsonSchema;
use serde::{Deserialize, Serialize};
use tun::TunInterface;
use anyhow::anyhow;
#[derive(Clone, Serialize, Deserialize, Debug, JsonSchema)]
pub struct DaemonResponse {
@ -19,9 +18,9 @@ impl DaemonResponse {
}
}
impl Into<DaemonResponse> for DaemonResponseData {
fn into(self) -> DaemonResponse {
DaemonResponse::new(Ok::<DaemonResponseData, String>(self))
impl From<DaemonResponseData> for DaemonResponse {
fn from(val: DaemonResponseData) -> Self {
DaemonResponse::new(Ok::<DaemonResponseData, String>(val))
}
}

View file

@ -5,7 +5,12 @@ pub mod wireguard;
mod daemon;
#[cfg(any(target_os = "linux", target_vendor = "apple"))]
pub use daemon::{
DaemonClient, DaemonCommand, DaemonResponse, DaemonResponseData, DaemonStartOptions, ServerInfo,
DaemonClient,
DaemonCommand,
DaemonResponse,
DaemonResponseData,
DaemonStartOptions,
ServerInfo,
};
#[cfg(target_vendor = "apple")]

View file

@ -232,6 +232,6 @@ fn system_log() -> Result<Option<OsLogger>> {
}
#[cfg(not(any(target_os = "linux", target_vendor = "apple")))]
pub fn main(){
pub fn main() {
eprintln!("This platform is not supported currently.")
}
}

View file

@ -1,13 +1,13 @@
use crate::wireguard::{Interface as WgInterface, Peer as WgPeer};
use std::{net::ToSocketAddrs, str::FromStr};
use anyhow::{anyhow, Error, Result};
use base64::engine::general_purpose;
use base64::Engine;
use base64::{engine::general_purpose, Engine};
use fehler::throws;
use ip_network::IpNetwork;
use std::net::ToSocketAddrs;
use std::str::FromStr;
use x25519_dalek::{PublicKey, StaticSecret};
use crate::wireguard::{Interface as WgInterface, Peer as WgPeer};
#[throws]
fn parse_key(string: &str) -> [u8; 32] {
let value = general_purpose::STANDARD.decode(string)?;
@ -68,12 +68,11 @@ impl TryFrom<Config> for WgInterface {
endpoint: p
.endpoint
.to_socket_addrs()?
.filter(|sock| sock.is_ipv4())
.next()
.find(|sock| sock.is_ipv4())
.ok_or(anyhow!("DNS Lookup Fails!"))?,
preshared_key: match &p.preshared_key {
None => Ok(None),
Some(k) => parse_key(k).map(|res| Some(res)),
Some(k) => parse_key(k).map(Some),
}?,
allowed_ips: p
.allowed_ips
@ -86,29 +85,28 @@ impl TryFrom<Config> for WgInterface {
})
})
.collect::<Result<Vec<WgPeer>>>()?;
Ok(WgInterface::new(wg_peers)?)
WgInterface::new(wg_peers)
}
}
impl Default for Config {
fn default() -> Self {
Self{
interface: Interface{
Self {
interface: Interface {
private_key: "GNqIAOCRxjl/cicZyvkvpTklgQuUmGUIEkH7IXF/sEE=".into(),
address: "10.13.13.2/24".into(),
listen_port: 51820,
dns: Default::default(),
mtu: Default::default()
mtu: Default::default(),
},
peers: vec![Peer{
peers: vec![Peer {
endpoint: "wg.burrow.rs:51820".into(),
allowed_ips: vec!["8.8.8.8/32".into()],
public_key: "uy75leriJay0+oHLhRMpV+A5xAQ0hCJ+q7Ww81AOvT4=".into(),
preshared_key: Some("s7lx/mg+reVEMnGnqeyYOQkzD86n2+gYnx1M9ygi08k=".into()),
persistent_keepalive: Default::default(),
name: Default::default()
}]
name: Default::default(),
}],
}
}
}
}

View file

@ -1,33 +1,15 @@
use std::{net::IpAddr, sync::Arc, time::Duration};
use std::{net::IpAddr, sync::Arc};
use anyhow::Error;
use async_trait::async_trait;
use fehler::throws;
use futures::{future::join_all, FutureExt};
use futures::future::join_all;
use ip_network_table::IpNetworkTable;
use tokio::{sync::RwLock, task::JoinHandle, time::timeout};
use tokio::sync::RwLock;
use tracing::{debug, error};
use tun::tokio::TunInterface;
use super::{noise::Tunnel, Peer, PeerPcb};
#[async_trait]
pub trait PacketInterface {
async fn recv(&mut self, buf: &mut [u8]) -> Result<usize, tokio::io::Error>;
async fn send(&mut self, buf: &[u8]) -> Result<usize, tokio::io::Error>;
}
#[async_trait]
impl PacketInterface for tun::tokio::TunInterface {
async fn recv(&mut self, buf: &mut [u8]) -> Result<usize, tokio::io::Error> {
self.recv(buf).await
}
async fn send(&mut self, buf: &[u8]) -> Result<usize, tokio::io::Error> {
self.send(buf).await
}
}
struct IndexedPcbs {
pcbs: Vec<Arc<PeerPcb>>,
allowed_ips: IpNetworkTable<usize>,
@ -44,7 +26,7 @@ impl IndexedPcbs {
pub fn insert(&mut self, pcb: PeerPcb) {
let idx: usize = self.pcbs.len();
for allowed_ip in pcb.allowed_ips.iter() {
self.allowed_ips.insert(allowed_ip.clone(), idx);
self.allowed_ips.insert(*allowed_ip, idx);
}
self.pcbs.insert(idx, Arc::new(pcb));
}
@ -53,10 +35,6 @@ impl IndexedPcbs {
let (_, &idx) = self.allowed_ips.longest_match(addr)?;
Some(idx)
}
pub async fn connect(&self, idx: usize, handle: JoinHandle<()>) {
self.pcbs[idx].handle.write().await.replace(handle);
}
}
impl FromIterator<PeerPcb> for IndexedPcbs {
@ -78,7 +56,7 @@ impl Interface {
pub fn new<I: IntoIterator<Item = Peer>>(peers: I) -> Self {
let pcbs: IndexedPcbs = peers
.into_iter()
.map(|peer| PeerPcb::new(peer))
.map(PeerPcb::new)
.collect::<Result<_, _>>()?;
let pcbs = Arc::new(pcbs);
@ -106,7 +84,7 @@ impl Interface {
Ok(len) => &buf[..len],
Err(e) => {
error!("Failed to read from interface: {}", e);
continue;
continue
}
};
debug!("Read {} bytes from interface", src.len());
@ -117,7 +95,7 @@ impl Interface {
Some(addr) => addr,
None => {
debug!("No destination found");
continue;
continue
}
};
@ -136,7 +114,7 @@ impl Interface {
}
Err(e) => {
log::error!("Failed to send packet {}", e);
continue;
continue
}
};
}
@ -160,12 +138,11 @@ impl Interface {
let tsk = async move {
if let Err(e) = pcb.open_if_closed().await {
log::error!("failed to open pcb: {}", e);
return;
return
}
let r2 = pcb.run(tun).await;
if let Err(e) = r2 {
log::error!("failed to run pcb: {}", e);
return;
} else {
debug!("pcb ran successfully");
}

View file

@ -4,21 +4,8 @@ mod noise;
mod pcb;
mod peer;
pub use config::Config;
pub use iface::Interface;
pub use pcb::PeerPcb;
pub use peer::Peer;
pub use x25519_dalek::{PublicKey, StaticSecret};
pub use config::Config;
const WIREGUARD_CONFIG: &str = r#"
[Interface]
# Device: Gentle Tomcat
PrivateKey = sIxpokQPnWctJKNaQ3DRdcQbL2S5OMbUrvr4bbsvTHw=
Address = 10.68.136.199/32,fc00:bbbb:bbbb:bb01::5:88c6/128
DNS = 10.64.0.1
[Peer]
public_key = EKZXvHlSDeqAjfC/m9aQR0oXfQ6Idgffa9L0DH5yaCo=
AllowedIPs = 0.0.0.0/0,::0/0
Endpoint = 146.70.173.66:51820
"#;

View file

@ -4,9 +4,7 @@
#[derive(Debug)]
pub enum WireGuardError {
DestinationBufferTooSmall,
IncorrectPacketLength,
UnexpectedPacket,
WrongPacketType,
WrongIndex,
WrongKey,
InvalidTai64nTimestamp,
@ -17,7 +15,6 @@ pub enum WireGuardError {
DuplicateCounter,
InvalidPacket,
NoCurrentSession,
LockFailed,
ConnectionExpired,
UnderLoad,
}

View file

@ -9,14 +9,20 @@ use std::{
use aead::{Aead, Payload};
use blake2::{
digest::{FixedOutput, KeyInit},
Blake2s256, Blake2sMac, Digest,
Blake2s256,
Blake2sMac,
Digest,
};
use chacha20poly1305::XChaCha20Poly1305;
use rand_core::OsRng;
use ring::aead::{Aad, LessSafeKey, Nonce, UnboundKey, CHACHA20_POLY1305};
use super::{
errors::WireGuardError, session::Session, x25519, HandshakeInit, HandshakeResponse,
errors::WireGuardError,
session::Session,
x25519,
HandshakeInit,
HandshakeResponse,
PacketCookieReply,
};
@ -203,7 +209,7 @@ impl Tai64N {
/// Parse a timestamp from a 12 byte u8 slice
fn parse(buf: &[u8; 12]) -> Result<Tai64N, WireGuardError> {
if buf.len() < 12 {
return Err(WireGuardError::InvalidTai64nTimestamp);
return Err(WireGuardError::InvalidTai64nTimestamp)
}
let (sec_bytes, nano_bytes) = buf.split_at(std::mem::size_of::<u64>());
@ -550,22 +556,19 @@ impl Handshake {
let timestamp = Tai64N::parse(&timestamp)?;
if !timestamp.after(&self.last_handshake_timestamp) {
// Possibly a replay
return Err(WireGuardError::WrongTai64nTimestamp);
return Err(WireGuardError::WrongTai64nTimestamp)
}
self.last_handshake_timestamp = timestamp;
// initiator.hash = HASH(initiator.hash || msg.encrypted_timestamp)
hash = b2s_hash(&hash, packet.encrypted_timestamp);
self.previous = std::mem::replace(
&mut self.state,
HandshakeState::InitReceived {
chaining_key,
hash,
peer_ephemeral_public,
peer_index,
},
);
self.previous = std::mem::replace(&mut self.state, HandshakeState::InitReceived {
chaining_key,
hash,
peer_ephemeral_public,
peer_index,
});
self.format_handshake_response(dst)
}
@ -666,7 +669,7 @@ impl Handshake {
let local_index = self.cookies.index;
if packet.receiver_idx != local_index {
return Err(WireGuardError::WrongIndex);
return Err(WireGuardError::WrongIndex)
}
// msg.encrypted_cookie = XAEAD(HASH(LABEL_COOKIE || responder.static_public),
// msg.nonce, cookie, last_received_msg.mac1)
@ -722,7 +725,7 @@ impl Handshake {
dst: &'a mut [u8],
) -> Result<&'a mut [u8], WireGuardError> {
if dst.len() < super::HANDSHAKE_INIT_SZ {
return Err(WireGuardError::DestinationBufferTooSmall);
return Err(WireGuardError::DestinationBufferTooSmall)
}
let (message_type, rest) = dst.split_at_mut(4);
@ -805,7 +808,7 @@ impl Handshake {
dst: &'a mut [u8],
) -> Result<(&'a mut [u8], Session), WireGuardError> {
if dst.len() < super::HANDSHAKE_RESP_SZ {
return Err(WireGuardError::DestinationBufferTooSmall);
return Err(WireGuardError::DestinationBufferTooSmall)
}
let state = std::mem::replace(&mut self.state, HandshakeState::None);

View file

@ -45,7 +45,11 @@ const N_SESSIONS: usize = 8;
pub mod x25519 {
pub use x25519_dalek::{
EphemeralSecret, PublicKey, ReusableSecret, SharedSecret, StaticSecret,
EphemeralSecret,
PublicKey,
ReusableSecret,
SharedSecret,
StaticSecret,
};
}
@ -129,15 +133,15 @@ pub struct PacketData<'a> {
pub enum Packet<'a> {
HandshakeInit(HandshakeInit<'a>),
HandshakeResponse(HandshakeResponse<'a>),
PacketCookieReply(PacketCookieReply<'a>),
PacketData(PacketData<'a>),
CookieReply(PacketCookieReply<'a>),
Data(PacketData<'a>),
}
impl Tunnel {
#[inline(always)]
pub fn parse_incoming_packet(src: &[u8]) -> Result<Packet, WireGuardError> {
if src.len() < 4 {
return Err(WireGuardError::InvalidPacket);
return Err(WireGuardError::InvalidPacket)
}
// Checks the type, as well as the reserved zero fields
@ -159,12 +163,12 @@ impl Tunnel {
.expect("length already checked above"),
encrypted_nothing: &src[44..60],
}),
(COOKIE_REPLY, COOKIE_REPLY_SZ) => Packet::PacketCookieReply(PacketCookieReply {
(COOKIE_REPLY, COOKIE_REPLY_SZ) => Packet::CookieReply(PacketCookieReply {
receiver_idx: u32::from_le_bytes(src[4..8].try_into().unwrap()),
nonce: &src[8..32],
encrypted_cookie: &src[32..64],
}),
(DATA, DATA_OVERHEAD_SZ..=std::usize::MAX) => Packet::PacketData(PacketData {
(DATA, DATA_OVERHEAD_SZ..=std::usize::MAX) => Packet::Data(PacketData {
receiver_idx: u32::from_le_bytes(src[4..8].try_into().unwrap()),
counter: u64::from_le_bytes(src[8..16].try_into().unwrap()),
encrypted_encapsulated_packet: &src[16..],
@ -179,7 +183,7 @@ impl Tunnel {
pub fn dst_address(packet: &[u8]) -> Option<IpAddr> {
if packet.is_empty() {
return None;
return None
}
match packet[0] >> 4 {
@ -203,7 +207,7 @@ impl Tunnel {
pub fn src_address(packet: &[u8]) -> Option<IpAddr> {
if packet.is_empty() {
return None;
return None
}
match packet[0] >> 4 {
@ -298,7 +302,7 @@ impl Tunnel {
self.timer_tick(TimerName::TimeLastDataPacketSent);
}
self.tx_bytes += src.len();
return TunnResult::WriteToNetwork(packet);
return TunnResult::WriteToNetwork(packet)
}
// If there is no session, queue the packet for future retry
@ -322,7 +326,7 @@ impl Tunnel {
) -> TunnResult<'a> {
if datagram.is_empty() {
// Indicates a repeated call
return self.send_queued_packet(dst);
return self.send_queued_packet(dst)
}
let mut cookie = [0u8; COOKIE_REPLY_SZ];
@ -333,7 +337,7 @@ impl Tunnel {
Ok(packet) => packet,
Err(TunnResult::WriteToNetwork(cookie)) => {
dst[..cookie.len()].copy_from_slice(cookie);
return TunnResult::WriteToNetwork(&mut dst[..cookie.len()]);
return TunnResult::WriteToNetwork(&mut dst[..cookie.len()])
}
Err(TunnResult::Err(e)) => return TunnResult::Err(e),
_ => unreachable!(),
@ -350,8 +354,8 @@ impl Tunnel {
match packet {
Packet::HandshakeInit(p) => self.handle_handshake_init(p, dst),
Packet::HandshakeResponse(p) => self.handle_handshake_response(p, dst),
Packet::PacketCookieReply(p) => self.handle_cookie_reply(p),
Packet::PacketData(p) => self.handle_data(p, dst),
Packet::CookieReply(p) => self.handle_cookie_reply(p),
Packet::Data(p) => self.handle_data(p, dst),
}
.unwrap_or_else(TunnResult::from)
}
@ -433,7 +437,7 @@ impl Tunnel {
let cur_idx = self.current;
if cur_idx == new_idx {
// There is nothing to do, already using this session, this is the common case
return;
return
}
if self.sessions[cur_idx % N_SESSIONS].is_none()
|| self.timers.session_timers[new_idx % N_SESSIONS]
@ -479,7 +483,7 @@ impl Tunnel {
force_resend: bool,
) -> TunnResult<'a> {
if self.handshake.is_in_progress() && !force_resend {
return TunnResult::Done;
return TunnResult::Done
}
if self.handshake.is_expired() {
@ -538,7 +542,7 @@ impl Tunnel {
};
if computed_len > packet.len() {
return TunnResult::Err(WireGuardError::InvalidPacket);
return TunnResult::Err(WireGuardError::InvalidPacket)
}
self.timer_tick(TimerName::TimeLastDataPacketReceived);

View file

@ -12,9 +12,19 @@ use ring::constant_time::verify_slices_are_equal;
use super::{
handshake::{
b2s_hash, b2s_keyed_mac_16, b2s_keyed_mac_16_2, b2s_mac_24, LABEL_COOKIE, LABEL_MAC1,
b2s_hash,
b2s_keyed_mac_16,
b2s_keyed_mac_16_2,
b2s_mac_24,
LABEL_COOKIE,
LABEL_MAC1,
},
HandshakeInit, HandshakeResponse, Packet, TunnResult, Tunnel, WireGuardError,
HandshakeInit,
HandshakeResponse,
Packet,
TunnResult,
Tunnel,
WireGuardError,
};
const COOKIE_REFRESH: u64 = 128; // Use 128 and not 120 so the compiler can optimize out the division
@ -126,7 +136,7 @@ impl RateLimiter {
dst: &'a mut [u8],
) -> Result<&'a mut [u8], WireGuardError> {
if dst.len() < super::COOKIE_REPLY_SZ {
return Err(WireGuardError::DestinationBufferTooSmall);
return Err(WireGuardError::DestinationBufferTooSmall)
}
let (message_type, rest) = dst.split_at_mut(4);
@ -192,7 +202,7 @@ impl RateLimiter {
let cookie_packet = self
.format_cookie_reply(sender_idx, cookie, mac1, dst)
.map_err(TunnResult::Err)?;
return Err(TunnResult::WriteToNetwork(cookie_packet));
return Err(TunnResult::WriteToNetwork(cookie_packet))
}
}
}

View file

@ -88,11 +88,11 @@ impl ReceivingKeyCounterValidator {
fn will_accept(&self, counter: u64) -> Result<(), WireGuardError> {
if counter >= self.next {
// As long as the counter is growing no replay took place for sure
return Ok(());
return Ok(())
}
if counter + N_BITS < self.next {
// Drop if too far back
return Err(WireGuardError::InvalidCounter);
return Err(WireGuardError::InvalidCounter)
}
if !self.check_bit(counter) {
Ok(())
@ -107,22 +107,22 @@ impl ReceivingKeyCounterValidator {
fn mark_did_receive(&mut self, counter: u64) -> Result<(), WireGuardError> {
if counter + N_BITS < self.next {
// Drop if too far back
return Err(WireGuardError::InvalidCounter);
return Err(WireGuardError::InvalidCounter)
}
if counter == self.next {
// Usually the packets arrive in order, in that case we simply mark the bit and
// increment the counter
self.set_bit(counter);
self.next += 1;
return Ok(());
return Ok(())
}
if counter < self.next {
// A packet arrived out of order, check if it is valid, and mark
if self.check_bit(counter) {
return Err(WireGuardError::InvalidCounter);
return Err(WireGuardError::InvalidCounter)
}
self.set_bit(counter);
return Ok(());
return Ok(())
}
// Packets where dropped, or maybe reordered, skip them and mark unused
if counter - self.next >= N_BITS {
@ -247,7 +247,7 @@ impl Session {
panic!("The destination buffer is too small");
}
if packet.receiver_idx != self.receiving_index {
return Err(WireGuardError::WrongIndex);
return Err(WireGuardError::WrongIndex)
}
// Don't reuse counters, in case this is a replay attack we want to quickly
// check the counter without running expensive decryption

View file

@ -190,7 +190,7 @@ impl Tunnel {
{
if self.handshake.is_expired() {
return TunnResult::Err(WireGuardError::ConnectionExpired);
return TunnResult::Err(WireGuardError::ConnectionExpired)
}
// Clear cookie after COOKIE_EXPIRATION_TIME
@ -206,7 +206,7 @@ impl Tunnel {
tracing::error!("CONNECTION_EXPIRED(REJECT_AFTER_TIME * 3)");
self.handshake.set_expired();
self.clear_all();
return TunnResult::Err(WireGuardError::ConnectionExpired);
return TunnResult::Err(WireGuardError::ConnectionExpired)
}
if let Some(time_init_sent) = self.handshake.timer() {
@ -219,7 +219,7 @@ impl Tunnel {
tracing::error!("CONNECTION_EXPIRED(REKEY_ATTEMPT_TIME)");
self.handshake.set_expired();
self.clear_all();
return TunnResult::Err(WireGuardError::ConnectionExpired);
return TunnResult::Err(WireGuardError::ConnectionExpired)
}
if time_init_sent.elapsed() >= REKEY_TIMEOUT {
@ -299,11 +299,11 @@ impl Tunnel {
}
if handshake_initiation_required {
return self.format_handshake_initiation(dst, true);
return self.format_handshake_initiation(dst, true)
}
if keepalive_required {
return self.encapsulate(&[], dst);
return self.encapsulate(&[], dst)
}
TunnResult::Done

View file

@ -1,10 +1,6 @@
use std::{
cell::{Cell, RefCell},
net::SocketAddr,
sync::Arc,
};
use std::{net::SocketAddr, sync::Arc};
use anyhow::{anyhow, Error};
use anyhow::Error;
use fehler::throws;
use ip_network::IpNetwork;
use rand::random;
@ -74,7 +70,7 @@ impl PeerPcb {
Ok(l) => l,
Err(e) => {
log::error!("{}: error reading from socket: {:?}", rid, e);
continue;
continue
}
};
let mut res_dat = &res_buf[..len];
@ -90,7 +86,7 @@ impl PeerPcb {
TunnResult::Done => break,
TunnResult::Err(e) => {
tracing::error!(message = "Decapsulate error", error = ?e);
break;
break
}
TunnResult::WriteToNetwork(packet) => {
tracing::debug!("WriteToNetwork: {:?}", packet);
@ -98,17 +94,17 @@ impl PeerPcb {
socket.send(packet).await?;
tracing::debug!("WriteToNetwork done");
res_dat = &[];
continue;
continue
}
TunnResult::WriteToTunnelV4(packet, addr) => {
tracing::debug!("WriteToTunnelV4: {:?}, {:?}", packet, addr);
tun_interface.read().await.send(packet).await?;
break;
break
}
TunnResult::WriteToTunnelV6(packet, addr) => {
tracing::debug!("WriteToTunnelV6: {:?}, {:?}", packet, addr);
tun_interface.read().await.send(packet).await?;
break;
break
}
}
}

View file

@ -26,7 +26,7 @@ async fn generate(out_dir: &std::path::Path) -> anyhow::Result<()> {
println!("cargo:rerun-if-changed={}", binary_path.to_str().unwrap());
if let (Ok(..), Ok(..)) = (File::open(&bindings_path), File::open(&binary_path)) {
return Ok(());
return Ok(())
};
let archive = download(out_dir)

View file

@ -34,7 +34,7 @@ impl TunInterface {
Ok(result) => return result,
Err(_would_block) => {
tracing::debug!("WouldBlock");
continue;
continue
}
}
}

View file

@ -1,6 +1,6 @@
use std::{
io::{Error, IoSlice},
mem::{self, ManuallyDrop},
mem,
net::{Ipv4Addr, SocketAddrV4},
os::fd::{AsRawFd, FromRawFd, RawFd},
};

View file

@ -2,11 +2,20 @@ use std::mem;
use libc::{c_char, c_int, c_short, c_uint, c_ulong, sockaddr};
pub use libc::{
c_void, sockaddr_ctl, sockaddr_in, socklen_t, AF_SYSTEM, AF_SYS_CONTROL, IFNAMSIZ,
c_void,
sockaddr_ctl,
sockaddr_in,
socklen_t,
AF_SYSTEM,
AF_SYS_CONTROL,
IFNAMSIZ,
SYSPROTO_CONTROL,
};
use nix::{
ioctl_read_bad, ioctl_readwrite, ioctl_write_ptr_bad, request_code_readwrite,
ioctl_read_bad,
ioctl_readwrite,
ioctl_write_ptr_bad,
request_code_readwrite,
request_code_write,
};

View file

@ -13,6 +13,7 @@ use fehler::throws;
use libc::in6_ifreq;
use socket2::{Domain, SockAddr, Socket, Type};
use tracing::{info, instrument};
use super::{ifname_to_string, string_to_ifname};
use crate::TunOptions;

View file

@ -1,5 +1,5 @@
use std::{
io::{Error, Read},
io::Error,
mem::MaybeUninit,
os::fd::{AsRawFd, FromRawFd, IntoRawFd, RawFd},
};
@ -51,7 +51,7 @@ impl TunInterface {
let mut tmp_buf = [MaybeUninit::uninit(); 1500];
let len = self.socket.recv(&mut tmp_buf)?;
let result_buf = unsafe { assume_init(&tmp_buf[4..len]) };
buf[..len - 4].copy_from_slice(&result_buf);
buf[..len - 4].copy_from_slice(result_buf);
len - 4
}

View file

@ -11,7 +11,7 @@ fn tst_read() {
// This test is interactive, you need to send a packet to any server through
// 192.168.1.10 EG. `sudo route add 8.8.8.8 192.168.1.10`,
//`dig @8.8.8.8 hackclub.com`
let mut tun = TunInterface::new()?;
let tun = TunInterface::new()?;
println!("tun name: {:?}", tun.name()?);
tun.set_ipv4_addr(Ipv4Addr::from([192, 168, 1, 10]))?;
println!("tun ip: {:?}", tun.ipv4_addr()?);