#[cfg(unix)]
use anyhow::Context;
#[cfg(any(unix, test))]
use anyhow::{Result, bail};
use serde::{Deserialize, Serialize};
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ClientSnapshot {
pub version: u32,
pub socket: String,
pub clients: Vec<ClientObservation>,
}
#[derive(Clone, Debug, Deserialize, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ClientObservation {
#[serde(default, skip_serializing_if = "Option::is_none")]
pub socket: Option<String>,
pub pid: u32,
pub start_time: u64,
pub session_id: String,
pub session: String,
pub tty: String,
pub connection: Option<SshConnection>,
#[serde(default)]
pub socket_verified: bool,
}
#[cfg(any(unix, test))]
#[derive(Debug, PartialEq, Eq, Hash, Clone)]
struct SocketRow {
local: std::net::SocketAddr,
remote: std::net::SocketAddr,
inode: u64,
}
#[cfg(any(unix, test))]
fn proc_endpoint(value: &str, ipv6: bool) -> Result<std::net::SocketAddr> {
use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
let (address, port) = value
.rsplit_once(':')
.ok_or_else(|| anyhow::anyhow!("invalid proc TCP endpoint"))?;
let port = u16::from_str_radix(port, 16)?;
let address = if ipv6 {
if address.len() != 32 {
bail!("invalid proc IPv6 address");
}
let mut octets = [0; 16];
for (index, word) in octets.as_chunks_mut::<4>().0.iter_mut().enumerate() {
word.copy_from_slice(
&u32::from_str_radix(&address[index * 8..index * 8 + 8], 16)?.to_ne_bytes(),
);
}
let address = Ipv6Addr::from(octets);
address
.to_ipv4_mapped()
.map_or(IpAddr::V6(address), IpAddr::V4)
} else {
if address.len() != 8 {
bail!("invalid proc IPv4 address");
}
IpAddr::V4(Ipv4Addr::from(
u32::from_str_radix(address, 16)?.to_ne_bytes(),
))
};
Ok(SocketAddr::new(address, port))
}
#[cfg(any(unix, test))]
fn socket_rows(text: &str, ipv6: bool, connection: &SshConnection) -> Result<Vec<SocketRow>> {
let canonical = |address: std::net::IpAddr| match address {
std::net::IpAddr::V6(v6) => v6.to_ipv4_mapped().map_or(address, std::net::IpAddr::V4),
address => address,
};
let local: std::net::SocketAddr = std::net::SocketAddr::new(
canonical(connection.server_address.parse()?),
connection.server_port,
);
let remote: std::net::SocketAddr = std::net::SocketAddr::new(
canonical(connection.client_address.parse()?),
connection.client_port,
);
let mut rows = Vec::new();
for line in text.lines().skip(1) {
let fields = line.split_whitespace().collect::<Vec<_>>();
if fields.len() < 10 {
bail!("truncated proc TCP row");
}
if fields[3] != "01" {
continue;
}
let row = SocketRow {
local: proc_endpoint(fields[1], ipv6)?,
remote: proc_endpoint(fields[2], ipv6)?,
inode: fields[9].parse()?,
};
if row.local == local && row.remote == remote && row.inode != 0 {
rows.push(row);
}
}
Ok(rows)
}
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct SshConnection {
pub client_address: String,
pub client_port: u16,
pub server_address: String,
pub server_port: u16,
}
#[cfg(any(unix, test))]
impl SshConnection {
fn parse(value: &str) -> Result<Self> {
let fields = value.split_whitespace().collect::<Vec<_>>();
if fields.len() != 4 {
bail!("invalid SSH connection metadata");
}
let client_address = fields[0].parse::<std::net::IpAddr>()?.to_string();
let server_address = fields[2].parse::<std::net::IpAddr>()?.to_string();
let client_port = fields[1].parse()?;
let server_port = fields[3].parse()?;
if client_port == 0 || server_port == 0 {
bail!("invalid SSH connection port");
}
Ok(Self {
client_address,
client_port,
server_address,
server_port,
})
}
}
#[cfg(unix)]
pub fn observe(
server: &tmux_session::Tmux,
runtime: &tmux_session::Runtime,
) -> Result<ClientSnapshot> {
use std::{
collections::HashSet,
fs,
io::Read,
os::unix::fs::MetadataExt,
time::{Duration, Instant},
};
fn bounded(
path: impl AsRef<std::path::Path>,
limit: usize,
deadline: Instant,
) -> Result<Vec<u8>> {
if Instant::now() >= deadline {
bail!("proc observation deadline exceeded");
}
let mut bytes = Vec::new();
fs::File::open(path)?
.take((limit + 1) as u64)
.read_to_end(&mut bytes)?;
if bytes.len() > limit || Instant::now() >= deadline {
bail!("proc observation limit exceeded");
}
Ok(bytes)
}
fn stat(pid: u32, deadline: Instant) -> Result<(u32, u64)> {
let text = String::from_utf8(bounded(format!("/proc/{pid}/stat"), 65536, deadline)?)?;
let fields = text
.rsplit_once(") ")
.context("invalid process identity")?
.1
.split_whitespace()
.collect::<Vec<_>>();
Ok((
fields.get(1).context("missing process parent")?.parse()?,
fields
.get(19)
.context("missing process creation time")?
.parse()?,
))
}
fn ssh_environment(pid: u32, deadline: Instant) -> Result<Option<SshConnection>> {
let environment = bounded(format!("/proc/{pid}/environ"), 1024 * 1024, deadline)?;
let values = environment
.split(|b| *b == 0)
.filter_map(|entry| entry.strip_prefix(b"SSH_CONNECTION="))
.collect::<Vec<_>>();
if values.len() > 1 {
bail!("ambiguous SSH connection metadata");
}
values
.first()
.map(|value| SshConnection::parse(std::str::from_utf8(value)?))
.transpose()
}
fn proof(
chain: &[(u32, (u32, u64), Option<SshConnection>)],
expected: &SshConnection,
deadline: Instant,
) -> Result<bool> {
use std::collections::{HashMap, hash_map::Entry};
let mut namespaces = HashMap::new();
let mut owners = Vec::new();
let mut fd_count = 0;
for (pid, _, _) in chain {
if Instant::now() >= deadline {
bail!("socket proof deadline exceeded");
}
let namespace = fs::read_link(format!("/proc/{pid}/ns/net"))?;
if let Entry::Vacant(entry) = namespaces.entry(namespace.clone()) {
let mut rows = Vec::new();
for (table, ipv6) in [("tcp", false), ("tcp6", true)] {
let path = format!("/proc/{pid}/net/{table}");
match bounded(&path, 8 * 1024 * 1024, deadline) {
Ok(bytes) => {
rows.extend(socket_rows(std::str::from_utf8(&bytes)?, ipv6, expected)?)
}
Err(error)
if ipv6
&& error
.downcast_ref::<std::io::Error>()
.is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) => {}
Err(error) => return Err(error),
}
}
entry.insert((*pid, rows));
}
for entry in fs::read_dir(format!("/proc/{pid}/fd"))? {
fd_count += 1;
if fd_count > 4096 || Instant::now() >= deadline {
bail!("socket FD observation limit exceeded");
}
let entry = entry?;
let target = match fs::read_link(entry.path()) {
Ok(target) => target,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => continue,
Err(error) => return Err(error.into()),
};
if let Some(inode) = target
.to_str()
.and_then(|s| s.strip_prefix("socket:["))
.and_then(|s| s.strip_suffix(']'))
.and_then(|s| s.parse::<u64>().ok())
&& namespaces[&namespace]
.1
.iter()
.any(|row| row.inode == inode)
{
owners.push((*pid, namespace.clone(), entry.path(), target, inode));
}
}
}
let matching = namespaces
.iter()
.flat_map(|(ns, (_, rows))| rows.iter().map(move |row| (ns.clone(), row.inode)))
.collect::<HashSet<_>>();
if matching.len() != 1 || owners.is_empty() {
return Ok(false);
}
let selected = matching.iter().next().context("missing unique socket")?;
if owners
.iter()
.any(|(_, ns, _, _, inode)| ns != &selected.0 || *inode != selected.1)
{
return Ok(false);
}
for (namespace, (pid, before)) in &namespaces {
if fs::read_link(format!("/proc/{pid}/ns/net"))? != *namespace {
return Ok(false);
}
let mut after = Vec::new();
for (table, ipv6) in [("tcp", false), ("tcp6", true)] {
match bounded(
format!("/proc/{pid}/net/{table}"),
8 * 1024 * 1024,
deadline,
) {
Ok(bytes) => {
after.extend(socket_rows(std::str::from_utf8(&bytes)?, ipv6, expected)?)
}
Err(error)
if ipv6
&& error
.downcast_ref::<std::io::Error>()
.is_some_and(|e| e.kind() == std::io::ErrorKind::NotFound) => {}
Err(error) => return Err(error),
}
}
if &after != before {
return Ok(false);
}
}
for (pid, namespace, path, target, _) in &owners {
if fs::read_link(path)? != *target
|| fs::read_link(format!("/proc/{pid}/ns/net"))? != *namespace
{
return Ok(false);
}
}
for (pid, identity, environment) in chain {
if stat(*pid, deadline)? != *identity
|| ssh_environment(*pid, deadline)? != *environment
{
return Ok(false);
}
}
Ok(Instant::now() < deadline)
}
fn connection(mut pid: u32, deadline: Instant) -> Result<(Option<SshConnection>, bool)> {
let mut seen = HashSet::new();
let mut chain = Vec::new();
let mut chosen = None;
let mut ambiguous = false;
for _ in 0..64 {
if pid <= 1 {
let verified = if let Some(expected) = &chosen {
!ambiguous && proof(&chain, expected, deadline).unwrap_or(false)
} else {
false
};
return Ok((chosen, verified));
}
if Instant::now() > deadline || !seen.insert(pid) {
bail!("process ancestry changed or exceeded its observation limit");
}
let before = stat(pid, deadline)?;
let observed = match ssh_environment(pid, deadline) {
Ok(value) => value,
Err(_) => return Ok((chosen, false)),
};
if stat(pid, deadline)? != before {
bail!("process identity changed during observation");
}
if let Some(value) = &observed {
if let Some(previous) = &chosen {
if previous != value {
ambiguous = true;
}
} else {
chosen = Some(value.clone());
}
}
chain.push((pid, before, observed));
pid = before.0;
}
Ok((chosen, false))
}
let deadline = Instant::now() + Duration::from_secs(25);
let socket = runtime.block_on(server.server_socket_path())?;
let socket = socket
.to_str()
.context("tmux socket is not UTF-8")?
.to_owned();
let socket_identity = fs::metadata(&socket)?;
let sessions = runtime.block_on(server.sessions())?;
let clients = runtime.block_on(server.clients())?;
if clients.len() > 256 {
bail!("too many tmux clients for one observation");
}
let mut result = Vec::with_capacity(clients.len());
for client in clients {
let before = stat(client.pid, deadline)?;
let session = sessions
.iter()
.find(|session| session.id == client.session_id)
.context("tmux session changed during observation")?;
let (observed_connection, socket_verified) = connection(client.pid, deadline)?;
if stat(client.pid, deadline)? != before {
bail!("tmux client identity changed during observation");
}
result.push(ClientObservation {
socket: None,
pid: client.pid,
start_time: before.1,
session_id: session.id.to_string(),
session: session
.name
.to_str()
.context("tmux session is not UTF-8")?
.into(),
tty: client
.tty
.to_str()
.context("tmux client tty is not UTF-8")?
.into(),
connection: observed_connection,
socket_verified,
});
}
let after_socket = fs::metadata(&socket)?;
if after_socket.dev() != socket_identity.dev() || after_socket.ino() != socket_identity.ino() {
bail!("tmux socket changed during observation");
}
let after_clients = runtime.block_on(server.clients())?;
if after_clients.len() != result.len()
|| result.iter().any(|client| {
!after_clients.iter().any(|after| {
after.pid == client.pid
&& after.session_id.to_string() == client.session_id
&& after.tty.to_str() == Some(client.tty.as_str())
})
})
{
bail!("tmux client membership changed during observation");
}
let after_sessions = runtime.block_on(server.sessions())?;
if result.iter().any(|client| {
!after_sessions.iter().any(|session| {
session.id.to_string() == client.session_id
&& session.name.to_str() == Some(client.session.as_str())
})
}) {
bail!("tmux session names changed during observation");
}
Ok(ClientSnapshot {
version: 1,
socket,
clients: result,
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn proc_endpoints_decode_native_words_and_network_ports() {
assert_eq!(
proc_endpoint("4601A8C0:0016", false).unwrap().to_string(),
"192.168.1.70:22"
);
assert_eq!(
proc_endpoint("00000000000000000000000001000000:0016", true)
.unwrap()
.to_string(),
"[::1]:22"
);
assert_eq!(
proc_endpoint("0000000000000000FFFF00004601A8C0:0016", true)
.unwrap()
.to_string(),
"192.168.1.70:22"
);
assert!(proc_endpoint("4601A8:0016", false).is_err());
}
#[test]
fn socket_proof_rows_require_exact_established_tuple_and_inode() {
let expected = SshConnection::parse("192.168.1.200 49973 192.168.1.70 22").unwrap();
let table = "header\n0: 4601A8C0:0016 C801A8C0:C335 01 0:0 00:0 0 0 0 12345\n";
assert_eq!(
socket_rows(table, false, &expected).unwrap()[0].inode,
12345
);
assert!(
socket_rows(&table.replace(" 01 ", " 08 "), false, &expected)
.unwrap()
.is_empty()
);
assert!(
socket_rows(&table.replace("12345", "0"), false, &expected)
.unwrap()
.is_empty()
);
assert!(
socket_rows(&table.replace(":C335", ":C336"), false, &expected)
.unwrap()
.is_empty()
);
assert!(socket_rows("header\nmalformed", false, &expected).is_err());
}
#[test]
fn connection_metadata_is_a_complete_tuple() {
assert_eq!(
SshConnection::parse("192.0.2.1 12345 192.0.2.2 22").unwrap(),
SshConnection {
client_address: "192.0.2.1".into(),
client_port: 12345,
server_address: "192.0.2.2".into(),
server_port: 22,
}
);
for value in [
"",
"host 42 192.0.2.2 22",
"192.0.2.1 0 192.0.2.2 22",
"192.0.2.1 12 192.0.2.2 22 extra",
] {
assert!(SshConnection::parse(value).is_err());
}
}
}