execkit 0.7.2

Stateful, structured, safe shell sessions for AI agents on real infrastructure.
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
// SPDX-License-Identifier: Apache-2.0
//! SSH transport configuration and host-key verification.
//!
//! The russh-backed I/O is wired separately; the pieces here - connection
//! config, auth, and the **host-key policy** (the load-bearing MITM defense) -
//! are pure and unit-tested, independent of any network.

use std::path::{Path, PathBuf};

use crate::error::Result;

/// How to reach an SSH host.
#[derive(Clone)]
pub struct SshConfig {
    pub host: String,
    pub port: u16,
    pub user: String,
    pub auth: SshAuth,
    pub host_key: HostKeyVerification,
}

impl SshConfig {
    /// `user@host` with sensible defaults (port 22, key path filled by caller).
    pub fn new(
        host: impl Into<String>,
        user: impl Into<String>,
        auth: SshAuth,
        host_key: HostKeyVerification,
    ) -> Self {
        Self {
            host: host.into(),
            port: 22,
            user: user.into(),
            auth,
            host_key,
        }
    }
}

/// Authentication method.
#[derive(Clone)]
pub enum SshAuth {
    Password(String),
    Key {
        path: PathBuf,
        passphrase: Option<String>,
    },
}

// Manual Debug so secrets never land in logs.
impl std::fmt::Debug for SshAuth {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SshAuth::Password(_) => f.write_str("Password(***)"),
            SshAuth::Key { path, .. } => write!(f, "Key {{ path: {path:?}, passphrase: *** }}"),
        }
    }
}

impl std::fmt::Debug for SshConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SshConfig")
            .field("host", &self.host)
            .field("port", &self.port)
            .field("user", &self.user)
            .field("auth", &self.auth)
            .field("host_key", &self.host_key)
            .finish()
    }
}

/// Server host-key policy - the defense against connecting into a MITM.
#[derive(Debug, Clone)]
pub enum HostKeyVerification {
    /// Require this exact fingerprint, e.g. `"SHA256:abc123..."`.
    Pinned(String),
    /// Trust-on-first-use against a `known_hosts`-style file (`host fingerprint`
    /// per line). A *changed* fingerprint for a known host is rejected.
    KnownHosts(PathBuf),
    /// DANGEROUS - accept any key. Tests only; never use in production.
    AcceptAny,
}

/// Verify a presented host fingerprint against the policy.
///
/// `Ok(true)` accept, `Ok(false)` reject (caller must abort the connection),
/// `Err` on IO trouble. Pure except for the known-hosts file read/append.
// Wired by the russh client Handler (next step); already unit-tested below.
#[allow(dead_code)]
pub(crate) fn verify_fingerprint(
    policy: &HostKeyVerification,
    host: &str,
    fingerprint: &str,
) -> Result<bool> {
    match policy {
        HostKeyVerification::AcceptAny => Ok(true),
        HostKeyVerification::Pinned(expected) => Ok(expected == fingerprint),
        HostKeyVerification::KnownHosts(path) => verify_known_hosts(path, host, fingerprint),
    }
}

#[allow(dead_code)]
fn verify_known_hosts(path: &Path, host: &str, fingerprint: &str) -> Result<bool> {
    // SEC-2: distinguish "file absent" (first use -> TOFU) from "file present
    // but unreadable" (any other I/O error -> fail closed, return Err).
    // Using read() + from_utf8_lossy so that real ASCII/hashed lines still
    // parse even if there is a stray high byte, while a genuine read error
    // propagates instead of silently becoming an empty file (MITM bypass).
    let content = match std::fs::read(path) {
        Ok(b) => String::from_utf8_lossy(&b).into_owned(),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => String::new(),
        Err(e) => return Err(e.into()),
    };
    for line in content.lines() {
        let mut it = line.split_whitespace();
        if let (Some(h), Some(fp)) = (it.next(), it.next()) {
            if h == host {
                // Known host: the fingerprint MUST match. A mismatch is a MITM
                // signal - reject loudly, never silently re-pin.
                return Ok(fp == fingerprint);
            }
        }
    }
    // Unseen host: trust on first use and pin it. One atomic O_APPEND write so a
    // concurrent reader never sees a partial line.
    use std::io::Write;
    let mut f = std::fs::OpenOptions::new()
        .create(true)
        .append(true)
        .open(path)?;
    f.write_all(format!("{host} {fingerprint}\n").as_bytes())?;
    Ok(true)
}

