agent-ssh 0.3.6

Arrange agent terminal layouts and reconnect through provider attachment plans
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
#[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 {
    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 {
            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());
        }
    }
}