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