Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1,171 changes: 1,161 additions & 10 deletions Cargo.lock

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ base64 = "0.22"
clap = { version = "4.5", features = ["derive", "env"] }
defguard_version = { git = "https://github.com/DefGuard/defguard.git", rev = "640bae9a0aea1e11395f0a29fb8c84eeefd7f115" }
defguard_wireguard_rs = { git = "https://github.com/DefGuard/wireguard-rs", rev = "6444a4e31336c4cdbb18dcb5af07f59ad6ce57ab" }
defguard_certs = { git = "https://github.com/DefGuard/defguard.git", rev = "290bdee718f51179c71e07f3bce3f8a0cbfb9379" }
env_logger = "0.11"
gethostname = "1.0"
ipnetwork = "0.21"
Expand Down
16 changes: 13 additions & 3 deletions deny.toml
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,10 @@ feature-depth = 1
#db-urls = ["https://github.com/rustsec/advisory-db"]
# A list of advisory IDs to ignore. Note that ignored advisories will still
# output a note when they are encountered.
ignore = [{ id = "RUSTSEC-2024-0436", reason = "Unmaintained" }]
ignore = [
{ id = "RUSTSEC-2024-0436", reason = "Unmaintained" },
{ id = "RUSTSEC-2025-0142", reason = "Awaiting upstream patch" },
]
# If this is true, then cargo deny will use the git executable to fetch advisory database.
# If this is false, then it uses a built-in git library.
# Setting this to true can be helpful if you have special authentication requirements that cargo-deny does not support.
Expand Down Expand Up @@ -108,8 +111,15 @@ confidence-threshold = 0.8
# Allow 1 or more licenses on a per-crate basis, so that particular licenses
# aren't accepted for every possible crate as with the normal allow list
exceptions = [
{ allow = ["AGPL-3.0-or-later"], crate = "defguard-gateway" },
{ allow = ["AGPL-3.0-or-later"], crate = "defguard_version" }
{ allow = [
"AGPL-3.0-or-later",
], crate = "defguard-gateway" },
{ allow = [
"AGPL-3.0-or-later",
], crate = "defguard_version" },
{ allow = [
"AGPL-3.0-or-later",
], crate = "defguard_certs" },
]

# Some crates don't have (easily) machine readable licensing information,
Expand Down
3 changes: 0 additions & 3 deletions example-config.toml
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
# This is an example config file for defguard VPN gateway
# To use it fill in actual values for your deployment below

# Required: secret token generated by defguard
# NOTE: must replace default with actual value
token = "<your_gateway_token>"
# Required: defguard server gRPC endpoint URL
# NOTE: must replace default with actual value
grpc_url = "<defguard_grpc_url>"
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
# NOTE: must replace default with actual value
token = "{{ OPNsense.defguardgateway.general.Token|default("") }}"
# Required: defguard server gRPC endpoint URL
# NOTE: must replace default with actual value
grpc_url = "{{ OPNsense.defguardgateway.general.GrpcUrl|default("") }}"
Expand Down
2 changes: 1 addition & 1 deletion proto
20 changes: 8 additions & 12 deletions src/config.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,17 +22,6 @@ pub struct Config {
#[serde(default = "default_log_level")]
pub log_level: String,

/// Token received from Defguard after completing the network wizard
#[arg(
long,
short = 't',
required_unless_present = "config_path",
env = "DEFGUARD_TOKEN",
default_value = ""
)]
#[serde(default)]
pub token: String,

#[arg(long, env = "DEFGUARD_GATEWAY_NAME")]
pub name: Option<String>,

Expand Down Expand Up @@ -120,6 +109,13 @@ pub struct Config {

#[arg(long, env = "DEFGUARD_HTTP_BIND_ADDRESS")]
pub http_bind_address: Option<IpAddr>,

#[arg(
long,
env = "DEFGUARD_GATEWAY_CERT_DIR",
default_value = "/etc/defguard/certs"
)]
pub cert_dir: PathBuf,
}

