Skip to content
Merged
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
169 changes: 153 additions & 16 deletions vm/devices/support/fs/lxutil/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -500,10 +500,10 @@ impl LxVolume {
/// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but
/// `list_xattr` will report them as lower case for greater compatibility with Linux.
///
/// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length
/// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty"
/// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these
/// prefixes.
/// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long
/// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed
/// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow.
/// `get_xattr` and `list_xattr` will strip these prefixes.
///
/// Security for accessing the various attribute namespaces is not enforced.
///
Expand Down Expand Up @@ -531,10 +531,10 @@ impl LxVolume {
/// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but
/// `list_xattr` will report them as lower case for greater compatibility with Linux.
///
/// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length
/// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty"
/// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these
/// prefixes.
/// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long
/// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed
/// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow.
/// `get_xattr` and `list_xattr` will strip these prefixes.
///
/// Security for accessing the various attribute namespaces is not enforced.
pub fn get_xattr(
Expand All @@ -557,10 +557,10 @@ impl LxVolume {
/// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but
/// `list_xattr` will report them as lower case for greater compatibility with Linux.
///
/// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length
/// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty"
/// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these
/// prefixes.
/// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long
/// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed
/// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow.
/// `get_xattr` and `list_xattr` will strip these prefixes.
///
/// Security for accessing the various attribute namespaces is not enforced.
pub fn list_xattr(&self, path: impl AsRef<Path>, list: Option<&mut [u8]>) -> lx::Result<usize> {
Expand All @@ -574,10 +574,10 @@ impl LxVolume {
/// Extended attribute names are not case sensitive. They are stored as upper case in NTFS but
/// `list_xattr` will report them as lower case for greater compatibility with Linux.
///
/// Extended attribute names are prefixed with "LX.", and have a slightly shorter maximum length
/// limit than Linux. Attribute values are prefixed with a 4-byte header to allow for "empty"
/// values, which NTFS does not normally allow. `get_xattr` and `list_xattr` will strip these
/// prefixes.
/// Extended attribute names are prefixed with "LX.", so they can be at most 251 bytes long
/// rather than 255 as on Linux; longer names fail with `ERANGE`. Attribute values are prefixed
/// with a 4-byte header to allow for "empty" values, which NTFS does not normally allow.
/// `get_xattr` and `list_xattr` will strip these prefixes.
///
/// Security for accessing the various attribute namespaces is not enforced.
pub fn remove_xattr(
Expand Down Expand Up @@ -1835,6 +1835,39 @@ mod tests {
);
}

/// Like Linux's `symlink(2)`, creating a symbolic link to an empty target
/// fails with `ENOENT` and creates nothing. On Windows, the empty target,
/// which names the link's own directory, would otherwise get an NT link
/// from a volume that does not confine paths, and a WSL-style link from
/// one that does.
#[test]
fn symlink_rejects_an_empty_target() {
for confine_paths in [false, true] {
let env = TestEnv::with_options(LxVolumeOptions::new().confine_paths(confine_paths));
env.create_file("testdir/testfile", "test");
let link = Path::from_lx("testdir/link").unwrap();
assert_eq!(
env.volume
.symlink(&link, "", LxCreateOptions::new(0, 0, 0))
.unwrap_err(),
lx::Error::ENOENT,
"confine_paths={confine_paths}"
);
assert_eq!(
env.volume
.symlink_stat(&link, "", LxCreateOptions::new(0, 0, 0))
.unwrap_err(),
lx::Error::ENOENT,
"confine_paths={confine_paths}"
);
assert_eq!(
env.volume.lstat(&link).unwrap_err(),
lx::Error::ENOENT,
"confine_paths={confine_paths}"
);
}
}

#[test]
fn symlink_ancestors_are_not_walked() {
fn expect_traversal_error<T>(result: lx::Result<T>) {
Expand Down Expand Up @@ -2365,6 +2398,25 @@ mod tests {
assert_eq!(stat2.link_count, 3);
}

#[test]
fn link_to_a_one_character_name() {
let env = TestEnv::new();
env.create_file("testfile", "test");
let stat = env.volume.lstat("testfile").unwrap();

// On Windows, a name of one UTF-16 unit makes the shortest
// FILE_LINK_INFORMATION buffer.
env.volume.link("testfile", "a").unwrap();
let stat2 = env.volume.lstat("a").unwrap();
assert_eq!(stat2.inode_nr, stat.inode_nr);
assert_eq!(stat2.link_count, 2);

let stat2 = env.volume.link_stat("testfile", "b").unwrap();
assert_eq!(stat2.inode_nr, stat.inode_nr);
assert_eq!(stat2.link_count, 3);
assert_eq!(fs::read(env.root_dir.path().join("b")).unwrap(), b"test");
}

#[test]
fn stat_fs() {
let env = TestEnv::new();
Expand Down Expand Up @@ -2550,6 +2602,91 @@ mod tests {
assert_eq!(&buffer[..3], b"baz");
}

#[test]
fn xattr_name_length() {
// Linux allows names of up to 255 bytes. On Windows, an attribute is an NTFS extended
// attribute named "LX." and the attribute's name, and NTFS allows EA names of up to 254
// bytes.
const NAME_MAX: usize = if cfg!(windows) { 251 } else { 255 };

fn name(len: usize) -> Vec<u8> {
let mut name = b"user.a".to_vec();
name.resize(len, b'x');
name
}

let env = TestEnv::new();
env.create_file("testfile", "test");
env.volume
.set_xattr("testfile", "user.a", b"secret", 0)
.unwrap();

// An attribute with the longest name can be set, read, and removed.
let longest = name(NAME_MAX);
let longest = lx::LxStr::from_bytes(&longest);
env.volume
.set_xattr("testfile", longest, b"long", 0)
.unwrap();

let mut value = [0u8; 16];
let size = env
.volume
.get_xattr("testfile", longest, Some(&mut value))
.unwrap();

assert_eq!(&value[..size], b"long");
env.volume.remove_xattr("testfile", longest).unwrap();
let err = env.volume.get_xattr("testfile", longest, None).unwrap_err();

assert_eq!(err.value(), lx::ENODATA);

// A longer name fails with ERANGE, rather than reaching an attribute whose name it starts
// with.
for len in NAME_MAX + 1..=262 {
let long = name(len);
let long = lx::LxStr::from_bytes(&long);
let results = [
(
"get",
env.volume
.get_xattr("testfile", long, Some(&mut value))
.map(drop),
),
(
"get size",
env.volume.get_xattr("testfile", long, None).map(drop),
),
("set", env.volume.set_xattr("testfile", long, b"long", 0)),
(
"create",
env.volume
.set_xattr("testfile", long, b"long", lx::XATTR_CREATE),
),
(
"replace",
env.volume
.set_xattr("testfile", long, b"long", lx::XATTR_REPLACE),
),
("remove", env.volume.remove_xattr("testfile", long)),
];

for (operation, result) in results {
assert_eq!(
result.map_err(|err| err.value()),
Err(lx::ERANGE),
"{operation} of a {len}-byte name"
);
}
}

let size = env
.volume
.get_xattr("testfile", "user.a", Some(&mut value))
.unwrap();

assert_eq!(&value[..size], b"secret");
}

// This test is disabled in CI on Windows only, because it requires NTFS support for setting
// the case sensitive directory attribute, which is only enabled if the WSL optional component
// is installed.
Expand Down
19 changes: 19 additions & 0 deletions vm/devices/support/fs/lxutil/src/windows/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -848,6 +848,13 @@ impl LxVolume {
mut options: super::LxCreateOptions,
) -> lx::Result<OwnedHandle> {
assert!(path.is_relative() && !path.as_os_str().is_empty());

// Linux has no symbolic link with an empty target: symlink(2) fails one with ENOENT,
// before it looks at the link's path, so do the same before creating anything.
if target.is_empty() {
return Err(lx::Error::ENOENT);
}

self.check_sandbox_enforcement(path)?;

// Handle filesystems that do not support reparse points.
Expand Down Expand Up @@ -2026,6 +2033,18 @@ mod tests {
assert_eq!(volume.read_link(path).unwrap(), target);
}

/// An NT link's reparse buffer starts with a whole `REPARSE_DATA_BUFFER`,
/// which extends past the start of the link's names, so the buffer of an
/// empty target could not hold it, and is refused with `ENOENT`, as Linux
/// refuses the target.
#[test]
fn nt_link_reparse_buffer_refuses_an_empty_target() {
assert_eq!(
util::create_nt_link_reparse_buffer(ffi::OsStr::new(""), 0).unwrap_err(),
lx::Error::ENOENT
);
}

#[test]
fn no_follow_stat_fallbacks() {
for (query_by_name, stat_info) in [(true, true), (false, true), (false, false)] {
Expand Down
18 changes: 17 additions & 1 deletion vm/devices/support/fs/lxutil/src/windows/util.rs
Original file line number Diff line number Diff line change
Expand Up @@ -604,6 +604,12 @@ pub fn file_info_to_stat(

// Create the reparse buffer for an NT symlink.
pub fn create_nt_link_reparse_buffer(target: &ffi::OsStr, flags: u32) -> lx::Result<Vec<u8>> {
// The whole REPARSE_DATA_BUFFER written below extends past the start of the names, so the
// buffer can hold it only if the target is not empty. Linux fails an empty target with ENOENT.
if target.is_empty() {
return Err(lx::Error::ENOENT);
}

let mut link_target: windows::UnicodeString =
target.try_into().map_err(|_| lx::Error::EINVAL)?;

Expand All @@ -619,7 +625,8 @@ pub fn create_nt_link_reparse_buffer(target: &ffi::OsStr, flags: u32) -> lx::Res

let mut reparse = vec![0; local_size];

// SAFETY: The buffer is large enough to hold the reparse data.
// SAFETY: The buffer is large enough to hold the reparse data, since the
// target is not empty: its two copies reach past the end of the struct.
// This is necessary because unfortunately the Windows types don't
// implement the necessary traits to use zerocopy.
unsafe {
Expand Down Expand Up @@ -1195,6 +1202,15 @@ pub fn create_link(
HeaderVec::<FILE_LINK_INFORMATION, u16, 1>::with_capacity(link, new_path.len());
buffer.extend_tail_from_slice(new_path.as_slice());

// NtSetInformationFile fails with STATUS_INFO_LENGTH_MISMATCH for a buffer
// shorter than the whole FILE_LINK_INFORMATION, whose size counts the first
// FileName unit and the trailing padding (24 bytes on 64-bit Windows), while
// the header above stops at FileName. Pad a name of one UTF-16 unit with a
// NUL that FileNameLength leaves out.
while buffer.total_byte_len() < size_of::<FileSystem::FILE_LINK_INFORMATION>() {
buffer.push_tail(0);
}

set_information_file(handle, &buffer)?;

Ok(())
Expand Down
31 changes: 18 additions & 13 deletions vm/devices/support/fs/lxutil/src/windows/xattr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,11 @@ const LX_UTIL_CASE_SENSITIVE: &str = "system.wsl_case_sensitive";

const LX_UTIL_XATTR_NAME_PREFIX: &str = "LX.";
const LX_UTIL_XATTR_NAME_PREFIX_LENGTH: usize = LX_UTIL_XATTR_NAME_PREFIX.len();
const LX_UTIL_XATTR_NAME_MAX: usize = u16::MAX as usize - LX_UTIL_XATTR_NAME_PREFIX_LENGTH;

/// The longest EA name, prefix included, that NTFS accepts. `EaNameLength` is one byte, and NTFS
/// rejects a name of 255 bytes.
const LX_UTILP_EA_NAME_MAX: usize = 254;
const LX_UTIL_XATTR_NAME_MAX: usize = LX_UTILP_EA_NAME_MAX - LX_UTIL_XATTR_NAME_PREFIX_LENGTH;

const LX_UTILP_XATTR_QUERY_RESTART_SCAN: i32 = 0x1;
const LX_UTILP_XATTR_QUERY_RETURN_SINGLE_ENTRY: i32 = 0x2;
Expand Down Expand Up @@ -114,26 +118,27 @@ pub fn get_system(handle: &OwnedHandle, name: &str, value: Option<&mut [u8]>) ->
Ok(1)
}

/// Copy the Linux EA attribute prefix and the specified name into the start of the provided buffer.
fn set_name(name: &str, buffer: &mut [u8]) -> lx::Result<usize> {
/// Copy the Linux EA attribute prefix and the specified name into the start of the provided buffer,
/// and return the length of the resulting EA name.
fn set_name(name: &str, buffer: &mut [u8]) -> lx::Result<u8> {
let name_bytes = name.as_bytes();

if name_bytes.len() >= LX_UTIL_XATTR_NAME_MAX {
if name_bytes.len() > LX_UTIL_XATTR_NAME_MAX {
return Err(lx::Error::ERANGE);
}

let total_required = LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len() + 1;
let ea_name_len = LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len();
let total_required = ea_name_len + 1;
if buffer.len() < total_required {
return Err(lx::Error::ERANGE);
}

buffer[..LX_UTIL_XATTR_NAME_PREFIX_LENGTH]
.copy_from_slice(LX_UTIL_XATTR_NAME_PREFIX.as_bytes());
buffer[LX_UTIL_XATTR_NAME_PREFIX_LENGTH..LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len()]
.copy_from_slice(name_bytes);
buffer[LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len()] = 0;
buffer[LX_UTIL_XATTR_NAME_PREFIX_LENGTH..ea_name_len].copy_from_slice(name_bytes);
buffer[ea_name_len] = 0;

Ok(LX_UTIL_XATTR_NAME_PREFIX_LENGTH + name_bytes.len())
ea_name_len.try_into().map_err(|_| lx::Error::ERANGE)
}

/// Queries an EA on a file.
Expand Down Expand Up @@ -167,7 +172,7 @@ fn query_ea(

let header = FileGetEaInformation {
next_entry_offset: Unalign::new(0),
ea_name_length: name_len as u8,
ea_name_length: name_len,
};
buffer[..size_of::<FileGetEaInformation>()].copy_from_slice(header.as_bytes());
Some(buffer)
Expand Down Expand Up @@ -354,13 +359,13 @@ pub fn set(handle: &OwnedHandle, name: &str, value: &[u8], flags: i32) -> lx::Re
let ea_info = FileFullEaInformation {
next_entry_offset: Unalign::new(0),
flags: 0,
ea_name_length: name_len as u8,
ea_name_length: name_len,
ea_value_length: Unalign::new(value_size as u16),
};
buffer[..size_of::<FileFullEaInformation>()].copy_from_slice(ea_info.as_bytes());

// Set the EA value header.
let ea_value_start = size_of::<FileFullEaInformation>() + name_len + 1;
let ea_value_start = size_of::<FileFullEaInformation>() + usize::from(name_len) + 1;
buffer[ea_value_start..ea_value_start + 4]
.copy_from_slice(&LX_UTILP_EA_VALUE_HEADER.to_le_bytes());

Expand Down Expand Up @@ -492,7 +497,7 @@ pub fn remove(handle: &OwnedHandle, name: &str) -> lx::Result<()> {
let ea_info = FileFullEaInformation {
next_entry_offset: Unalign::new(0),
flags: 0,
ea_name_length: name_len as u8,
ea_name_length: name_len,
ea_value_length: Unalign::new(0), // Zero length to remove the attribute
};
buf[..size_of::<FileFullEaInformation>()].copy_from_slice(ea_info.as_bytes());
Expand Down
Loading
Loading