Skip to content

Commit

Permalink
Refactor: Use wireguard as submodule (#63)
Browse files Browse the repository at this point in the history
* Make use of wireguard repository as submodule
  • Loading branch information
dzania authored Sep 11, 2023
1 parent 9d7d9cb commit a99f4f4
Show file tree
Hide file tree
Showing 20 changed files with 109 additions and 2,850 deletions.
4 changes: 4 additions & 0 deletions .gitmodules
Original file line number Diff line number Diff line change
@@ -1,3 +1,7 @@
[submodule "proto"]
path = proto
url = ../proto.git

[submodule "wireguard-rs"]
path = wireguard-rs
url = ../wireguard-rs.git
36 changes: 31 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ tokio = { version = "1", features = ["macros", "rt-multi-thread"] }
tokio-stream = { version = "0.1", features = [] }
toml = "0.7"
serde = { version = "1.0", features = ["derive"] }
wireguard_rs = { path = "wireguard-rs" }

[dev-dependencies]
tokio = { version = "1", features = ["io-std", "io-util"] }
Expand Down
4 changes: 2 additions & 2 deletions examples/api.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@ use std::str::FromStr;
use x25519_dalek::{EphemeralSecret, PublicKey, StaticSecret};

#[cfg(target_os = "linux")]
use defguard_gateway::wireguard::netlink::{address_interface, create_interface};
use defguard_gateway::wireguard::{wgapi::WGApi, Host, IpAddrMask, Key, Peer};
use wireguard_rs::netlink::{address_interface, create_interface};
use wireguard_rs::{wgapi::WGApi, Host, IpAddrMask, Key, Peer};

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
Expand Down
9 changes: 3 additions & 6 deletions examples/server.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,4 @@
use defguard_gateway::proto::ConfigurationRequest;
use defguard_gateway::{
proto,
wireguard::{Host, IpAddrMask, Key, Peer},
};
use defguard_gateway::proto;
use std::{
collections::HashMap,
io::{stdout, Write},
Expand All @@ -18,6 +14,7 @@ use tokio::{
};
use tokio_stream::wrappers::UnboundedReceiverStream;
use tonic::{transport::Server, Request, Response, Status, Streaming};
use wireguard_rs::{Host, IpAddrMask, Key, Peer};

pub struct HostConfig {
name: String,
Expand Down Expand Up @@ -84,7 +81,7 @@ impl proto::gateway_service_server::GatewayService for GatewayServer {

async fn config(
&self,
request: Request<ConfigurationRequest>,
request: Request<proto::ConfigurationRequest>,
) -> Result<Response<proto::Configuration>, Status> {
let address = request.remote_addr().unwrap();
eprintln!("CONFIG connected from: {}", address);
Expand Down
6 changes: 5 additions & 1 deletion src/error.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
use thiserror::Error;
use wireguard_rs::{error::WireguardError, IpAddrParseError};

#[derive(Debug, Error)]
pub enum GatewayError {
Expand All @@ -16,7 +17,7 @@ pub enum GatewayError {
KeyDecode(#[from] base64::DecodeError),

#[error("IP address/mask error")]
IpAddrMask(#[from] super::wireguard::IpAddrParseError),
IpAddrMask(#[from] IpAddrParseError),

#[error("Logger error")]
Logger(#[from] log::SetLoggerError),
Expand All @@ -35,4 +36,7 @@ pub enum GatewayError {

#[error("Invalid config file. Error: {0}")]
InvalidConfigFile(String),

#[error("Wireguard error")]
WireguardError(#[from] WireguardError),
}
8 changes: 4 additions & 4 deletions src/gateway.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@ use tonic::{
Request, Status, Streaming,
};

#[cfg(target_os = "linux")]
use crate::wireguard::netlink::delete_interface;
use crate::{
config::Config,
error::GatewayError,
Expand All @@ -26,9 +24,11 @@ use crate::{
gateway_service_client::GatewayServiceClient, update, Configuration, ConfigurationRequest,
Peer, Update,
},
wireguard::{setup_interface, wgapi::WGApi},
wireguard_rs::{setup_interface, wgapi::WGApi},
VERSION,
};
#[cfg(target_os = "linux")]
use wireguard_rs::netlink::delete_interface;

// helper struct which stores just the interface config without peers
#[derive(Clone, PartialEq)]
Expand Down Expand Up @@ -208,7 +208,7 @@ impl Gateway {
setup_interface(
&self.config.ifname,
self.config.userspace,
&new_configuration,
&new_configuration.clone().into(),
)?;
info!(
"Reconfigured WireGuard interface: {:?}",
Expand Down
60 changes: 58 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,20 +3,23 @@
pub mod config;
pub mod error;
pub mod gateway;
pub mod wireguard;

#[allow(non_snake_case)]
pub mod proto {
tonic::include_proto!("gateway");
}

#[macro_use]
extern crate log;

use std::{process, str::FromStr};
extern crate wireguard_rs;

use std::{process, str::FromStr, time::SystemTime};

use config::Config;
use error::GatewayError;
use syslog::{BasicLogger, Facility, Formatter3164};
use wireguard_rs::{InterfaceConfiguration, IpAddrMask, Peer};

pub const VERSION: &str = env!("CARGO_PKG_VERSION");

Expand Down Expand Up @@ -69,3 +72,56 @@ pub fn execute_command(command: &str) -> Result<(), GatewayError> {
}
Ok(())
}

impl From<proto::Configuration> for InterfaceConfiguration {
fn from(config: proto::Configuration) -> Self {
let peers = config.peers.into_iter().map(Peer::from).collect();
InterfaceConfiguration {
name: config.name,
prvkey: config.prvkey,
address: config.address,
port: config.port,
peers,
}
}
}

impl From<proto::Peer> for Peer {
fn from(proto_peer: proto::Peer) -> Self {
let mut peer = Self::new(proto_peer.pubkey.as_str().try_into().unwrap_or_default());
peer.allowed_ips = proto_peer
.allowed_ips
.iter()
.filter_map(|entry| IpAddrMask::from_str(entry).ok())
.collect();
peer
}
}

impl From<&Peer> for proto::Peer {
fn from(peer: &Peer) -> Self {
Self {
pubkey: peer.public_key.to_string(),
allowed_ips: peer.allowed_ips.iter().map(ToString::to_string).collect(),
}
}
}

impl From<&Peer> for proto::PeerStats {
fn from(peer: &Peer) -> Self {
Self {
public_key: peer.public_key.to_string(),
endpoint: peer
.endpoint
.map_or(String::new(), |endpoint| endpoint.to_string()),
allowed_ips: peer.allowed_ips.iter().map(ToString::to_string).collect(),
latest_handshake: peer.last_handshake.map_or(0, |ts| {
ts.duration_since(SystemTime::UNIX_EPOCH)
.map_or(0, |duration| duration.as_secs() as i64)
}),
download: peer.rx_bytes as i64,
upload: peer.tx_bytes as i64,
keepalive_interval: i64::from(peer.persistent_keepalive_interval.unwrap_or_default()),
}
}
}
Loading

0 comments on commit a99f4f4

Please sign in to comment.