Skip to content

Commit

Permalink
Merge pull request #174 from kunai-project/fix-rlimit-memlock
Browse files Browse the repository at this point in the history
Fix rlimit memlock
  • Loading branch information
qjerome authored Jan 29, 2025
2 parents bb947e7 + 382e0be commit 561a795
Showing 2 changed files with 37 additions and 1 deletion.
12 changes: 12 additions & 0 deletions kunai/src/bin/main.rs
Original file line number Diff line number Diff line change
@@ -36,6 +36,7 @@ use kunai_common::config::Filter;
use kunai_common::{inspect_err, kernel};

use kunai_macros::StrEnum;
use libc::{RLIMIT_MEMLOCK, RLIM_INFINITY};
use log::LevelFilter;
use lru_st::collections::LruHashSet;
use namespace::{Mnt, Namespace};
@@ -3394,6 +3395,17 @@ impl Command {
None => Config::default(),
};

// we set RLIMIT_MEMLOCK programmatically otherwise kunai fails at starting
// as a service on old kernels, even though securityfs has been set properly.
// This is very likely because securityfs isn't mounted when kunai starts
// mounted yet
let mut rlimit =
getrlimit(RLIMIT_MEMLOCK).map_err(|e| anyhow!("failed to get RLIMIT_MEMLOCK: {e}"))?;
rlimit.rlim_cur = RLIM_INFINITY;
rlimit.rlim_max = RLIM_INFINITY;
setrlimit(RLIMIT_MEMLOCK, rlimit)
.map_err(|e| anyhow!("failed to set RLIMIT_MEMLOCK: {e}"))?;

// checks on harden mode
if conf.harden {
if current_kernel < kernel!(5, 7, 0) {
26 changes: 25 additions & 1 deletion kunai/src/util.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use core::mem::{size_of, MaybeUninit};
use ip_network::IpNetwork;
use libc::{clock_gettime, timespec, CLOCK_MONOTONIC};
use libc::{clock_gettime, rlimit, timespec, CLOCK_MONOTONIC};
use md5::{Digest, Md5};
use sha1::Sha1;
use sha2::{Sha256, Sha512};
@@ -98,6 +98,30 @@ pub fn kill(pid: i32, sig: i32) -> Result<(), io::Error> {
Ok(())
}

#[inline(always)]
pub fn getrlimit(resource: u32) -> Result<rlimit, io::Error> {
let mut rlim: rlimit = rlimit {
rlim_cur: 0, // Set the soft limit to 0 initially
rlim_max: 0, // Set the hard limit to 0 initially
};

// Get the current limit
if unsafe { libc::getrlimit(resource, &mut rlim) } != 0 {
return Err(io::Error::last_os_error());
}

Ok(rlim)
}

#[inline(always)]
pub fn setrlimit(resource: u32, rlimit: rlimit) -> Result<(), io::Error> {
// Set the new limit
if unsafe { libc::setrlimit(resource, &rlimit) } != 0 {
return Err(io::Error::last_os_error());
}
Ok(())
}

#[inline]
pub fn md5_data<T: AsRef<[u8]>>(data: T) -> String {
let mut h = Md5::new();

0 comments on commit 561a795

Please sign in to comment.