From 80ab6e712d1ed1d19987e00a60f80ed8aba1b259 Mon Sep 17 00:00:00 2001 From: Yao Jingxi <23722032@bjtu.edu.cn> Date: Sat, 21 Nov 2026 06:59:51 +0800 Subject: [PATCH] =?UTF-8?q?refactor(platform):=20=E8=BF=9C=E7=A8=8B?= =?UTF-8?q?=E6=9C=8D=E5=8A=A1=E7=AB=AF=E4=B8=8E=20AskPass=20=E5=85=B1?= =?UTF-8?q?=E7=94=A8=E5=90=8C=E4=B8=80=E4=BB=BD=20Unix=20socket=20?= =?UTF-8?q?=E5=AF=B9=E7=AB=AF=E8=B4=A6=E6=88=B7=E6=A3=80=E6=9F=A5=EF=BC=88?= =?UTF-8?q?#2231=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit git-host 的 AskPass 通道和 remote 服务端的常驻会话各有一份逐字相同的 peer_uid(Linux 用 SO_PEERCRED,其他 Unix 用 getpeereid)。现在合并到 lithe_platform::socket,两处都改用它;git-host 的 effective_uid 也一并移入。 remote 服务端多依赖一个只依赖 libc 的叶子 crate lithe-platform;remote 自己的 current_uid(getuid,也是 server.hello 的 userId)不变,行为不变。新增 lithe-platform-tests 的真实 socket 测试,两端都核对对端账户。 --- rust/Cargo.lock | 4 ++ .../git-host/src/authentication/unix.rs | 50 +------------- .../platform-tests/tests/platform/main.rs | 1 + .../platform-tests/tests/platform/socket.rs | 39 +++++++++++ rust/crates/platform/Cargo.toml | 6 +- rust/crates/platform/src/lib.rs | 8 ++- rust/crates/platform/src/socket.rs | 67 +++++++++++++++++++ rust/crates/remote/Cargo.toml | 8 ++- rust/crates/remote/src/server/daemon.rs | 2 +- .../remote/src/server/platform/linux.rs | 25 ------- .../remote/src/server/platform/macos.rs | 11 --- rust/crates/remote/src/server/platform/mod.rs | 7 +- 12 files changed, 135 insertions(+), 93 deletions(-) create mode 100644 rust/crates/platform-tests/tests/platform/socket.rs create mode 100644 rust/crates/platform/src/socket.rs diff --git a/rust/Cargo.lock b/rust/Cargo.lock index c94b4ff7..447dcd7c 100644 --- a/rust/Cargo.lock +++ b/rust/Cargo.lock @@ -1193,6 +1193,9 @@ dependencies = [ [[package]] name = "lithe-platform" version = "0.1.0" +dependencies = [ + "libc", +] [[package]] name = "lithe-platform-tests" @@ -1469,6 +1472,7 @@ dependencies = [ "base64", "libc", "lithe-diagnostics", + "lithe-platform", "serde", "serde_json", "sha2", diff --git a/rust/crates/git-host/src/authentication/unix.rs b/rust/crates/git-host/src/authentication/unix.rs index f8fa8b39..db30f637 100644 --- a/rust/crates/git-host/src/authentication/unix.rs +++ b/rust/crates/git-host/src/authentication/unix.rs @@ -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}; @@ -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. @@ -83,7 +83,7 @@ pub(super) fn connect(address: &OsStr) -> io::Result { 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 @@ -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 { - let mut credentials = libc::ucred { - pid: 0, - uid: 0, - gid: 0, - }; - let mut length = std::mem::size_of::() 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 { - 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) -} diff --git a/rust/crates/platform-tests/tests/platform/main.rs b/rust/crates/platform-tests/tests/platform/main.rs index 3857cf5e..8de6c9a5 100644 --- a/rust/crates/platform-tests/tests/platform/main.rs +++ b/rust/crates/platform-tests/tests/platform/main.rs @@ -8,4 +8,5 @@ mod git_executable; mod lsp_process; mod permissions; mod process_tree; +mod socket; mod support; diff --git a/rust/crates/platform-tests/tests/platform/socket.rs b/rust/crates/platform-tests/tests/platform/socket.rs new file mode 100644 index 00000000..b4281644 --- /dev/null +++ b/rust/crates/platform-tests/tests/platform/socket.rs @@ -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() + ); + } +} diff --git a/rust/crates/platform/Cargo.toml b/rust/crates/platform/Cargo.toml index 4be74e50..4cc86e5e 100644 --- a/rust/crates/platform/Cargo.toml +++ b/rust/crates/platform/Cargo.toml @@ -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] diff --git a/rust/crates/platform/src/lib.rs b/rust/crates/platform/src/lib.rs index f9aca1b4..17b82dea 100644 --- a/rust/crates/platform/src/lib.rs +++ b/rust/crates/platform/src/lib.rs @@ -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)] diff --git a/rust/crates/platform/src/socket.rs b/rust/crates/platform/src/socket.rs new file mode 100644 index 00000000..e962531d --- /dev/null +++ b/rust/crates/platform/src/socket.rs @@ -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 { + let mut credentials = libc::ucred { + pid: 0, + uid: 0, + gid: 0, + }; + let mut length = std::mem::size_of::() 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 { + 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) +} diff --git a/rust/crates/remote/Cargo.toml b/rust/crates/remote/Cargo.toml index 44b8c162..543768eb 100644 --- a/rust/crates/remote/Cargo.toml +++ b/rust/crates/remote/Cargo.toml @@ -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 @@ -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" } diff --git a/rust/crates/remote/src/server/daemon.rs b/rust/crates/remote/src/server/daemon.rs index f81d3ec7..50d9631f 100644 --- a/rust/crates/remote/src/server/daemon.rs +++ b/rust/crates/remote/src/server/daemon.rs @@ -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; } diff --git a/rust/crates/remote/src/server/platform/linux.rs b/rust/crates/remote/src/server/platform/linux.rs index 4d675b3c..06aef12f 100644 --- a/rust/crates/remote/src/server/platform/linux.rs +++ b/rust/crates/remote/src/server/platform/linux.rs @@ -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; @@ -113,30 +112,6 @@ fn stat_session(stat: &str) -> Option { 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 { - let mut credentials = libc::ucred { - pid: 0, - uid: 0, - gid: 0, - }; - let mut length = std::mem::size_of::() 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. diff --git a/rust/crates/remote/src/server/platform/macos.rs b/rust/crates/remote/src/server/platform/macos.rs index a75d8c05..fa18eba8 100644 --- a/rust/crates/remote/src/server/platform/macos.rs +++ b/rust/crates/remote/src/server/platform/macos.rs @@ -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}; @@ -111,16 +110,6 @@ fn process_sessions() -> Vec<(u32, u32)> { .collect() } -pub(crate) fn peer_uid(socket: RawFd) -> io::Result { - 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. diff --git a/rust/crates/remote/src/server/platform/mod.rs b/rust/crates/remote/src/server/platform/mod.rs index 79a4154e..5fd1a1a4 100644 --- a/rust/crates/remote/src/server/platform/mod.rs +++ b/rust/crates/remote/src/server/platform/mod.rs @@ -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,