-
-
Notifications
You must be signed in to change notification settings - Fork 33
Expand file tree
/
Copy pathdaemon.rs
More file actions
592 lines (531 loc) · 21.3 KB
/
daemon.rs
File metadata and controls
592 lines (531 loc) · 21.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
use std::{
collections::HashMap,
pin::Pin,
sync::{Arc, Mutex, RwLock},
time::{Duration, SystemTime},
};
#[cfg(unix)]
use std::{fs, os::unix::fs::PermissionsExt, path::Path};
use common::dns_borrow;
use defguard_wireguard_rs::{
error::WireguardInterfaceError, InterfaceConfiguration, Kernel, WGApi, WireguardInterfaceApi,
};
#[cfg(unix)]
use nix::unistd::{chown, Group};
#[cfg(unix)]
use tokio::net::UnixListener;
use tokio::{sync::mpsc, task::JoinHandle, time::interval};
#[cfg(unix)]
use tokio_stream::wrappers::UnixListenerStream;
use tonic::{
codegen::tokio_stream::{wrappers::ReceiverStream, Stream},
transport::Server,
Code, Response, Status,
};
#[cfg(not(windows))]
use tracing::warn;
use tracing::{debug, error, info, info_span, Instrument};
use super::{
config::Config,
proto::defguard::client::v1::{
desktop_daemon_service_server::{DesktopDaemonService, DesktopDaemonServiceServer},
CreateInterfaceRequest, DeleteServiceLocationsRequest, InterfaceData,
ReadInterfaceDataRequest, RemoveInterfaceRequest, SaveServiceLocationsRequest,
},
};
use crate::{
enterprise::service_locations::ServiceLocationError,
service::proto::defguard::enterprise::posture::v2::DevicePostureData, VERSION,
};
#[cfg(windows)]
use crate::{
enterprise::service_locations::ServiceLocationManager,
service::named_pipe::{get_named_pipe_server_stream, PIPE_NAME},
};
#[cfg(unix)]
pub(super) const DAEMON_SOCKET_PATH: &str = "/var/run/defguard.socket";
#[cfg(target_os = "linux")]
pub(super) const DAEMON_SOCKET_GROUP: &str = "defguard";
#[derive(Debug, thiserror::Error)]
pub enum DaemonError {
#[error(transparent)]
WireguardError(#[from] WireguardInterfaceError),
#[error("Unexpected error: {0}")]
Unexpected(String),
#[error(transparent)]
TransportError(#[from] tonic::transport::Error),
#[error(transparent)]
ServiceLocationError(#[from] ServiceLocationError),
#[cfg(windows)]
#[error(transparent)]
WindowsServiceError(#[from] windows_service::Error),
}
type IfName = String;
#[cfg(not(target_os = "macos"))]
type WG = WGApi<Kernel>;
#[cfg(target_os = "macos")]
type WG = WGApi<Userspace>;
#[derive(Default)]
pub(crate) struct DaemonService {
// Map of running `WGApi`s; key is interface name.
wgapis: Arc<RwLock<HashMap<IfName, WG>>>,
stats_period: Duration,
stat_tasks: Arc<Mutex<HashMap<IfName, JoinHandle<()>>>>,
#[cfg(windows)]
service_location_manager: Arc<RwLock<ServiceLocationManager>>,
}
impl DaemonService {
#[must_use]
pub fn new(
config: &Config,
#[cfg(windows)] service_location_manager: Arc<RwLock<ServiceLocationManager>>,
) -> Self {
Self {
wgapis: Arc::new(RwLock::new(HashMap::new())),
stats_period: Duration::from_secs(config.stats_period),
stat_tasks: Arc::new(Mutex::new(HashMap::new())),
#[cfg(windows)]
service_location_manager,
}
}
}
/// Helper function used to perform required configuration steps for a new interface.
///
/// This allows us to roll back interface creation if some configuration step fails.
fn configure_new_interface(
ifname: &str,
request: &CreateInterfaceRequest,
wgapi: &mut WGApi,
interface_config: &InterfaceConfiguration,
) -> Result<(), Status> {
// The WireGuard DNS config value can be a list of IP addresses and domain names, which will
// be used as DNS servers and search domains respectively.
debug!("Preparing DNS configuration for interface {ifname}");
let (dns, search_domains) = dns_borrow(&request.dns);
debug!(
"DNS configuration for interface {ifname}: DNS: {dns:?}, Search domains: \
{search_domains:?}"
);
let configure_interface_result = wgapi.configure_interface(interface_config);
configure_interface_result.map_err(|err| {
let msg = format!("Failed to configure WireGuard interface {ifname}: {err}");
error!("{msg}");
Status::new(Code::Internal, msg)
})?;
#[cfg(not(windows))]
{
debug!("Configuring interface {ifname} routing");
wgapi
.configure_peer_routing(&interface_config.peers)
.map_err(|err| {
let msg =
format!("Failed to configure routing for WireGuard interface {ifname}: {err}");
error!("{msg}");
Status::new(Code::Internal, msg)
})?;
}
if dns.is_empty() {
debug!(
"No DNS configuration provided for interface {ifname}, skipping DNS \
configuration"
);
} else {
debug!(
"The following DNS servers will be set: {dns:?}, search domains: \
{search_domains:?}"
);
wgapi.configure_dns(&dns, &search_domains).map_err(|err| {
let msg = format!("Failed to configure DNS for WireGuard interface {ifname}: {err}");
error!("{msg}");
Status::new(Code::Internal, msg)
})?;
}
Ok(())
}
type InterfaceDataStream = Pin<Box<dyn Stream<Item = Result<InterfaceData, Status>> + Send>>;
pub(crate) fn setup_wgapi(ifname: &str) -> Result<WG, Status> {
let wgapi = WG::new(ifname).map_err(|err| {
let msg = format!("Failed to setup WireGuard API for interface {ifname}: {err}");
error!("{msg}");
Status::new(Code::Internal, msg)
})?;
Ok(wgapi)
}
#[tonic::async_trait]
impl DesktopDaemonService for DaemonService {
type ReadInterfaceDataStream = InterfaceDataStream;
#[cfg(not(windows))]
async fn save_service_locations(
&self,
_request: tonic::Request<SaveServiceLocationsRequest>,
) -> Result<Response<()>, Status> {
debug!("Save service location request received, this is currently not supported on Unix systems");
Ok(Response::new(()))
}
#[cfg(not(windows))]
async fn delete_service_locations(
&self,
_request: tonic::Request<DeleteServiceLocationsRequest>,
) -> Result<Response<()>, Status> {
debug!("Delete service location request received, this is currently not supported on Unix systems");
Ok(Response::new(()))
}
#[cfg(windows)]
async fn save_service_locations(
&self,
request: tonic::Request<SaveServiceLocationsRequest>,
) -> Result<Response<()>, Status> {
debug!("Received a request to save service location");
let service_location = request.into_inner();
match self
.service_location_manager
.clone()
.read()
.unwrap()
.save_service_locations(
service_location.service_locations.as_slice(),
&service_location.instance_id,
&service_location.private_key,
) {
Ok(()) => {
debug!("Service location saved successfully");
}
Err(e) => {
let msg = format!("Failed to save service location: {e}");
error!(msg);
return Err(Status::internal(msg));
}
}
for saved_location in service_location.service_locations {
match self
.service_location_manager
.clone()
.write()
.unwrap()
.reset_service_location_state(&service_location.instance_id, &saved_location.pubkey)
{
Ok(()) => {
debug!(
"Service location '{}' state reset successfully",
saved_location.name
);
}
Err(e) => {
error!(
"Failed to reset state for service location '{}': {e}",
saved_location.name
);
}
}
}
Ok(Response::new(()))
}
#[cfg(not(windows))]
async fn get_posture_data(
&self,
_request: tonic::Request<()>,
) -> Result<Response<DevicePostureData>, Status> {
warn!(
"Daemon service received a get_posture_data request. Daemon posture requests are only supported on windows systems. Unix systems perform client-side posture checks."
);
Err(Status::unimplemented(
"Service-side posture checks are only supported on Unix systems",
))
}
#[cfg(windows)]
async fn delete_service_locations(
&self,
request: tonic::Request<DeleteServiceLocationsRequest>,
) -> Result<Response<()>, Status> {
debug!("Received a request to delete service location");
let instance_id = request.into_inner().instance_id;
self.service_location_manager
.clone()
.write()
.unwrap()
.disconnect_service_locations_by_instance(&instance_id)
.map_err(|err| {
let msg = format!("Failed to disconnect service location: {err}");
error!(msg);
Status::internal(msg)
})?;
match self
.service_location_manager
.clone()
.read()
.unwrap()
.delete_all_service_locations_for_instance(&instance_id)
{
Ok(()) => {
debug!("Service location deleted successfully");
Ok(Response::new(()))
}
Err(err) => {
error!("Failed to delete service location: {err}");
Err(Status::internal(format!(
"Failed to delete service location: {err}"
)))
}
}
}
async fn create_interface(
&self,
request: tonic::Request<CreateInterfaceRequest>,
) -> Result<Response<()>, Status> {
debug!("Received a request to create a new interface");
let request = request.into_inner();
let config: InterfaceConfiguration = request
.config
.clone()
.ok_or(Status::new(
Code::InvalidArgument,
"Missing interface config in request",
))?
.into();
let ifname = &config.name;
let _span = info_span!("create_interface", interface_name = &ifname).entered();
// Setup WireGuard API.
let Ok(mut wgapis_map) = self.wgapis.write() else {
error!("Failed to acquire read-write lock for WGApis");
return Err(Status::new(Code::Internal, "read-write lock error"));
};
let wgapi = wgapis_map
.entry(ifname.clone())
.or_insert(setup_wgapi(ifname)?);
// create new interface
debug!("Creating new interface {ifname}");
wgapi.create_interface().map_err(|err| {
let msg = format!("Failed to create WireGuard interface {ifname}: {err}");
error!("{msg}");
Status::new(Code::Internal, msg)
})?;
info!("Done creating a new interface {ifname}");
// attempt to configure new interface
// remove interface if configuration fails to avoid duplicate interfaces
match configure_new_interface(ifname, &request, wgapi, &config) {
Ok(()) => info!("Finished configuring new interface {ifname}"),
Err(err) => {
error!("Failed to configure interface {ifname}. Error: {err}");
debug!("Removing newly created interface {ifname} due to configuration failure");
wgapi.remove_interface().map_err(|err| {
let msg = format!("Failed to remove WireGuard interface {ifname}: {err}");
error!("{msg}");
Status::new(Code::Internal, msg)
})?;
return Err(err);
}
}
debug!("Finished creating a new interface {ifname}");
Ok(Response::new(()))
}
async fn remove_interface(
&self,
request: tonic::Request<RemoveInterfaceRequest>,
) -> Result<Response<()>, Status> {
debug!("Received a request to remove an interface");
let request = request.into_inner();
let ifname = request.interface_name;
let _span = info_span!("remove_interface", interface_name = &ifname).entered();
debug!("Removing interface {ifname}");
// Stop stats task.
if let Ok(mut tasks) = self.stat_tasks.lock() {
if let Some(handle) = tasks.remove(&ifname) {
info!("Stopping statistics collector task for interface {ifname}");
handle.abort();
}
}
// `WGApi::remove_interface`` takes `&mut self` under Windows.
#[allow(unused_mut)]
let mut wgapi = {
let Ok(mut wgapis_map) = self.wgapis.write() else {
error!("Failed to acquire read-write lock for WGApis");
return Err(Status::new(Code::Internal, "read-write lock error"));
};
let Some(wgapi) = wgapis_map.remove(&ifname) else {
error!("Unknown interface {ifname}");
return Err(Status::new(Code::Internal, "unknown interface"));
};
wgapi
};
#[cfg(not(windows))]
{
debug!("Cleaning up interface {ifname} routing");
// Ignore error as this should not be considered fatal,
// e.g. endpoint might fail to resolve DNS name.
if let Err(err) = wgapi.remove_endpoint_routing(&request.endpoint) {
error!(
"Failed to remove routing for endpoint {}: {err}",
request.endpoint
);
}
}
wgapi.remove_interface().map_err(|err| {
let msg = format!("Failed to remove WireGuard interface {ifname}: {err}");
error!("{msg}");
Status::new(Code::Internal, msg)
})?;
debug!("Finished removing interface {ifname}");
Ok(Response::new(()))
}
async fn read_interface_data(
&self,
request: tonic::Request<ReadInterfaceDataRequest>,
) -> Result<Response<Self::ReadInterfaceDataStream>, Status> {
let request = request.into_inner();
let ifname = request.interface_name.clone();
debug!(
"Received a request to start a new network usage stats data stream for interface \
{ifname}"
);
let span = info_span!("read_interface_data", interface_name = &ifname);
let wgapis = Arc::clone(&self.wgapis);
let mut interval = interval(self.stats_period);
let (tx, rx) = mpsc::channel(64);
span.in_scope(|| {
info!("Spawning statistics collector task for interface {ifname}");
});
let handle = tokio::spawn(
async move {
// Helper map to track if peer data is actually changing to avoid sending duplicate
// stats.
let mut peer_map = HashMap::new();
loop {
// Loop delay
interval.tick().await;
debug!(
"Gathering network usage statistics for client's network activity on {ifname}");
let result = {
let Ok(wgapis_map) = wgapis.read() else {
error!("Failed to acquire read-write lock for WGApis");
break;
};
let Some(wgapi) = wgapis_map.get(&ifname) else {
error!("Unknown interface {ifname}");
break;
};
wgapi.read_interface_data()
};
match result {
Ok(mut host) => {
let peers = &mut host.peers;
debug!(
"Found {} peers configured on WireGuard interface",
peers.len()
);
// Filter out never connected peers.
peers.retain(|_, peer| {
// Last handshake time-stamp must exist.
if let Some(last_hs) = peer.last_handshake {
// ...and not be UNIX epoch.
if last_hs != SystemTime::UNIX_EPOCH
&& match peer_map.get(&peer.public_key) {
Some(last_peer) => last_peer != peer,
None => true,
}
{
debug!(
"Peer {} statistics changed; keeping it.",
peer.public_key
);
peer_map.insert(peer.public_key.clone(), peer.clone());
return true;
}
}
debug!(
"Peer {} statistics didn't change; ignoring it.",
peer.public_key
);
false
});
if let Err(err) = tx.send(Ok(host.into())).await {
error!(
"Couldn't send network usage stats update for {ifname}: {err}"
);
break;
}
}
Err(err) => {
error!(
"Failed to retrieve network usage stats for interface {ifname}: \
{err}"
);
break;
}
}
debug!("Network activity statistics for interface {ifname} sent to the client");
}
debug!(
"The client has disconnected from the network usage statistics data stream \
for interface {ifname}, stopping the statistics data collection task."
);
}
.instrument(span),
);
if let Ok(mut tasks) = self.stat_tasks.lock() {
tasks.insert(request.interface_name, handle);
}
let output_stream = ReceiverStream::new(rx);
Ok(Response::new(
Box::pin(output_stream) as Self::ReadInterfaceDataStream
))
}
#[cfg(windows)]
async fn get_posture_data(
&self,
_request: tonic::Request<()>,
) -> Result<Response<DevicePostureData>, Status> {
debug!("Get posture data request received");
Ok(Response::new(DevicePostureData::new()))
}
}
#[cfg(unix)]
pub async fn run_server(config: Config) -> anyhow::Result<()> {
debug!("Starting Defguard interface management daemon");
let daemon_service = DaemonService::new(&config);
// Remove existing socket if it exists
if Path::new(DAEMON_SOCKET_PATH).exists() {
debug!("Removing existing socket file at {DAEMON_SOCKET_PATH}");
fs::remove_file(DAEMON_SOCKET_PATH)?;
}
debug!("Binding socket file at {DAEMON_SOCKET_PATH}");
let uds = UnixListener::bind(DAEMON_SOCKET_PATH)?;
// change owner group for socket file
// get the group ID by name
let group = Group::from_name(DAEMON_SOCKET_GROUP)?.ok_or_else(|| {
error!("Group '{DAEMON_SOCKET_GROUP}' not found");
crate::error::Error::InternalError(format!("Group '{DAEMON_SOCKET_GROUP}' not found"))
})?;
// change ownership - keep current user, change group
debug!("Changing owner group of socket file at {DAEMON_SOCKET_PATH} to group {DAEMON_SOCKET_GROUP}");
chown(DAEMON_SOCKET_PATH, None, Some(group.gid))?;
// Set socket permissions to allow client access
// 0o660 allows read/write for owner and group only
debug!("Setting permissions for socket file at {DAEMON_SOCKET_PATH} to 0x660");
fs::set_permissions(DAEMON_SOCKET_PATH, fs::Permissions::from_mode(0o660))?;
let uds_stream = UnixListenerStream::new(uds);
info!("Defguard daemon version {VERSION} started, listening on socket {DAEMON_SOCKET_PATH}",);
debug!("Defguard daemon configuration: {config:?}");
Server::builder()
.trace_fn(|_| tracing::info_span!("defguard_service"))
.add_service(DesktopDaemonServiceServer::new(daemon_service))
.serve_with_incoming(uds_stream)
.await?;
Ok(())
}
#[cfg(windows)]
pub(crate) async fn run_server(
config: Config,
service_location_manager: Arc<RwLock<ServiceLocationManager>>,
) -> anyhow::Result<()> {
debug!("Starting Defguard interface management daemon");
let stream = get_named_pipe_server_stream();
let daemon_service = DaemonService::new(&config, service_location_manager);
info!("Defguard daemon version {VERSION} started, listening on named pipe {PIPE_NAME}");
debug!("Defguard daemon configuration: {config:?}");
Server::builder()
.trace_fn(|_| tracing::info_span!("defguard_service"))
.add_service(DesktopDaemonServiceServer::new(daemon_service))
.serve_with_incoming(stream)
.await?;
Ok(())
}