// ===========================================================================
// russh-backed transport (feature = "ssh")
// ===========================================================================

#[cfg(feature = "ssh")]
mod imp {
    use std::sync::mpsc as std_mpsc;
    use std::sync::Arc;
    use std::thread::JoinHandle;
    use std::time::Duration;

    use russh::client;
    use tokio::io::{AsyncReadExt, AsyncWriteExt};
    use tokio::sync::mpsc as tokio_mpsc;

    use super::{verify_fingerprint, HostKeyVerification, SshAuth, SshConfig};
    use crate::error::{Error, Result};
    use crate::transport::Transport;

    const CHANNEL_CAP: usize = 64;

    /// A persistent shell over SSH. A dedicated thread runs a current-thread
    /// tokio runtime; bytes bridge to the sync [`Transport`] API via channels.
    pub struct SshTransport {
        write_tx: Option<tokio_mpsc::Sender<Vec<u8>>>,
        // Option so Drop can close it *before* join - otherwise a runtime thread
        // parked in a full `read_tx.send()` (after a flood/timeout that stopped
        // draining) never observes shutdown and join() hangs forever.
        read_rx: Option<std_mpsc::Receiver<Vec<u8>>>,
        thread: Option<JoinHandle<()>>,
    }

    impl SshTransport {
        pub fn connect(cfg: SshConfig) -> Result<Self> {
            let (write_tx, write_rx) = tokio_mpsc::channel::<Vec<u8>>(CHANNEL_CAP);
            let (read_tx, read_rx) = std_mpsc::sync_channel::<Vec<u8>>(CHANNEL_CAP);
            let (ready_tx, ready_rx) = std_mpsc::channel::<Result<()>>();

            let thread = std::thread::spawn(move || {
                let rt = match tokio::runtime::Builder::new_current_thread()
                    .enable_all()
                    .build()
                {
                    Ok(rt) => rt,
                    Err(e) => {
                        let _ = ready_tx.send(Err(Error::Transport(format!("runtime: {e}"))));
                        return;
                    }
                };
                rt.block_on(io_loop(cfg, write_rx, read_tx, ready_tx));
            });

            // Block until the connection + auth + shell are established (or fail).
            match ready_rx.recv() {
                Ok(Ok(())) => Ok(SshTransport {
                    write_tx: Some(write_tx),
                    read_rx: Some(read_rx),
                    thread: Some(thread),
                }),
                Ok(Err(e)) => {
                    let _ = thread.join();
                    Err(e)
                }
                Err(_) => Err(Error::Transport("ssh thread died during connect".into())),
            }
        }
    }

    impl Transport for SshTransport {
        fn write_all(&mut self, bytes: &[u8]) -> Result<()> {
            let tx = self
                .write_tx
                .as_ref()
                .ok_or_else(|| Error::Transport("ssh session closed".into()))?;
            tx.blocking_send(bytes.to_vec())
                .map_err(|_| Error::Transport("ssh session closed".into()))
        }

        fn recv_timeout(&self, dur: Duration) -> Option<Vec<u8>> {
            self.read_rx.as_ref()?.recv_timeout(dur).ok()
        }
    }

    impl Drop for SshTransport {
        fn drop(&mut self) {
            // End the I/O loop regardless of where its thread is parked:
            //  - dropping write_tx  -> the select! write arm returns None -> break
            //  - dropping read_rx   -> a blocked read_tx.send() returns Err -> break
            // The second is essential: after a flood/timeout the thread sits in a
            // full blocking send, NOT in select!, so closing only writes wouldn't
            // wake it and join() would hang.
            self.write_tx = None;
            self.read_rx = None;
            if let Some(t) = self.thread.take() {
                let _ = t.join();
            }
        }
    }

