|
| 1 | +use crate::{ |
| 2 | + config::{DaemonConfig, NetworkConfig, ServerConfig}, |
| 3 | + crypto::decrypt_config, |
| 4 | + dns::resolve_to_ip, |
| 5 | +}; |
| 6 | +use defguard_wireguard_rs::{ |
| 7 | + InterfaceConfiguration, WGApi, WireguardInterfaceApi, host::Peer, key::Key, net::IpAddrMask, |
| 8 | +}; |
| 9 | +use std::{error::Error, fs::read_to_string, net::IpAddr, str::FromStr, time::Duration}; |
| 10 | +use url::Url; |
| 11 | + |
| 12 | +pub async fn fetch_config_content(config_url: &str) -> Result<String, Box<dyn Error>> { |
| 13 | + // Try to parse as URL first |
| 14 | + if let Ok(url) = Url::parse(config_url) { |
| 15 | + match url.scheme() { |
| 16 | + "file" => { |
| 17 | + // Handle file:// URLs |
| 18 | + let path = url |
| 19 | + .to_file_path() |
| 20 | + .map_err(|_| format!("Invalid file URL: {}", config_url))?; |
| 21 | + Ok(read_to_string(path)?) |
| 22 | + } |
| 23 | + "http" | "https" => { |
| 24 | + // Handle HTTP(S) URLs with 30-second timeout |
| 25 | + let client = reqwest::Client::builder() |
| 26 | + .timeout(Duration::from_secs(30)) |
| 27 | + .build()?; |
| 28 | + Ok(client.get(config_url).send().await?.text().await?) |
| 29 | + } |
| 30 | + scheme => Err(format!("Unsupported URL scheme: {}", scheme).into()), |
| 31 | + } |
| 32 | + } else { |
| 33 | + // If URL parsing fails, treat it as a plain file path |
| 34 | + Ok(read_to_string(config_url)?) |
| 35 | + } |
| 36 | +} |
| 37 | + |
| 38 | +pub(crate) async fn fetch_and_apply_config( |
| 39 | + wgapi: &WGApi, |
| 40 | + interface_config: &mut InterfaceConfiguration, |
| 41 | + pubkey: &str, |
| 42 | + config: &DaemonConfig, |
| 43 | +) -> Result<(), Box<dyn Error>> { |
| 44 | + let mut r = fetch_config_content(&config.config_url).await?; |
| 45 | + if config.secret.is_some() { |
| 46 | + r = decrypt_config(&r, &config.secret.as_ref().unwrap())?; |
| 47 | + } |
| 48 | + let r: NetworkConfig = serde_json::from_str(&r)?; |
| 49 | + let mut my_config: Option<ServerConfig> = None; |
| 50 | + for peer in r.peers.iter() { |
| 51 | + if peer.pubkey == pubkey { |
| 52 | + my_config = Some(peer.clone()); |
| 53 | + } |
| 54 | + } |
| 55 | + if my_config.is_none() { |
| 56 | + println!("Current server is not configured in the network"); |
| 57 | + return Ok(()); |
| 58 | + } |
| 59 | + let my_config = my_config.unwrap(); |
| 60 | + let current_address = if interface_config.addresses.len() > 0 { |
| 61 | + interface_config.addresses[0].to_string() |
| 62 | + } else { |
| 63 | + "".to_string() |
| 64 | + }; |
| 65 | + if current_address != my_config.internal_cidr |
| 66 | + || my_config.port != interface_config.port |
| 67 | + || Some(r.mtu) != interface_config.mtu |
| 68 | + { |
| 69 | + if interface_config.port == 0 { |
| 70 | + wgapi.create_interface()?; |
| 71 | + } |
| 72 | + interface_config.addresses = vec![IpAddrMask::from_str(&my_config.internal_cidr)?]; |
| 73 | + interface_config.port = my_config.port; |
| 74 | + interface_config.mtu = Some(r.mtu); |
| 75 | + wgapi.configure_interface(&interface_config)?; |
| 76 | + } |
| 77 | + let current_peers = wgapi.read_interface_data()?; |
| 78 | + let mut next_peers = std::collections::HashSet::new(); |
| 79 | + for peer in r.peers.iter() { |
| 80 | + if peer.pubkey == pubkey { |
| 81 | + continue; |
| 82 | + } |
| 83 | + let pubkey = Key::from_str(&peer.pubkey)?; |
| 84 | + next_peers.insert(pubkey.clone()); |
| 85 | + let current_peer = current_peers.peers.get(&pubkey); |
| 86 | + let mut should_reconfigure = false; |
| 87 | + let mut peer_cidr = IpAddrMask::from_str(&peer.internal_cidr)?; |
| 88 | + peer_cidr.cidr = 32; |
| 89 | + let peer_endpoint_host = if my_config.vpc_id.is_some() |
| 90 | + && my_config.vpc_id == peer.vpc_id |
| 91 | + && peer.vpc_ip.is_some() |
| 92 | + { |
| 93 | + peer.vpc_ip.as_ref().unwrap().clone() |
| 94 | + } else { |
| 95 | + peer.ip.clone() |
| 96 | + }; |
| 97 | + |
| 98 | + // Resolve domain name to IP address |
| 99 | + let peer_endpoint_ip = resolve_to_ip(&peer_endpoint_host).await; |
| 100 | + |
| 101 | + // Calculate keepalive interval as minimum of both endpoints |
| 102 | + let keepalive_interval = match ( |
| 103 | + my_config.persistent_keepalive_interval, |
| 104 | + peer.persistent_keepalive_interval, |
| 105 | + ) { |
| 106 | + (Some(a), Some(b)) => Some(a.min(b)), |
| 107 | + (Some(a), None) => Some(a), |
| 108 | + (None, Some(b)) => Some(b), |
| 109 | + (None, None) => None, |
| 110 | + }; |
| 111 | + |
| 112 | + if let Some(p) = current_peer { |
| 113 | + if let Some(endpoint) = p.endpoint { |
| 114 | + if let Some(resolved_ip) = &peer_endpoint_ip { |
| 115 | + if endpoint.ip().to_string() != *resolved_ip |
| 116 | + || endpoint.port() as u32 != peer.port |
| 117 | + { |
| 118 | + should_reconfigure = true; |
| 119 | + } |
| 120 | + } else { |
| 121 | + // Resolution failed, need to reconfigure to clear endpoint |
| 122 | + should_reconfigure = true; |
| 123 | + } |
| 124 | + } else { |
| 125 | + should_reconfigure = true; |
| 126 | + } |
| 127 | + if p.allowed_ips.len() != 1 { |
| 128 | + should_reconfigure = true; |
| 129 | + } else if p.allowed_ips[0] != peer_cidr { |
| 130 | + should_reconfigure = true; |
| 131 | + } |
| 132 | + if p.persistent_keepalive_interval != keepalive_interval { |
| 133 | + should_reconfigure = true; |
| 134 | + } |
| 135 | + } else { |
| 136 | + should_reconfigure = true; |
| 137 | + } |
| 138 | + if should_reconfigure { |
| 139 | + let endpoint = match &peer_endpoint_ip { |
| 140 | + Some(ip) => { |
| 141 | + // Check if IP is IPv6 and needs brackets for SocketAddr parsing |
| 142 | + let endpoint_str = match ip.parse::<IpAddr>() { |
| 143 | + Ok(IpAddr::V6(_)) => format!("[{}]:{}", ip, peer.port), |
| 144 | + _ => format!("{}:{}", ip, peer.port), |
| 145 | + }; |
| 146 | + match endpoint_str.parse() { |
| 147 | + Ok(addr) => Some(addr), |
| 148 | + Err(e) => { |
| 149 | + println!("Failed to parse endpoint {}: {}", endpoint_str, e); |
| 150 | + None |
| 151 | + } |
| 152 | + } |
| 153 | + } |
| 154 | + None => None, |
| 155 | + }; |
| 156 | + let wg_peer = Peer { |
| 157 | + public_key: pubkey, |
| 158 | + preshared_key: None, |
| 159 | + protocol_version: None, |
| 160 | + endpoint, |
| 161 | + last_handshake: None, |
| 162 | + tx_bytes: 0, |
| 163 | + rx_bytes: 0, |
| 164 | + persistent_keepalive_interval: keepalive_interval, |
| 165 | + allowed_ips: vec![peer_cidr], |
| 166 | + }; |
| 167 | + let endpoint_display = peer_endpoint_ip |
| 168 | + .as_ref() |
| 169 | + .map(|ip| format!("{}:{}", ip, peer.port)) |
| 170 | + .unwrap_or_else(|| "(no endpoint - resolution failed)".to_string()); |
| 171 | + println!( |
| 172 | + "Configuring peer: {} {} {}", |
| 173 | + &peer.pubkey, endpoint_display, &peer.internal_cidr |
| 174 | + ); |
| 175 | + wgapi.configure_peer(&wg_peer)?; |
| 176 | + } |
| 177 | + } |
| 178 | + for peer in current_peers.peers.iter() { |
| 179 | + if next_peers.contains(&peer.0) { |
| 180 | + continue; |
| 181 | + } |
| 182 | + wgapi.remove_peer(&peer.0)?; |
| 183 | + } |
| 184 | + Ok(()) |
| 185 | +} |
0 commit comments