Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 7 additions & 2 deletions kenny-agent/src/handlers/agent_update.rs
Original file line number Diff line number Diff line change
Expand Up @@ -814,7 +814,12 @@ mod tests {
if !src.exists() {
return; // No `sleep` on this host; skip rather than fail.
}
let target = std::env::temp_dir().join(format!("kenny-wait-test-{}", std::process::id()));
// The copy keeps the file name `sleep` inside a private directory: where
// `sleep` is an applet of a multi-call binary (uutils, busybox), the binary
// picks the applet by the name it is run as and exits at once under any other.
let dir = std::env::temp_dir().join(format!("kenny-wait-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).expect("create private dir");
let target = dir.join("sleep");
std::fs::copy(src, &target).expect("copy sleep binary");
// Make the copy executable for hosts that don't preserve the mode bit.
#[cfg(unix)]
Expand All @@ -838,7 +843,7 @@ mod tests {

let _ = child.kill();
let _ = child.wait();
let _ = std::fs::remove_file(&target);
let _ = std::fs::remove_dir_all(&dir);

assert!(
!freed,
Expand Down
93 changes: 88 additions & 5 deletions kenny-agent/src/telemetry/collectors/browser_extensions.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,42 @@ pub mod core {
/// Contract cap on the `extensions` list.
pub const MAX_EXTENSIONS: usize = 200;

/// Largest manifest, locale catalogue or Firefox `extensions.json` the
/// collector reads. These files sit in user profiles, so any local user
/// chooses their size; real ones stay far below this.
pub const MAX_FILE_BYTES: u64 = 16 * 1024 * 1024;

/// Cap on the `errors` list — one entry per unreadable file would otherwise
/// let a user profile grow the section without bound.
pub const MAX_ERRORS: usize = 50;

/// Read a profile file as text, refusing one larger than [`MAX_FILE_BYTES`].
///
/// At most one byte past the cap is ever held, whatever the file claims
/// about its size.
pub fn read_text(path: &Path) -> std::io::Result<String> {
use std::io::Read as _;

let mut text = String::new();
std::fs::File::open(path)?
.take(MAX_FILE_BYTES + 1)
.read_to_string(&mut text)?;
if text.len() as u64 > MAX_FILE_BYTES {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"file too large",
));
}
Ok(text)
}

/// Record a per-file problem, up to [`MAX_ERRORS`] of them.
pub fn note_error(errors: &mut Vec<String>, message: String) {
if errors.len() < MAX_ERRORS {
errors.push(message);
}
}

/// One installed extension, already stripped of any per-user attribution.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Extension {
Expand Down Expand Up @@ -199,11 +235,14 @@ pub mod core {
versions.sort();
for vdir in versions.iter().rev() {
let manifest_path = vdir.join("manifest.json");
let Ok(text) = std::fs::read_to_string(&manifest_path) else {
let Ok(text) = read_text(&manifest_path) else {
continue;
};
let Some(manifest) = parse_chromium_manifest(&text) else {
errors.push(format!("{}: invalid manifest", manifest_path.display()));
note_error(
errors,
format!("{}: invalid manifest", manifest_path.display()),
);
continue;
};
let name = resolve_chromium_name(&manifest, vdir, &id);
Expand Down Expand Up @@ -241,7 +280,7 @@ pub mod core {
.join("_locales")
.join(&locale)
.join("messages.json");
if let Ok(text) = std::fs::read_to_string(&path) {
if let Ok(text) = read_text(&path) {
if let Some(name) = resolve_msg(&text, key) {
return name;
}
Expand Down Expand Up @@ -373,6 +412,50 @@ pub mod core {
assert!(parse_firefox_extensions("garbage").is_empty());
}

/// A profile file is as large as its owner makes it; the scan must not
/// hold more than the cap, and must not report one error per planted file.
#[test]
fn scan_skips_an_oversized_manifest_and_caps_the_error_list() {
let dir = std::env::temp_dir().join(format!(
"kenny-brext-{}-{}",
std::process::id(),
line!()
));
let ext_root = dir.join("Extensions");
// A sparse 1 GiB manifest: skipped like an unreadable one.
let huge = ext_root.join("aaaahugeid").join("1.0_0");
std::fs::create_dir_all(&huge).unwrap();
let manifest = huge.join("manifest.json");
std::fs::File::create(&manifest)
.unwrap()
.set_len(1 << 30)
.unwrap();
assert_eq!(
read_text(&manifest).unwrap_err().kind(),
std::io::ErrorKind::InvalidData
);
for i in 0..MAX_ERRORS + 20 {
let broken = ext_root.join(format!("broken{i:04}")).join("1.0_0");
std::fs::create_dir_all(&broken).unwrap();
std::fs::write(broken.join("manifest.json"), "not json").unwrap();
}
let good = ext_root.join("zzzzgoodid").join("1.0_0");
std::fs::create_dir_all(&good).unwrap();
std::fs::write(
good.join("manifest.json"),
r#"{ "name": "Good", "version": "1.0" }"#,
)
.unwrap();

let mut errors = Vec::new();
let exts = scan_chromium_extensions(&ext_root, "chrome", &mut errors);
std::fs::remove_dir_all(&dir).ok();

assert_eq!(exts.len(), 1);
assert_eq!(exts[0].name, "Good");
assert_eq!(errors.len(), MAX_ERRORS);
}

/// Fabricate a Chromium `Extensions` tree and scan it — exercises version
/// selection, `__MSG_*__` resolution, and error recording on Linux CI.
#[test]
Expand Down Expand Up @@ -512,12 +595,12 @@ mod windows_impl {
if !file.is_file() {
continue;
}
match std::fs::read_to_string(&file) {
match core::read_text(&file) {
Ok(text) => {
profiles_read += 1;
extensions.extend(core::parse_firefox_extensions(&text));
}
Err(e) => errors.push(format!("{}: {e}", file.display())),
Err(e) => core::note_error(&mut errors, format!("{}: {e}", file.display())),
}
}
}
Expand Down
93 changes: 73 additions & 20 deletions kenny-agent/src/telemetry/collectors/local_accounts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1088,17 +1088,31 @@ pub mod linux_impl {
Path::new("/run/systemd/seats").exists() || Path::new("/run/systemd/sessions").exists()
}

/// The last-login timestamp for `uid`, from the fixed-record `/var/log/lastlog`.
/// Size of one `/var/log/lastlog` record: `int32 time`, `char line[32]`,
/// `char host[256]`. Records are indexed by uid.
const LASTLOG_RECORD: u64 = 292;

/// The login-time field of `uid`'s record in an open `/var/log/lastlog`.
///
/// Reads the four bytes it needs and nothing else. The file is sparse and as
/// long as the highest uid that ever logged in — over a gigabyte on a host
/// with directory-backed uids in the millions — so it is never read whole.
/// `None` when the record lies past the end of the file.
fn lastlog_secs(lastlog: &impl std::os::unix::fs::FileExt, uid: u32) -> Option<u32> {
let mut secs = [0u8; 4];
lastlog
.read_exact_at(&mut secs, u64::from(uid) * LASTLOG_RECORD)
.ok()?;
Some(u32::from_ne_bytes(secs))
}

/// The last-login timestamp from a `lastlog` login-time field.
///
/// Records are 292 bytes indexed by uid: `int32 time`, `char line[32]`,
/// `char host[256]`. Best-effort — distros migrating to `lastlog2` have no such
/// file, and a never-logged-in account has a zero record. Reporting `null` in
/// both cases matches what Windows does for an account that never signed in.
fn last_logon(lastlog: &[u8], uid: u32) -> Option<String> {
const RECORD: usize = 292;
let start = (uid as usize).checked_mul(RECORD)?;
let secs = lastlog.get(start..start + 4)?;
let secs = i64::from(u32::from_ne_bytes([secs[0], secs[1], secs[2], secs[3]]));
/// Best-effort — distros migrating to `lastlog2` have no such file, and a
/// never-logged-in account has a zero record. Reporting `null` in both cases
/// matches what Windows does for an account that never signed in.
fn last_logon(secs: Option<u32>) -> Option<String> {
let secs = i64::from(secs?);
if secs == 0 {
return None;
}
Expand All @@ -1118,7 +1132,8 @@ pub mod linux_impl {
pub sudoers_users: &'a [String],
pub sudoers_groups: &'a [String],
pub ssh_denied: &'a [String],
pub lastlog: &'a [u8],
/// The `lastlog` login-time field for a uid, `None` when there is no record.
pub lastlog: &'a dyn Fn(u32) -> Option<u32>,
pub today_days: i64,
}

Expand Down Expand Up @@ -1205,7 +1220,7 @@ pub mod linux_impl {
// blank-password crit on every unprivileged dev build.
password_required: facts.map(|f| f.password_required).unwrap_or(true),
password_last_set: facts.and_then(|f| f.password_last_set.clone()),
last_logon: last_logon(src.lastlog, uid),
last_logon: last_logon((src.lastlog)(uid)),
// root is the built-in, undeletable administrator — the same fact
// `builtin_admin` records for Windows RID 500, so the portable
// guard protects it with no Linux-specific rule.
Expand Down Expand Up @@ -1367,7 +1382,8 @@ pub mod linux_impl {
};
let group = std::fs::read_to_string("/etc/group").unwrap_or_default();
let shadow = std::fs::read_to_string("/etc/shadow").ok();
let lastlog = std::fs::read("/var/log/lastlog").unwrap_or_default();
let lastlog = std::fs::File::open("/var/log/lastlog").ok();
let lastlog = |uid: u32| lastlog.as_ref().and_then(|file| lastlog_secs(file, uid));
let ssh_denied = std::fs::read_to_string(SSHD_DROPIN)
.map(|text| parse_deny_users(&text))
.unwrap_or_default();
Expand Down Expand Up @@ -1441,7 +1457,7 @@ devs:x:1100:deploy
sudoers_users: &[],
sudoers_groups: &[],
ssh_denied: denied,
lastlog: &[],
lastlog: &|_| None,
today_days: 20_500,
}
}
Expand Down Expand Up @@ -1601,16 +1617,53 @@ kid:$6$a$b:20000:0:99999:7::1:
assert!(!sshd_includes_dropin_dir("Port 22\n"));
}

/// An empty scratch file, already unlinked so nothing is left behind.
fn scratch_lastlog(tag: &str) -> std::fs::File {
let path =
std::env::temp_dir().join(format!("kenny-lastlog-{tag}-{}", std::process::id()));
let file = std::fs::OpenOptions::new()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(&path)
.unwrap();
std::fs::remove_file(&path).unwrap();
file
}

#[test]
fn lastlog_reads_a_record_and_tolerates_a_missing_file() {
let mut buf = vec![0u8; 292 * 2];
buf[292..296].copy_from_slice(&1_700_000_000u32.to_ne_bytes());
assert_eq!(last_logon(&buf, 1).as_deref(), Some("2023-11-14T22:13:20Z"));
use std::os::unix::fs::FileExt as _;

let file = scratch_lastlog("record");
file.set_len(292 * 2).unwrap();
file.write_all_at(&1_700_000_000u32.to_ne_bytes(), 292)
.unwrap();
assert_eq!(
last_logon(lastlog_secs(&file, 1)).as_deref(),
Some("2023-11-14T22:13:20Z")
);
// uid 0 has a zero record: never logged in, not "logged in at epoch".
assert_eq!(last_logon(&buf, 0), None);
assert_eq!(last_logon(lastlog_secs(&file, 0)), None);
// Past the end of the file, or no file at all.
assert_eq!(last_logon(&buf, 9999), None);
assert_eq!(last_logon(&[], 0), None);
assert_eq!(lastlog_secs(&file, 9999), None);
assert_eq!(last_logon(None), None);
}

#[test]
fn lastlog_lookup_reads_one_record_of_a_file_sized_by_the_highest_uid() {
use std::os::unix::fs::FileExt as _;

// One login by uid 5,000,000 makes the sparse file 1.4 GiB long.
let uid = 5_000_000u32;
let file = scratch_lastlog("sparse");
file.set_len((u64::from(uid) + 1) * 292).unwrap();
file.write_all_at(&1_700_000_000u32.to_ne_bytes(), u64::from(uid) * 292)
.unwrap();
assert_eq!(lastlog_secs(&file, uid), Some(1_700_000_000));
assert_eq!(lastlog_secs(&file, uid - 1), Some(0));
assert_eq!(lastlog_secs(&file, u32::MAX), None);
}
}
}
Expand Down
Loading