    /// Verifies the server host key against the configured policy.
    struct Handler {
        policy: HostKeyVerification,
        host: String,
    }

    impl client::Handler for Handler {
        type Error = russh::Error;

        async fn check_server_key(
            &mut self,
            server_public_key: &russh::keys::ssh_key::PublicKey,
        ) -> std::result::Result<bool, Self::Error> {
            let fp = server_public_key
                .fingerprint(russh::keys::ssh_key::HashAlg::Sha256)
                .to_string();
            Ok(verify_fingerprint(&self.policy, &self.host, &fp).unwrap_or(false))
        }
    }

    async fn establish(
        cfg: &SshConfig,
    ) -> Result<(client::Handle<Handler>, russh::Channel<client::Msg>)> {
        let config = Arc::new(client::Config::default());
        let handler = Handler {
            policy: cfg.host_key.clone(),
            host: cfg.host.clone(),
        };
        let mut handle = client::connect(config, (cfg.host.as_str(), cfg.port), handler)
            .await
            .map_err(|e| Error::Transport(format!("ssh connect: {e}")))?;

        let result = match &cfg.auth {
            SshAuth::Password(p) => handle
                .authenticate_password(cfg.user.clone(), p.clone())
                .await
                .map_err(|e| Error::Transport(format!("ssh auth: {e}")))?,
            SshAuth::Key { path, passphrase } => {
                let key = russh::keys::load_secret_key(path, passphrase.as_deref())
                    .map_err(|e| Error::Transport(format!("load key: {e}")))?;
                // RSA keys must sign with rsa-sha2 (SHA-256/512) against modern
                // servers, which reject the legacy ssh-rsa (SHA-1). Negotiate the
                // server's preferred RSA hash; ignored for non-RSA keys.
                let hash = handle
                    .best_supported_rsa_hash()
                    .await
                    .ok()
                    .flatten()
                    .flatten();
                let key = russh::keys::PrivateKeyWithHashAlg::new(Arc::new(key), hash);
                handle
                    .authenticate_publickey(cfg.user.clone(), key)
                    .await
                    .map_err(|e| Error::Transport(format!("ssh auth: {e}")))?
            }
        };
        if !result.success() {
            return Err(Error::Transport("ssh authentication failed".into()));
        }

        let channel = handle
            .channel_open_session()
            .await
            .map_err(|e| Error::Transport(format!("open channel: {e}")))?;
        channel
            .request_pty(false, "xterm-256color", 120, 40, 0, 0, &[])
            .await
            .map_err(|e| Error::Transport(format!("request pty: {e}")))?;
        // Run a clean POSIX shell rather than request_shell, which starts the
        // interactive LOGIN shell - its profile/rc, prompt, and readline behavior
        // desync the sentinel framing. /bin/sh is universally present (bash is
        // not, e.g. on Alpine); the framing is POSIX-compatible.
        channel
            .exec(false, "/bin/sh")
            .await
            .map_err(|e| Error::Transport(format!("start shell: {e}")))?;
        Ok((handle, channel))
    }

    async fn io_loop(
        cfg: SshConfig,
        mut write_rx: tokio_mpsc::Receiver<Vec<u8>>,
        read_tx: std_mpsc::SyncSender<Vec<u8>>,
        ready_tx: std_mpsc::Sender<Result<()>>,
    ) {
        let (handle, channel) = match establish(&cfg).await {
            Ok(v) => v,
            Err(e) => {
                let _ = ready_tx.send(Err(e));
                return;
            }
        };
        let _ = ready_tx.send(Ok(()));
        let _keep = handle; // keep the SSH session alive for the channel's lifetime

        // INVARIANT: we always request_pty above, so the server merges the
        // command's fd2 into the single PTY stream and never sends SSH
        // ExtendedData. `into_stream()` builds a reader with `ext: None`, whose
        // poll_read busy-spins on an ExtendedData message - so do NOT drop the
        // PTY request without also handling ext data here.
        let stream = channel.into_stream(); // AsyncRead + AsyncWrite (merged streams)
        let (mut rd, mut wr) = tokio::io::split(stream);
        let mut buf = [0u8; 8192];

        loop {
            tokio::select! {
                r = rd.read(&mut buf) => match r {
                    Ok(0) | Err(_) => break,
                    // Blocking send into the bounded queue applies backpressure
                    // (stalls reads -> TCP backpressure) under a flood.
                    Ok(n) => if read_tx.send(buf[..n].to_vec()).is_err() { break; },
                },
                w = write_rx.recv() => match w {
                    Some(bytes) => {
                        if wr.write_all(&bytes).await.is_err() { break; }
                        let _ = wr.flush().await;
                    }
                    None => break, // transport dropped
                },
            }
        }
    }
}