impl Config {
Expand All @@ -133,7 +129,6 @@ impl Default for Config {
fn default() -> Self {
Self {
log_level: "info".into(),
token: "TOKEN".into(),
name: None,
grpc_port: 50066,
userspace: false,
Expand All @@ -155,6 +150,7 @@ impl Default for Config {
fw_priority: None,
disable_firewall_management: false,
http_bind_address: None,
cert_dir: PathBuf::from("/etc/defguard/certs"),
}
}
}
Expand Down
4 changes: 2 additions & 2 deletions src/enterprise/firewall/packetfilter/calls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -847,13 +847,13 @@ ioctl_readwrite!(pf_rollback, b'D', 83, IocTrans);

#[cfg(test)]
mod tests {
use ipnetwork::{Ipv4Network, Ipv6Network};

use std::{
mem::align_of,
net::{Ipv4Addr, Ipv6Addr},
};

use ipnetwork::{Ipv4Network, Ipv6Network};

use super::*;

#[test]
Expand Down
3 changes: 3 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,4 +50,7 @@ pub enum GatewayError {

#[error(transparent)]
SemverError(#[from] SemverError),

#[error("Encountered an error during Gateway setup: {0}")]
SetupError(String),
}
57 changes: 37 additions & 20 deletions src/gateway.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,5 @@
use defguard_version::{
ComponentInfo, DefguardComponent, Version, get_tracing_variables, server::DefguardVersionLayer,
};
use defguard_wireguard_rs::{WireguardInterfaceApi, net::IpAddrMask};
use gethostname::gethostname;
use std::{
collections::HashMap,
fs::read_to_string,
net::{IpAddr, Ipv4Addr, SocketAddr},
str::FromStr,
sync::{
Expand All @@ -14,6 +8,12 @@ use std::{
},
time::{Duration, SystemTime},
};

use defguard_version::{
ComponentInfo, DefguardComponent, Version, get_tracing_variables, server::DefguardVersionLayer,
};
use defguard_wireguard_rs::{WireguardInterfaceApi, net::IpAddrMask};
use gethostname::gethostname;
use tokio::{sync::mpsc, time::interval};
use tokio_stream::wrappers::UnboundedReceiverStream;
use tonic::{
Expand Down Expand Up @@ -71,6 +71,12 @@ impl From<Configuration> for InterfaceConfiguration {

type PubKey = String;

#[derive(Clone, Debug)]
pub struct TlsConfig {
pub grpc_cert_pem: String,
pub grpc_key_pem: String,
}

pub struct Gateway {
config: Config,
interface_configuration: Option<InterfaceConfiguration>,
Expand All @@ -81,6 +87,7 @@ pub struct Gateway {
pub connected: Arc<AtomicBool>,
// Transmission channel. Important: allows only one connected client.
client_tx: Option<mpsc::UnboundedSender<Result<CoreRequest, Status>>>,
pub(crate) tls_config: Option<TlsConfig>,
}

impl Gateway {
Expand All @@ -98,6 +105,7 @@ impl Gateway {
firewall_config: None,
connected: Arc::new(AtomicBool::new(false)),
client_tx: None,
tls_config: None,
})
}

Expand Down Expand Up @@ -440,16 +448,14 @@ impl Gateway {
}

pub struct GatewayServer {
auth_token: String,
message_id: AtomicU64,
gateway: Arc<Mutex<Gateway>>,
}

impl GatewayServer {
#[must_use]
pub fn new(auth_token: String, gateway: Arc<Mutex<Gateway>>) -> Self {
pub fn new(gateway: Arc<Mutex<Gateway>>) -> Self {
Self {
auth_token,
message_id: AtomicU64::new(0),
gateway,
}
Expand All @@ -462,7 +468,7 @@ impl GatewayServer {
pub async fn start(self, config: Config) -> Result<(), GatewayError> {
info!(
"Starting Defguard Gateway version {VERSION} with configuration: {:?}",
mask!(config, token)
config
);

// Try to create network interface for WireGuard.
Expand Down Expand Up @@ -495,17 +501,20 @@ impl GatewayServer {
execute_command(post_up)?;
}

// Optionally, read gRPC TLS certificate and key.
debug!("Configuring certificates for gRPC");
let grpc_cert = config
.grpc_cert
let grpc_cert = self
.gateway
.lock()
.unwrap()
.tls_config
.as_ref()
.and_then(|path| read_to_string(path).ok());
let grpc_key = config
.grpc_key
.map(|c| c.grpc_cert_pem.clone());
let grpc_key = self
.gateway
.lock()
.unwrap()
.tls_config
.as_ref()
.and_then(|path| read_to_string(path).ok());
debug!("Configured certificates for gRPC, cert: {grpc_cert:?}");
.map(|c| c.grpc_key_pem.clone());

// Build gRPC server.
let addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::UNSPECIFIED), config.grpc_port);
Expand Down Expand Up @@ -534,6 +543,12 @@ impl GatewayServer {

Ok(())
}

pub fn set_tls_config(&mut self, tls_config: TlsConfig) {
if let Ok(mut gateway) = self.gateway.lock() {
gateway.tls_config = Some(tls_config);
}
}
}

#[tonic::async_trait]
Expand Down Expand Up @@ -593,7 +608,6 @@ impl gateway_server::Gateway for GatewayServer {
#[allow(deprecated)]
let payload = ConfigurationRequest {
name: None, // TODO: remove?
auth_token: self.auth_token.clone(),
hostname,
};
let req = CoreRequest {
Expand Down Expand Up @@ -783,6 +797,7 @@ mod tests {
firewall_config: None,
connected: Arc::new(AtomicBool::new(false)),
client_tx: None,
tls_config: None,
};

// new config is the same
Expand Down Expand Up @@ -970,6 +985,7 @@ mod tests {
firewall_config: None,
connected: Arc::new(AtomicBool::new(false)),
client_tx: None,
tls_config: None,
};

// Gateway has no firewall config, new rules are empty
Expand Down Expand Up @@ -1036,6 +1052,7 @@ mod tests {
firewall_config: None,
connected: Arc::new(AtomicBool::new(false)),
client_tx: None,
tls_config: None,
};
// Gateway has no config
gateway.firewall_config = None;
Expand Down
12 changes: 11 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,17 +18,27 @@ pub mod proto {
#[macro_use]
extern crate log;

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

use config::Config;
use defguard_wireguard_rs::{InterfaceConfiguration, net::IpAddrMask, peer::Peer};
use error::GatewayError;
use syslog::{BasicLogger, Facility, Formatter3164};
use tokio::sync::oneshot;

pub mod enterprise;
pub mod setup;

pub const VERSION: &str = concat!(env!("CARGO_PKG_VERSION"), "+", env!("VERGEN_GIT_SHA"));

type CommsChannel<T> = (
Arc<tokio::sync::Mutex<Option<oneshot::Sender<T>>>>,
Arc<tokio::sync::Mutex<oneshot::Receiver<T>>>,
);

pub const GRPC_CERT_NAME: &str = "gateway_grpc_cert.pem";
pub const GRPC_KEY_NAME: &str = "gateway_grpc_key.pem";

/// Masks object's field with "***" string.
/// Used to log sensitive/secret objects.
#[macro_export]
Expand Down
46 changes: 42 additions & 4 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,19 +1,20 @@
use std::{
fs::File,
fs::{File, read_to_string},
io::Write,
process,
sync::{Arc, Mutex},
};

use defguard_gateway::{
VERSION,
GRPC_CERT_NAME, GRPC_KEY_NAME, VERSION,
config::get_config,
enterprise::firewall::api::FirewallApi,
error::GatewayError,
execute_command,
gateway::{Gateway, GatewayServer, run_stats},
gateway::{Gateway, GatewayServer, TlsConfig, run_stats},
init_syslog,
server::run_server,
setup::GatewaySetupServer,
};
use defguard_version::Version;
#[cfg(not(any(target_os = "macos", target_os = "netbsd")))]
Expand Down Expand Up @@ -85,8 +86,45 @@ async fn main() -> Result<(), GatewayError> {
let gateway = Arc::new(Mutex::new(gateway));
tasks.spawn(run_stats(Arc::clone(&gateway), config.stats_period()));

let cert_dir = &config.cert_dir;
if !cert_dir.exists() {
tokio::fs::create_dir_all(cert_dir).await?;
}
let tls_config = if let (Some(cert), Some(key)) = (
read_to_string(cert_dir.join(GRPC_CERT_NAME)).ok(),
read_to_string(cert_dir.join(GRPC_KEY_NAME)).ok(),
) {
log::info!(
"Using existing gRPC TLS certificates from {}",
cert_dir.display()
);
TlsConfig {
grpc_cert_pem: cert,
grpc_key_pem: key,
}
} else {
log::info!(
"gRPC TLS certificates not found in {}. They will be generated during setup.",
cert_dir.display()
);
let setup_server = GatewaySetupServer::default();
let tls_config = setup_server.await_setup(config.clone()).await?;

let cert_path = cert_dir.join(GRPC_CERT_NAME);
let key_path = cert_dir.join(GRPC_KEY_NAME);
tokio::fs::write(cert_path, &tls_config.grpc_cert_pem).await?;
tokio::fs::write(key_path, &tls_config.grpc_key_pem).await?;
log::info!(
"Generated gRPC TLS certificates have been saved to {}",
cert_dir.display()
);

tls_config
};

// Launch gRPC server.
let gateway_server = GatewayServer::new(config.token.clone(), gateway);
let mut gateway_server = GatewayServer::new(gateway);
gateway_server.set_tls_config(tls_config);
tasks.spawn(gateway_server.start(config.clone()));

while let Some(Ok(result)) = tasks.join_next().await {
Expand Down
Loading