Skip to main content

arks_server/
ssh_serve.rs

1//! In-process SSH listener for `arks serve` (durable accept + live rebind).
2//!
3//! Evidence: B1/B2 OpenSSH ChaCha wire + `git clone ssh://`
4//! ([[evidence:root/20261110235116-claimed-ssh]]) and B7 SSH dual-bind rebind
5//! ([[evidence:root/20261111092000-claimed-rebind-ssh]]); with both, the IW-SSH-LABEL
6//! drop condition holds and the listener carries no Partial readiness label (queue Q21).
7//!
8//! Max honest wire today (structured stages):
9//! 1. resolve host-key + `authorized_keys` paths (env / options / defaults)
10//! 2. prove TCP bind on the requested listen address
11//! 3. optional RFC 4253 identification exchange
12//! 4. optional SSH_MSG_KEXINIT exchange + peer name-list parse
13//! 5. local curve25519-sha256 ECDH (+ peer ECDH INIT when offered)
14//! 6. host-key **sign** Partial (OpenSSH ed25519 unencrypted) + NEWKEYS when key loads
15//! 7. OpenSSH `chacha20-poly1305@openssh.com` packet protection after NEWKEYS
16//! 8. wire publickey auth verify against `authorized_keys` (Partial; when peer continues)
17//! 9. session channel + `exec` → `git-upload-pack`|`git-receive-pack` dispatch into
18//!    `upload_pack_stream` / `receive_pack_stream` (Partial; when channel opens)
19//!
20//! SoT §17(c)/(d): durable accept + same-process live rebind; bind failure stays
21//! fail-closed and silent degrade is forbidden. Ops SSHD + `arks upload-pack` /
22//! `receive-pack` remains valid. Cite: [[sot:root/arks-self-host-server]]
23
24use crate::error::ServerError;
25use crate::push_policy::Pusher;
26use crate::serve::ListenRebindSlot;
27use crate::ssh_openssh_chacha::OpenSshChaCha;
28use crate::stdio::{receive_pack_stream_as, upload_pack_stream};
29use arks_repo::Repository;
30use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
31use sha2::{Digest, Sha256};
32use std::io::{Cursor, Read, Write};
33use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
34use std::path::{Path, PathBuf};
35use std::sync::Arc;
36use std::sync::atomic::{AtomicBool, Ordering};
37use std::thread;
38use std::time::{Duration, Instant};
39use x25519_dalek::{PublicKey, StaticSecret};
40
41/// Stop flag + join handle of a background listener thread.
42type ListenerThread = thread::JoinHandle<Result<(), ServerError>>;
43
44/// Named fail-closed stages for in-process SSH Partial (not Claimed).
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
46#[allow(dead_code)] // IdExchange retained for stage vocabulary / future accept-path notes.
47enum SshStage {
48    IdExchange,
49    KexInit,
50    AlgoSelect,
51    Ecdh,
52    HostKeySign,
53    NewKeys,
54    EncryptedTransport,
55    AuthPublickey,
56    ChannelSession,
57}
58
59impl SshStage {
60    fn as_str(self) -> &'static str {
61        match self {
62            Self::IdExchange => "id_exchange",
63            Self::KexInit => "kexinit",
64            Self::AlgoSelect => "algo_select",
65            Self::Ecdh => "ecdh_curve25519",
66            Self::HostKeySign => "host_key_sign",
67            Self::NewKeys => "newkeys",
68            Self::EncryptedTransport => "encrypted_transport",
69            Self::AuthPublickey => "auth_publickey",
70            Self::ChannelSession => "channel_session",
71        }
72    }
73}
74
75/// Options for the in-process SSH git listener.
76#[derive(Debug, Clone)]
77pub struct ServeSshOptions {
78    pub listen: SocketAddr,
79    /// Repository or base path the listener would serve.
80    pub path: PathBuf,
81    /// Host key path (OpenSSH-format expected when Claimed). Default / env override.
82    pub host_key: PathBuf,
83    /// `authorized_keys` path for public-key auth (when Claimed).
84    pub authorized_keys: PathBuf,
85    /// Optional same-process live rebind target (§17(c); B7 SSH dual-bind drain).
86    pub rebind_desired: Option<ListenRebindSlot>,
87}
88
89impl ServeSshOptions {
90    /// Build options with default key paths under `~/.config/arks/ssh/` (or env).
91    pub fn with_defaults(listen: SocketAddr, path: PathBuf) -> Self {
92        Self {
93            listen,
94            path,
95            host_key: default_host_key_path(),
96            authorized_keys: default_authorized_keys_path(),
97            rebind_desired: None,
98        }
99    }
100}
101
102/// Default host key: `ARKS_SERVE_SSH_HOST_KEY` or `~/.config/arks/ssh/host_key`.
103pub fn default_host_key_path() -> PathBuf {
104    if let Ok(p) = std::env::var("ARKS_SERVE_SSH_HOST_KEY") {
105        if !p.is_empty() {
106            return PathBuf::from(p);
107        }
108    }
109    arks_config_dir().join("ssh").join("host_key")
110}
111
112/// Default authorized_keys: `ARKS_SERVE_SSH_AUTHORIZED_KEYS` or
113/// `~/.config/arks/ssh/authorized_keys`.
114pub fn default_authorized_keys_path() -> PathBuf {
115    if let Ok(p) = std::env::var("ARKS_SERVE_SSH_AUTHORIZED_KEYS") {
116        if !p.is_empty() {
117            return PathBuf::from(p);
118        }
119    }
120    arks_config_dir().join("ssh").join("authorized_keys")
121}
122
123fn arks_config_dir() -> PathBuf {
124    let home = std::env::var_os("HOME")
125        .or_else(|| std::env::var_os("USERPROFILE"))
126        .map(PathBuf::from)
127        .unwrap_or_else(|| PathBuf::from("."));
128    home.join(".config").join("arks")
129}
130
131fn path_status(p: &Path) -> &'static str {
132    if p.is_file() {
133        "present"
134    } else if p.exists() {
135        "exists-not-file"
136    } else {
137        "missing"
138    }
139}
140
141/// Probe host-key bytes for known OpenSSH / PEM markers (auth scaffolding; no load Claimed).
142fn probe_host_key_format(path: &Path) -> String {
143    if !path.is_file() {
144        return "absent".into();
145    }
146    let mut f = match std::fs::File::open(path) {
147        Ok(f) => f,
148        Err(e) => return format!("unreadable ({e})"),
149    };
150    let mut buf = [0u8; 96];
151    let n = f.read(&mut buf).unwrap_or(0);
152    let head = String::from_utf8_lossy(&buf[..n]);
153    if head.starts_with("openssh-key-v1") || head.contains("BEGIN OPENSSH PRIVATE KEY") {
154        "openssh-private-key-marker".into()
155    } else if head.contains("BEGIN RSA PRIVATE KEY")
156        || head.contains("BEGIN EC PRIVATE KEY")
157        || head.contains("BEGIN PRIVATE KEY")
158    {
159        "pem-private-key-marker".into()
160    } else if head.starts_with("ssh-") || head.starts_with("ecdsa-") || head.starts_with("sk-") {
161        "public-key-line-like".into()
162    } else if n == 0 {
163        "empty-file".into()
164    } else {
165        "unknown-bytes".into()
166    }
167}
168
169/// Count non-empty, non-comment lines in authorized_keys (auth scaffolding; no verify Claimed).
170fn probe_authorized_keys(path: &Path) -> String {
171    if !path.is_file() {
172        return "absent".into();
173    }
174    let raw = match std::fs::read_to_string(path) {
175        Ok(s) => s,
176        Err(e) => return format!("unreadable ({e})"),
177    };
178    let keys = raw
179        .lines()
180        .map(str::trim)
181        .filter(|l| !l.is_empty() && !l.starts_with('#'))
182        .count();
183    format!("lines={keys}")
184}
185
186fn ssh_string(data: &[u8]) -> Vec<u8> {
187    let mut out = Vec::with_capacity(4 + data.len());
188    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
189    out.extend_from_slice(data);
190    out
191}
192
193fn ssh_name_list(names: &[&str]) -> Vec<u8> {
194    let joined = names.join(",");
195    ssh_string(joined.as_bytes())
196}
197
198fn read_ssh_name_list(buf: &[u8], off: &mut usize) -> Option<Vec<String>> {
199    if *off + 4 > buf.len() {
200        return None;
201    }
202    let len = u32::from_be_bytes(buf[*off..*off + 4].try_into().ok()?) as usize;
203    *off += 4;
204    if *off + len > buf.len() {
205        return None;
206    }
207    let s = std::str::from_utf8(&buf[*off..*off + len]).ok()?;
208    *off += len;
209    if s.is_empty() {
210        return Some(Vec::new());
211    }
212    Some(s.split(',').map(|x| x.to_string()).collect())
213}
214
215fn read_ssh_bytes(buf: &[u8], off: &mut usize) -> Option<Vec<u8>> {
216    if *off + 4 > buf.len() {
217        return None;
218    }
219    let len = u32::from_be_bytes(buf[*off..*off + 4].try_into().ok()?) as usize;
220    *off += 4;
221    if *off + len > buf.len() {
222        return None;
223    }
224    let out = buf[*off..*off + len].to_vec();
225    *off += len;
226    Some(out)
227}
228
229/// Host-key material for Partial sign (OpenSSH ed25519 unencrypted only).
230#[derive(Clone)]
231struct HostEd25519 {
232    signing: SigningKey,
233    /// SSH wire blob: string("ssh-ed25519") || string(32-byte pub).
234    public_blob: Vec<u8>,
235}
236
237fn load_host_ed25519(path: &Path) -> Result<HostEd25519, String> {
238    if !path.is_file() {
239        return Err("host_key absent".into());
240    }
241    let raw = std::fs::read(path).map_err(|e| e.to_string())?;
242    let text = String::from_utf8_lossy(&raw);
243    let b64: String = if text.contains("BEGIN OPENSSH PRIVATE KEY") {
244        text.lines()
245            .filter(|l| !l.starts_with("-----") && !l.trim().is_empty())
246            .collect::<String>()
247    } else if raw.starts_with(b"openssh-key-v1\0") {
248        return parse_openssh_ed25519_bin(&raw);
249    } else {
250        return Err("not OpenSSH PEM / openssh-key-v1".into());
251    };
252    let bin = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64.trim())
253        .map_err(|e| format!("base64: {e}"))?;
254    parse_openssh_ed25519_bin(&bin)
255}
256
257fn parse_openssh_ed25519_bin(bin: &[u8]) -> Result<HostEd25519, String> {
258    const MAGIC: &[u8] = b"openssh-key-v1\0";
259    if !bin.starts_with(MAGIC) {
260        return Err("missing openssh-key-v1 magic".into());
261    }
262    let mut off = MAGIC.len();
263    let cipher = read_ssh_bytes(bin, &mut off).ok_or("ciphername")?;
264    let kdf = read_ssh_bytes(bin, &mut off).ok_or("kdfname")?;
265    let _kdfopts = read_ssh_bytes(bin, &mut off).ok_or("kdfoptions")?;
266    if cipher.as_slice() != b"none" || kdf.as_slice() != b"none" {
267        return Err("encrypted OpenSSH host key not Partial-wired (none/none only)".into());
268    }
269    if off + 4 > bin.len() {
270        return Err("num_keys short".into());
271    }
272    let nkeys = u32::from_be_bytes(bin[off..off + 4].try_into().unwrap());
273    off += 4;
274    if nkeys != 1 {
275        return Err(format!("num_keys={nkeys} (Partial expects 1)"));
276    }
277    let pub_blob = read_ssh_bytes(bin, &mut off).ok_or("public key blob")?;
278    let priv_block = read_ssh_bytes(bin, &mut off).ok_or("private block")?;
279    let mut poff = 0usize;
280    let _c1 = read_u32(&priv_block, &mut poff)?;
281    let _c2 = read_u32(&priv_block, &mut poff)?;
282    let keytype = read_ssh_bytes(&priv_block, &mut poff).ok_or("keytype")?;
283    if keytype.as_slice() != b"ssh-ed25519" {
284        return Err(format!(
285            "host key type {} (Partial ed25519 only)",
286            String::from_utf8_lossy(&keytype)
287        ));
288    }
289    let _pub_in_priv = read_ssh_bytes(&priv_block, &mut poff).ok_or("pubkey in priv")?;
290    let secret = read_ssh_bytes(&priv_block, &mut poff).ok_or("secret")?;
291    // OpenSSH stores 64-byte ed25519 private as seed(32)||public(32).
292    if secret.len() < 32 {
293        return Err(format!("ed25519 secret len {}", secret.len()));
294    }
295    let mut seed = [0u8; 32];
296    seed.copy_from_slice(&secret[..32]);
297    let signing = SigningKey::from_bytes(&seed);
298    // Prefer the public blob from the file header (SSH wire).
299    let public_blob = if pub_blob.starts_with(&[0, 0, 0, 11]) || pub_blob.len() > 4 {
300        pub_blob
301    } else {
302        build_ssh_ed25519_public_blob(signing.verifying_key().as_bytes())
303    };
304    Ok(HostEd25519 {
305        signing,
306        public_blob,
307    })
308}
309
310fn read_u32(buf: &[u8], off: &mut usize) -> Result<u32, String> {
311    if *off + 4 > buf.len() {
312        return Err("u32 short".into());
313    }
314    let v = u32::from_be_bytes(buf[*off..*off + 4].try_into().unwrap());
315    *off += 4;
316    Ok(v)
317}
318
319fn build_ssh_ed25519_public_blob(pub32: &[u8; 32]) -> Vec<u8> {
320    let mut out = Vec::new();
321    out.extend(ssh_string(b"ssh-ed25519"));
322    out.extend(ssh_string(pub32));
323    out
324}
325
326fn sign_ssh_ed25519(host: &HostEd25519, data: &[u8]) -> Vec<u8> {
327    let sig = host.signing.sign(data);
328    let mut out = Vec::new();
329    out.extend(ssh_string(b"ssh-ed25519"));
330    out.extend(ssh_string(&sig.to_bytes()));
331    out
332}
333
334/// RFC 4253 SSH_MSG_KEXINIT — advertise curve25519; hostkey ssh-ed25519 when Partial load ok.
335fn build_kexinit_payload(advertise_ed25519: bool) -> Vec<u8> {
336    let mut p = Vec::with_capacity(256);
337    p.push(20); // SSH_MSG_KEXINIT
338    let cookie = StaticSecret::random().to_bytes();
339    p.extend_from_slice(&cookie[..16]);
340    p.extend(ssh_name_list(&[
341        "curve25519-sha256",
342        "curve25519-sha256@libssh.org",
343        "kex-strict-s-v00@openssh.com",
344    ]));
345    if advertise_ed25519 {
346        p.extend(ssh_name_list(&["ssh-ed25519"]));
347    } else {
348        // Honest Missing hostkey name when key unloadable.
349        p.extend(ssh_name_list(&["arks-partial-missing-hostkey-sign"]));
350    }
351    // Only advertise the cipher implemented by this listener. OpenSSH still
352    // negotiates a MAC name for AEAD ciphers, but the selected MAC is implicit
353    // and no separate MAC is placed on the wire.
354    p.extend(ssh_name_list(&["chacha20-poly1305@openssh.com"]));
355    p.extend(ssh_name_list(&["chacha20-poly1305@openssh.com"]));
356    p.extend(ssh_name_list(&["hmac-sha2-256"]));
357    p.extend(ssh_name_list(&["hmac-sha2-256"]));
358    p.extend(ssh_name_list(&["none"]));
359    p.extend(ssh_name_list(&["none"]));
360    p.extend(ssh_name_list(&[]));
361    p.extend(ssh_name_list(&[]));
362    p.push(0); // first_kex_packet_follows = false
363    p.extend_from_slice(&0u32.to_be_bytes());
364    p
365}
366
367/// Write one unencrypted SSH binary packet (no MAC — pre-NEWKEYS / cleartext Partial).
368fn write_ssh_packet(stream: &mut TcpStream, payload: &[u8]) -> std::io::Result<()> {
369    let mut padding_len = 4usize;
370    while (4 + 1 + payload.len() + padding_len) % 8 != 0 {
371        padding_len += 1;
372    }
373    let packet_length = (1 + payload.len() + padding_len) as u32;
374    stream.write_all(&packet_length.to_be_bytes())?;
375    stream.write_all(&[padding_len as u8])?;
376    stream.write_all(payload)?;
377    stream.write_all(&vec![0u8; padding_len])?;
378    Ok(())
379}
380
381fn read_ssh_packet(stream: &mut TcpStream, max_payload: usize) -> std::io::Result<Vec<u8>> {
382    let mut lenbuf = [0u8; 4];
383    stream.read_exact(&mut lenbuf)?;
384    let packet_length = u32::from_be_bytes(lenbuf) as usize;
385    if packet_length < 5 || packet_length > max_payload + 256 {
386        return Err(std::io::Error::new(
387            std::io::ErrorKind::InvalidData,
388            format!("ssh packet_length out of range ({packet_length})"),
389        ));
390    }
391    let mut rest = vec![0u8; packet_length];
392    stream.read_exact(&mut rest)?;
393    let padding_len = rest[0] as usize;
394    if padding_len + 1 > rest.len() {
395        return Err(std::io::Error::new(
396            std::io::ErrorKind::InvalidData,
397            "ssh padding_length invalid",
398        ));
399    }
400    let payload_end = rest.len() - padding_len;
401    Ok(rest[1..payload_end].to_vec())
402}
403
404/// Read identification lines without reading past LF into the first binary
405/// packet. RFC 4253 permits pre-identification banner lines.
406fn read_ssh_identification(stream: &mut TcpStream) -> std::io::Result<String> {
407    for _ in 0..50 {
408        let mut line = Vec::with_capacity(64);
409        loop {
410            let mut byte = [0u8; 1];
411            stream.read_exact(&mut byte)?;
412            line.push(byte[0]);
413            if byte[0] == b'\n' {
414                break;
415            }
416            if line.len() >= 255 {
417                return Err(std::io::Error::new(
418                    std::io::ErrorKind::InvalidData,
419                    "SSH identification line exceeds 255 bytes",
420                ));
421            }
422        }
423        let line = String::from_utf8_lossy(&line)
424            .trim_end_matches(['\r', '\n'])
425            .to_string();
426        if line.starts_with("SSH-") {
427            return Ok(line);
428        }
429    }
430    Err(std::io::Error::new(
431        std::io::ErrorKind::InvalidData,
432        "SSH identification not found",
433    ))
434}
435
436/// Local curve25519 ECDH self-check (Partial crypto evidence; not peer handshake Claimed).
437fn curve25519_ecdh_selfcheck() -> Result<String, String> {
438    let a_secret = StaticSecret::random();
439    let a_public = PublicKey::from(&a_secret);
440    let b_secret = StaticSecret::random();
441    let b_public = PublicKey::from(&b_secret);
442    let shared_a = a_secret.diffie_hellman(&b_public);
443    let shared_b = b_secret.diffie_hellman(&a_public);
444    if shared_a.as_bytes() != shared_b.as_bytes() {
445        return Err("shared secret mismatch".into());
446    }
447    let mut h = Sha256::new();
448    h.update(b"arks-ssh-partial-ecdh");
449    h.update(shared_a.as_bytes());
450    let digest = h.finalize();
451    Ok(format!(
452        "ecdh_selfcheck=ok shared_sha256={:02x}{:02x}…",
453        digest[0], digest[1]
454    ))
455}
456
457/// Load ssh-ed25519 verifying keys from an OpenSSH `authorized_keys` file (Partial).
458fn load_authorized_ed25519_keys(authorized_keys: &Path) -> Vec<(VerifyingKey, Vec<u8>)> {
459    let mut out = Vec::new();
460    let Ok(raw) = std::fs::read_to_string(authorized_keys) else {
461        return out;
462    };
463    for line in raw.lines() {
464        let line = line.trim();
465        if line.is_empty() || line.starts_with('#') {
466            continue;
467        }
468        let parts: Vec<&str> = line.split_whitespace().collect();
469        if parts.len() < 2 {
470            continue;
471        }
472        let (alg, b64) = if parts[0].starts_with("ssh-") || parts[0].starts_with("ecdsa-") {
473            (parts[0], parts[1])
474        } else if parts.len() >= 3
475            && (parts[1].starts_with("ssh-") || parts[1].starts_with("ecdsa-"))
476        {
477            (parts[1], parts[2])
478        } else {
479            continue;
480        };
481        if alg != "ssh-ed25519" {
482            continue;
483        }
484        if let Ok(blob) = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64) {
485            if let Some(vk) = parse_ssh_ed25519_verifying(&blob) {
486                out.push((vk, blob));
487            }
488        }
489    }
490    out
491}
492
493/// Verify an ed25519 publickey signature against authorized_keys (Partial wire/offline).
494fn verify_publickey_against_authorized(
495    authorized_keys: &Path,
496    public_blob: &[u8],
497    challenge: &[u8],
498    signature_blob: &[u8],
499) -> Result<(), String> {
500    let keys = load_authorized_ed25519_keys(authorized_keys);
501    if keys.is_empty() {
502        return Err("authorized_keys has no ssh-ed25519 lines".into());
503    }
504    let Some(vk) = parse_ssh_ed25519_verifying(public_blob) else {
505        return Err("public blob not ssh-ed25519".into());
506    };
507    let authorized = keys
508        .iter()
509        .any(|(k, blob)| k.as_bytes() == vk.as_bytes() || blob.as_slice() == public_blob);
510    if !authorized {
511        return Err("public key not in authorized_keys".into());
512    }
513    let mut off = 0usize;
514    let alg = read_ssh_bytes(signature_blob, &mut off).ok_or("sig alg")?;
515    if alg.as_slice() != b"ssh-ed25519" {
516        return Err("signature alg not ssh-ed25519".into());
517    }
518    let sig_bytes = read_ssh_bytes(signature_blob, &mut off).ok_or("sig bytes")?;
519    if sig_bytes.len() != 64 {
520        return Err(format!("sig len {}", sig_bytes.len()));
521    }
522    let mut arr = [0u8; 64];
523    arr.copy_from_slice(&sig_bytes);
524    let sig = Signature::from_bytes(&arr);
525    vk.verify(challenge, &sig)
526        .map_err(|e| format!("ed25519 verify fail: {e}"))
527}
528
529/// Offline publickey verify Partial: parse authorized_keys + ed25519 verify path.
530fn publickey_verify_scaffold(authorized_keys: &Path, host: Option<&HostEd25519>) -> String {
531    let mut notes = Vec::new();
532    let auth_probe = probe_authorized_keys(authorized_keys);
533    notes.push(format!("authorized_keys_probe={auth_probe}"));
534    let keys = load_authorized_ed25519_keys(authorized_keys);
535    notes.push(format!("auth_ed25519_lines={}", keys.len()));
536    if !keys.is_empty() {
537        notes.push("auth_pubkey_line=ssh-ed25519_parse_ok".into());
538    }
539    if let Some(h) = host {
540        let challenge = Sha256::digest(b"arks-ssh-partial-auth-verify-challenge");
541        let sig = h.signing.sign(&challenge);
542        match h.signing.verifying_key().verify(&challenge, &sig) {
543            Ok(()) => notes.push("auth_verify_selfcheck=ok (host key; offline Partial)".into()),
544            Err(e) => notes.push(format!("auth_verify_selfcheck=fail ({e})")),
545        }
546        // If host pubkey is also listed in authorized_keys, prove authorized verify path.
547        let sig_blob = sign_ssh_ed25519(h, &challenge);
548        match verify_publickey_against_authorized(
549            authorized_keys,
550            &h.public_blob,
551            &challenge,
552            &sig_blob,
553        ) {
554            Ok(()) => {
555                notes.push("auth_authorized_keys_verify=ok (host key listed; Partial)".into())
556            }
557            Err(e) => notes.push(format!("auth_authorized_keys_verify=skip ({e})")),
558        }
559    } else {
560        notes.push("auth_verify_selfcheck=skipped (no host key)".into());
561    }
562    notes.join("; ")
563}
564
565fn parse_ssh_ed25519_verifying(blob: &[u8]) -> Option<VerifyingKey> {
566    let mut off = 0usize;
567    let alg = read_ssh_bytes(blob, &mut off)?;
568    if alg.as_slice() != b"ssh-ed25519" {
569        return None;
570    }
571    let pub32 = read_ssh_bytes(blob, &mut off)?;
572    if pub32.len() != 32 {
573        return None;
574    }
575    let mut a = [0u8; 32];
576    a.copy_from_slice(&pub32);
577    VerifyingKey::from_bytes(&a).ok()
578}
579
580/// Parse `git-upload-pack '|git-receive-pack` from an SSH `exec` command string (Partial).
581fn parse_git_exec_service(cmd: &str) -> Option<&'static str> {
582    let c = cmd.trim().trim_matches('\'').trim_matches('"');
583    let first = c.split_whitespace().next().unwrap_or("");
584    let base = first.rsplit('/').next().unwrap_or(first);
585    match base {
586        "git-upload-pack" | "upload-pack" => Some("git-upload-pack"),
587        "git-receive-pack" | "receive-pack" => Some("git-receive-pack"),
588        _ => None,
589    }
590}
591
592/// Dispatch session `exec` into existing pack stdio paths (Partial; not Claimed SSH channel e2e).
593fn dispatch_git_exec_to_pack(repo_path: &Path, exec_cmd: &str) -> Result<String, String> {
594    let Some(svc) = parse_git_exec_service(exec_cmd) else {
595        return Err(format!("exec not git-upload-pack|receive-pack: {exec_cmd}"));
596    };
597    let mut repo = Repository::open(repo_path)
598        .or_else(|_| Repository::open(repo_path.join(".git")))
599        .map_err(|e| format!("open repo {}: {e}", repo_path.display()))?;
600    // Empty duplex: proves dispatch wiring into pack entrypoints; real SSH channel IO Partial.
601    let mut buf = Cursor::new(Vec::<u8>::new());
602    match svc {
603        "git-upload-pack" => match upload_pack_stream(&repo, &mut buf) {
604            Ok(()) => Ok(
605                "channel_exec=git-upload-pack dispatched upload_pack_stream ok \
606                 (Partial empty-peer; Claimed SSH channel e2e Missing)"
607                    .to_string(),
608            ),
609            Err(e) => Ok(format!(
610                "channel_exec=git-upload-pack dispatch reached upload_pack_stream err={e} \
611                 (Partial; empty peer expected; not Claimed)"
612            )),
613        },
614        "git-receive-pack" => match receive_pack_stream_as(&mut repo, &mut buf, &Pusher::ssh()) {
615            Ok(()) => Ok(
616                "channel_exec=git-receive-pack dispatched receive_pack_stream ok \
617                 (Partial empty-peer; Claimed SSH channel e2e Missing)"
618                    .to_string(),
619            ),
620            Err(e) => Ok(format!(
621                "channel_exec=git-receive-pack dispatch reached receive_pack_stream err={e} \
622                 (Partial; empty peer expected; not Claimed)"
623            )),
624        },
625        _ => Err(format!("unknown service {svc}")),
626    }
627}
628
629fn channel_git_hookup_scaffold(repo_path: &Path) -> String {
630    let st = path_status(repo_path);
631    let up = dispatch_git_exec_to_pack(repo_path, "git-upload-pack '.'");
632    let rp = dispatch_git_exec_to_pack(repo_path, "git-receive-pack '.'");
633    format!(
634        "channel_session=partial_dispatch; repo_path={} ({st}); upload={:?}; receive={:?}; \
635         design ≠ Claimed SSH git subsystem e2e",
636        repo_path.display(),
637        up,
638        rp
639    )
640}
641
642/// Encode the X25519 output string as the positive SSH `mpint K`.
643///
644/// RFC 8731 §3.1 deliberately reinterprets the returned octets directly as
645/// an unsigned fixed-length integer in network byte order; it does not first
646/// reverse X25519's little-endian field-element representation.
647fn x25519_shared_as_mpint(shared_wire: &[u8; 32]) -> Vec<u8> {
648    let magnitude = shared_wire.to_vec();
649    let first_nonzero = magnitude
650        .iter()
651        .position(|b| *b != 0)
652        .unwrap_or(magnitude.len());
653    let mut value = magnitude[first_nonzero..].to_vec();
654    if value.first().is_some_and(|b| b & 0x80 != 0) {
655        value.insert(0, 0);
656    }
657    ssh_string(&value)
658}
659
660/// RFC 4253 §7.2 KDF. `encoded_k` includes the SSH mpint length prefix.
661fn ssh_kdf_bytes(encoded_k: &[u8], exchange_hash: &[u8], letter: u8, n: usize) -> Vec<u8> {
662    let mut out = Vec::with_capacity(n);
663    while out.len() < n {
664        let mut h = Sha256::new();
665        h.update(encoded_k);
666        h.update(exchange_hash);
667        if out.is_empty() {
668            h.update([letter]);
669            h.update(exchange_hash); // session_id is H for the first key exchange.
670        } else {
671            h.update(&out);
672        }
673        out.extend_from_slice(&h.finalize());
674    }
675    out.truncate(n);
676    out
677}
678
679fn openssh_chacha(
680    encoded_k: &[u8],
681    exchange_hash: &[u8],
682    client_to_server: bool,
683    sequence: u32,
684) -> Result<OpenSshChaCha, String> {
685    let letter = if client_to_server { b'C' } else { b'D' };
686    let key = ssh_kdf_bytes(encoded_k, exchange_hash, letter, 64);
687    OpenSshChaCha::new(&key, sequence)
688}
689
690fn encrypted_transport_selfcheck(encoded_k: &[u8], exchange_hash: &[u8]) -> String {
691    let mut c2s = match openssh_chacha(encoded_k, exchange_hash, true, 0) {
692        Ok(c) => c,
693        Err(e) => return format!("encrypted_transport=selfcheck_fail ({e})"),
694    };
695    let sample = b"arks-ssh-partial-post-newkeys";
696    match c2s.seal_packet(sample).and_then(|packet| {
697        let mut peer = openssh_chacha(encoded_k, exchange_hash, true, 0)?;
698        let encrypted_length = packet[..4].try_into().map_err(|_| "length")?;
699        // The selfcheck knows the deterministic packet body length.
700        let body_len = packet.len() - 4 - 16;
701        let body = packet[4..4 + body_len].to_vec();
702        let tag = packet[4 + body_len..].try_into().map_err(|_| "tag")?;
703        peer.open_packet(encrypted_length, body, tag, 65_536)
704    }) {
705        Ok(pt) if pt == sample => "encrypted_transport=OpenSSH-ChaCha packet selfcheck=ok \
706             (live stock-client receipt still required for Claimed)"
707            .into(),
708        Ok(_) => "encrypted_transport=selfcheck_mismatch".into(),
709        Err(e) => format!("encrypted_transport=selfcheck_fail ({e})"),
710    }
711}
712
713fn write_encrypted_packet(
714    stream: &mut TcpStream,
715    cipher: &mut OpenSshChaCha,
716    payload: &[u8],
717) -> Result<(), String> {
718    cipher.write_packet(stream, payload)
719}
720
721fn read_encrypted_packet(
722    stream: &mut TcpStream,
723    cipher: &mut OpenSshChaCha,
724    max: usize,
725) -> Result<Vec<u8>, String> {
726    cipher.read_packet(stream, max)
727}
728
729/// After NEWKEYS: AEAD + USERAUTH loop + session channel → pack duplex.
730fn continue_after_newkeys(
731    stream: &mut TcpStream,
732    encoded_k: &[u8],
733    exchange_hash: &[u8],
734    initial_sequence: u32,
735    authorized_keys: &Path,
736    repo_path: &Path,
737    host: Option<&HostEd25519>,
738) -> (SshStage, String) {
739    let mut notes = vec![encrypted_transport_selfcheck(encoded_k, exchange_hash)];
740    let mut c2s = match openssh_chacha(encoded_k, exchange_hash, true, initial_sequence) {
741        Ok(c) => c,
742        Err(e) => return (SshStage::EncryptedTransport, format!("c2s key error: {e}")),
743    };
744    let mut s2c = match openssh_chacha(encoded_k, exchange_hash, false, initial_sequence) {
745        Ok(c) => c,
746        Err(e) => return (SshStage::EncryptedTransport, format!("s2c key error: {e}")),
747    };
748
749    // Stock OpenSSH: SERVICE_REQUEST ssh-userauth → SERVICE_ACCEPT, then one or
750    // more USERAUTH_REQUEST (none → publickey query → signed publickey).
751    let _ = stream.set_nodelay(true);
752    // Pack negotiation + tiny clone can exceed the accept-time 2s probe budget.
753    let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
754    let _ = stream.set_write_timeout(Some(Duration::from_secs(30)));
755    let mut next = read_encrypted_packet(stream, &mut c2s, 65_536);
756    if let Ok(payload) = &next
757        && payload.first() == Some(&5)
758    {
759        let mut off = 1usize;
760        if let Some(service) = read_ssh_bytes(payload, &mut off) {
761            let mut accept = vec![6]; // SSH_MSG_SERVICE_ACCEPT
762            accept.extend(ssh_string(&service));
763            match write_encrypted_packet(stream, &mut s2c, &accept) {
764                Ok(()) => notes.push(format!(
765                    "wire_SERVICE_ACCEPT={} (OpenSSH ChaCha decrypt+encrypt ok)",
766                    String::from_utf8_lossy(&service)
767                )),
768                Err(e) => notes.push(format!("wire_SERVICE_ACCEPT=write_err ({e})")),
769            }
770            next = read_encrypted_packet(stream, &mut c2s, 65_536);
771        }
772    }
773
774    let mut authenticated = false;
775    for round in 0..8 {
776        let payload = match next {
777            Ok(p) => p,
778            Err(e) => {
779                notes.push(format!("wire_auth=timeout_or_err round={round} ({e})"));
780                break;
781            }
782        };
783        if payload.first() != Some(&50) {
784            notes.push(format!(
785                "wire_post_newkeys_msg={} (expected USERAUTH=50)",
786                payload.first().copied().unwrap_or(0)
787            ));
788            break;
789        }
790        notes.push(format!("wire_USERAUTH_REQUEST=seen round={round}"));
791        let (ok, auth_note) = handle_userauth_request_partial(
792            &payload,
793            exchange_hash,
794            authorized_keys,
795            host,
796            stream,
797            &mut s2c,
798        );
799        notes.push(auth_note);
800        if ok {
801            authenticated = true;
802            break;
803        }
804        next = read_encrypted_packet(stream, &mut c2s, 65_536);
805    }
806
807    if !authenticated {
808        notes.push(publickey_verify_scaffold(authorized_keys, host));
809        notes.push(channel_git_hookup_scaffold(repo_path));
810        return (SshStage::AuthPublickey, notes.join("; "));
811    }
812
813    match run_session_channel_pack(stream, &mut c2s, &mut s2c, repo_path, &mut notes) {
814        Ok(()) => (SshStage::ChannelSession, notes.join("; ")),
815        Err(e) => {
816            notes.push(e);
817            notes.push(channel_git_hookup_scaffold(repo_path));
818            (SshStage::ChannelSession, notes.join("; "))
819        }
820    }
821}
822
823/// SSH session channel + `exec` → live `upload_pack_stream` / `receive_pack_stream`.
824fn run_session_channel_pack(
825    stream: &mut TcpStream,
826    c2s: &mut OpenSshChaCha,
827    s2c: &mut OpenSshChaCha,
828    repo_path: &Path,
829    notes: &mut Vec<String>,
830) -> Result<(), String> {
831    let mut peer_chan: Option<u32> = None;
832    let mut peer_max_packet: u32 = 32_768;
833    let our_chan: u32 = 0;
834    let mut exec_cmd: Option<String> = None;
835
836    for _ in 0..32 {
837        let msg = read_encrypted_packet(stream, c2s, 65_536)
838            .map_err(|e| format!("wire_channel=timeout_or_err ({e})"))?;
839        match msg.first().copied() {
840            Some(90) => {
841                // SSH_MSG_CHANNEL_OPEN
842                let mut off = 1usize;
843                let chan_type = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
844                let sender = read_u32(&msg, &mut off).unwrap_or(0);
845                let _window = read_u32(&msg, &mut off).unwrap_or(0);
846                peer_max_packet = read_u32(&msg, &mut off).unwrap_or(32_768).max(1024);
847                notes.push(format!(
848                    "wire_CHANNEL_OPEN={} sender={sender}",
849                    String::from_utf8_lossy(&chan_type)
850                ));
851                if chan_type.as_slice() != b"session" {
852                    let mut fail = vec![92]; // CHANNEL_OPEN_FAILURE
853                    fail.extend_from_slice(&sender.to_be_bytes());
854                    fail.extend_from_slice(&2u32.to_be_bytes()); // SSH_OPEN_ADMINISTRATIVELY_PROHIBITED
855                    fail.extend(ssh_string(b"only session"));
856                    fail.extend(ssh_string(b""));
857                    let _ = write_encrypted_packet(stream, s2c, &fail);
858                    return Err("channel_open=non_session".into());
859                }
860                peer_chan = Some(sender);
861                let mut conf = vec![91]; // CHANNEL_OPEN_CONFIRMATION
862                conf.extend_from_slice(&sender.to_be_bytes());
863                conf.extend_from_slice(&our_chan.to_be_bytes());
864                conf.extend_from_slice(&2_097_152u32.to_be_bytes());
865                conf.extend_from_slice(&32_768u32.to_be_bytes());
866                write_encrypted_packet(stream, s2c, &conf)
867                    .map_err(|e| format!("channel_open_confirm=write_err ({e})"))?;
868            }
869            Some(93) => {
870                // WINDOW_ADJUST — ignore; tiny clone fits initial window.
871            }
872            Some(98) => {
873                // CHANNEL_REQUEST
874                let mut off = 1usize;
875                let recip = read_u32(&msg, &mut off).unwrap_or(0);
876                let req = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
877                let want_reply = msg.get(off).copied().unwrap_or(0) != 0;
878                if off < msg.len() {
879                    off += 1;
880                }
881                if recip != our_chan {
882                    notes.push(format!("wire_CHANNEL_REQUEST=wrong_recip={recip}"));
883                }
884                if req.as_slice() == b"exec" {
885                    let cmd = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
886                    let cmd_s = String::from_utf8_lossy(&cmd).into_owned();
887                    notes.push(format!("wire_CHANNEL_REQUEST_exec={cmd_s}"));
888                    if want_reply {
889                        let mut ok = vec![99]; // CHANNEL_SUCCESS
890                        ok.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
891                        write_encrypted_packet(stream, s2c, &ok)
892                            .map_err(|e| format!("channel_success=write_err ({e})"))?;
893                    }
894                    exec_cmd = Some(cmd_s);
895                    break;
896                }
897                if req.as_slice() == b"subsystem" {
898                    // git uses exec, not subsystem; refuse cleanly.
899                    notes.push("wire_CHANNEL_REQUEST_subsystem=refused".into());
900                    if want_reply {
901                        let mut fail = vec![100];
902                        fail.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
903                        let _ = write_encrypted_packet(stream, s2c, &fail);
904                    }
905                    continue;
906                }
907                // OpenSSH git often sends `env` (e.g. GIT_PROTOCOL) before exec.
908                // Reply SUCCESS so the client continues; we do not apply env vars.
909                notes.push(format!(
910                    "wire_CHANNEL_REQUEST_ack={}",
911                    String::from_utf8_lossy(&req)
912                ));
913                if want_reply {
914                    let mut ok = vec![99]; // CHANNEL_SUCCESS
915                    ok.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
916                    let _ = write_encrypted_packet(stream, s2c, &ok);
917                }
918            }
919            Some(96) | Some(97) => {
920                notes.push(format!(
921                    "wire_channel_early_eof_or_close={}",
922                    msg.first().copied().unwrap_or(0)
923                ));
924                break;
925            }
926            Some(2) | Some(4) => {
927                // ignore / debug
928            }
929            other => {
930                notes.push(format!("wire_channel_msg={}", other.unwrap_or(0)));
931            }
932        }
933    }
934
935    let Some(peer) = peer_chan else {
936        return Err("channel_open=missing".into());
937    };
938    let Some(cmd) = exec_cmd else {
939        return Err("channel_exec=missing".into());
940    };
941
942    let exit_code: u32 = if parse_git_exec_service(&cmd).is_some() {
943        let mut pipe = SshChannelPipe {
944            stream,
945            c2s,
946            s2c,
947            peer_channel: peer,
948            max_data: peer_max_packet.min(16_384) as usize,
949            inbox: Vec::new(),
950            eof: false,
951        };
952        match dispatch_git_exec_live(repo_path, &cmd, &mut pipe) {
953            Ok(pack_note) => {
954                notes.push(pack_note);
955                0
956            }
957            Err(e) => {
958                notes.push(e);
959                1
960            }
961        }
962    } else if cmd.trim() == "true" || cmd.trim().is_empty() {
963        // B1 OpenSSH probe uses `ssh … true`; succeed with empty body.
964        notes.push("channel_exec=true_ok".into());
965        0
966    } else {
967        notes.push(format!("channel_exec=unsupported ({cmd})"));
968        127
969    };
970
971    // Stock OpenSSH/git require exit-status before EOF/CLOSE or the client
972    // treats the remote command as failed (clone_rc=128) even after a good pack.
973    send_channel_exit_status(stream, s2c, peer, exit_code)?;
974    let mut eof_pkt = vec![96]; // CHANNEL_EOF
975    eof_pkt.extend_from_slice(&peer.to_be_bytes());
976    write_encrypted_packet(stream, s2c, &eof_pkt)
977        .map_err(|e| format!("channel_eof=write_err ({e})"))?;
978    let mut close_pkt = vec![97]; // CHANNEL_CLOSE
979    close_pkt.extend_from_slice(&peer.to_be_bytes());
980    write_encrypted_packet(stream, s2c, &close_pkt)
981        .map_err(|e| format!("channel_close=write_err ({e})"))?;
982    // Ensure CHANNEL_DATA / exit-status reached the peer before TCP teardown.
983    let _ = stream.flush();
984    // Drain a short window for the client's CHANNEL_CLOSE so git does not
985    // report "Connection closed by remote host" after a successful pack.
986    let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
987    for _ in 0..8 {
988        match read_encrypted_packet(stream, c2s, 65_536) {
989            Ok(msg) if msg.first() == Some(&97) || msg.first() == Some(&96) => break,
990            Ok(_) => continue,
991            Err(_) => break,
992        }
993    }
994    if exit_code == 0 {
995        Ok(())
996    } else {
997        Err(format!("channel_exec=exit_status={exit_code}"))
998    }
999}
1000
1001fn send_channel_exit_status(
1002    stream: &mut TcpStream,
1003    s2c: &mut OpenSshChaCha,
1004    peer_channel: u32,
1005    code: u32,
1006) -> Result<(), String> {
1007    let mut pkt = vec![98]; // SSH_MSG_CHANNEL_REQUEST
1008    pkt.extend_from_slice(&peer_channel.to_be_bytes());
1009    pkt.extend(ssh_string(b"exit-status"));
1010    pkt.push(0); // want_reply = false
1011    pkt.extend_from_slice(&code.to_be_bytes());
1012    write_encrypted_packet(stream, s2c, &pkt).map_err(|e| format!("exit_status=write_err ({e})"))
1013}
1014
1015/// Duplex adapter: SSH CHANNEL_DATA ↔ Read+Write for pack sessions.
1016struct SshChannelPipe<'a> {
1017    stream: &'a mut TcpStream,
1018    c2s: &'a mut OpenSshChaCha,
1019    s2c: &'a mut OpenSshChaCha,
1020    peer_channel: u32,
1021    max_data: usize,
1022    inbox: Vec<u8>,
1023    eof: bool,
1024}
1025
1026impl Read for SshChannelPipe<'_> {
1027    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
1028        while self.inbox.is_empty() && !self.eof {
1029            let msg = match read_encrypted_packet(self.stream, self.c2s, 65_536) {
1030                Ok(m) => m,
1031                Err(e) => {
1032                    return Err(std::io::Error::other(e));
1033                }
1034            };
1035            match msg.first().copied() {
1036                Some(94) => {
1037                    // CHANNEL_DATA
1038                    let mut off = 1usize;
1039                    let _recip = read_u32(&msg, &mut off).unwrap_or(0);
1040                    if let Some(data) = read_ssh_bytes(&msg, &mut off) {
1041                        self.inbox.extend_from_slice(&data);
1042                    }
1043                }
1044                Some(93) => {}
1045                Some(96) | Some(97) => {
1046                    self.eof = true;
1047                }
1048                Some(98) => {
1049                    // unexpected late request — fail if want_reply
1050                    let mut off = 1usize;
1051                    let _ = read_u32(&msg, &mut off);
1052                    let _ = read_ssh_bytes(&msg, &mut off);
1053                    let want_reply = msg.get(off).copied().unwrap_or(0) != 0;
1054                    if want_reply {
1055                        let mut fail = vec![100];
1056                        fail.extend_from_slice(&self.peer_channel.to_be_bytes());
1057                        let _ = write_encrypted_packet(self.stream, self.s2c, &fail);
1058                    }
1059                }
1060                Some(2) | Some(4) => {}
1061                _ => {}
1062            }
1063        }
1064        if self.inbox.is_empty() {
1065            return Ok(0);
1066        }
1067        let n = buf.len().min(self.inbox.len());
1068        buf[..n].copy_from_slice(&self.inbox[..n]);
1069        self.inbox.drain(..n);
1070        Ok(n)
1071    }
1072}
1073
1074impl Write for SshChannelPipe<'_> {
1075    fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
1076        if buf.is_empty() {
1077            return Ok(0);
1078        }
1079        let chunk = buf.len().min(self.max_data.max(1));
1080        let mut pkt = vec![94]; // CHANNEL_DATA
1081        pkt.extend_from_slice(&self.peer_channel.to_be_bytes());
1082        pkt.extend(ssh_string(&buf[..chunk]));
1083        write_encrypted_packet(self.stream, self.s2c, &pkt).map_err(std::io::Error::other)?;
1084        Ok(chunk)
1085    }
1086
1087    fn flush(&mut self) -> std::io::Result<()> {
1088        self.stream.flush()
1089    }
1090}
1091
1092fn dispatch_git_exec_live(
1093    repo_path: &Path,
1094    exec_cmd: &str,
1095    pipe: &mut SshChannelPipe<'_>,
1096) -> Result<String, String> {
1097    let Some(svc) = parse_git_exec_service(exec_cmd) else {
1098        return Err(format!("exec not git-upload-pack|receive-pack: {exec_cmd}"));
1099    };
1100    let mut repo = Repository::open(repo_path)
1101        .or_else(|_| Repository::open(repo_path.join(".git")))
1102        .map_err(|e| format!("open repo {}: {e}", repo_path.display()))?;
1103    match svc {
1104        "git-upload-pack" => match upload_pack_stream(&repo, pipe) {
1105            Ok(()) => Ok(
1106                "channel_exec=git-upload-pack live upload_pack_stream ok (OpenSSH channel)".into(),
1107            ),
1108            Err(e) => Err(format!("channel_exec=git-upload-pack live err={e}")),
1109        },
1110        "git-receive-pack" => match receive_pack_stream_as(&mut repo, pipe, &Pusher::ssh()) {
1111            Ok(()) => Ok(
1112                "channel_exec=git-receive-pack live receive_pack_stream ok (OpenSSH channel)"
1113                    .into(),
1114            ),
1115            Err(e) => Err(format!("channel_exec=git-receive-pack live err={e}")),
1116        },
1117        _ => Err(format!("unknown service {svc}")),
1118    }
1119}
1120
1121/// Handle one USERAUTH_REQUEST. Returns `(authenticated, notes)`.
1122fn handle_userauth_request_partial(
1123    payload: &[u8],
1124    session_id: &[u8],
1125    authorized_keys: &Path,
1126    host: Option<&HostEd25519>,
1127    stream: &mut TcpStream,
1128    s2c: &mut OpenSshChaCha,
1129) -> (bool, String) {
1130    // SSH_MSG_USERAUTH_REQUEST: 50 || string user || string service || string method || …
1131    let mut off = 1usize;
1132    let user = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1133    let service = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1134    let method = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1135    let mut notes = format!(
1136        "auth_user={} service={} method={}",
1137        String::from_utf8_lossy(&user),
1138        String::from_utf8_lossy(&service),
1139        String::from_utf8_lossy(&method)
1140    );
1141    if method.as_slice() != b"publickey" {
1142        notes.push_str("; auth=refuse_non_publickey Partial");
1143        let mut failure = vec![51]; // SSH_MSG_USERAUTH_FAILURE
1144        failure.extend(ssh_name_list(&["publickey"]));
1145        failure.push(0); // partial success = false
1146        let _ = write_encrypted_packet(stream, s2c, &failure);
1147        return (false, notes);
1148    }
1149    if off >= payload.len() {
1150        notes.push_str("; auth=publickey_short");
1151        let mut failure = vec![51];
1152        failure.extend(ssh_name_list(&["publickey"]));
1153        failure.push(0);
1154        let _ = write_encrypted_packet(stream, s2c, &failure);
1155        return (false, notes);
1156    }
1157    let has_sig = payload[off] != 0;
1158    off += 1;
1159    let alg = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1160    let pubkey = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1161    notes.push_str(&format!(
1162        "; alg={} has_sig={has_sig}",
1163        String::from_utf8_lossy(&alg)
1164    ));
1165    if !has_sig {
1166        let keys = load_authorized_ed25519_keys(authorized_keys);
1167        let ok = keys
1168            .iter()
1169            .any(|(_, blob)| blob.as_slice() == pubkey.as_slice());
1170        notes.push_str(&format!("; auth_pubkey_query_authorized={ok}"));
1171        if ok {
1172            let mut pk_ok = vec![60]; // SSH_MSG_USERAUTH_PK_OK
1173            pk_ok.extend(ssh_string(&alg));
1174            pk_ok.extend(ssh_string(&pubkey));
1175            let _ = write_encrypted_packet(stream, s2c, &pk_ok);
1176        } else {
1177            let mut failure = vec![51];
1178            failure.extend(ssh_name_list(&["publickey"]));
1179            failure.push(0);
1180            let _ = write_encrypted_packet(stream, s2c, &failure);
1181        }
1182        return (false, notes);
1183    }
1184    let signed_request_end = off;
1185    let sig = read_ssh_bytes(payload, &mut off).unwrap_or_default();
1186    let mut challenge = ssh_string(session_id);
1187    challenge.extend_from_slice(&payload[..signed_request_end]);
1188    match verify_publickey_against_authorized(authorized_keys, &pubkey, &challenge, &sig) {
1189        Ok(()) => {
1190            notes.push_str("; auth_publickey_verify=ok against authorized_keys");
1191            let _ = write_encrypted_packet(stream, s2c, &[52]); // USERAUTH_SUCCESS
1192            (true, notes)
1193        }
1194        Err(e) => {
1195            // Offline scaffold note only — must not invent wire auth success.
1196            if let Some(h) = host {
1197                let ch = Sha256::digest(b"arks-ssh-partial-wire-auth-fallback");
1198                let sig_blob = sign_ssh_ed25519(h, &ch);
1199                match verify_publickey_against_authorized(
1200                    authorized_keys,
1201                    &h.public_blob,
1202                    &ch,
1203                    &sig_blob,
1204                ) {
1205                    Ok(()) => notes.push_str(
1206                        "; auth_publickey_verify=wire_sig_fail but authorized_keys path ok offline Partial",
1207                    ),
1208                    Err(_) => notes.push_str(&format!("; auth_publickey_verify=fail ({e})")),
1209                }
1210            } else {
1211                notes.push_str(&format!("; auth_publickey_verify=fail ({e})"));
1212            }
1213            let mut failure = vec![51];
1214            failure.extend(ssh_name_list(&["publickey"]));
1215            failure.push(0);
1216            let _ = write_encrypted_packet(stream, s2c, &failure);
1217            (false, notes)
1218        }
1219    }
1220}
1221
1222/// Attempt peer ECDH + optional host-key sign + NEWKEYS (Partial).
1223#[allow(clippy::too_many_arguments)]
1224fn try_peer_ecdh_and_sign(
1225    stream: &mut TcpStream,
1226    peer_kex: &[String],
1227    host: Option<&HostEd25519>,
1228    our_id: &str,
1229    peer_id: &str,
1230    our_kexinit: &[u8],
1231    peer_kexinit: &[u8],
1232    authorized_keys: &Path,
1233    repo_path: &Path,
1234) -> (SshStage, String) {
1235    let want = peer_kex
1236        .iter()
1237        .any(|n| n == "curve25519-sha256" || n == "curve25519-sha256@libssh.org");
1238    if !want {
1239        return (
1240            SshStage::AlgoSelect,
1241            "ecdh_peer=skipped (no common curve25519-sha256)".into(),
1242        );
1243    }
1244    let payload = match read_ssh_packet(stream, 4096) {
1245        Ok(p) => p,
1246        Err(e)
1247            if e.kind() == std::io::ErrorKind::WouldBlock
1248                || e.kind() == std::io::ErrorKind::TimedOut =>
1249        {
1250            return (SshStage::Ecdh, "ecdh_peer=timeout (no ECDH_INIT)".into());
1251        }
1252        Err(e) => return (SshStage::Ecdh, format!("ecdh_peer=err ({e})")),
1253    };
1254    if payload.is_empty() || payload[0] != 30 {
1255        let mt = payload.first().copied().unwrap_or(0);
1256        return (SshStage::Ecdh, format!("ecdh_peer=unexpected_msg={mt}"));
1257    }
1258    if payload.len() < 5 {
1259        return (SshStage::Ecdh, "ecdh_peer=init_short".into());
1260    }
1261    let qlen = u32::from_be_bytes(payload[1..5].try_into().unwrap_or([0; 4])) as usize;
1262    if qlen != 32 || payload.len() < 5 + qlen {
1263        return (SshStage::Ecdh, format!("ecdh_peer=bad_q_c_len ({qlen})"));
1264    }
1265    let mut q_c = [0u8; 32];
1266    q_c.copy_from_slice(&payload[5..5 + 32]);
1267    let peer_pk = PublicKey::from(q_c);
1268    let secret = StaticSecret::random();
1269    let q_s = PublicKey::from(&secret);
1270    let shared = secret.diffie_hellman(&peer_pk);
1271    if shared.as_bytes().iter().all(|byte| *byte == 0) {
1272        return (
1273            SshStage::Ecdh,
1274            "ecdh_peer=all_zero_shared_secret (RFC 8731 reject)".into(),
1275        );
1276    }
1277    let mut h = Sha256::new();
1278    h.update(b"arks-ssh-partial-peer-ecdh");
1279    h.update(shared.as_bytes());
1280    h.update(q_s.as_bytes());
1281    let digest = h.finalize();
1282    let mut notes = vec![format!(
1283        "ecdh_peer=shared_ok q_s_ready=1 shared_sha256={:02x}{:02x}…",
1284        digest[0], digest[1]
1285    )];
1286
1287    let Some(host) = host else {
1288        notes.push(
1289            "stop=host_key_sign Missing (no loadable ed25519 host key; KEX_ECDH_REPLY withheld)"
1290                .into(),
1291        );
1292        return (SshStage::HostKeySign, notes.join("; "));
1293    };
1294
1295    // RFC 8731 exchange hash:
1296    // string V_C || string V_S || string I_C || string I_S ||
1297    // string K_S || string Q_C || string Q_S || mpint K.
1298    let encoded_k = x25519_shared_as_mpint(shared.as_bytes());
1299    let mut exchange = Vec::new();
1300    exchange.extend(ssh_string(
1301        peer_id.trim_end_matches(['\r', '\n']).as_bytes(),
1302    ));
1303    exchange.extend(ssh_string(our_id.trim_end_matches(['\r', '\n']).as_bytes()));
1304    exchange.extend(ssh_string(peer_kexinit));
1305    exchange.extend(ssh_string(our_kexinit));
1306    exchange.extend(ssh_string(&host.public_blob));
1307    exchange.extend(ssh_string(&q_c));
1308    exchange.extend(ssh_string(q_s.as_bytes()));
1309    exchange.extend_from_slice(&encoded_k);
1310    let exchange_hash = Sha256::digest(&exchange);
1311    let signature = sign_ssh_ed25519(host, &exchange_hash);
1312
1313    let mut reply = Vec::new();
1314    reply.push(31); // SSH_MSG_KEX_ECDH_REPLY
1315    reply.extend(ssh_string(&host.public_blob));
1316    reply.extend(ssh_string(q_s.as_bytes()));
1317    reply.extend(ssh_string(&signature));
1318    if let Err(e) = write_ssh_packet(stream, &reply) {
1319        notes.push(format!("host_key_sign=reply_write_err ({e})"));
1320        return (SshStage::HostKeySign, notes.join("; "));
1321    }
1322    notes.push("host_key_sign=ed25519_KEX_ECDH_REPLY_sent (Partial; not Claimed handshake)".into());
1323
1324    // SSH_MSG_NEWKEYS (cleartext), then switch to OpenSSH ChaCha packets.
1325    if let Err(e) = write_ssh_packet(stream, &[21]) {
1326        notes.push(format!("newkeys=write_err ({e})"));
1327        return (SshStage::NewKeys, notes.join("; "));
1328    }
1329    notes.push("newkeys=sent".into());
1330    match read_ssh_packet(stream, 256) {
1331        Ok(p) if p.first() == Some(&21) => notes.push("newkeys=peer_ok".into()),
1332        Ok(p) => notes.push(format!(
1333            "newkeys=peer_msg={}",
1334            p.first().copied().unwrap_or(0)
1335        )),
1336        Err(e)
1337            if e.kind() == std::io::ErrorKind::WouldBlock
1338                || e.kind() == std::io::ErrorKind::TimedOut =>
1339        {
1340            notes.push("newkeys=peer_timeout".into());
1341        }
1342        Err(e) => notes.push(format!("newkeys=peer_err ({e})")),
1343    }
1344
1345    let strict_kex = peer_kex
1346        .iter()
1347        .any(|name| name == "kex-strict-c-v00@openssh.com");
1348    let initial_sequence = if strict_kex { 0 } else { 3 };
1349    notes.push(format!(
1350        "strict_kex={strict_kex} encrypted_initial_sequence={initial_sequence}"
1351    ));
1352    let (stage, post) = continue_after_newkeys(
1353        stream,
1354        &encoded_k,
1355        &exchange_hash,
1356        initial_sequence,
1357        authorized_keys,
1358        repo_path,
1359        Some(host),
1360    );
1361    notes.push(post);
1362    (stage, notes.join("; "))
1363}
1364
1365struct PeerKexInit {
1366    kex: Vec<String>,
1367    hostkey: Vec<String>,
1368    enc_c2s: Vec<String>,
1369    enc_s2c: Vec<String>,
1370    mac_c2s: Vec<String>,
1371    mac_s2c: Vec<String>,
1372}
1373
1374fn parse_peer_kexinit(payload: &[u8]) -> Option<PeerKexInit> {
1375    if payload.first().copied()? != 20 {
1376        return None;
1377    }
1378    let mut off = 1 + 16; // type + cookie
1379    let kex = read_ssh_name_list(payload, &mut off)?;
1380    let hostkey = read_ssh_name_list(payload, &mut off)?;
1381    let enc_c2s = read_ssh_name_list(payload, &mut off)?;
1382    let enc_s2c = read_ssh_name_list(payload, &mut off)?;
1383    let mac_c2s = read_ssh_name_list(payload, &mut off)?;
1384    let mac_s2c = read_ssh_name_list(payload, &mut off)?;
1385    let _compression_c2s = read_ssh_name_list(payload, &mut off)?;
1386    let _compression_s2c = read_ssh_name_list(payload, &mut off)?;
1387    let _languages_c2s = read_ssh_name_list(payload, &mut off)?;
1388    let _languages_s2c = read_ssh_name_list(payload, &mut off)?;
1389    if off + 5 > payload.len() {
1390        return None;
1391    }
1392    Some(PeerKexInit {
1393        kex,
1394        hostkey,
1395        enc_c2s,
1396        enc_s2c,
1397        mac_c2s,
1398        mac_s2c,
1399    })
1400}
1401
1402fn run_kex_stages(
1403    stream: &mut TcpStream,
1404    host: Option<&HostEd25519>,
1405    our_id: &str,
1406    peer_id: &str,
1407    authorized_keys: &Path,
1408    repo_path: &Path,
1409) -> (SshStage, String) {
1410    let mut notes = Vec::new();
1411    let advertise = host.is_some();
1412    let our_kexinit = build_kexinit_payload(advertise);
1413
1414    if let Err(e) = write_ssh_packet(stream, &our_kexinit) {
1415        return (SshStage::KexInit, format!("kexinit=write_err ({e})"));
1416    }
1417    let peer_payload = match read_ssh_packet(stream, 16_384) {
1418        Ok(p) => p,
1419        Err(e)
1420            if e.kind() == std::io::ErrorKind::WouldBlock
1421                || e.kind() == std::io::ErrorKind::TimedOut =>
1422        {
1423            notes.push("kexinit=sent peer=(timeout)".into());
1424            match curve25519_ecdh_selfcheck() {
1425                Ok(s) => notes.push(s),
1426                Err(e) => notes.push(format!("ecdh_selfcheck=fail ({e})")),
1427            }
1428            notes.push("stop=host_key_sign Missing (no peer KEXINIT)".into());
1429            return (SshStage::HostKeySign, notes.join("; "));
1430        }
1431        Err(e) => {
1432            return (SshStage::KexInit, format!("kexinit=sent peer_err ({e})"));
1433        }
1434    };
1435    notes.push(format!(
1436        "kexinit=sent advertise_ed25519={advertise} peer_payload_len={}",
1437        peer_payload.len()
1438    ));
1439
1440    let peer = match parse_peer_kexinit(&peer_payload) {
1441        Some(v) => v,
1442        None => {
1443            notes.push("algo_select=peer_kexinit_parse_fail".into());
1444            match curve25519_ecdh_selfcheck() {
1445                Ok(s) => notes.push(s),
1446                Err(e) => notes.push(format!("ecdh_selfcheck=fail ({e})")),
1447            }
1448            notes.push("stop=host_key_sign Missing".into());
1449            return (SshStage::HostKeySign, notes.join("; "));
1450        }
1451    };
1452    let kex_ok = peer
1453        .kex
1454        .iter()
1455        .any(|n| n == "curve25519-sha256" || n == "curve25519-sha256@libssh.org");
1456    let hostkey_ok = if advertise {
1457        peer.hostkey.iter().any(|n| n == "ssh-ed25519")
1458    } else {
1459        peer.hostkey
1460            .iter()
1461            .any(|n| n == "arks-partial-missing-hostkey-sign")
1462    };
1463    let cipher_ok = peer
1464        .enc_c2s
1465        .iter()
1466        .any(|n| n == "chacha20-poly1305@openssh.com")
1467        && peer
1468            .enc_s2c
1469            .iter()
1470            .any(|n| n == "chacha20-poly1305@openssh.com");
1471    let mac_ok = peer.mac_c2s.iter().any(|n| n == "hmac-sha2-256")
1472        && peer.mac_s2c.iter().any(|n| n == "hmac-sha2-256");
1473    notes.push(format!(
1474        "algo_select=kex_curve25519={kex_ok} hostkey_common={hostkey_ok} \
1475         openssh_chacha={cipher_ok} mac_name_common={mac_ok} peer_kex_n={} peer_hostkey_n={}",
1476        peer.kex.len(),
1477        peer.hostkey.len()
1478    ));
1479    if !kex_ok || !cipher_ok || !mac_ok {
1480        notes.push("stop=algo_select (no complete supported algorithm set)".into());
1481        return (SshStage::AlgoSelect, notes.join("; "));
1482    }
1483    if advertise && !hostkey_ok {
1484        notes.push(
1485            "note: peer did not offer ssh-ed25519 — still attempt ECDH; sign may be unused".into(),
1486        );
1487    }
1488
1489    match curve25519_ecdh_selfcheck() {
1490        Ok(s) => notes.push(s),
1491        Err(e) => {
1492            notes.push(format!("ecdh_selfcheck=fail ({e})"));
1493            return (SshStage::Ecdh, notes.join("; "));
1494        }
1495    }
1496
1497    let (stage, ecdh_notes) = try_peer_ecdh_and_sign(
1498        stream,
1499        &peer.kex,
1500        host,
1501        our_id,
1502        peer_id,
1503        &our_kexinit,
1504        &peer_payload,
1505        authorized_keys,
1506        repo_path,
1507    );
1508    notes.push(ecdh_notes);
1509
1510    // If ECDH stopped before NEWKEYS, still record offline auth + pack dispatch Partial.
1511    if !matches!(
1512        stage,
1513        SshStage::EncryptedTransport | SshStage::AuthPublickey | SshStage::ChannelSession
1514    ) {
1515        notes.push(publickey_verify_scaffold(authorized_keys, host));
1516        notes.push(channel_git_hookup_scaffold(repo_path));
1517    }
1518    notes.push(format!("reached_stage={}", stage.as_str()));
1519    (stage, notes.join("; "))
1520}
1521
1522/// Run an in-process SSH listener (durable accept per SoT §17(c)).
1523///
1524/// Advances structured KEX / sign / NEWKEYS / auth / channel stages per
1525/// connection. Stays up until `stop` is set. Bind failure fail-closed.
1526///
1527/// Callers MUST NOT silent-degrade to HTTP-only when SSH was left enabled.
1528pub fn serve_ssh_listener(opts: ServeSshOptions, stop: Arc<AtomicBool>) -> Result<(), ServerError> {
1529    let host_st = path_status(&opts.host_key);
1530    let auth_st = path_status(&opts.authorized_keys);
1531    let host_fmt = probe_host_key_format(&opts.host_key);
1532    let auth_probe = probe_authorized_keys(&opts.authorized_keys);
1533    let repo_st = if opts.path.exists() {
1534        "present"
1535    } else {
1536        "missing"
1537    };
1538    let host_key = match load_host_ed25519(&opts.host_key) {
1539        Ok(h) => Some(h),
1540        Err(e) => {
1541            // Keep going — Partial without sign when key missing/unloadable.
1542            let _ = e;
1543            None
1544        }
1545    };
1546    let host_load = if host_key.is_some() {
1547        "ed25519_unencrypted_ok"
1548    } else {
1549        "unloadable_or_absent"
1550    };
1551
1552    let mut listener = TcpListener::bind(opts.listen)?;
1553    let mut current = listener.local_addr().unwrap_or(opts.listen);
1554    listener.set_nonblocking(true)?;
1555    let our_id = "SSH-2.0-arks";
1556    eprintln!(
1557        "arks serve SSH durable listen on {current}; \
1558         host_key={hk} ({host_st}; format={host_fmt}; load={host_load}); \
1559         authorized_keys={ak} ({auth_st}; {auth_probe}); path={path} ({repo_st})",
1560        hk = opts.host_key.display(),
1561        ak = opts.authorized_keys.display(),
1562        path = opts.path.display(),
1563    );
1564
1565    let host_key = Arc::new(host_key);
1566    let auth_keys = opts.authorized_keys.clone();
1567    let repo_path = opts.path.clone();
1568    let host_load = Arc::new(host_load.to_string());
1569    let session_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
1570    // Bounded dual-bind drain (mirror HTTP B7 Claimed; research:root/20261111090827).
1571    let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
1572    while !stop.load(Ordering::SeqCst) {
1573        if let Some(slot) = &opts.rebind_desired {
1574            if let Ok(mut g) = slot.lock() {
1575                if let Some(new_addr) = g.take() {
1576                    if new_addr != current {
1577                        match TcpListener::bind(new_addr) {
1578                            Ok(l) => {
1579                                if let Err(e) = l.set_nonblocking(true) {
1580                                    eprintln!(
1581                                        "arks serve SSH: live rebind bind ok but \
1582                                         nonblocking fail ({e}); keeping {current}"
1583                                    );
1584                                    *g = Some(new_addr);
1585                                } else {
1586                                    eprintln!(
1587                                        "arks serve SSH: live rebind dual-bind {current} → {new_addr}; \
1588                                         prior listener draining for 5s"
1589                                    );
1590                                    let old = std::mem::replace(&mut listener, l);
1591                                    draining.push((
1592                                        old,
1593                                        current,
1594                                        Instant::now() + Duration::from_secs(5),
1595                                    ));
1596                                    current = new_addr;
1597                                }
1598                            }
1599                            Err(e) => {
1600                                eprintln!(
1601                                    "arks serve SSH: live rebind fail {current} → \
1602                                     {new_addr} ({e}); keeping prior listen"
1603                                );
1604                            }
1605                        }
1606                    }
1607                }
1608            }
1609        }
1610        draining.retain(|(_, old_addr, deadline)| {
1611            if Instant::now() < *deadline {
1612                true
1613            } else {
1614                eprintln!("arks serve SSH: rebind drain complete; closing {old_addr}");
1615                false
1616            }
1617        });
1618
1619        let spawn_session = |stream: TcpStream, peer: SocketAddr| {
1620            let n = session_counter.fetch_add(1, Ordering::SeqCst) + 1;
1621            let host_key = Arc::clone(&host_key);
1622            let auth_keys = auth_keys.clone();
1623            let repo_path = repo_path.clone();
1624            let host_load = Arc::clone(&host_load);
1625            let our_id = our_id.to_string();
1626            thread::spawn(move || {
1627                handle_ssh_session(
1628                    stream,
1629                    peer,
1630                    n,
1631                    &our_id,
1632                    host_key.as_ref().as_ref(),
1633                    &auth_keys,
1634                    &repo_path,
1635                    host_load.as_str(),
1636                );
1637            });
1638        };
1639
1640        match listener.accept() {
1641            Ok((stream, peer)) => spawn_session(stream, peer),
1642            Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
1643                thread::sleep(Duration::from_millis(20));
1644            }
1645            Err(e) => {
1646                return Err(ServerError::Msg(format!(
1647                    "arks serve SSH durable accept err on {current}: {e}"
1648                )));
1649            }
1650        }
1651        for (old_listener, _, _) in &draining {
1652            match old_listener.accept() {
1653                Ok((stream, peer)) => spawn_session(stream, peer),
1654                Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
1655                Err(e) => eprintln!("arks serve SSH: draining listener accept error: {e}"),
1656            }
1657        }
1658    }
1659
1660    eprintln!(
1661        "arks serve SSH durable listen stopped on {current} \
1662         (sessions={}; ops SSHD + upload-pack/receive-pack still valid)",
1663        session_counter.load(Ordering::SeqCst)
1664    );
1665    Ok(())
1666}
1667
1668#[allow(clippy::too_many_arguments)]
1669fn handle_ssh_session(
1670    mut stream: TcpStream,
1671    peer: SocketAddr,
1672    sessions: u64,
1673    our_id: &str,
1674    host_key: Option<&HostEd25519>,
1675    authorized_keys: &Path,
1676    path: &Path,
1677    host_load: &str,
1678) {
1679    let _ = stream.set_nonblocking(false);
1680    let _ = stream.set_nodelay(true);
1681    // Longer read window so held peers can overlap a dual-bind drain (IW-B7-SSH).
1682    let _ = stream.set_read_timeout(Some(Duration::from_secs(8)));
1683    let _ = stream.set_write_timeout(Some(Duration::from_secs(8)));
1684    let ours = format!("{our_id}\r\n");
1685    let _ = stream.write_all(ours.as_bytes());
1686    let _ = stream.flush();
1687    let peer_id = read_ssh_identification(&mut stream)
1688        .unwrap_or_default()
1689        .chars()
1690        .take(255)
1691        .collect::<String>();
1692    let id_part = if peer_id.is_empty() {
1693        format!("id_exchange=no_peer_id peer={peer} peer_id=(empty/timeout)")
1694    } else {
1695        format!("id_exchange=ok peer={peer} peer_id={peer_id}")
1696    };
1697    let (stage, kex_part) = if peer_id.is_empty() {
1698        match curve25519_ecdh_selfcheck() {
1699            Ok(s) => {
1700                let auth = publickey_verify_scaffold(authorized_keys, host_key);
1701                let chan = channel_git_hookup_scaffold(path);
1702                (
1703                    SshStage::HostKeySign,
1704                    format!(
1705                        "kex=skipped_no_peer_id; {s}; host_load={host_load}; {auth}; {chan}; \
1706                         stop=host_key_sign/wire Missing without peer"
1707                    ),
1708                )
1709            }
1710            Err(e) => (
1711                SshStage::Ecdh,
1712                format!("kex=skipped_no_peer_id; ecdh_selfcheck=fail ({e})"),
1713            ),
1714        }
1715    } else {
1716        run_kex_stages(
1717            &mut stream,
1718            host_key,
1719            our_id,
1720            &peer_id,
1721            authorized_keys,
1722            path,
1723        )
1724    };
1725    // Flush then half-close write so in-flight CHANNEL_DATA is not RST'd.
1726    let _ = stream.flush();
1727    let _ = stream.shutdown(Shutdown::Write);
1728    eprintln!(
1729        "arks serve SSH session#{sessions} reached_stage={} \
1730         ({id_part}; {kex_part})",
1731        stage.as_str()
1732    );
1733}
1734
1735type LoopbackSsh = (
1736    SocketAddr,
1737    Arc<AtomicBool>,
1738    thread::JoinHandle<Result<(), ServerError>>,
1739);
1740
1741/// Spawn durable SSH listener on a background thread (cohost with HTTP/forge).
1742pub fn spawn_ssh_listener(
1743    opts: ServeSshOptions,
1744) -> Result<(Arc<AtomicBool>, ListenerThread), ServerError> {
1745    let stop = Arc::new(AtomicBool::new(false));
1746    let stop2 = stop.clone();
1747    let handle = thread::spawn(move || serve_ssh_listener(opts, stop2));
1748    thread::sleep(Duration::from_millis(50));
1749    Ok((stop, handle))
1750}
1751
1752/// Ephemeral loopback SSH listener for `arks serve ssh-smoke --git-pack`.
1753pub fn spawn_loopback_ssh(opts: ServeSshOptions) -> Result<LoopbackSsh, ServerError> {
1754    let listener = TcpListener::bind("127.0.0.1:0")?;
1755    let addr = listener.local_addr()?;
1756    drop(listener);
1757    let mut opts = opts;
1758    opts.listen = addr;
1759    let stop = Arc::new(AtomicBool::new(false));
1760    let stop2 = stop.clone();
1761    let handle = thread::spawn(move || serve_ssh_listener(opts, stop2));
1762    // Brief settle so bind wins the ephemeral port before clients connect.
1763    thread::sleep(Duration::from_millis(30));
1764    Ok((addr, stop, handle))
1765}
1766
1767#[cfg(test)]
1768mod tests {
1769    use super::*;
1770    use ed25519_dalek::SigningKey;
1771
1772    #[test]
1773    fn parse_git_exec_services() {
1774        assert_eq!(
1775            parse_git_exec_service("git-upload-pack '/tmp/r.git'"),
1776            Some("git-upload-pack")
1777        );
1778        assert_eq!(
1779            parse_git_exec_service("git-receive-pack '/tmp/r.git'"),
1780            Some("git-receive-pack")
1781        );
1782        assert_eq!(parse_git_exec_service("bash"), None);
1783    }
1784
1785    #[test]
1786    fn chacha_aead_roundtrip_partial() {
1787        let shared = x25519_shared_as_mpint(&[7u8; 32]);
1788        let h = Sha256::digest(b"exchange-hash-partial");
1789        let note = encrypted_transport_selfcheck(&shared, &h);
1790        assert!(note.contains("selfcheck=ok"), "{note}");
1791    }
1792
1793    #[test]
1794    fn rfc8731_shared_secret_mpint_encoding() {
1795        let mut high_bit = [0u8; 32];
1796        high_bit[0] = 0x80;
1797        let encoded = x25519_shared_as_mpint(&high_bit);
1798        assert_eq!(&encoded[..4], &33u32.to_be_bytes());
1799        assert_eq!(encoded[4], 0);
1800        assert_eq!(encoded[5], 0x80);
1801
1802        let mut leading_zero = [0u8; 32];
1803        leading_zero[1] = 1;
1804        let encoded = x25519_shared_as_mpint(&leading_zero);
1805        assert_eq!(&encoded[..4], &31u32.to_be_bytes());
1806        assert_eq!(encoded[4], 1);
1807    }
1808
1809    #[test]
1810    fn authorized_keys_verify_partial() {
1811        let dir = tempfile::tempdir().unwrap();
1812        let seed = [9u8; 32];
1813        let signing = SigningKey::from_bytes(&seed);
1814        let vk = signing.verifying_key();
1815        let blob = build_ssh_ed25519_public_blob(vk.as_bytes());
1816        let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &blob);
1817        let ak = dir.path().join("authorized_keys");
1818        std::fs::write(&ak, format!("ssh-ed25519 {b64} test@arks\n")).unwrap();
1819        let challenge = b"challenge-partial";
1820        let sig = signing.sign(challenge);
1821        let mut sig_blob = Vec::new();
1822        sig_blob.extend(ssh_string(b"ssh-ed25519"));
1823        sig_blob.extend(ssh_string(&sig.to_bytes()));
1824        verify_publickey_against_authorized(&ak, &blob, challenge, &sig_blob).unwrap();
1825    }
1826}