Skip to main content

tilo_process/
local_socket.rs

1//! Connecting to a service socket that only this user can have created.
2//!
3//! A session service publishes its socket below a directory private to the user (the
4//! runtime directory, `0700`), and a client checks that every directory from that root
5//! down to the socket, and the socket itself, belongs to it, so another user cannot
6//! have planted it. The connect has a deadline.
7
8use std::io;
9use std::os::fd::{AsFd, BorrowedFd};
10use std::os::unix::fs::{FileTypeExt, MetadataExt};
11use std::os::unix::net::UnixStream;
12use std::path::Path;
13use std::time::Duration;
14
15/// A stream to a session service, connected by [`connect_owner_only`]. An app holds one of
16/// these rather than the OS stream, so nothing it writes names a platform socket type.
17#[derive(Debug)]
18pub struct ServiceSocket(UnixStream);
19
20impl ServiceSocket {
21    /// The longest a read or write on this socket may wait, both at once.
22    pub fn set_timeout(&self, timeout: Duration) -> io::Result<()> {
23        self.0.set_read_timeout(Some(timeout))?;
24        self.0.set_write_timeout(Some(timeout))
25    }
26
27    /// The longest a read on this socket may wait, when one is set.
28    pub fn read_timeout(&self) -> io::Result<Option<Duration>> {
29        self.0.read_timeout()
30    }
31
32    /// Another handle on the same connection, for a caller whose API names the OS stream.
33    ///
34    /// # Errors
35    ///
36    /// The OS refused to duplicate the descriptor.
37    pub fn try_clone_stream(&self) -> io::Result<UnixStream> {
38        self.0.try_clone()
39    }
40
41    /// The longest a read on this socket may wait.
42    pub fn set_read_timeout(&self, timeout: Option<Duration>) -> io::Result<()> {
43        self.0.set_read_timeout(timeout)
44    }
45}
46
47impl From<UnixStream> for ServiceSocket {
48    fn from(stream: UnixStream) -> Self {
49        Self(stream)
50    }
51}
52
53impl AsFd for ServiceSocket {
54    fn as_fd(&self) -> BorrowedFd<'_> {
55        self.0.as_fd()
56    }
57}
58
59impl io::Read for &ServiceSocket {
60    fn read(&mut self, buffer: &mut [u8]) -> io::Result<usize> {
61        (&self.0).read(buffer)
62    }
63}
64
65impl io::Write for &ServiceSocket {
66    fn write(&mut self, buffer: &[u8]) -> io::Result<usize> {
67        (&self.0).write(buffer)
68    }
69
70    fn flush(&mut self) -> io::Result<()> {
71        (&self.0).flush()
72    }
73}
74
75/// Connect to `socket`, which lies below `root`, once every directory from `root` down to
76/// `socket`, and the socket itself, are owned by this process's user and closed to group
77/// and others.
78pub fn connect_owner_only(
79    root: &Path,
80    socket: &Path,
81    timeout: Duration,
82) -> io::Result<ServiceSocket> {
83    let invalid = |why| io::Error::new(io::ErrorKind::InvalidInput, why);
84    if !root.is_absolute() {
85        return Err(invalid("the service root is not absolute"));
86    }
87    let below = socket
88        .strip_prefix(root)
89        .map_err(|_| invalid("the service socket is not below its root"))?;
90    let parent = below.parent().unwrap_or_else(|| Path::new(""));
91    let owner = rustix::process::geteuid().as_raw();
92    let private = |path: &Path, is_kind: fn(&std::fs::FileType) -> bool| {
93        let metadata = std::fs::symlink_metadata(path)?;
94        let exposed = metadata.mode() & 0o077 != 0;
95        if !is_kind(&metadata.file_type()) || metadata.uid() != owner || exposed {
96            return Err(io::Error::new(
97                io::ErrorKind::PermissionDenied,
98                format!("{} is not private to this user", path.display()),
99            ));
100        }
101        Ok(())
102    };
103    private(root, std::fs::FileType::is_dir)?;
104    let mut directory = root.to_path_buf();
105    for component in parent.components() {
106        directory.push(component);
107        private(&directory, std::fs::FileType::is_dir)?;
108    }
109    private(socket, FileTypeExt::is_socket)?;
110
111    let address = socket2::SockAddr::unix(socket)?;
112    let stream = socket2::Socket::new(socket2::Domain::UNIX, socket2::Type::STREAM, None)?;
113    stream.connect_timeout(&address, timeout)?;
114    Ok(UnixStream::from(stream).into())
115}
116
117#[cfg(test)]
118mod tests {
119    use std::os::unix::fs::PermissionsExt;
120    use std::os::unix::net::UnixListener;
121
122    use super::*;
123
124    fn private_dir(path: &Path) {
125        std::fs::create_dir_all(path).unwrap();
126        std::fs::set_permissions(path, std::fs::Permissions::from_mode(0o700)).unwrap();
127    }
128
129    #[test]
130    fn only_an_owner_only_chain_is_connected() {
131        let root = tempfile::tempdir().unwrap();
132        private_dir(root.path());
133        let services = root.path().join("tilo/services");
134        private_dir(&root.path().join("tilo"));
135        private_dir(&services);
136        let socket = services.join("svc.sock");
137        let _listener = UnixListener::bind(&socket).unwrap();
138        std::fs::set_permissions(&socket, std::fs::Permissions::from_mode(0o600)).unwrap();
139        let timeout = tilo_test_env::hang_bound();
140
141        connect_owner_only(root.path(), &socket, timeout).expect("a private chain connects");
142
143        std::fs::set_permissions(&services, std::fs::Permissions::from_mode(0o755)).unwrap();
144        let open = connect_owner_only(root.path(), &socket, timeout).unwrap_err();
145        assert_eq!(open.kind(), io::ErrorKind::PermissionDenied);
146
147        let outside = connect_owner_only(&services, Path::new("/elsewhere.sock"), timeout);
148        assert_eq!(outside.unwrap_err().kind(), io::ErrorKind::InvalidInput);
149        let relative = connect_owner_only(Path::new("run"), Path::new("run/a.sock"), timeout);
150        assert_eq!(relative.unwrap_err().kind(), io::ErrorKind::InvalidInput);
151    }
152}