Skip to content

Commit 80ab6e7

Browse files
committed
refactor(platform): 远程服务端与 AskPass 共用同一份 Unix socket 对端账户检查(#2231)
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 测试,两端都核对对端账户。
1 parent 94408ca commit 80ab6e7

12 files changed

Lines changed: 135 additions & 93 deletions

File tree

‎rust/Cargo.lock‎

Lines changed: 4 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎rust/crates/git-host/src/authentication/unix.rs‎

Lines changed: 3 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -10,11 +10,11 @@ use crate::failure_log;
1010
use lithe_platform::fs::{
1111
restrict_directory_to_owner, OWNER_ONLY_DIRECTORY_MODE, OWNER_ONLY_FILE_MODE,
1212
};
13+
use lithe_platform::socket::{effective_uid, peer_uid};
1314
use std::ffi::OsStr;
1415
use std::fs::{self, DirBuilder, Permissions};
1516
use std::io;
1617
use std::os::unix::fs::{DirBuilderExt, MetadataExt, PermissionsExt};
17-
use std::os::unix::io::{AsRawFd, RawFd};
1818
use std::os::unix::net::{UnixListener, UnixStream};
1919
use std::path::{Path, PathBuf};
2020

@@ -66,7 +66,7 @@ impl Listener {
6666
Err(error) => return Err(error),
6767
};
6868
// A peer whose account cannot be read is treated like another account.
69-
if peer_uid(stream.as_raw_fd()).ok() != Some(effective_uid()) {
69+
if peer_uid(&stream).ok() != Some(effective_uid()) {
7070
return Ok(Accept::Rejected("peer-identity"));
7171
}
7272
// Linux does not carry O_NONBLOCK from the listener to accepted sockets.
@@ -83,7 +83,7 @@ pub(super) fn connect(address: &OsStr) -> io::Result<UnixStream> {
8383
return Err(io::ErrorKind::InvalidInput.into());
8484
}
8585
let stream = UnixStream::connect(path)?;
86-
if peer_uid(stream.as_raw_fd())? != effective_uid() {
86+
if peer_uid(&stream)? != effective_uid() {
8787
return Err(io::ErrorKind::PermissionDenied.into());
8888
}
8989
// The session's own prompt and write deadlines end first and close the
@@ -181,47 +181,3 @@ fn verify_private(directory: &Path) -> io::Result<()> {
181181
Err(io::ErrorKind::PermissionDenied.into())
182182
}
183183
}
184-
185-
fn effective_uid() -> u32 {
186-
// SAFETY: geteuid has no preconditions and cannot fail.
187-
unsafe { libc::geteuid() }
188-
}
189-
190-
/// Account of the process on the other end of a connected Unix socket. For a
191-
/// client this is the account that created the listening socket.
192-
#[cfg(any(target_os = "linux", target_os = "android"))]
193-
fn peer_uid(socket: RawFd) -> io::Result<u32> {
194-
let mut credentials = libc::ucred {
195-
pid: 0,
196-
uid: 0,
197-
gid: 0,
198-
};
199-
let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
200-
// SAFETY: the out-pointers reference live locals of the declared size.
201-
let status = unsafe {
202-
libc::getsockopt(
203-
socket,
204-
libc::SOL_SOCKET,
205-
libc::SO_PEERCRED,
206-
(&mut credentials as *mut libc::ucred).cast(),
207-
&mut length,
208-
)
209-
};
210-
if status == -1 {
211-
return Err(io::Error::last_os_error());
212-
}
213-
Ok(credentials.uid)
214-
}
215-
216-
/// Account of the process on the other end of a connected Unix socket. For a
217-
/// client this is the account that created the listening socket.
218-
#[cfg(not(any(target_os = "linux", target_os = "android")))]
219-
fn peer_uid(socket: RawFd) -> io::Result<u32> {
220-
let mut uid: libc::uid_t = 0;
221-
let mut gid: libc::gid_t = 0;
222-
// SAFETY: the out-pointers reference live locals.
223-
if unsafe { libc::getpeereid(socket, &mut uid, &mut gid) } == -1 {
224-
return Err(io::Error::last_os_error());
225-
}
226-
Ok(uid)
227-
}

‎rust/crates/platform-tests/tests/platform/main.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,4 +8,5 @@ mod git_executable;
88
mod lsp_process;
99
mod permissions;
1010
mod process_tree;
11+
mod socket;
1112
mod support;
Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,39 @@
1+
//! The account on the other end of a Unix socket, read through
2+
//! `lithe_platform::socket` with the host's own system call.
3+
4+
#[cfg(unix)]
5+
mod unix {
6+
use crate::support::TempDir;
7+
use lithe_platform::socket::{effective_uid, peer_uid};
8+
use std::io;
9+
use std::os::unix::net::{UnixListener, UnixStream};
10+
11+
#[test]
12+
fn both_ends_of_a_socket_see_the_account_that_opened_the_other() {
13+
let directory = TempDir::new("lithe peer");
14+
let path = directory.path().join("peer.sock");
15+
let listener = UnixListener::bind(&path).expect("listening socket");
16+
let client = UnixStream::connect(&path).expect("connect");
17+
// A Unix-domain connect completes once the connection is queued, so a
18+
// non-blocking accept takes it without waiting.
19+
listener
20+
.set_nonblocking(true)
21+
.expect("non-blocking listener");
22+
let (server, _) = match listener.accept() {
23+
Ok(accepted) => accepted,
24+
Err(error) if error.kind() == io::ErrorKind::WouldBlock => {
25+
panic!("the queued connection was not ready to accept")
26+
}
27+
Err(error) => panic!("accept: {error}"),
28+
};
29+
30+
assert_eq!(
31+
peer_uid(&server).expect("peer of the server end"),
32+
effective_uid()
33+
);
34+
assert_eq!(
35+
peer_uid(&client).expect("peer of the client end"),
36+
effective_uid()
37+
);
38+
}
39+
}

‎rust/crates/platform/Cargo.toml‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,14 @@ name = "lithe-platform"
33
version = "0.1.0"
44
edition = "2021"
55
license = "Apache-2.0"
6-
description = "Host platform rules as data: path comparison, Windows file names, Unix permissions and console-less processes"
6+
description = "Host platform rules as data: path comparison, Windows file names, Unix permissions, Unix socket peers and console-less processes"
77

88
[dependencies]
99

10+
# Only the Unix socket peer checks need a system call that std does not wrap.
11+
[target.'cfg(unix)'.dependencies]
12+
libc = "0.2"
13+
1014
# Its tests check `Platform::HOST` against the host they run on, so CI also
1115
# runs them on macOS and Windows (scripts/rust-core/affected-crates.mjs).
1216
[package.metadata.lithe-ci]

‎rust/crates/platform/src/lib.rs‎

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,15 +7,17 @@
77
//! [`Platform::HOST`]; tests pass the platform whose rule they check.
88
//!
99
//! The few calls that need an operating-system API, such as Unix permission
10-
//! bits or Windows process creation flags, stay behind `cfg` inside this
11-
//! crate. Tests that need a real Windows or Unix host to observe them live in
12-
//! the `lithe-platform-tests` package.
10+
//! bits, the account behind a Unix socket or Windows process creation flags,
11+
//! stay behind `cfg` inside this crate. Tests that need a real Windows or Unix
12+
//! host to observe them live in the `lithe-platform-tests` package.
1313
1414
pub mod cli;
1515
pub mod fs;
1616
pub mod names;
1717
pub mod paths;
1818
pub mod process;
19+
#[cfg(unix)]
20+
pub mod socket;
1921

2022
/// A family of host operating systems that share the rules in this crate.
2123
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]

‎rust/crates/platform/src/socket.rs‎

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
//! The accounts on the two ends of a Unix socket.
2+
//!
3+
//! A process that hands out secrets or a session over a Unix socket checks the
4+
//! account on the other end before it reads or writes a byte, so the
5+
//! permissions of the socket's directory are a second layer rather than the
6+
//! only one. Linux reports the peer through `SO_PEERCRED`, macOS and the BSDs
7+
//! through `getpeereid`; both report the effective user id the peer had when
8+
//! it connected or started listening, so a peer that changes its ids later
9+
//! cannot change the answer.
10+
11+
use std::io;
12+
use std::os::fd::AsRawFd;
13+
use std::os::unix::net::UnixStream;
14+
15+
/// Effective user id of this process: the account that owns the files,
16+
/// directories and sockets it creates, and the one peers are compared with.
17+
pub fn effective_uid() -> u32 {
18+
// SAFETY: geteuid has no preconditions and cannot fail.
19+
unsafe { libc::geteuid() }
20+
}
21+
22+
/// Effective user id of the process on the other end of `socket`.
23+
///
24+
/// For a stream accepted from a listener this is the account that connected;
25+
/// for a client's stream it is the account that created the listening socket.
26+
/// Callers that cannot read it must treat the peer as another account.
27+
#[cfg(any(target_os = "linux", target_os = "android"))]
28+
pub fn peer_uid(socket: &UnixStream) -> io::Result<u32> {
29+
let mut credentials = libc::ucred {
30+
pid: 0,
31+
uid: 0,
32+
gid: 0,
33+
};
34+
let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
35+
// SAFETY: the descriptor is borrowed from a live stream, and the
36+
// out-pointers reference live locals of the declared size.
37+
let status = unsafe {
38+
libc::getsockopt(
39+
socket.as_raw_fd(),
40+
libc::SOL_SOCKET,
41+
libc::SO_PEERCRED,
42+
(&mut credentials as *mut libc::ucred).cast(),
43+
&mut length,
44+
)
45+
};
46+
if status == -1 {
47+
return Err(io::Error::last_os_error());
48+
}
49+
Ok(credentials.uid)
50+
}
51+
52+
/// Effective user id of the process on the other end of `socket`.
53+
///
54+
/// For a stream accepted from a listener this is the account that connected;
55+
/// for a client's stream it is the account that created the listening socket.
56+
/// Callers that cannot read it must treat the peer as another account.
57+
#[cfg(not(any(target_os = "linux", target_os = "android")))]
58+
pub fn peer_uid(socket: &UnixStream) -> io::Result<u32> {
59+
let mut uid: libc::uid_t = 0;
60+
let mut gid: libc::gid_t = 0;
61+
// SAFETY: the descriptor is borrowed from a live stream, and the
62+
// out-pointers reference live locals.
63+
if unsafe { libc::getpeereid(socket.as_raw_fd(), &mut uid, &mut gid) } == -1 {
64+
return Err(io::Error::last_os_error());
65+
}
66+
Ok(uid)
67+
}

‎rust/crates/remote/Cargo.toml‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ default = ["client"]
1212
client = ["dep:sha2"]
1313
# Host adapters must not become desktop client dependencies. Linux releases
1414
# target musl so the same static executable works in minimal containers.
15-
server = ["dep:libc", "dep:sha2", "dep:trash"]
15+
server = ["dep:libc", "dep:lithe-platform", "dep:sha2", "dep:trash"]
1616

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

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

‎rust/crates/remote/src/server/daemon.rs‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -410,7 +410,7 @@ pub fn run_daemon(options: &PersistentOptions) -> io::Result<()> {
410410
while !shutdown.load(Ordering::Acquire) {
411411
match listener.accept() {
412412
Ok((stream, _)) => {
413-
if platform::peer_uid(stream.as_raw_fd()).ok() != Some(platform::current_uid()) {
413+
if platform::peer_uid(&stream).ok() != Some(platform::current_uid()) {
414414
eprintln!("lithe-remote-server: rejected a connection from another user");
415415
continue;
416416
}

‎rust/crates/remote/src/server/platform/linux.rs‎

Lines changed: 0 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ use crate::protocol::methods::{ListeningPort, OperatingSystem, OrphanProtection}
55
use std::collections::HashSet;
66
use std::io;
77
use std::net::{Ipv4Addr, Ipv6Addr};
8-
use std::os::fd::RawFd;
98
use std::os::unix::process::CommandExt;
109
use std::path::Path;
1110
use std::process::Command;
@@ -113,30 +112,6 @@ fn stat_session(stat: &str) -> Option<u32> {
113112
after_name.split_whitespace().nth(3)?.parse().ok()
114113
}
115114

116-
/// User id of the process on the other end of a Unix socket.
117-
pub(crate) fn peer_uid(socket: RawFd) -> io::Result<u32> {
118-
let mut credentials = libc::ucred {
119-
pid: 0,
120-
uid: 0,
121-
gid: 0,
122-
};
123-
let mut length = std::mem::size_of::<libc::ucred>() as libc::socklen_t;
124-
// SAFETY: the out-pointers reference live locals of the declared size.
125-
let status = unsafe {
126-
libc::getsockopt(
127-
socket,
128-
libc::SOL_SOCKET,
129-
libc::SO_PEERCRED,
130-
(&mut credentials as *mut libc::ucred).cast(),
131-
&mut length,
132-
)
133-
};
134-
if status == -1 {
135-
return Err(io::Error::last_os_error());
136-
}
137-
Ok(credentials.uid)
138-
}
139-
140115
/// Listening TCP sockets in the server's network namespace, which inside a
141116
/// container is the container's own. Sockets of other users are included:
142117
/// Docker's port proxies, for example, run as root.

0 commit comments

Comments
 (0)