#[cfg(feature = "ssh")]
pub use imp::SshTransport;

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pinned_matches_only_exact() {
        let p = HostKeyVerification::Pinned("SHA256:abc".into());
        assert!(verify_fingerprint(&p, "h", "SHA256:abc").unwrap());
        assert!(!verify_fingerprint(&p, "h", "SHA256:evil").unwrap());
    }

    #[test]
    fn known_hosts_tofu_then_pins_and_detects_change() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("execkit_kh_test_{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let p = HostKeyVerification::KnownHosts(path.clone());

        // First sight: accepted (TOFU) and pinned.
        assert!(verify_fingerprint(&p, "prod-1", "SHA256:good").unwrap());
        // Same key again: accepted.
        assert!(verify_fingerprint(&p, "prod-1", "SHA256:good").unwrap());
        // Changed key for a known host: REJECTED (MITM).
        assert!(!verify_fingerprint(&p, "prod-1", "SHA256:evil").unwrap());
        // A different host is independent.
        assert!(verify_fingerprint(&p, "prod-2", "SHA256:other").unwrap());

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn auth_debug_redacts_secrets() {
        let a = SshAuth::Password("hunter2".into());
        assert!(!format!("{a:?}").contains("hunter2"));
    }

    /// SEC-2: a known_hosts file containing any non-UTF-8 / undecodable bytes
    /// must NOT silently fall through to TOFU and accept a different key.
    /// The result must be Err (fail closed), not Ok(true).
    #[test]
    fn known_hosts_corrupt_file_fails_closed() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("execkit_kh_corrupt_{}", std::process::id()));
        // Write a valid pinned line followed by a raw non-UTF-8 byte sequence.
        let mut bytes = b"prod-1 SHA256:GOODKEY\n".to_vec();
        bytes.extend_from_slice(b"\xff\xfe bad\n");
        std::fs::write(&path, &bytes).unwrap();

        let p = HostKeyVerification::KnownHosts(path.clone());
        // Present a DIFFERENT (attacker) fingerprint for the already-pinned host.
        let result = verify_fingerprint(&p, "prod-1", "SHA256:ATTACKER");
        let _ = std::fs::remove_file(&path);

        // Must be Ok(false) (pinned entry found and key mismatched) OR Err.
        // It must NOT be Ok(true) (TOFU bypass / silent MITM accept).
        if let Ok(true) = result {
            panic!("SEC-2: corrupt known_hosts silently accepted attacker key (TOFU bypass)");
        }
    }

    /// Confirm that an ABSENT known_hosts file still triggers TOFU (first-use accept + pin).
    #[test]
    fn known_hosts_absent_file_tofu_preserved() {
        let dir = std::env::temp_dir();
        let path = dir.join(format!("execkit_kh_absent_{}", std::process::id()));
        let _ = std::fs::remove_file(&path);
        let p = HostKeyVerification::KnownHosts(path.clone());

        // File absent: first sight must be accepted (TOFU).
        assert!(
            verify_fingerprint(&p, "new-host", "SHA256:firstkey").unwrap(),
            "TOFU must accept first-ever connection when known_hosts is absent"
        );
        let _ = std::fs::remove_file(&path);
    }
}