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
4 changes: 4 additions & 0 deletions rust/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

50 changes: 3 additions & 47 deletions rust/crates/git-host/src/authentication/unix.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@ use crate::failure_log;
use lithe_platform::fs::{
restrict_directory_to_owner, OWNER_ONLY_DIRECTORY_MODE, OWNER_ONLY_FILE_MODE,
};
use lithe_platform::socket::{effective_uid, peer_uid};
use std::ffi::OsStr;
use std::fs::{self, DirBuilder, Permissions};
use std::io;
use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
use std::os::unix::io::{AsRawFd, RawFd};
use std::os::unix::net::{UnixListener, UnixStream};
use std::path::{Path, PathBuf};

Expand Down Expand Up @@ -66,7 +66,7 @@ impl Listener {
Err(error) => return Err(error),
};
// A peer whose account cannot be read is treated like another account.
if peer_uid(stream.as_raw_fd()).ok() != Some(effective_uid()) {
if peer_uid(&stream).ok() != Some(effective_uid()) {
return Ok(Accept::Rejected("peer-identity"));
}
// Linux does not carry O_NONBLOCK from the listener to accepted sockets.
Expand All @@ -83,7 +83,7 @@ pub(super) fn connect(address: &OsStr) -> io::Result<UnixStream> {
return Err(io::ErrorKind::InvalidInput.into());
}
let stream = UnixStream::connect(path)?;
if peer_uid(stream.as_raw_fd())? != effective_uid() {
if peer_uid(&stream)? != effective_uid() {
return Err(io::ErrorKind::PermissionDenied.into());
}
// The session's own prompt and write deadlines end first and close the
Expand Down Expand Up @@ -181,47 +181,3 @@ fn verify_private(directory: &Path) -> io::Result<()> {
Err(io::ErrorKind::PermissionDenied.into())
}
}

fn effective_uid() -> u32 {
// SAFETY: geteuid has no preconditions and cannot fail.
unsafe { libc::geteuid() }
}

/// Account of the process on the other end of a connected Unix socket. For a
/// client this is the account that created the listening socket.
#[cfg(any(target_os = "linux", target_os = "android"))]
fn peer_uid(socket: RawFd) -> io::Result<u32> {
let mut credentials = libc::ucred {
pid: 0,
uid: 0,
gid: 0,
};
let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
// SAFETY: the out-pointers reference live locals of the declared size.
let status = unsafe {
libc::getsockopt(
socket,
libc::SOL_SOCKET,
libc::SO_PEERCRED,
(&mut credentials as *mut libc::ucred).cast(),
&mut length,
)
};
if status == -1 {
return Err(io::Error::last_os_error());
}
Ok(credentials.uid)
}

/// Account of the process on the other end of a connected Unix socket. For a
/// client this is the account that created the listening socket.
#[cfg(not(any(target_os = "linux", target_os = "android")))]
fn peer_uid(socket: RawFd) -> io::Result<u32> {
let mut uid: libc::uid_t = 0;
let mut gid: libc::gid_t = 0;
// SAFETY: the out-pointers reference live locals.
if unsafe { libc::getpeereid(socket, &mut uid, &mut gid) } == -1 {
return Err(io::Error::last_os_error());
}
Ok(uid)
}
1 change: 1 addition & 0 deletions rust/crates/platform-tests/tests/platform/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,5 @@ mod git_executable;
mod lsp_process;
mod permissions;
mod process_tree;
mod socket;
mod support;
39 changes: 39 additions & 0 deletions rust/crates/platform-tests/tests/platform/socket.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//! The account on the other end of a Unix socket, read through
//! `lithe_platform::socket` with the host's own system call.

#[cfg(unix)]
mod unix {
use crate::support::TempDir;
use lithe_platform::socket::{effective_uid, peer_uid};
use std::io;
use std::os::unix::net::{UnixListener, UnixStream};

#[test]
fn both_ends_of_a_socket_see_the_account_that_opened_the_other() {
let directory = TempDir::new("lithe peer");
let path = directory.path().join("peer.sock");
let listener = UnixListener::bind(&path).expect("listening socket");
let client = UnixStream::connect(&path).expect("connect");
// A Unix-domain connect completes once the connection is queued, so a
// non-blocking accept takes it without waiting.
listener
.set_nonblocking(true)
.expect("non-blocking listener");
let (server, _) = match listener.accept() {
Ok(accepted) => accepted,
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
panic!("the queued connection was not ready to accept")
}
Err(error) => panic!("accept: {error}"),
};

assert_eq!(
peer_uid(&server).expect("peer of the server end"),
effective_uid()
);
assert_eq!(
peer_uid(&client).expect("peer of the client end"),
effective_uid()
);
}
}
6 changes: 5 additions & 1 deletion rust/crates/platform/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,14 @@ name = "lithe-platform"
version = "0.1.0"
edition = "2021"
license = "Apache-2.0"
description = "Host platform rules as data: path comparison, Windows file names, Unix permissions and console-less processes"
description = "Host platform rules as data: path comparison, Windows file names, Unix permissions, Unix socket peers and console-less processes"

