udp, http: move privilege drop code into aquatic_common

This commit is contained in:
Joakim Frostegård 2021-10-27 20:49:15 +02:00
parent ead7650d41
commit d6d5cc78b7
11 changed files with 72 additions and 87 deletions

View file

@ -16,5 +16,6 @@ arc-swap = "1"
hashbrown = "0.11.2"
hex = "0.4"
indexmap = "1"
privdrop = "0.5"
rand = { version = "0.8", features = ["small_rng"] }
serde = { version = "1", features = ["derive"] }

View file

@ -6,6 +6,7 @@ use rand::Rng;
pub mod access_list;
pub mod cpu_pinning;
pub mod privileges;
/// Peer or connection valid until this instant
///

View file

@ -0,0 +1,59 @@
use std::{sync::{Arc, atomic::{AtomicUsize, Ordering}}, time::Duration};
use privdrop::PrivDrop;
use serde::{Serialize, Deserialize};
#[derive(Clone, Debug, Serialize, Deserialize)]
#[serde(default)]
pub struct PrivilegeConfig {
/// Chroot and switch user after binding to sockets
pub drop_privileges: bool,
/// Chroot to this path
pub chroot_path: String,
/// User to switch to after chrooting
pub user: String,
}
impl Default for PrivilegeConfig {
fn default() -> Self {
Self {
drop_privileges: false,
chroot_path: ".".to_string(),
user: "nobody".to_string(),
}
}
}
pub fn drop_privileges_after_socket_binding(
config: &PrivilegeConfig,
num_bound_sockets: Arc<AtomicUsize>,
target_num: usize,
) -> anyhow::Result<()> {
if config.drop_privileges {
let mut counter = 0usize;
loop {
let num_bound = num_bound_sockets.load(Ordering::SeqCst);
if num_bound == target_num {
PrivDrop::default()
.chroot(config.chroot_path.clone())
.user(config.user.clone())
.apply()?;
break;
}
::std::thread::sleep(Duration::from_millis(10));
counter += 1;
if counter == 500 {
panic!("Sockets didn't bind in time for privilege drop.");
}
}
}
Ok(())
}