utils: Add function to drop priveleges

This function is meant to be used before operations
such as accessing network to make sure those operations
are not performed as a privilged user.

Fixes: #5331

Signed-off-by: Archana Shinde <archana.m.shinde@intel.com>
This commit is contained in:
Archana Shinde 2022-10-13 17:35:43 -07:00
parent c745d6648d
commit 699f821e12
3 changed files with 36 additions and 0 deletions

View File

@ -15,6 +15,8 @@ clap = { version = "3.2.20", features = ["derive", "cargo"] }
reqwest = { version = "0.11", default-features = false, features = ["json", "blocking", "rustls-tls"] }
serde_json = "1.0.85"
thiserror = "1.0.35"
privdrop = "0.5.2"
nix = "0.25.0"
[dev-dependencies]
semver = "1.0.12"

View File

@ -7,6 +7,7 @@ mod arch;
mod args;
mod check;
mod ops;
mod utils;
use anyhow::Result;
use clap::Parser;

View File

@ -0,0 +1,33 @@
// Copyright (c) 2022 Intel Corporation
//
// SPDX-License-Identifier: Apache-2.0
//
#![allow(dead_code)]
use anyhow::{anyhow, Result};
const NON_PRIV_USER: &str = "nobody";
pub fn drop_privs() -> Result<()> {
if nix::unistd::Uid::effective().is_root() {
privdrop::PrivDrop::default()
.chroot("/")
.user(NON_PRIV_USER)
.apply()
.map_err(|e| anyhow!("Failed to drop privileges to user {}: {}", NON_PRIV_USER, e))?;
}
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_drop_privs() {
let res = drop_privs();
assert!(res.is_ok());
}
}