[dependencies]

# Only the Unix socket peer checks need a system call that std does not wrap.
[target.'cfg(unix)'.dependencies]
libc = "0.2"

# Its tests check `Platform::HOST` against the host they run on, so CI also
# runs them on macOS and Windows (scripts/rust-core/affected-crates.mjs).
[package.metadata.lithe-ci]
Expand Down
8 changes: 5 additions & 3 deletions rust/crates/platform/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,15 +7,17 @@
//! [`Platform::HOST`]; tests pass the platform whose rule they check.
//!
//! The few calls that need an operating-system API, such as Unix permission
//! bits or Windows process creation flags, stay behind `cfg` inside this
//! crate. Tests that need a real Windows or Unix host to observe them live in
//! the `lithe-platform-tests` package.
//! bits, the account behind a Unix socket or Windows process creation flags,
//! stay behind `cfg` inside this crate. Tests that need a real Windows or Unix
//! host to observe them live in the `lithe-platform-tests` package.

pub mod cli;
pub mod fs;
pub mod names;
pub mod paths;
pub mod process;
#[cfg(unix)]
pub mod socket;

/// A family of host operating systems that share the rules in this crate.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
Expand Down
67 changes: 67 additions & 0 deletions rust/crates/platform/src/socket.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
//! The accounts on the two ends of a Unix socket.
//!
//! A process that hands out secrets or a session over a Unix socket checks the
//! account on the other end before it reads or writes a byte, so the
//! permissions of the socket's directory are a second layer rather than the
//! only one. Linux reports the peer through `SO_PEERCRED`, macOS and the BSDs
//! through `getpeereid`; both report the effective user id the peer had when
//! it connected or started listening, so a peer that changes its ids later
//! cannot change the answer.

use std::io;
use std::os::fd::AsRawFd;
use std::os::unix::net::UnixStream;

/// Effective user id of this process: the account that owns the files,
/// directories and sockets it creates, and the one peers are compared with.
pub fn effective_uid() -> u32 {
// SAFETY: geteuid has no preconditions and cannot fail.
unsafe { libc::geteuid() }
}

/// Effective user id of the process on the other end of `socket`.
///
/// For a stream accepted from a listener this is the account that connected;
/// for a client's stream it is the account that created the listening socket.
/// Callers that cannot read it must treat the peer as another account.
#[cfg(any(target_os = "linux", target_os = "android"))]
pub fn peer_uid(socket: &UnixStream) -> io::Result<u32> {
let mut credentials = libc::ucred {
pid: 0,
uid: 0,
gid: 0,
};
let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
// SAFETY: the descriptor is borrowed from a live stream, and the
// out-pointers reference live locals of the declared size.
let status = unsafe {
libc::getsockopt(
socket.as_raw_fd(),
libc::SOL_SOCKET,
libc::SO_PEERCRED,
(&mut credentials as *mut libc::ucred).cast(),
&mut length,
)
};
if status == -1 {
return Err(io::Error::last_os_error());
}
Ok(credentials.uid)
}

/// Effective user id of the process on the other end of `socket`.
///
/// For a stream accepted from a listener this is the account that connected;
/// for a client's stream it is the account that created the listening socket.
/// Callers that cannot read it must treat the peer as another account.
#[cfg(not(any(target_os = "linux", target_os = "android")))]
pub fn peer_uid(socket: &UnixStream) -> io::Result<u32> {
let mut uid: libc::uid_t = 0;
let mut gid: libc::gid_t = 0;
// SAFETY: the descriptor is borrowed from a live stream, and the
// out-pointers reference live locals.
if unsafe { libc::getpeereid(socket.as_raw_fd(), &mut uid, &mut gid) } == -1 {
return Err(io::Error::last_os_error());
}
Ok(uid)
}
8 changes: 6 additions & 2 deletions rust/crates/remote/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ default = ["client"]
client = ["dep:sha2"]
# Host adapters must not become desktop client dependencies. Linux releases
# target musl so the same static executable works in minimal containers.
server = ["dep:libc", "dep:sha2", "dep:trash"]
server = ["dep:libc", "dep:lithe-platform", "dep:sha2", "dep:trash"]

