use std::fs;
use std::io::{self, Read};
use std::os::unix::fs::{FileTypeExt, MetadataExt, OpenOptionsExt, PermissionsExt};
use std::path::{Component, Path, PathBuf};
use tar::EntryType;
#[derive(Clone, Copy, Debug)]
pub struct Limits {
pub max_bytes: u64,
pub max_entries: u64,
}
impl Default for Limits {
fn default() -> Self {
Self {
max_bytes: 4 << 30,
max_entries: 500_000,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Whiteout {
File,
Opaque,
}
fn bad(msg: impl Into<String>) -> io::Error {
io::Error::new(io::ErrorKind::InvalidData, msg.into())
}
pub fn clean(p: &Path) -> io::Result<PathBuf> {
let mut out = PathBuf::new();
for c in p.components() {
match c {
Component::Normal(n) => out.push(n),
Component::CurDir | Component::RootDir => {}
_ => return Err(bad(format!("layer path escapes root: {}", p.display()))),
}
}
if out.as_os_str().len() > 4096 {
return Err(bad("layer path too long"));
}
Ok(out)
}
fn no_symlink_parents(root: &Path, rel: &Path) -> io::Result<()> {
let mut cur = root.to_path_buf();
let comps: Vec<_> = rel.components().collect();
for c in comps.iter().take(comps.len().saturating_sub(1)) {
cur.push(c);
match fs::symlink_metadata(&cur) {
Ok(m) if m.file_type().is_symlink() => {
return Err(bad(format!(
"layer writes through symlink {}",
rel.display()
)));
}
Ok(m) if !m.is_dir() => {
return Err(bad(format!(
"layer parent is not a directory: {}",
rel.display()
)));
}
Ok(_) => {}
Err(e) if e.kind() == io::ErrorKind::NotFound => {
fs::create_dir(&cur)?;
fs::set_permissions(&cur, fs::Permissions::from_mode(0o755))?;
}
Err(e) => return Err(e),
}
}
Ok(())
}
fn remove_existing(p: &Path, keep_dir: bool) -> io::Result<()> {
match fs::symlink_metadata(p) {
Ok(m) if m.is_dir() && keep_dir => Ok(()),
Ok(m) if m.is_dir() => fs::remove_dir_all(p),
Ok(_) => fs::remove_file(p),
Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
Err(e) => Err(e),
}
}
fn lower_entry(lowers: &[PathBuf], rel: &Path) -> io::Result<(PathBuf, fs::Metadata)> {
let missing = || bad(format!("hardlink target missing: {}", rel.display()));
let comps: Vec<_> = rel.components().collect();
'layers: for root in lowers {
let mut cur = root.clone();
for (i, c) in comps.iter().enumerate() {
cur.push(c);
let m = match fs::symlink_metadata(&cur) {
Ok(m) => m,
Err(e) if e.kind() == io::ErrorKind::NotFound => continue 'layers,
Err(e) => return Err(e),
};
if m.file_type().is_char_device() {
return Err(missing());
}
if i + 1 == comps.len() {
if m.is_dir() {
return Err(bad("hardlink to directory"));
}
return Ok((cur, m));
}
if m.file_type().is_symlink() {
return Err(bad(format!("hardlink through symlink {}", rel.display())));
}
if !m.is_dir() {
return Err(missing());
}
}
}
Err(missing())
}
fn copy_lower(src: &Path, m: &fs::Metadata, target: &Path, chown: bool) -> io::Result<u64> {
remove_existing(target, false)?;
if m.file_type().is_symlink() {
std::os::unix::fs::symlink(fs::read_link(src)?, target)?;
if chown {
std::os::unix::fs::lchown(target, Some(m.uid()), Some(m.gid()))?;
}
return Ok(0);
}
let mut from = fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(src)?;
if !from.metadata()?.is_file() {
return Err(bad("hardlink target is not a regular file"));
}
let mut f = fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(target)?;
let n = io::copy(&mut from, &mut f)?;
if chown {
std::os::unix::fs::fchown(&f, Some(m.uid()), Some(m.gid()))?;
}
f.set_permissions(fs::Permissions::from_mode(m.mode() & 0o7777))?;
Ok(n)
}
pub fn unpack<R: Read>(
r: R,
dst: &Path,
lim: Limits,
whiteout: &dyn Fn(&Path, Whiteout) -> io::Result<()>,
) -> io::Result<()> {
let mut lim = lim;
unpack_in(r, dst, &mut lim, &[], whiteout)
}
pub fn unpack_in<R: Read>(
r: R,
dst: &Path,
budget: &mut Limits,
lowers: &[PathBuf],
whiteout: &dyn Fn(&Path, Whiteout) -> io::Result<()>,
) -> io::Result<()> {
let lim = *budget;
fs::create_dir_all(dst)?;
let chown = super::sys::is_root();
let mut ar = tar::Archive::new(r);
let mut total = 0u64;
let mut count = 0u64;
for entry in ar.entries()? {
let mut e = entry?;
count += 1;
if count > lim.max_entries {
return Err(bad("layer has too many entries"));
}
let rel = clean(&e.path()?)?;
if rel.as_os_str().is_empty() {
continue;
}
let name = rel
.file_name()
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_default();
no_symlink_parents(dst, &rel)?;
let target = dst.join(&rel);
if let Some(hidden) = name.strip_prefix(".wh.") {
if name == ".wh..wh..opq" {
let dir = target.parent().unwrap_or(dst);
whiteout(dir, Whiteout::Opaque)?;
} else {
if hidden.is_empty() || hidden == "." || hidden == ".." || hidden.contains('/') {
return Err(bad(format!("bad whiteout {}", rel.display())));
}
let victim = target.with_file_name(hidden);
remove_existing(&victim, false)?;
whiteout(&victim, Whiteout::File)?;
}
continue;
}
let h = e.header();
let mode = h.mode().unwrap_or(0o644) & 0o7777;
let (uid, gid) = (h.uid().unwrap_or(0) as u32, h.gid().unwrap_or(0) as u32);
let kind = h.entry_type();
match kind {
EntryType::Directory => {
remove_existing(&target, true)?;
if !target.exists() {
fs::create_dir(&target)?;
}
fs::set_permissions(&target, fs::Permissions::from_mode(mode))?;
}
EntryType::Regular | EntryType::Continuous => {
let size = e.size();
total = total.saturating_add(size);
if total > lim.max_bytes {
return Err(bad("layer exceeds unpacked size limit"));
}
remove_existing(&target, false)?;
let mut f = fs::OpenOptions::new()
.write(true)
.create_new(true)
.mode(0o600)
.custom_flags(libc::O_NOFOLLOW)
.open(&target)?;
let copied = io::copy(&mut (&mut e).take(size), &mut f)?;
if copied != size {
return Err(bad("layer entry truncated"));
}
f.set_permissions(fs::Permissions::from_mode(mode))?;
}
EntryType::Symlink => {
let link = e
.link_name()?
.ok_or_else(|| bad("symlink without target"))?
.into_owned();
if link.as_os_str().is_empty() || link.as_os_str().len() > 4096 {
return Err(bad("bad symlink target"));
}
remove_existing(&target, false)?;
std::os::unix::fs::symlink(&link, &target)?;
}
EntryType::Link => {
let link = e
.link_name()?
.ok_or_else(|| bad("hardlink without target"))?;
let src_rel = clean(&link)?;
no_symlink_parents(dst, &src_rel)?;
let src = dst.join(&src_rel);
let m = match fs::symlink_metadata(&src) {
Ok(m) => m,
Err(e) if e.kind() == io::ErrorKind::NotFound => {
let (lsrc, lm) = lower_entry(lowers, &src_rel)?;
total = total.saturating_add(lm.len());
if total > lim.max_bytes {
return Err(bad("layer exceeds unpacked size limit"));
}
copy_lower(&lsrc, &lm, &target, chown)?;
continue;
}
Err(e) => return Err(e),
};
if m.is_dir() {
return Err(bad("hardlink to directory"));
}
remove_existing(&target, false)?;
fs::hard_link(&src, &target)?;
continue;
}
_ => continue,
}
if chown {
std::os::unix::fs::lchown(&target, Some(uid), Some(gid))?;
if kind != EntryType::Symlink && mode & 0o7000 != 0 {
fs::set_permissions(&target, fs::Permissions::from_mode(mode))?;
}
}
}
budget.max_bytes = lim.max_bytes - total;
budget.max_entries = lim.max_entries - count;
Ok(())
}
pub fn read_in_root(root: &Path, rel: &str, max: u64) -> io::Result<Vec<u8>> {
let mut stack: Vec<String> = Vec::new();
let mut todo: Vec<String> = rel.split('/').rev().map(str::to_string).collect();
let mut hops = 0;
while let Some(c) = todo.pop() {
match c.as_str() {
"" | "." => continue,
".." => {
stack.pop();
continue;
}
_ => {}
}
stack.push(c);
let cur: PathBuf = stack.iter().fold(root.to_path_buf(), |p, s| p.join(s));
let m = fs::symlink_metadata(&cur)?;
if m.file_type().is_symlink() {
hops += 1;
if hops > 40 {
return Err(bad("too many symlinks"));
}
let t = fs::read_link(&cur)?;
stack.pop();
let t = t.to_string_lossy().into_owned();
if t.starts_with('/') {
stack.clear();
}
todo.extend(t.split('/').rev().map(str::to_string));
}
}
let p: PathBuf = stack.iter().fold(root.to_path_buf(), |p, s| p.join(s));
let f = fs::OpenOptions::new()
.read(true)
.custom_flags(libc::O_NOFOLLOW)
.open(&p)?;
if !f.metadata()?.is_file() {
return Err(bad("not a regular file"));
}
let mut out = Vec::new();
f.take(max).read_to_end(&mut out)?;
Ok(out)
}
#[cfg(test)]
mod tests {
use super::*;
use std::cell::RefCell;
fn tmp(tag: &str) -> PathBuf {
let d = std::env::temp_dir().join(format!("krab-layer-{tag}-{}", std::process::id()));
let _ = fs::remove_dir_all(&d);
d
}
fn header(path: &str, kind: EntryType, size: u64) -> tar::Header {
let mut h = tar::Header::new_gnu();
h.as_gnu_mut().unwrap().name[..path.len()].copy_from_slice(path.as_bytes());
h.set_entry_type(kind);
h.set_size(size);
h.set_mode(0o644);
h.set_cksum();
h
}
fn file(b: &mut tar::Builder<Vec<u8>>, path: &str, data: &[u8]) {
let h = header(path, EntryType::Regular, data.len() as u64);
b.append(&h, data).unwrap();
}
fn link(b: &mut tar::Builder<Vec<u8>>, path: &str, kind: EntryType, target: &str) {
let mut h = header(path, kind, 0);
h.as_gnu_mut().unwrap().linkname[..target.len()].copy_from_slice(target.as_bytes());
h.set_cksum();
b.append(&h, &[][..]).unwrap();
}
fn none(_: &Path, _: Whiteout) -> io::Result<()> {
Ok(())
}
#[test]
fn unpacks_regular_tree() {
let d = tmp("ok");
let mut b = tar::Builder::new(Vec::new());
let mut dh = header("etc/", EntryType::Directory, 0);
dh.set_mode(0o755);
dh.set_cksum();
b.append(&dh, &[][..]).unwrap();
file(&mut b, "etc/passwd", b"root:x:0:0::/root:/bin/sh\n");
file(&mut b, "./usr/bin/tool", b"bin");
link(&mut b, "bin/sh", EntryType::Symlink, "/usr/bin/tool");
link(&mut b, "usr/bin/tool2", EntryType::Link, "usr/bin/tool");
let data = b.into_inner().unwrap();
unpack(&data[..], &d, Limits::default(), &none).unwrap();
assert_eq!(fs::read(d.join("usr/bin/tool2")).unwrap(), b"bin");
assert_eq!(
fs::read_link(d.join("bin/sh")).unwrap(),
Path::new("/usr/bin/tool")
);
let got = read_in_root(&d, "bin/sh", 100).unwrap();
assert_eq!(got, b"bin");
fs::remove_dir_all(&d).unwrap();
}
#[test]
fn rejects_traversal() {
let d = tmp("trav");
for evil in ["../evil", "a/../../evil"] {
let mut b = tar::Builder::new(Vec::new());
let mut h = tar::Header::new_gnu();
h.as_gnu_mut().unwrap().name[..evil.len()].copy_from_slice(evil.as_bytes());
h.set_entry_type(EntryType::Regular);
h.set_size(1);
h.set_cksum();
b.append(&h, &b"x"[..]).unwrap();
let data = b.into_inner().unwrap();
assert!(
unpack(&data[..], &d, Limits::default(), &none).is_err(),
"{evil}"
);
}
assert!(!d.parent().unwrap().join("evil").exists());
let mut b = tar::Builder::new(Vec::new());
link(&mut b, "hl", EntryType::Link, "../../etc/passwd");
let data = b.into_inner().unwrap();
assert!(unpack(&data[..], &d, Limits::default(), &none).is_err());
let _ = fs::remove_dir_all(&d);
}
#[test]
fn rejects_write_through_symlink() {
let d = tmp("sym");
let outside = tmp("sym-out");
fs::create_dir_all(&outside).unwrap();
let mut b = tar::Builder::new(Vec::new());
link(&mut b, "esc", EntryType::Symlink, outside.to_str().unwrap());
file(&mut b, "esc/pwned", b"x");
let data = b.into_inner().unwrap();
assert!(unpack(&data[..], &d, Limits::default(), &none).is_err());
assert!(!outside.join("pwned").exists());
let mut b = tar::Builder::new(Vec::new());
link(
&mut b,
"f",
EntryType::Symlink,
outside.join("victim").to_str().unwrap(),
);
file(&mut b, "f", b"over");
let data = b.into_inner().unwrap();
let d2 = tmp("sym2");
unpack(&data[..], &d2, Limits::default(), &none).unwrap();
assert!(!outside.join("victim").exists());
assert_eq!(fs::read(d2.join("f")).unwrap(), b"over");
fs::write(outside.join("secret"), b"host").unwrap();
std::os::unix::fs::symlink(outside.join("secret"), d2.join("abs")).unwrap();
assert!(read_in_root(&d2, "abs", 100).is_err());
std::os::unix::fs::symlink("../../../../../../f", d2.join("rel")).unwrap();
assert_eq!(read_in_root(&d2, "rel", 100).unwrap(), b"over");
for p in [&d, &d2, &outside] {
let _ = fs::remove_dir_all(p);
}
}
#[test]
fn whiteouts_are_reported_not_written() {
let d = tmp("wh");
fs::create_dir_all(d.join("etc")).unwrap();
fs::write(d.join("etc/old"), b"x").unwrap();
let seen = RefCell::new(Vec::new());
let rec = |p: &Path, w: Whiteout| {
seen.borrow_mut()
.push((p.strip_prefix(&d).unwrap().to_path_buf(), w));
Ok(())
};
let mut b = tar::Builder::new(Vec::new());
file(&mut b, "etc/.wh.old", b"");
file(&mut b, "var/.wh..wh..opq", b"");
let data = b.into_inner().unwrap();
unpack(&data[..], &d, Limits::default(), &rec).unwrap();
assert!(!d.join("etc/old").exists());
assert!(!d.join("etc/.wh.old").exists());
assert_eq!(
*seen.borrow(),
vec![
(PathBuf::from("etc/old"), Whiteout::File),
(PathBuf::from("var"), Whiteout::Opaque)
]
);
let mut b = tar::Builder::new(Vec::new());
file(&mut b, "a/.wh...", b"");
let data = b.into_inner().unwrap();
assert!(unpack(&data[..], &d, Limits::default(), &rec).is_err());
fs::remove_dir_all(&d).unwrap();
}
#[test]
fn enforces_limits() {
let d = tmp("lim");
let mut b = tar::Builder::new(Vec::new());
file(&mut b, "big", &[0u8; 2048]);
file(&mut b, "big2", &[0u8; 2048]);
let data = b.into_inner().unwrap();
let lim = Limits {
max_bytes: 3000,
max_entries: 10,
};
assert!(unpack(&data[..], &d, lim, &none).is_err());
let lim = Limits {
max_bytes: 1 << 20,
max_entries: 1,
};
let _ = fs::remove_dir_all(&d);
assert!(unpack(&data[..], &d, lim, &none).is_err());
let _ = fs::remove_dir_all(&d);
}
#[test]
fn budget_is_shared_across_layers() {
let d = tmp("budget");
let mut b = tar::Builder::new(Vec::new());
let mut dh = header("dir/", EntryType::Directory, 0);
dh.set_mode(0o755);
dh.set_cksum();
b.append(&dh, &[][..]).unwrap();
file(&mut b, "dir/f", &[0u8; 1000]);
link(&mut b, "s", EntryType::Symlink, "dir/f");
let data = b.into_inner().unwrap();
let mut budget = Limits {
max_bytes: 1500,
max_entries: 100,
};
unpack_in(&data[..], &d.join("l1"), &mut budget, &[], &none).unwrap();
assert_eq!((budget.max_bytes, budget.max_entries), (500, 97));
assert!(unpack_in(&data[..], &d.join("l2"), &mut budget, &[], &none).is_err());
let mut budget = Limits {
max_bytes: 1 << 20,
max_entries: 5,
};
unpack_in(&data[..], &d.join("l3"), &mut budget, &[], &none).unwrap();
assert!(unpack_in(&data[..], &d.join("l4"), &mut budget, &[], &none).is_err());
let _ = fs::remove_dir_all(&d);
}
#[test]
fn hardlink_to_lower_layer() {
let d = tmp("hl-lower");
let outside = tmp("hl-out");
fs::create_dir_all(&outside).unwrap();
fs::write(outside.join("secret"), b"host").unwrap();
let lower = d.join("lower");
let mut b = tar::Builder::new(Vec::new());
file(&mut b, "usr/bin/tool", b"bin");
link(&mut b, "esc", EntryType::Symlink, outside.to_str().unwrap());
let data = b.into_inner().unwrap();
unpack(&data[..], &lower, Limits::default(), &none).unwrap();
let mut b = tar::Builder::new(Vec::new());
link(&mut b, "usr/bin/tool2", EntryType::Link, "usr/bin/tool");
let data = b.into_inner().unwrap();
let upper = d.join("upper");
let mut budget = Limits::default();
unpack_in(
&data[..],
&upper,
&mut budget,
std::slice::from_ref(&lower),
&none,
)
.unwrap();
assert_eq!(fs::read(upper.join("usr/bin/tool2")).unwrap(), b"bin");
assert_ne!(
fs::metadata(upper.join("usr/bin/tool2")).unwrap().ino(),
fs::metadata(lower.join("usr/bin/tool")).unwrap().ino()
);
assert_eq!(budget.max_bytes, Limits::default().max_bytes - 3);
for evil in [
"esc/secret",
"../lower/usr/bin/tool",
"usr/bin/missing",
"usr/bin",
] {
let mut b = tar::Builder::new(Vec::new());
link(&mut b, "x", EntryType::Link, evil);
let data = b.into_inner().unwrap();
let up = d.join("evil");
let _ = fs::remove_dir_all(&up);
assert!(
unpack_in(
&data[..],
&up,
&mut Limits::default(),
std::slice::from_ref(&lower),
&none
)
.is_err(),
"{evil}"
);
assert!(!up.join("x").exists(), "{evil}");
}
for p in [&d, &outside] {
let _ = fs::remove_dir_all(p);
}
}
}