Add ability to drop privileges after binding to port

This commit is contained in:
Tobias Reisinger 2023-11-27 17:36:44 +01:00
parent 3b596de06f
commit 7ed3a9e52d
Signed by: serguzim
GPG key ID: 13AD60C237A28DFE
7 changed files with 79 additions and 4 deletions
emgauwa-lib

View file

@ -24,3 +24,4 @@ libsqlite3-sys = { version = "*", features = ["bundled"] }
log = "0.4"
uuid = "1.6"
futures = "0.3"
libc = "0.2"

View file

@ -6,7 +6,6 @@ use actix::{Actor, StreamHandler};
use actix_web::{get, web, HttpRequest, HttpResponse};
use actix_web_actors::ws;
use actix_web_actors::ws::ProtocolError;
use futures::FutureExt;
use serde_derive::{Deserialize, Serialize};
use sqlx::pool::PoolConnection;
use sqlx::{Pool, Sqlite};

View file

@ -1,3 +1,6 @@
use std::ffi::CString;
use std::io::{Error, ErrorKind};
pub fn load_settings<T>(config_name: &str, env_prefix: &str) -> T
where
for<'de> T: serde::Deserialize<'de>,
@ -16,3 +19,46 @@ where
.try_deserialize::<T>()
.expect("Error reading settings")
}
// https://blog.lxsang.me/post/id/28.0
pub fn drop_privileges(user: &str, group: &str) -> Result<(), Error> {
// the group id need to be set first, otherwise,
// when the user privileges drop, it is unable to
// drop the group privileges
// get the gid from username
if let Ok(cstr) = CString::new(group.as_bytes()) {
let p = unsafe { libc::getgrnam(cstr.as_ptr()) };
if p.is_null() {
eprintln!("Unable to getgrnam of group: {}", group);
return Err(Error::last_os_error());
}
if unsafe { libc::setgid((*p).gr_gid) } != 0 {
eprintln!("Unable to setgid of group: {}", group);
return Err(Error::last_os_error());
}
} else {
return Err(Error::new(
ErrorKind::Other,
"Cannot create CString from String (group)!",
));
}
// drop the user privileges
// get the uid from username
if let Ok(cstr) = CString::new(user.as_bytes()) {
let p = unsafe { libc::getpwnam(cstr.as_ptr()) };
if p.is_null() {
eprintln!("Unable to getpwnam of user: {}", user);
return Err(Error::last_os_error());
}
if unsafe { libc::setuid((*p).pw_uid) } != 0 {
eprintln!("Unable to setuid of user: {}", user);
return Err(Error::last_os_error());
}
} else {
return Err(Error::new(
ErrorKind::Other,
"Cannot create CString from String (user)!",
));
}
Ok(())
}