# The server runs on Linux and macOS hosts, and its integration tests start
# the server binary of this package, so they cannot move to
Expand All @@ -29,9 +29,13 @@ serde_json = "1"
sha2 = { version = "0.10", optional = true }
libc = { version = "0.2", optional = true }
trash = { version = "5.2.6", default-features = false, features = ["chrono"], optional = true }
# The server checks socket peers with the same code as the AskPass channel.
# lithe-platform is a leaf crate of host rules that depends only on libc.
lithe-platform = { path = "../platform", optional = true }

# Tests check every lifecycle fact against the log catalog Core validates with.
# Only tests use it: the server and the client stay free of Core crates.
# Only tests use it: apart from lithe-platform, the server and the client stay
# free of Core crates.
[dev-dependencies]
lithe-diagnostics = { path = "../diagnostics" }

Expand Down
2 changes: 1 addition & 1 deletion rust/crates/remote/src/server/daemon.rs
Original file line number Diff line number Diff line change
Expand Up @@ -410,7 +410,7 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> {
while !shutdown.load(Ordering::Acquire) {
match listener.accept() {
Ok((stream, _)) => {
if platform::peer_uid(stream.as_raw_fd()).ok() != Some(platform::current_uid()) {
if platform::peer_uid(&stream).ok() != Some(platform::current_uid()) {
eprintln!("lithe-remote-server: rejected a connection from another user");
continue;
}
Expand Down
25 changes: 0 additions & 25 deletions rust/crates/remote/src/server/platform/linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@ use crate::protocol::methods::{ListeningPort, OperatingSystem, OrphanProtection}
use std::collections::HashSet;
use std::io;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::os::fd::RawFd;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::Command;
Expand Down Expand Up @@ -113,30 +112,6 @@ fn stat_session(stat: &str) -> Option<u32> {
after_name.split_whitespace().nth(3)?.parse().ok()
}

/// User id of the process on the other end of a Unix socket.
pub(crate) fn peer_uid(socket: RawFd) -> io::Result<u32> {
let mut credentials = libc::ucred {
pid: 0,
uid: 0,
gid: 0,
};
let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
// SAFETY: the out-pointers reference live locals of the declared size.
let status = unsafe {
libc::getsockopt(
socket,
libc::SOL_SOCKET,
libc::SO_PEERCRED,
(&mut credentials as *mut libc::ucred).cast(),
&mut length,
)
};
if status == -1 {
return Err(io::Error::last_os_error());
}
Ok(credentials.uid)
}

/// Listening TCP sockets in the server's network namespace, which inside a
/// container is the container's own. Sockets of other users are included:
/// Docker's port proxies, for example, run as root.
Expand Down
11 changes: 0 additions & 11 deletions rust/crates/remote/src/server/platform/macos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ use super::{unix, ChildKind};
use crate::protocol::methods::{ListeningPort, OperatingSystem, OrphanProtection};
use std::collections::HashSet;
use std::io;
use std::os::fd::RawFd;
use std::os::unix::process::CommandExt;
use std::path::Path;
use std::process::{Command, Stdio};
Expand Down Expand Up @@ -111,16 +110,6 @@ fn process_sessions() -> Vec<(u32, u32)> {
.collect()
}

pub(crate) fn peer_uid(socket: RawFd) -> io::Result<u32> {
let mut uid: libc::uid_t = 0;
let mut gid: libc::gid_t = 0;
// SAFETY: the out-pointers reference live locals.
if unsafe { libc::getpeereid(socket, &mut uid, &mut gid) } == -1 {
return Err(io::Error::last_os_error());
}
Ok(uid)
}

/// Listening TCP sockets of the remote user's processes. macOS has no
/// `/proc`; `lsof` ships with the system and is the supported way to list
/// sockets without elevated rights.
Expand Down
7 changes: 4 additions & 3 deletions rust/crates/remote/src/server/platform/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,10 @@ use macos as host;
#[cfg(target_os = "macos")]
pub(crate) use macos_watch as watcher;

pub(crate) use host::{
case_sensitive, listening_ports, peer_uid, prepare_child, rename_no_replace,
};
pub(crate) use host::{case_sensitive, listening_ports, prepare_child, rename_no_replace};
// Linux and macOS read a socket peer through different calls; lithe-platform
// keeps both for every Lithe process that checks who is on a Unix socket.
pub(crate) use lithe_platform::socket::peer_uid;
pub(crate) use unix::{
collect_output, current_account, current_uid, live_sessions, open_pty, set_window_size,
signal_process_group, signal_session,
Expand Down
Loading