use crate::error::ServerError;
use crate::push_policy::Pusher;
use crate::serve::ListenRebindSlot;
use crate::ssh_openssh_chacha::OpenSshChaCha;
use crate::stdio::{receive_pack_stream_as, upload_pack_stream};
use crate::web_ui::store::ForgeStore;
use arks_repo::Repository;
use ed25519_dalek::{Signature, Signer, SigningKey, Verifier, VerifyingKey};
use sha2::{Digest, Sha256};
use std::collections::VecDeque;
use std::io::{Cursor, Read, Write};
use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::thread;
use std::time::{Duration, Instant};
use x25519_dalek::{PublicKey, StaticSecret};
const SSH_LOCAL_INITIAL_WINDOW: u32 = 2 * 1024 * 1024;
const SSH_LOCAL_WINDOW_REFILL_THRESHOLD: u32 = 512 * 1024;
const SSH_LOCAL_MAX_PACKET: u32 = 32_768;
type ListenerThread = thread::JoinHandle<Result<(), ServerError>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[allow(dead_code)] enum SshStage {
IdExchange,
KexInit,
AlgoSelect,
Ecdh,
HostKeySign,
NewKeys,
EncryptedTransport,
AuthPublickey,
ChannelSession,
}
impl SshStage {
fn as_str(self) -> &'static str {
match self {
Self::IdExchange => "id_exchange",
Self::KexInit => "kexinit",
Self::AlgoSelect => "algo_select",
Self::Ecdh => "ecdh_curve25519",
Self::HostKeySign => "host_key_sign",
Self::NewKeys => "newkeys",
Self::EncryptedTransport => "encrypted_transport",
Self::AuthPublickey => "auth_publickey",
Self::ChannelSession => "channel_session",
}
}
}
#[derive(Debug, Clone)]
pub struct ServeSshOptions {
pub listen: SocketAddr,
pub path: PathBuf,
pub host_key: PathBuf,
pub authorized_keys: PathBuf,
pub rebind_desired: Option<ListenRebindSlot>,
}
impl ServeSshOptions {
pub fn with_defaults(listen: SocketAddr, path: PathBuf) -> Self {
Self {
listen,
path,
host_key: default_host_key_path(),
authorized_keys: default_authorized_keys_path(),
rebind_desired: None,
}
}
}
pub fn default_host_key_path() -> PathBuf {
if let Ok(p) = std::env::var("ARKS_SERVE_SSH_HOST_KEY") {
if !p.is_empty() {
return PathBuf::from(p);
}
}
arks_config_dir().join("ssh").join("host_key")
}
pub fn default_authorized_keys_path() -> PathBuf {
if let Ok(p) = std::env::var("ARKS_SERVE_SSH_AUTHORIZED_KEYS") {
if !p.is_empty() {
return PathBuf::from(p);
}
}
arks_config_dir().join("ssh").join("authorized_keys")
}
fn arks_config_dir() -> PathBuf {
let home = std::env::var_os("HOME")
.or_else(|| std::env::var_os("USERPROFILE"))
.map(PathBuf::from)
.unwrap_or_else(|| PathBuf::from("."));
home.join(".config").join("arks")
}
fn path_status(p: &Path) -> &'static str {
if p.is_file() {
"present"
} else if p.exists() {
"exists-not-file"
} else {
"missing"
}
}
fn probe_host_key_format(path: &Path) -> String {
if !path.is_file() {
return "absent".into();
}
let mut f = match std::fs::File::open(path) {
Ok(f) => f,
Err(e) => return format!("unreadable ({e})"),
};
let mut buf = [0u8; 96];
let n = f.read(&mut buf).unwrap_or(0);
let head = String::from_utf8_lossy(&buf[..n]);
if head.starts_with("openssh-key-v1") || head.contains("BEGIN OPENSSH PRIVATE KEY") {
"openssh-private-key-marker".into()
} else if head.contains("BEGIN RSA PRIVATE KEY")
|| head.contains("BEGIN EC PRIVATE KEY")
|| head.contains("BEGIN PRIVATE KEY")
{
"pem-private-key-marker".into()
} else if head.starts_with("ssh-") || head.starts_with("ecdsa-") || head.starts_with("sk-") {
"public-key-line-like".into()
} else if n == 0 {
"empty-file".into()
} else {
"unknown-bytes".into()
}
}
fn probe_authorized_keys(path: &Path) -> String {
if !path.is_file() {
return "absent".into();
}
let raw = match std::fs::read_to_string(path) {
Ok(s) => s,
Err(e) => return format!("unreadable ({e})"),
};
let mut ed25519 = 0usize;
let mut rsa = 0usize;
let mut ecdsa = 0usize;
let mut total = 0usize;
for line in raw
.lines()
.map(str::trim)
.filter(|l| !l.is_empty() && !l.starts_with('#'))
{
total += 1;
let algo = line.split_whitespace().next().unwrap_or("");
if algo.contains("ed25519") {
ed25519 += 1;
} else if algo.starts_with("ssh-rsa") || algo.starts_with("rsa-sha2-") {
rsa += 1;
} else if algo.starts_with("ecdsa-sha2-") {
ecdsa += 1;
}
}
if rsa > 0 || ecdsa > 0 {
format!(
"lines={total} (ed25519={ed25519}, rsa={rsa}, ecdsa={ecdsa}; note: in-process SSH authenticates ed25519 keys)"
)
} else {
format!("lines={total} (ed25519={ed25519})")
}
}
fn ssh_string(data: &[u8]) -> Vec<u8> {
let mut out = Vec::with_capacity(4 + data.len());
out.extend_from_slice(&(data.len() as u32).to_be_bytes());
out.extend_from_slice(data);
out
}
fn ssh_name_list(names: &[&str]) -> Vec<u8> {
let joined = names.join(",");
ssh_string(joined.as_bytes())
}
fn read_ssh_name_list(buf: &[u8], off: &mut usize) -> Option<Vec<String>> {
if *off + 4 > buf.len() {
return None;
}
let len = u32::from_be_bytes(buf[*off..*off + 4].try_into().ok()?) as usize;
*off += 4;
if *off + len > buf.len() {
return None;
}
let s = std::str::from_utf8(&buf[*off..*off + len]).ok()?;
*off += len;
if s.is_empty() {
return Some(Vec::new());
}
Some(s.split(',').map(|x| x.to_string()).collect())
}
fn read_ssh_bytes(buf: &[u8], off: &mut usize) -> Option<Vec<u8>> {
if *off + 4 > buf.len() {
return None;
}
let len = u32::from_be_bytes(buf[*off..*off + 4].try_into().ok()?) as usize;
*off += 4;
if *off + len > buf.len() {
return None;
}
let out = buf[*off..*off + len].to_vec();
*off += len;
Some(out)
}
#[derive(Clone)]
struct HostEd25519 {
signing: SigningKey,
public_blob: Vec<u8>,
}
fn load_host_ed25519(path: &Path) -> Result<HostEd25519, String> {
if !path.is_file() {
return Err("host_key absent".into());
}
let raw = std::fs::read(path).map_err(|e| e.to_string())?;
let text = String::from_utf8_lossy(&raw);
let b64: String = if text.contains("BEGIN OPENSSH PRIVATE KEY") {
text.lines()
.filter(|l| !l.starts_with("-----") && !l.trim().is_empty())
.collect::<String>()
} else if raw.starts_with(b"openssh-key-v1\0") {
return parse_openssh_ed25519_bin(&raw);
} else {
return Err("not OpenSSH PEM / openssh-key-v1".into());
};
let bin = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64.trim())
.map_err(|e| format!("base64: {e}"))?;
parse_openssh_ed25519_bin(&bin)
}
fn parse_openssh_ed25519_bin(bin: &[u8]) -> Result<HostEd25519, String> {
const MAGIC: &[u8] = b"openssh-key-v1\0";
if !bin.starts_with(MAGIC) {
return Err("missing openssh-key-v1 magic".into());
}
let mut off = MAGIC.len();
let cipher = read_ssh_bytes(bin, &mut off).ok_or("ciphername")?;
let kdf = read_ssh_bytes(bin, &mut off).ok_or("kdfname")?;
let _kdfopts = read_ssh_bytes(bin, &mut off).ok_or("kdfoptions")?;
if cipher.as_slice() != b"none" || kdf.as_slice() != b"none" {
return Err("encrypted OpenSSH host key not Partial-wired (none/none only)".into());
}
let nkeys = read_u32(bin, &mut off).map_err(|_| "num_keys short".to_string())?;
if nkeys != 1 {
return Err(format!("num_keys={nkeys} (Partial expects 1)"));
}
let pub_blob = read_ssh_bytes(bin, &mut off).ok_or("public key blob")?;
let priv_block = read_ssh_bytes(bin, &mut off).ok_or("private block")?;
let mut poff = 0usize;
let _c1 = read_u32(&priv_block, &mut poff)?;
let _c2 = read_u32(&priv_block, &mut poff)?;
let keytype = read_ssh_bytes(&priv_block, &mut poff).ok_or("keytype")?;
if keytype.as_slice() != b"ssh-ed25519" {
return Err(format!(
"host key type {} (Partial ed25519 only)",
String::from_utf8_lossy(&keytype)
));
}
let _pub_in_priv = read_ssh_bytes(&priv_block, &mut poff).ok_or("pubkey in priv")?;
let secret = read_ssh_bytes(&priv_block, &mut poff).ok_or("secret")?;
if secret.len() < 32 {
return Err(format!("ed25519 secret len {}", secret.len()));
}
let mut seed = [0u8; 32];
seed.copy_from_slice(&secret[..32]);
let signing = SigningKey::from_bytes(&seed);
let public_blob = if pub_blob.starts_with(&[0, 0, 0, 11]) || pub_blob.len() > 4 {
pub_blob
} else {
build_ssh_ed25519_public_blob(signing.verifying_key().as_bytes())
};
Ok(HostEd25519 {
signing,
public_blob,
})
}
fn read_u32(buf: &[u8], off: &mut usize) -> Result<u32, String> {
let slice = buf
.get(*off..off.saturating_add(4))
.ok_or_else(|| "u32 short".to_string())?;
let bytes: [u8; 4] = slice.try_into().map_err(|_| "u32 short".to_string())?;
*off += 4;
Ok(u32::from_be_bytes(bytes))
}
fn build_ssh_ed25519_public_blob(pub32: &[u8; 32]) -> Vec<u8> {
let mut out = Vec::new();
out.extend(ssh_string(b"ssh-ed25519"));
out.extend(ssh_string(pub32));
out
}
fn sign_ssh_ed25519(host: &HostEd25519, data: &[u8]) -> Vec<u8> {
let sig = host.signing.sign(data);
let mut out = Vec::new();
out.extend(ssh_string(b"ssh-ed25519"));
out.extend(ssh_string(&sig.to_bytes()));
out
}
fn build_kexinit_payload(advertise_ed25519: bool) -> Vec<u8> {
let mut p = Vec::with_capacity(256);
p.push(20); let cookie = StaticSecret::random().to_bytes();
p.extend_from_slice(&cookie[..16]);
p.extend(ssh_name_list(&[
"curve25519-sha256",
"curve25519-sha256@libssh.org",
"kex-strict-s-v00@openssh.com",
]));
if advertise_ed25519 {
p.extend(ssh_name_list(&["ssh-ed25519"]));
} else {
p.extend(ssh_name_list(&["arks-partial-missing-hostkey-sign"]));
}
p.extend(ssh_name_list(&["chacha20-poly1305@openssh.com"]));
p.extend(ssh_name_list(&["chacha20-poly1305@openssh.com"]));
p.extend(ssh_name_list(&["hmac-sha2-256"]));
p.extend(ssh_name_list(&["hmac-sha2-256"]));
p.extend(ssh_name_list(&["none"]));
p.extend(ssh_name_list(&["none"]));
p.extend(ssh_name_list(&[]));
p.extend(ssh_name_list(&[]));
p.push(0); p.extend_from_slice(&0u32.to_be_bytes());
p
}
fn write_ssh_packet(stream: &mut TcpStream, payload: &[u8]) -> std::io::Result<()> {
let mut padding_len = 4usize;
while (4 + 1 + payload.len() + padding_len) % 8 != 0 {
padding_len += 1;
}
let packet_length = (1 + payload.len() + padding_len) as u32;
stream.write_all(&packet_length.to_be_bytes())?;
stream.write_all(&[padding_len as u8])?;
stream.write_all(payload)?;
stream.write_all(&vec![0u8; padding_len])?;
Ok(())
}
fn read_ssh_packet(stream: &mut TcpStream, max_payload: usize) -> std::io::Result<Vec<u8>> {
let mut lenbuf = [0u8; 4];
stream.read_exact(&mut lenbuf)?;
let packet_length = u32::from_be_bytes(lenbuf) as usize;
if packet_length < 5 || packet_length > max_payload + 256 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
format!("ssh packet_length out of range ({packet_length})"),
));
}
let mut rest = vec![0u8; packet_length];
stream.read_exact(&mut rest)?;
let padding_len = rest[0] as usize;
if padding_len + 1 > rest.len() {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"ssh padding_length invalid",
));
}
let payload_end = rest.len() - padding_len;
Ok(rest[1..payload_end].to_vec())
}
fn read_ssh_identification(stream: &mut TcpStream) -> std::io::Result<String> {
for _ in 0..50 {
let mut line = Vec::with_capacity(64);
loop {
let mut byte = [0u8; 1];
stream.read_exact(&mut byte)?;
line.push(byte[0]);
if byte[0] == b'\n' {
break;
}
if line.len() >= 255 {
return Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"SSH identification line exceeds 255 bytes",
));
}
}
let line = String::from_utf8_lossy(&line)
.trim_end_matches(['\r', '\n'])
.to_string();
if line.starts_with("SSH-") {
return Ok(line);
}
}
Err(std::io::Error::new(
std::io::ErrorKind::InvalidData,
"SSH identification not found",
))
}
fn curve25519_ecdh_selfcheck() -> Result<String, String> {
let a_secret = StaticSecret::random();
let a_public = PublicKey::from(&a_secret);
let b_secret = StaticSecret::random();
let b_public = PublicKey::from(&b_secret);
let shared_a = a_secret.diffie_hellman(&b_public);
let shared_b = b_secret.diffie_hellman(&a_public);
if shared_a.as_bytes() != shared_b.as_bytes() {
return Err("shared secret mismatch".into());
}
let mut h = Sha256::new();
h.update(b"arks-ssh-partial-ecdh");
h.update(shared_a.as_bytes());
let digest = h.finalize();
Ok(format!(
"ecdh_selfcheck=ok shared_sha256={:02x}{:02x}…",
digest[0], digest[1]
))
}
struct AuthorizedEd25519Key {
verifying: VerifyingKey,
blob: Vec<u8>,
comment_user: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct SshAuthIdentity {
request_user: String,
key_comment_user: Option<String>,
public_blob: Vec<u8>,
}
fn parse_authorized_keys_comment_user(comment_line: &str) -> Option<String> {
let rest = comment_line.trim().strip_prefix('#')?.trim();
let (user_part, title_part) = rest.split_once('(')?;
if !title_part.ends_with(')') {
return None;
}
let user = user_part.trim();
if user.is_empty()
|| user.len() > 80
|| user.starts_with('.')
|| !user
.chars()
.all(|c| c.is_ascii_alphanumeric() || matches!(c, '-' | '_' | '.'))
{
return None;
}
Some(user.to_string())
}
fn parse_authorized_ed25519_line(line: &str) -> Option<(VerifyingKey, Vec<u8>)> {
let parts: Vec<&str> = line.split_whitespace().collect();
if parts.len() < 2 {
return None;
}
let (alg, b64) = if parts[0].starts_with("ssh-") || parts[0].starts_with("ecdsa-") {
(parts[0], parts[1])
} else if parts.len() >= 3 && (parts[1].starts_with("ssh-") || parts[1].starts_with("ecdsa-")) {
(parts[1], parts[2])
} else {
return None;
};
if alg != "ssh-ed25519" {
return None;
}
let blob = base64::Engine::decode(&base64::engine::general_purpose::STANDARD, b64).ok()?;
let vk = parse_ssh_ed25519_verifying(&blob)?;
Some((vk, blob))
}
fn load_authorized_ed25519_keys(authorized_keys: &Path) -> Vec<AuthorizedEd25519Key> {
let mut out = Vec::new();
let Ok(raw) = std::fs::read_to_string(authorized_keys) else {
return out;
};
let mut pending_comment_user: Option<String> = None;
for line in raw.lines() {
let line = line.trim();
if line.is_empty() {
pending_comment_user = None;
continue;
}
if line.starts_with('#') {
pending_comment_user = parse_authorized_keys_comment_user(line);
continue;
}
let comment_user = pending_comment_user.take();
if let Some((verifying, blob)) = parse_authorized_ed25519_line(line) {
out.push(AuthorizedEd25519Key {
verifying,
blob,
comment_user,
});
}
}
out
}
fn verify_publickey_against_authorized(
authorized_keys: &Path,
public_blob: &[u8],
challenge: &[u8],
signature_blob: &[u8],
) -> Result<Option<String>, String> {
let keys = load_authorized_ed25519_keys(authorized_keys);
if keys.is_empty() {
return Err("authorized_keys has no ssh-ed25519 lines".into());
}
let Some(vk) = parse_ssh_ed25519_verifying(public_blob) else {
return Err("public blob not ssh-ed25519".into());
};
let Some(matched) = keys.iter().find(|entry| {
entry.verifying.as_bytes() == vk.as_bytes() || entry.blob.as_slice() == public_blob
}) else {
return Err("public key not in authorized_keys".into());
};
let mut off = 0usize;
let alg = read_ssh_bytes(signature_blob, &mut off).ok_or("sig alg")?;
if alg.as_slice() != b"ssh-ed25519" {
return Err("signature alg not ssh-ed25519".into());
}
let sig_bytes = read_ssh_bytes(signature_blob, &mut off).ok_or("sig bytes")?;
if sig_bytes.len() != 64 {
return Err(format!("sig len {}", sig_bytes.len()));
}
let mut arr = [0u8; 64];
arr.copy_from_slice(&sig_bytes);
let sig = Signature::from_bytes(&arr);
vk.verify(challenge, &sig)
.map_err(|e| format!("ed25519 verify fail: {e}"))?;
Ok(matched.comment_user.clone())
}
fn resolve_ssh_identity(store: &ForgeStore, auth: &SshAuthIdentity) -> Option<String> {
if store.corrupt {
return None;
}
let presented_vk = parse_ssh_ed25519_verifying(&auth.public_blob);
if let Some(ref vk) = presented_vk {
for acct in &store.users {
for rec in &acct.ssh_keys {
if let Some((stored_vk, stored_blob)) =
parse_authorized_ed25519_line(rec.public_key.trim())
{
if stored_vk.as_bytes() == vk.as_bytes()
|| stored_blob.as_slice() == auth.public_blob.as_slice()
{
return Some(acct.username.clone());
}
}
}
}
}
if let Some(ref comment_user) = auth.key_comment_user {
let cu = comment_user.trim();
if !cu.is_empty() {
if store.users.is_empty() {
return Some(cu.to_string());
}
if let Some(acct) = store.users.iter().find(|u| u.username == cu) {
return Some(acct.username.clone());
}
return None;
}
}
if !store.users.is_empty() {
return None;
}
let req_user = auth.request_user.trim();
if req_user.is_empty() {
return None;
}
Some(req_user.to_string())
}
fn check_ssh_repo_rbac(
store: &ForgeStore,
effective_user: Option<&str>,
is_write: bool,
) -> Result<(), String> {
if store.corrupt {
return Err("forge store is corrupted (fail-closed)".into());
}
if is_write && store.archived {
return Err("repository is archived (read-only)".into());
}
if store.users.is_empty() {
return Ok(());
}
let is_private = store.visibility == "private";
if !is_write && !is_private {
return Ok(());
}
let Some(username) = effective_user else {
return Err(if is_write {
"permission denied: SSH key is not bound to a repository write account".into()
} else {
"permission denied: private repository requires an authorized SSH user".into()
});
};
let Some(acct) = store.users.iter().find(|u| u.username == username) else {
return Err(format!(
"permission denied: SSH user '{username}' is not registered"
));
};
let is_collaborator = store.collaborators.iter().any(|c| c == username);
let is_privileged = acct.role == "admin" || acct.role == "maintainer";
if is_privileged || (!is_write && is_collaborator) {
Ok(())
} else if is_write {
Err(format!(
"permission denied: role '{}' cannot push to this repository",
acct.role
))
} else {
Err(format!(
"permission denied: role '{}' cannot read private repository",
acct.role
))
}
}
fn publickey_verify_scaffold(authorized_keys: &Path, host: Option<&HostEd25519>) -> String {
let mut notes = Vec::new();
let auth_probe = probe_authorized_keys(authorized_keys);
notes.push(format!("authorized_keys_probe={auth_probe}"));
let keys = load_authorized_ed25519_keys(authorized_keys);
notes.push(format!("auth_ed25519_lines={}", keys.len()));
if !keys.is_empty() {
notes.push("auth_pubkey_line=ssh-ed25519_parse_ok".into());
}
if let Some(h) = host {
let challenge = Sha256::digest(b"arks-ssh-partial-auth-verify-challenge");
let sig = h.signing.sign(&challenge);
match h.signing.verifying_key().verify(&challenge, &sig) {
Ok(()) => notes.push("auth_verify_selfcheck=ok (host key; offline Partial)".into()),
Err(e) => notes.push(format!("auth_verify_selfcheck=fail ({e})")),
}
let sig_blob = sign_ssh_ed25519(h, &challenge);
match verify_publickey_against_authorized(
authorized_keys,
&h.public_blob,
&challenge,
&sig_blob,
) {
Ok(_) => notes.push("auth_authorized_keys_verify=ok (host key listed; Partial)".into()),
Err(e) => notes.push(format!("auth_authorized_keys_verify=skip ({e})")),
}
} else {
notes.push("auth_verify_selfcheck=skipped (no host key)".into());
}
notes.join("; ")
}
fn parse_ssh_ed25519_verifying(blob: &[u8]) -> Option<VerifyingKey> {
let mut off = 0usize;
let alg = read_ssh_bytes(blob, &mut off)?;
if alg.as_slice() != b"ssh-ed25519" {
return None;
}
let pub32 = read_ssh_bytes(blob, &mut off)?;
if pub32.len() != 32 {
return None;
}
let mut a = [0u8; 32];
a.copy_from_slice(&pub32);
VerifyingKey::from_bytes(&a).ok()
}
fn parse_git_exec_service(cmd: &str) -> Option<&'static str> {
if cmd.contains('\0') {
return None;
}
let c = cmd.trim().trim_matches('\'').trim_matches('"');
let first = c.split_whitespace().next().unwrap_or("");
let base = first.rsplit('/').next().unwrap_or(first);
match base {
"git-upload-pack" | "upload-pack" => Some("git-upload-pack"),
"git-receive-pack" | "receive-pack" => Some("git-receive-pack"),
_ => None,
}
}
fn extract_ssh_exec_path_arg(exec_cmd: &str) -> Result<String, String> {
if exec_cmd.contains('\0') {
return Err("invalid ssh exec command: NUL byte rejected".into());
}
let trimmed = exec_cmd.trim();
let mut parts = trimmed.splitn(2, char::is_whitespace);
let _svc = parts.next().unwrap_or("");
let raw = parts.next().unwrap_or("").trim();
let unquoted = if (raw.starts_with('\'') && raw.ends_with('\'') && raw.len() >= 2)
|| (raw.starts_with('"') && raw.ends_with('"') && raw.len() >= 2)
{
&raw[1..raw.len() - 1]
} else {
raw
};
if unquoted.contains('\0') {
return Err("invalid multi-repo ssh path: NUL byte rejected".into());
}
Ok(unquoted.to_string())
}
fn open_ssh_repo(base_path: &Path, exec_cmd: &str) -> Result<Repository, String> {
if exec_cmd.contains('\0') {
return Err("invalid ssh exec command: NUL byte rejected".into());
}
if base_path.join("HEAD").is_file() {
return Repository::open(base_path)
.map_err(|e| format!("open repo {}: {e}", base_path.display()));
}
let dot_git = base_path.join(".git");
if dot_git.join("HEAD").is_file() {
return Repository::open(&dot_git)
.map_err(|e| format!("open repo {}: {e}", dot_git.display()));
}
let arg = extract_ssh_exec_path_arg(exec_cmd)?;
if arg.is_empty() || arg.contains("..") || arg.contains('\\') || arg.contains('\0') {
return Err(format!("invalid multi-repo ssh path: {arg}"));
}
let rel = arg.trim_start_matches('/').trim_end_matches('/');
if rel.is_empty() || rel.contains("//") {
return Err(format!("invalid multi-repo ssh path: {arg}"));
}
let mut seg_count = 0usize;
for comp in Path::new(rel).components() {
match comp {
Component::Normal(os) => {
let Some(seg) = os.to_str() else {
return Err(format!("invalid multi-repo ssh path: {arg}"));
};
if seg.is_empty()
|| seg.starts_with('.')
|| seg.contains("..")
|| seg.contains('\\')
|| seg.contains('\0')
{
return Err(format!("invalid multi-repo ssh path: {arg}"));
}
seg_count += 1;
}
_ => return Err(format!("invalid multi-repo ssh path: {arg}")),
}
}
if seg_count == 0 {
return Err(format!("invalid multi-repo ssh path: {arg}"));
}
let clean = rel.trim_end_matches(".git");
if clean.is_empty() || clean.ends_with('/') {
return Err(format!("invalid multi-repo ssh path: {arg}"));
}
if Path::new(clean)
.file_name()
.and_then(|n| n.to_str())
.is_none_or(|n| n.is_empty() || n.starts_with('.'))
{
return Err(format!("invalid multi-repo ssh path: {arg}"));
}
let canon_base = std::fs::canonicalize(base_path)
.map_err(|e| format!("open repo root {}: {e}", base_path.display()))?;
let candidates = [
base_path.join(format!("{clean}.git")),
base_path.join(clean),
base_path.join(clean).join(".git"),
];
for candidate in candidates {
if !candidate.join("HEAD").is_file() {
continue;
}
let canon_cand = std::fs::canonicalize(&candidate)
.map_err(|e| format!("open repo {}: {e}", candidate.display()))?;
if !canon_cand.starts_with(&canon_base) || canon_cand == canon_base {
return Err(format!("invalid multi-repo ssh path (escapes root): {arg}"));
}
return Repository::open(&canon_cand)
.map_err(|e| format!("open repo {}: {e}", canon_cand.display()));
}
Err(format!(
"open repo {}: not found under {}",
arg,
base_path.display()
))
}
fn dispatch_git_exec_to_pack(repo_path: &Path, exec_cmd: &str) -> Result<String, String> {
let Some(svc) = parse_git_exec_service(exec_cmd) else {
return Err(format!("exec not git-upload-pack|receive-pack: {exec_cmd}"));
};
let mut repo = open_ssh_repo(repo_path, exec_cmd)?;
let mut buf = Cursor::new(Vec::<u8>::new());
match svc {
"git-upload-pack" => match upload_pack_stream(&repo, &mut buf) {
Ok(()) => Ok(
"channel_exec=git-upload-pack dispatched upload_pack_stream ok \
(Partial empty-peer; Claimed SSH channel e2e Missing)"
.to_string(),
),
Err(e) => Ok(format!(
"channel_exec=git-upload-pack dispatch reached upload_pack_stream err={e} \
(Partial; empty peer expected; not Claimed)"
)),
},
"git-receive-pack" => {
let store = ForgeStore::load_shared(repo.common_dir());
if store.corrupt {
return Err("forge store is corrupted (fail-closed)".into());
}
if store.archived {
return Err("repository is archived (read-only)".into());
}
match receive_pack_stream_as(&mut repo, &mut buf, &Pusher::ssh()) {
Ok(()) => Ok(
"channel_exec=git-receive-pack dispatched receive_pack_stream ok \
(Partial empty-peer; Claimed SSH channel e2e Missing)"
.to_string(),
),
Err(e) => Ok(format!(
"channel_exec=git-receive-pack dispatch reached receive_pack_stream err={e} \
(Partial; empty peer expected; not Claimed)"
)),
}
}
_ => Err(format!("unknown service {svc}")),
}
}
fn channel_git_hookup_scaffold(repo_path: &Path) -> String {
let st = path_status(repo_path);
let up = dispatch_git_exec_to_pack(repo_path, "git-upload-pack '.'");
let rp = dispatch_git_exec_to_pack(repo_path, "git-receive-pack '.'");
format!(
"channel_session=partial_dispatch; repo_path={} ({st}); upload={:?}; receive={:?}; \
design ≠Claimed SSH git subsystem e2e",
repo_path.display(),
up,
rp
)
}
fn x25519_shared_as_mpint(shared_wire: &[u8; 32]) -> Vec<u8> {
let magnitude = shared_wire.to_vec();
let first_nonzero = magnitude
.iter()
.position(|b| *b != 0)
.unwrap_or(magnitude.len());
let mut value = magnitude[first_nonzero..].to_vec();
if value.first().is_some_and(|b| b & 0x80 != 0) {
value.insert(0, 0);
}
ssh_string(&value)
}
fn ssh_kdf_bytes(encoded_k: &[u8], exchange_hash: &[u8], letter: u8, n: usize) -> Vec<u8> {
let mut out = Vec::with_capacity(n);
while out.len() < n {
let mut h = Sha256::new();
h.update(encoded_k);
h.update(exchange_hash);
if out.is_empty() {
h.update([letter]);
h.update(exchange_hash); } else {
h.update(&out);
}
out.extend_from_slice(&h.finalize());
}
out.truncate(n);
out
}
fn openssh_chacha(
encoded_k: &[u8],
exchange_hash: &[u8],
client_to_server: bool,
sequence: u32,
) -> Result<OpenSshChaCha, String> {
let letter = if client_to_server { b'C' } else { b'D' };
let key = ssh_kdf_bytes(encoded_k, exchange_hash, letter, 64);
OpenSshChaCha::new(&key, sequence)
}
fn encrypted_transport_selfcheck(encoded_k: &[u8], exchange_hash: &[u8]) -> String {
let mut c2s = match openssh_chacha(encoded_k, exchange_hash, true, 0) {
Ok(c) => c,
Err(e) => return format!("encrypted_transport=selfcheck_fail ({e})"),
};
let sample = b"arks-ssh-partial-post-newkeys";
match c2s.seal_packet(sample).and_then(|packet| {
let mut peer = openssh_chacha(encoded_k, exchange_hash, true, 0)?;
let encrypted_length = packet[..4].try_into().map_err(|_| "length")?;
let body_len = packet.len() - 4 - 16;
let body = packet[4..4 + body_len].to_vec();
let tag = packet[4 + body_len..].try_into().map_err(|_| "tag")?;
peer.open_packet(encrypted_length, body, tag, 65_536)
}) {
Ok(pt) if pt == sample => "encrypted_transport=OpenSSH-ChaCha packet selfcheck=ok \
(live stock-client receipt still required for Claimed)"
.into(),
Ok(_) => "encrypted_transport=selfcheck_mismatch".into(),
Err(e) => format!("encrypted_transport=selfcheck_fail ({e})"),
}
}
fn write_encrypted_packet(
stream: &mut TcpStream,
cipher: &mut OpenSshChaCha,
payload: &[u8],
) -> Result<(), String> {
cipher.write_packet(stream, payload)
}
fn read_encrypted_packet(
stream: &mut TcpStream,
cipher: &mut OpenSshChaCha,
max: usize,
) -> Result<Vec<u8>, String> {
cipher.read_packet(stream, max)
}
fn continue_after_newkeys(
stream: &mut TcpStream,
encoded_k: &[u8],
exchange_hash: &[u8],
initial_sequence: u32,
authorized_keys: &Path,
repo_path: &Path,
host: Option<&HostEd25519>,
) -> (SshStage, String) {
let mut notes = vec![encrypted_transport_selfcheck(encoded_k, exchange_hash)];
let mut c2s = match openssh_chacha(encoded_k, exchange_hash, true, initial_sequence) {
Ok(c) => c,
Err(e) => return (SshStage::EncryptedTransport, format!("c2s key error: {e}")),
};
let mut s2c = match openssh_chacha(encoded_k, exchange_hash, false, initial_sequence) {
Ok(c) => c,
Err(e) => return (SshStage::EncryptedTransport, format!("s2c key error: {e}")),
};
let _ = stream.set_nodelay(true);
let _ = stream.set_read_timeout(Some(Duration::from_secs(30)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(30)));
let mut next = read_encrypted_packet(stream, &mut c2s, 65_536);
if let Ok(payload) = &next
&& payload.first() == Some(&5)
{
let mut off = 1usize;
if let Some(service) = read_ssh_bytes(payload, &mut off) {
let mut accept = vec![6]; accept.extend(ssh_string(&service));
match write_encrypted_packet(stream, &mut s2c, &accept) {
Ok(()) => notes.push(format!(
"wire_SERVICE_ACCEPT={} (OpenSSH ChaCha decrypt+encrypt ok)",
String::from_utf8_lossy(&service)
)),
Err(e) => notes.push(format!("wire_SERVICE_ACCEPT=write_err ({e})")),
}
next = read_encrypted_packet(stream, &mut c2s, 65_536);
}
}
let mut authed_identity: Option<SshAuthIdentity> = None;
for round in 0..8 {
let payload = match next {
Ok(p) => p,
Err(e) => {
notes.push(format!("wire_auth=timeout_or_err round={round} ({e})"));
break;
}
};
if payload.first() != Some(&50) {
notes.push(format!(
"wire_post_newkeys_msg={} (expected USERAUTH=50)",
payload.first().copied().unwrap_or(0)
));
break;
}
notes.push(format!("wire_USERAUTH_REQUEST=seen round={round}"));
let (identity, auth_note) = handle_userauth_request_partial(
&payload,
exchange_hash,
authorized_keys,
host,
stream,
&mut s2c,
);
notes.push(auth_note);
if let Some(id) = identity {
authed_identity = Some(id);
break;
}
next = read_encrypted_packet(stream, &mut c2s, 65_536);
}
let Some(auth_id) = authed_identity else {
notes.push(publickey_verify_scaffold(authorized_keys, host));
notes.push(channel_git_hookup_scaffold(repo_path));
return (SshStage::AuthPublickey, notes.join("; "));
};
match run_session_channel_pack(stream, &mut c2s, &mut s2c, repo_path, &auth_id, &mut notes) {
Ok(()) => (SshStage::ChannelSession, notes.join("; ")),
Err(e) => {
notes.push(e);
notes.push(channel_git_hookup_scaffold(repo_path));
(SshStage::ChannelSession, notes.join("; "))
}
}
}
fn run_session_channel_pack(
stream: &mut TcpStream,
c2s: &mut OpenSshChaCha,
s2c: &mut OpenSshChaCha,
repo_path: &Path,
auth_id: &SshAuthIdentity,
notes: &mut Vec<String>,
) -> Result<(), String> {
let mut peer_chan: Option<u32> = None;
let mut peer_initial_window: u32 = 0;
let mut peer_max_packet: u32 = SSH_LOCAL_MAX_PACKET;
let our_chan: u32 = 0;
let mut exec_cmd: Option<String> = None;
for _ in 0..32 {
let msg = read_encrypted_packet(stream, c2s, 65_536)
.map_err(|e| format!("wire_channel=timeout_or_err ({e})"))?;
match msg.first().copied() {
Some(90) => {
let mut off = 1usize;
let chan_type = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
let sender = read_u32(&msg, &mut off).unwrap_or(0);
peer_initial_window = read_u32(&msg, &mut off).unwrap_or(0);
peer_max_packet = read_u32(&msg, &mut off)
.unwrap_or(SSH_LOCAL_MAX_PACKET)
.max(1024);
notes.push(format!(
"wire_CHANNEL_OPEN={} sender={sender} peer_window={peer_initial_window}",
String::from_utf8_lossy(&chan_type)
));
if chan_type.as_slice() != b"session" {
let mut fail = vec![92]; fail.extend_from_slice(&sender.to_be_bytes());
fail.extend_from_slice(&2u32.to_be_bytes()); fail.extend(ssh_string(b"only session"));
fail.extend(ssh_string(b""));
let _ = write_encrypted_packet(stream, s2c, &fail);
return Err("channel_open=non_session".into());
}
peer_chan = Some(sender);
let mut conf = vec![91]; conf.extend_from_slice(&sender.to_be_bytes());
conf.extend_from_slice(&our_chan.to_be_bytes());
conf.extend_from_slice(&SSH_LOCAL_INITIAL_WINDOW.to_be_bytes());
conf.extend_from_slice(&SSH_LOCAL_MAX_PACKET.to_be_bytes());
write_encrypted_packet(stream, s2c, &conf)
.map_err(|e| format!("channel_open_confirm=write_err ({e})"))?;
}
Some(93) => {
let mut off = 1usize;
let _recip = read_u32(&msg, &mut off).unwrap_or(0);
let bytes_to_add = read_u32(&msg, &mut off).unwrap_or(0);
peer_initial_window = peer_initial_window.saturating_add(bytes_to_add);
}
Some(98) => {
let mut off = 1usize;
let recip = read_u32(&msg, &mut off).unwrap_or(0);
let req = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
let want_reply = msg.get(off).copied().unwrap_or(0) != 0;
if off < msg.len() {
off += 1;
}
if recip != our_chan {
notes.push(format!("wire_CHANNEL_REQUEST=wrong_recip={recip}"));
}
if req.as_slice() == b"exec" {
let cmd = read_ssh_bytes(&msg, &mut off).unwrap_or_default();
let cmd_s = String::from_utf8_lossy(&cmd).into_owned();
notes.push(format!("wire_CHANNEL_REQUEST_exec={cmd_s}"));
if want_reply {
let mut ok = vec![99]; ok.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
write_encrypted_packet(stream, s2c, &ok)
.map_err(|e| format!("channel_success=write_err ({e})"))?;
}
exec_cmd = Some(cmd_s);
break;
}
if req.as_slice() == b"subsystem" {
notes.push("wire_CHANNEL_REQUEST_subsystem=refused".into());
if want_reply {
let mut fail = vec![100];
fail.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
let _ = write_encrypted_packet(stream, s2c, &fail);
}
continue;
}
notes.push(format!(
"wire_CHANNEL_REQUEST_ack={}",
String::from_utf8_lossy(&req)
));
if want_reply {
let mut ok = vec![99]; ok.extend_from_slice(&peer_chan.unwrap_or(0).to_be_bytes());
let _ = write_encrypted_packet(stream, s2c, &ok);
}
}
Some(96) | Some(97) => {
notes.push(format!(
"wire_channel_early_eof_or_close={}",
msg.first().copied().unwrap_or(0)
));
break;
}
Some(2) | Some(4) => {
}
other => {
notes.push(format!("wire_channel_msg={}", other.unwrap_or(0)));
}
}
}
let Some(peer) = peer_chan else {
return Err("channel_open=missing".into());
};
let Some(cmd) = exec_cmd else {
return Err("channel_exec=missing".into());
};
let exit_code: u32 = if parse_git_exec_service(&cmd).is_some() {
let mut pipe = SshChannelPipe {
stream,
c2s,
s2c,
peer_channel: peer,
max_data: peer_max_packet.min(16_384) as usize,
local_window_remaining: SSH_LOCAL_INITIAL_WINDOW,
local_window_consumed: 0,
peer_window_remaining: peer_initial_window,
inbox: VecDeque::new(),
eof: false,
closed: false,
};
match dispatch_git_exec_live(repo_path, &cmd, auth_id, &mut pipe) {
Ok(pack_note) => {
notes.push(pack_note);
0
}
Err(e) => {
notes.push(e);
1
}
}
} else if cmd.trim() == "true" || cmd.trim().is_empty() {
notes.push("channel_exec=true_ok".into());
0
} else {
notes.push(format!("channel_exec=unsupported ({cmd})"));
127
};
send_channel_exit_status(stream, s2c, peer, exit_code)?;
let mut eof_pkt = vec![96]; eof_pkt.extend_from_slice(&peer.to_be_bytes());
write_encrypted_packet(stream, s2c, &eof_pkt)
.map_err(|e| format!("channel_eof=write_err ({e})"))?;
let mut close_pkt = vec![97]; close_pkt.extend_from_slice(&peer.to_be_bytes());
write_encrypted_packet(stream, s2c, &close_pkt)
.map_err(|e| format!("channel_close=write_err ({e})"))?;
let _ = stream.flush();
let _ = stream.set_read_timeout(Some(Duration::from_millis(500)));
for _ in 0..8 {
match read_encrypted_packet(stream, c2s, 65_536) {
Ok(msg) if msg.first() == Some(&97) || msg.first() == Some(&96) => break,
Ok(_) => continue,
Err(_) => break,
}
}
if exit_code == 0 {
Ok(())
} else {
Err(format!("channel_exec=exit_status={exit_code}"))
}
}
fn send_channel_exit_status(
stream: &mut TcpStream,
s2c: &mut OpenSshChaCha,
peer_channel: u32,
code: u32,
) -> Result<(), String> {
let mut pkt = vec![98]; pkt.extend_from_slice(&peer_channel.to_be_bytes());
pkt.extend(ssh_string(b"exit-status"));
pkt.push(0); pkt.extend_from_slice(&code.to_be_bytes());
write_encrypted_packet(stream, s2c, &pkt).map_err(|e| format!("exit_status=write_err ({e})"))
}
fn send_channel_window_adjust(
stream: &mut TcpStream,
s2c: &mut OpenSshChaCha,
peer_channel: u32,
bytes_to_add: u32,
) -> Result<(), String> {
let mut pkt = Vec::with_capacity(9);
pkt.push(93); pkt.extend_from_slice(&peer_channel.to_be_bytes());
pkt.extend_from_slice(&bytes_to_add.to_be_bytes());
write_encrypted_packet(stream, s2c, &pkt).map_err(|e| format!("window_adjust=write_err ({e})"))
}
struct SshChannelPipe<'a> {
stream: &'a mut TcpStream,
c2s: &'a mut OpenSshChaCha,
s2c: &'a mut OpenSshChaCha,
peer_channel: u32,
max_data: usize,
local_window_remaining: u32,
local_window_consumed: u32,
peer_window_remaining: u32,
inbox: VecDeque<u8>,
eof: bool,
closed: bool,
}
impl SshChannelPipe<'_> {
fn consume_local_window(&mut self, bytes: usize) -> std::io::Result<()> {
let delta = u32::try_from(bytes).unwrap_or(u32::MAX);
self.local_window_remaining = self.local_window_remaining.saturating_sub(delta);
self.local_window_consumed = self.local_window_consumed.saturating_add(delta);
if self.local_window_consumed >= SSH_LOCAL_WINDOW_REFILL_THRESHOLD
|| (self.local_window_remaining < SSH_LOCAL_WINDOW_REFILL_THRESHOLD
&& self.local_window_consumed > 0)
{
let add = self.local_window_consumed;
send_channel_window_adjust(self.stream, self.s2c, self.peer_channel, add)
.map_err(std::io::Error::other)?;
self.local_window_remaining = self.local_window_remaining.saturating_add(add);
self.local_window_consumed = 0;
}
Ok(())
}
fn pump_one_packet(&mut self) -> std::io::Result<()> {
let msg =
read_encrypted_packet(self.stream, self.c2s, 65_536).map_err(std::io::Error::other)?;
match msg.first().copied() {
Some(94) => {
let mut off = 1usize;
let _recip = read_u32(&msg, &mut off).unwrap_or(0);
if let Some(data) = read_ssh_bytes(&msg, &mut off) {
let n = data.len();
self.inbox.extend(data);
self.consume_local_window(n)?;
}
}
Some(95) => {
let mut off = 1usize;
let _recip = read_u32(&msg, &mut off).unwrap_or(0);
let _data_type = read_u32(&msg, &mut off).unwrap_or(0);
if let Some(data) = read_ssh_bytes(&msg, &mut off) {
self.consume_local_window(data.len())?;
}
}
Some(93) => {
let mut off = 1usize;
let _recip = read_u32(&msg, &mut off).unwrap_or(0);
let bytes_to_add = read_u32(&msg, &mut off).unwrap_or(0);
self.peer_window_remaining =
self.peer_window_remaining.saturating_add(bytes_to_add);
}
Some(96) => {
self.eof = true;
}
Some(97) => {
self.eof = true;
self.closed = true;
}
Some(98) => {
let mut off = 1usize;
let _ = read_u32(&msg, &mut off);
let _ = read_ssh_bytes(&msg, &mut off);
let want_reply = msg.get(off).copied().unwrap_or(0) != 0;
if want_reply {
let mut fail = vec![100];
fail.extend_from_slice(&self.peer_channel.to_be_bytes());
let _ = write_encrypted_packet(self.stream, self.s2c, &fail);
}
}
Some(2) | Some(4) => {}
_ => {}
}
Ok(())
}
fn send_stderr_notice(&mut self, msg: &str) {
if msg.is_empty() || self.closed {
return;
}
let data = msg.as_bytes();
let allowed = usize::try_from(self.peer_window_remaining).unwrap_or(usize::MAX);
let chunk = data.len().min(self.max_data.max(1)).min(allowed);
if chunk == 0 {
return;
}
let mut pkt = vec![95]; pkt.extend_from_slice(&self.peer_channel.to_be_bytes());
pkt.extend_from_slice(&1u32.to_be_bytes()); pkt.extend(ssh_string(&data[..chunk]));
if write_encrypted_packet(self.stream, self.s2c, &pkt).is_ok() {
self.peer_window_remaining = self
.peer_window_remaining
.saturating_sub(u32::try_from(chunk).unwrap_or(u32::MAX));
}
}
}
impl Read for SshChannelPipe<'_> {
fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
while self.inbox.is_empty() && !self.eof {
self.pump_one_packet()?;
}
if self.inbox.is_empty() {
return Ok(0);
}
self.inbox.read(buf)
}
}
impl Write for SshChannelPipe<'_> {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
if buf.is_empty() {
return Ok(0);
}
while self.peer_window_remaining == 0 {
if self.closed {
return Err(std::io::Error::new(
std::io::ErrorKind::BrokenPipe,
"SSH peer closed channel with zero send window",
));
}
self.pump_one_packet()?;
}
let allowed = usize::try_from(self.peer_window_remaining).unwrap_or(usize::MAX);
let chunk = buf.len().min(self.max_data.max(1)).min(allowed);
let mut pkt = vec![94]; pkt.extend_from_slice(&self.peer_channel.to_be_bytes());
pkt.extend(ssh_string(&buf[..chunk]));
write_encrypted_packet(self.stream, self.s2c, &pkt).map_err(std::io::Error::other)?;
self.peer_window_remaining = self
.peer_window_remaining
.saturating_sub(u32::try_from(chunk).unwrap_or(u32::MAX));
Ok(chunk)
}
fn flush(&mut self) -> std::io::Result<()> {
self.stream.flush()
}
}
fn dispatch_git_exec_live(
repo_path: &Path,
exec_cmd: &str,
auth_id: &SshAuthIdentity,
pipe: &mut SshChannelPipe<'_>,
) -> Result<String, String> {
let Some(svc) = parse_git_exec_service(exec_cmd) else {
return Err(format!("exec not git-upload-pack|receive-pack: {exec_cmd}"));
};
let mut repo = open_ssh_repo(repo_path, exec_cmd)?;
let is_single_repo =
repo_path.join("HEAD").is_file() || repo_path.join(".git").join("HEAD").is_file();
if !is_single_repo
&& repo.common_dir() != repo_path
&& repo_path.join(".arks-global-auth").exists()
{
let global_store = ForgeStore::load_shared(&repo_path.join(".arks-global-auth"));
if global_store.corrupt {
let reason = "global forge store is corrupted (fail-closed)".to_string();
pipe.send_stderr_notice(&format!("remote: {reason}\n"));
return Err(reason);
}
crate::web_ui::sync_global_auth_into_repo(repo_path, repo.common_dir());
}
let store = ForgeStore::load_shared(repo.common_dir());
let effective_user = resolve_ssh_identity(&store, auth_id);
match svc {
"git-upload-pack" => {
if let Err(reason) = check_ssh_repo_rbac(&store, effective_user.as_deref(), false) {
pipe.send_stderr_notice(&format!("remote: {reason}\n"));
return Err(reason);
}
match upload_pack_stream(&repo, pipe) {
Ok(()) => Ok(
"channel_exec=git-upload-pack live upload_pack_stream ok (OpenSSH channel)"
.into(),
),
Err(e) => Err(format!("channel_exec=git-upload-pack live err={e}")),
}
}
"git-receive-pack" => {
if let Err(reason) = check_ssh_repo_rbac(&store, effective_user.as_deref(), true) {
pipe.send_stderr_notice(&format!("remote: {reason}\n"));
return Err(reason);
}
let pusher = match effective_user {
Some(ref user) => Pusher::ssh_user(user.as_str()),
None => Pusher::ssh(),
};
match receive_pack_stream_as(&mut repo, pipe, &pusher) {
Ok(()) => Ok(
"channel_exec=git-receive-pack live receive_pack_stream ok (OpenSSH channel)"
.into(),
),
Err(e) => Err(format!("channel_exec=git-receive-pack live err={e}")),
}
}
_ => Err(format!("unknown service {svc}")),
}
}
fn handle_userauth_request_partial(
payload: &[u8],
session_id: &[u8],
authorized_keys: &Path,
host: Option<&HostEd25519>,
stream: &mut TcpStream,
s2c: &mut OpenSshChaCha,
) -> (Option<SshAuthIdentity>, String) {
let mut off = 1usize;
let user = read_ssh_bytes(payload, &mut off).unwrap_or_default();
let service = read_ssh_bytes(payload, &mut off).unwrap_or_default();
let method = read_ssh_bytes(payload, &mut off).unwrap_or_default();
let request_user = String::from_utf8_lossy(&user).trim().to_string();
let mut notes = format!(
"auth_user={} service={} method={}",
request_user,
String::from_utf8_lossy(&service),
String::from_utf8_lossy(&method)
);
if method.as_slice() != b"publickey" {
notes.push_str("; auth=refuse_non_publickey Partial");
let mut failure = vec![51]; failure.extend(ssh_name_list(&["publickey"]));
failure.push(0); let _ = write_encrypted_packet(stream, s2c, &failure);
return (None, notes);
}
if off >= payload.len() {
notes.push_str("; auth=publickey_short");
let mut failure = vec![51];
failure.extend(ssh_name_list(&["publickey"]));
failure.push(0);
let _ = write_encrypted_packet(stream, s2c, &failure);
return (None, notes);
}
let has_sig = payload[off] != 0;
off += 1;
let alg = read_ssh_bytes(payload, &mut off).unwrap_or_default();
let pubkey = read_ssh_bytes(payload, &mut off).unwrap_or_default();
notes.push_str(&format!(
"; alg={} has_sig={has_sig}",
String::from_utf8_lossy(&alg)
));
if !has_sig {
let keys = load_authorized_ed25519_keys(authorized_keys);
let ok = keys
.iter()
.any(|entry| entry.blob.as_slice() == pubkey.as_slice());
notes.push_str(&format!("; auth_pubkey_query_authorized={ok}"));
if ok {
let mut pk_ok = vec![60]; pk_ok.extend(ssh_string(&alg));
pk_ok.extend(ssh_string(&pubkey));
let _ = write_encrypted_packet(stream, s2c, &pk_ok);
} else {
let mut failure = vec![51];
failure.extend(ssh_name_list(&["publickey"]));
failure.push(0);
let _ = write_encrypted_packet(stream, s2c, &failure);
}
return (None, notes);
}
let signed_request_end = off;
let sig = read_ssh_bytes(payload, &mut off).unwrap_or_default();
let mut challenge = ssh_string(session_id);
challenge.extend_from_slice(&payload[..signed_request_end]);
match verify_publickey_against_authorized(authorized_keys, &pubkey, &challenge, &sig) {
Ok(key_comment_user) => {
notes.push_str("; auth_publickey_verify=ok against authorized_keys");
let _ = write_encrypted_packet(stream, s2c, &[52]); let id = SshAuthIdentity {
request_user,
key_comment_user,
public_blob: pubkey,
};
(Some(id), notes)
}
Err(e) => {
if let Some(h) = host {
let ch = Sha256::digest(b"arks-ssh-partial-wire-auth-fallback");
let sig_blob = sign_ssh_ed25519(h, &ch);
match verify_publickey_against_authorized(
authorized_keys,
&h.public_blob,
&ch,
&sig_blob,
) {
Ok(_) => notes.push_str(
"; auth_publickey_verify=wire_sig_fail but authorized_keys path ok offline Partial",
),
Err(_) => notes.push_str(&format!("; auth_publickey_verify=fail ({e})")),
}
} else {
notes.push_str(&format!("; auth_publickey_verify=fail ({e})"));
}
let mut failure = vec![51];
failure.extend(ssh_name_list(&["publickey"]));
failure.push(0);
let _ = write_encrypted_packet(stream, s2c, &failure);
(None, notes)
}
}
}
#[allow(clippy::too_many_arguments)]
fn try_peer_ecdh_and_sign(
stream: &mut TcpStream,
peer_kex: &[String],
host: Option<&HostEd25519>,
our_id: &str,
peer_id: &str,
our_kexinit: &[u8],
peer_kexinit: &[u8],
authorized_keys: &Path,
repo_path: &Path,
) -> (SshStage, String) {
let want = peer_kex
.iter()
.any(|n| n == "curve25519-sha256" || n == "curve25519-sha256@libssh.org");
if !want {
return (
SshStage::AlgoSelect,
"ecdh_peer=skipped (no common curve25519-sha256)".into(),
);
}
let payload = match read_ssh_packet(stream, 4096) {
Ok(p) => p,
Err(e)
if e.kind() == std::io::ErrorKind::WouldBlock
|| e.kind() == std::io::ErrorKind::TimedOut =>
{
return (SshStage::Ecdh, "ecdh_peer=timeout (no ECDH_INIT)".into());
}
Err(e) => return (SshStage::Ecdh, format!("ecdh_peer=err ({e})")),
};
if payload.is_empty() || payload[0] != 30 {
let mt = payload.first().copied().unwrap_or(0);
return (SshStage::Ecdh, format!("ecdh_peer=unexpected_msg={mt}"));
}
if payload.len() < 5 {
return (SshStage::Ecdh, "ecdh_peer=init_short".into());
}
let qlen = u32::from_be_bytes(payload[1..5].try_into().unwrap_or([0; 4])) as usize;
if qlen != 32 || payload.len() < 5 + qlen {
return (SshStage::Ecdh, format!("ecdh_peer=bad_q_c_len ({qlen})"));
}
let mut q_c = [0u8; 32];
q_c.copy_from_slice(&payload[5..5 + 32]);
let peer_pk = PublicKey::from(q_c);
let secret = StaticSecret::random();
let q_s = PublicKey::from(&secret);
let shared = secret.diffie_hellman(&peer_pk);
if shared.as_bytes().iter().all(|byte| *byte == 0) {
return (
SshStage::Ecdh,
"ecdh_peer=all_zero_shared_secret (RFC 8731 reject)".into(),
);
}
let mut h = Sha256::new();
h.update(b"arks-ssh-partial-peer-ecdh");
h.update(shared.as_bytes());
h.update(q_s.as_bytes());
let digest = h.finalize();
let mut notes = vec![format!(
"ecdh_peer=shared_ok q_s_ready=1 shared_sha256={:02x}{:02x}…",
digest[0], digest[1]
)];
let Some(host) = host else {
notes.push(
"stop=host_key_sign Missing (no loadable ed25519 host key; KEX_ECDH_REPLY withheld)"
.into(),
);
return (SshStage::HostKeySign, notes.join("; "));
};
let encoded_k = x25519_shared_as_mpint(shared.as_bytes());
let mut exchange = Vec::new();
exchange.extend(ssh_string(
peer_id.trim_end_matches(['\r', '\n']).as_bytes(),
));
exchange.extend(ssh_string(our_id.trim_end_matches(['\r', '\n']).as_bytes()));
exchange.extend(ssh_string(peer_kexinit));
exchange.extend(ssh_string(our_kexinit));
exchange.extend(ssh_string(&host.public_blob));
exchange.extend(ssh_string(&q_c));
exchange.extend(ssh_string(q_s.as_bytes()));
exchange.extend_from_slice(&encoded_k);
let exchange_hash = Sha256::digest(&exchange);
let signature = sign_ssh_ed25519(host, &exchange_hash);
let mut reply = Vec::new();
reply.push(31); reply.extend(ssh_string(&host.public_blob));
reply.extend(ssh_string(q_s.as_bytes()));
reply.extend(ssh_string(&signature));
if let Err(e) = write_ssh_packet(stream, &reply) {
notes.push(format!("host_key_sign=reply_write_err ({e})"));
return (SshStage::HostKeySign, notes.join("; "));
}
notes.push("host_key_sign=ed25519_KEX_ECDH_REPLY_sent (Partial; not Claimed handshake)".into());
if let Err(e) = write_ssh_packet(stream, &[21]) {
notes.push(format!("newkeys=write_err ({e})"));
return (SshStage::NewKeys, notes.join("; "));
}
notes.push("newkeys=sent".into());
match read_ssh_packet(stream, 256) {
Ok(p) if p.first() == Some(&21) => notes.push("newkeys=peer_ok".into()),
Ok(p) => notes.push(format!(
"newkeys=peer_msg={}",
p.first().copied().unwrap_or(0)
)),
Err(e)
if e.kind() == std::io::ErrorKind::WouldBlock
|| e.kind() == std::io::ErrorKind::TimedOut =>
{
notes.push("newkeys=peer_timeout".into());
}
Err(e) => notes.push(format!("newkeys=peer_err ({e})")),
}
let strict_kex = peer_kex
.iter()
.any(|name| name == "kex-strict-c-v00@openssh.com");
let initial_sequence = if strict_kex { 0 } else { 3 };
notes.push(format!(
"strict_kex={strict_kex} encrypted_initial_sequence={initial_sequence}"
));
let (stage, post) = continue_after_newkeys(
stream,
&encoded_k,
&exchange_hash,
initial_sequence,
authorized_keys,
repo_path,
Some(host),
);
notes.push(post);
(stage, notes.join("; "))
}
struct PeerKexInit {
kex: Vec<String>,
hostkey: Vec<String>,
enc_c2s: Vec<String>,
enc_s2c: Vec<String>,
mac_c2s: Vec<String>,
mac_s2c: Vec<String>,
}
fn parse_peer_kexinit(payload: &[u8]) -> Option<PeerKexInit> {
if payload.first().copied()? != 20 {
return None;
}
let mut off = 1 + 16; let kex = read_ssh_name_list(payload, &mut off)?;
let hostkey = read_ssh_name_list(payload, &mut off)?;
let enc_c2s = read_ssh_name_list(payload, &mut off)?;
let enc_s2c = read_ssh_name_list(payload, &mut off)?;
let mac_c2s = read_ssh_name_list(payload, &mut off)?;
let mac_s2c = read_ssh_name_list(payload, &mut off)?;
let _compression_c2s = read_ssh_name_list(payload, &mut off)?;
let _compression_s2c = read_ssh_name_list(payload, &mut off)?;
let _languages_c2s = read_ssh_name_list(payload, &mut off)?;
let _languages_s2c = read_ssh_name_list(payload, &mut off)?;
if off + 5 > payload.len() {
return None;
}
Some(PeerKexInit {
kex,
hostkey,
enc_c2s,
enc_s2c,
mac_c2s,
mac_s2c,
})
}
fn run_kex_stages(
stream: &mut TcpStream,
host: Option<&HostEd25519>,
our_id: &str,
peer_id: &str,
authorized_keys: &Path,
repo_path: &Path,
) -> (SshStage, String) {
let mut notes = Vec::new();
let advertise = host.is_some();
let our_kexinit = build_kexinit_payload(advertise);
if let Err(e) = write_ssh_packet(stream, &our_kexinit) {
return (SshStage::KexInit, format!("kexinit=write_err ({e})"));
}
let peer_payload = match read_ssh_packet(stream, 16_384) {
Ok(p) => p,
Err(e)
if e.kind() == std::io::ErrorKind::WouldBlock
|| e.kind() == std::io::ErrorKind::TimedOut =>
{
notes.push("kexinit=sent peer=(timeout)".into());
match curve25519_ecdh_selfcheck() {
Ok(s) => notes.push(s),
Err(e) => notes.push(format!("ecdh_selfcheck=fail ({e})")),
}
notes.push("stop=host_key_sign Missing (no peer KEXINIT)".into());
return (SshStage::HostKeySign, notes.join("; "));
}
Err(e) => {
return (SshStage::KexInit, format!("kexinit=sent peer_err ({e})"));
}
};
notes.push(format!(
"kexinit=sent advertise_ed25519={advertise} peer_payload_len={}",
peer_payload.len()
));
let peer = match parse_peer_kexinit(&peer_payload) {
Some(v) => v,
None => {
notes.push("algo_select=peer_kexinit_parse_fail".into());
match curve25519_ecdh_selfcheck() {
Ok(s) => notes.push(s),
Err(e) => notes.push(format!("ecdh_selfcheck=fail ({e})")),
}
notes.push("stop=host_key_sign Missing".into());
return (SshStage::HostKeySign, notes.join("; "));
}
};
let kex_ok = peer
.kex
.iter()
.any(|n| n == "curve25519-sha256" || n == "curve25519-sha256@libssh.org");
let hostkey_ok = if advertise {
peer.hostkey.iter().any(|n| n == "ssh-ed25519")
} else {
peer.hostkey
.iter()
.any(|n| n == "arks-partial-missing-hostkey-sign")
};
let cipher_ok = peer
.enc_c2s
.iter()
.any(|n| n == "chacha20-poly1305@openssh.com")
&& peer
.enc_s2c
.iter()
.any(|n| n == "chacha20-poly1305@openssh.com");
let mac_ok = peer.mac_c2s.iter().any(|n| n == "hmac-sha2-256")
&& peer.mac_s2c.iter().any(|n| n == "hmac-sha2-256");
notes.push(format!(
"algo_select=kex_curve25519={kex_ok} hostkey_common={hostkey_ok} \
openssh_chacha={cipher_ok} mac_name_common={mac_ok} peer_kex_n={} peer_hostkey_n={}",
peer.kex.len(),
peer.hostkey.len()
));
if !kex_ok || !cipher_ok || !mac_ok {
notes.push("stop=algo_select (no complete supported algorithm set)".into());
return (SshStage::AlgoSelect, notes.join("; "));
}
if advertise && !hostkey_ok {
notes.push(
"note: peer did not offer ssh-ed25519 — still attempt ECDH; sign may be unused".into(),
);
}
match curve25519_ecdh_selfcheck() {
Ok(s) => notes.push(s),
Err(e) => {
notes.push(format!("ecdh_selfcheck=fail ({e})"));
return (SshStage::Ecdh, notes.join("; "));
}
}
let (stage, ecdh_notes) = try_peer_ecdh_and_sign(
stream,
&peer.kex,
host,
our_id,
peer_id,
&our_kexinit,
&peer_payload,
authorized_keys,
repo_path,
);
notes.push(ecdh_notes);
if !matches!(
stage,
SshStage::EncryptedTransport | SshStage::AuthPublickey | SshStage::ChannelSession
) {
notes.push(publickey_verify_scaffold(authorized_keys, host));
notes.push(channel_git_hookup_scaffold(repo_path));
}
notes.push(format!("reached_stage={}", stage.as_str()));
(stage, notes.join("; "))
}
pub fn serve_ssh_listener(opts: ServeSshOptions, stop: Arc<AtomicBool>) -> Result<(), ServerError> {
let listener = TcpListener::bind(opts.listen)?;
listener.set_nonblocking(true)?;
serve_ssh_on_listener(listener, opts, stop)
}
fn serve_ssh_on_listener(
mut listener: TcpListener,
opts: ServeSshOptions,
stop: Arc<AtomicBool>,
) -> Result<(), ServerError> {
let host_st = path_status(&opts.host_key);
let auth_st = path_status(&opts.authorized_keys);
let host_fmt = probe_host_key_format(&opts.host_key);
let auth_probe = probe_authorized_keys(&opts.authorized_keys);
let repo_st = if opts.path.exists() {
"present"
} else {
"missing"
};
let host_key = match load_host_ed25519(&opts.host_key) {
Ok(h) => Some(h),
Err(e) => {
let _ = e;
None
}
};
let host_load = if host_key.is_some() {
"ed25519_unencrypted_ok"
} else {
"unloadable_or_absent"
};
let mut current = listener.local_addr().unwrap_or(opts.listen);
let our_id = "SSH-2.0-arks";
eprintln!(
"arks serve SSH durable listen on {current}; \
host_key={hk} ({host_st}; format={host_fmt}; load={host_load}); \
authorized_keys={ak} ({auth_st}; {auth_probe}); path={path} ({repo_st})",
hk = opts.host_key.display(),
ak = opts.authorized_keys.display(),
path = opts.path.display(),
);
let host_key = Arc::new(host_key);
let auth_keys = opts.authorized_keys.clone();
let repo_path = opts.path.clone();
let host_load = Arc::new(host_load.to_string());
let session_counter = Arc::new(std::sync::atomic::AtomicU64::new(0));
let mut draining: Vec<(TcpListener, SocketAddr, Instant)> = Vec::new();
while !stop.load(Ordering::SeqCst) {
if let Some(slot) = &opts.rebind_desired {
if let Ok(mut g) = slot.lock() {
if let Some(new_addr) = g.take() {
if new_addr != current {
match TcpListener::bind(new_addr) {
Ok(l) => {
if let Err(e) = l.set_nonblocking(true) {
eprintln!(
"arks serve SSH: live rebind bind ok but \
nonblocking fail ({e}); keeping {current}"
);
*g = Some(new_addr);
} else {
eprintln!(
"arks serve SSH: live rebind dual-bind {current} → {new_addr}; \
prior listener draining for 5s"
);
let old = std::mem::replace(&mut listener, l);
draining.push((
old,
current,
Instant::now() + Duration::from_secs(5),
));
current = new_addr;
}
}
Err(e) => {
eprintln!(
"arks serve SSH: live rebind fail {current} → \
{new_addr} ({e}); keeping prior listen"
);
}
}
}
}
}
}
draining.retain(|(_, old_addr, deadline)| {
if Instant::now() < *deadline {
true
} else {
eprintln!("arks serve SSH: rebind drain complete; closing {old_addr}");
false
}
});
let spawn_session = |stream: TcpStream, peer: SocketAddr| {
let n = session_counter.fetch_add(1, Ordering::SeqCst) + 1;
let host_key = Arc::clone(&host_key);
let auth_keys = auth_keys.clone();
let repo_path = repo_path.clone();
let host_load = Arc::clone(&host_load);
let our_id = our_id.to_string();
thread::spawn(move || {
handle_ssh_session(
stream,
peer,
n,
&our_id,
host_key.as_ref().as_ref(),
&auth_keys,
&repo_path,
host_load.as_str(),
);
});
};
match listener.accept() {
Ok((stream, peer)) => spawn_session(stream, peer),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {
thread::sleep(Duration::from_millis(20));
}
Err(e) => {
return Err(ServerError::Msg(format!(
"arks serve SSH durable accept err on {current}: {e}"
)));
}
}
for (old_listener, _, _) in &draining {
match old_listener.accept() {
Ok((stream, peer)) => spawn_session(stream, peer),
Err(e) if e.kind() == std::io::ErrorKind::WouldBlock => {}
Err(e) => eprintln!("arks serve SSH: draining listener accept error: {e}"),
}
}
}
eprintln!(
"arks serve SSH durable listen stopped on {current} \
(sessions={}; ops SSHD + upload-pack/receive-pack still valid)",
session_counter.load(Ordering::SeqCst)
);
Ok(())
}
#[allow(clippy::too_many_arguments)]
fn handle_ssh_session(
mut stream: TcpStream,
peer: SocketAddr,
sessions: u64,
our_id: &str,
host_key: Option<&HostEd25519>,
authorized_keys: &Path,
path: &Path,
host_load: &str,
) {
let _ = stream.set_nonblocking(false);
let _ = stream.set_nodelay(true);
let _ = stream.set_read_timeout(Some(Duration::from_secs(8)));
let _ = stream.set_write_timeout(Some(Duration::from_secs(8)));
let ours = format!("{our_id}\r\n");
let _ = stream.write_all(ours.as_bytes());
let _ = stream.flush();
let peer_id = read_ssh_identification(&mut stream)
.unwrap_or_default()
.chars()
.take(255)
.collect::<String>();
let id_part = if peer_id.is_empty() {
format!("id_exchange=no_peer_id peer={peer} peer_id=(empty/timeout)")
} else {
format!("id_exchange=ok peer={peer} peer_id={peer_id}")
};
let (stage, kex_part) = if peer_id.is_empty() {
match curve25519_ecdh_selfcheck() {
Ok(s) => {
let auth = publickey_verify_scaffold(authorized_keys, host_key);
let chan = channel_git_hookup_scaffold(path);
(
SshStage::HostKeySign,
format!(
"kex=skipped_no_peer_id; {s}; host_load={host_load}; {auth}; {chan}; \
stop=host_key_sign/wire Missing without peer"
),
)
}
Err(e) => (
SshStage::Ecdh,
format!("kex=skipped_no_peer_id; ecdh_selfcheck=fail ({e})"),
),
}
} else {
run_kex_stages(
&mut stream,
host_key,
our_id,
&peer_id,
authorized_keys,
path,
)
};
let _ = stream.flush();
let _ = stream.shutdown(Shutdown::Write);
eprintln!(
"arks serve SSH session#{sessions} reached_stage={} \
({id_part}; {kex_part})",
stage.as_str()
);
}
type LoopbackSsh = (
SocketAddr,
Arc<AtomicBool>,
thread::JoinHandle<Result<(), ServerError>>,
);
pub fn spawn_ssh_listener(
opts: ServeSshOptions,
) -> Result<(Arc<AtomicBool>, ListenerThread), ServerError> {
let listener = TcpListener::bind(opts.listen)?;
listener.set_nonblocking(true)?;
let stop = Arc::new(AtomicBool::new(false));
let stop2 = stop.clone();
let handle = thread::spawn(move || serve_ssh_on_listener(listener, opts, stop2));
Ok((stop, handle))
}
pub fn spawn_loopback_ssh(opts: ServeSshOptions) -> Result<LoopbackSsh, ServerError> {
let listener = TcpListener::bind("127.0.0.1:0")?;
let addr = listener.local_addr()?;
listener.set_nonblocking(true)?;
let mut opts = opts;
opts.listen = addr;
let stop = Arc::new(AtomicBool::new(false));
let stop2 = stop.clone();
let handle = thread::spawn(move || serve_ssh_on_listener(listener, opts, stop2));
Ok((addr, stop, handle))
}
#[cfg(test)]
mod tests {
use super::*;
use ed25519_dalek::SigningKey;
#[test]
fn parse_git_exec_services() {
assert_eq!(
parse_git_exec_service("git-upload-pack '/tmp/r.git'"),
Some("git-upload-pack")
);
assert_eq!(
parse_git_exec_service("git-receive-pack '/tmp/r.git'"),
Some("git-receive-pack")
);
assert_eq!(parse_git_exec_service("bash"), None);
}
#[test]
fn chacha_aead_roundtrip_partial() {
let shared = x25519_shared_as_mpint(&[7u8; 32]);
let h = Sha256::digest(b"exchange-hash-partial");
let note = encrypted_transport_selfcheck(&shared, &h);
assert!(note.contains("selfcheck=ok"), "{note}");
}
#[test]
fn rfc8731_shared_secret_mpint_encoding() {
let mut high_bit = [0u8; 32];
high_bit[0] = 0x80;
let encoded = x25519_shared_as_mpint(&high_bit);
assert_eq!(&encoded[..4], &33u32.to_be_bytes());
assert_eq!(encoded[4], 0);
assert_eq!(encoded[5], 0x80);
let mut leading_zero = [0u8; 32];
leading_zero[1] = 1;
let encoded = x25519_shared_as_mpint(&leading_zero);
assert_eq!(&encoded[..4], &31u32.to_be_bytes());
assert_eq!(encoded[4], 1);
}
#[test]
fn authorized_keys_verify_partial() {
let dir = tempfile::tempdir().unwrap();
let seed = [9u8; 32];
let signing = SigningKey::from_bytes(&seed);
let vk = signing.verifying_key();
let blob = build_ssh_ed25519_public_blob(vk.as_bytes());
let b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &blob);
let ak = dir.path().join("authorized_keys");
std::fs::write(&ak, format!("ssh-ed25519 {b64} test@arks\n")).unwrap();
let challenge = b"challenge-partial";
let sig = signing.sign(challenge);
let mut sig_blob = Vec::new();
sig_blob.extend(ssh_string(b"ssh-ed25519"));
sig_blob.extend(ssh_string(&sig.to_bytes()));
verify_publickey_against_authorized(&ak, &blob, challenge, &sig_blob).unwrap();
}
#[test]
fn ssh_receive_pack_rejects_archived_repo() {
let dir = tempfile::tempdir().unwrap();
let repo_path = dir.path().join("arch.git");
std::fs::create_dir_all(repo_path.join("objects")).unwrap();
std::fs::create_dir_all(repo_path.join("refs").join("heads")).unwrap();
std::fs::write(repo_path.join("HEAD"), "ref: refs/heads/main\n").unwrap();
std::fs::write(
repo_path.join("config"),
"[core]\n\trepositoryformatversion = 0\n\tbare = true\n",
)
.unwrap();
let mut store = crate::web_ui::store::ForgeStore::load(&repo_path);
store.archived = true;
store.save(&repo_path).unwrap();
let err = dispatch_git_exec_to_pack(&repo_path, "git-receive-pack '.'").unwrap_err();
assert!(
err.contains("archived"),
"SSH receive-pack must reject archived repo: {err}"
);
}
#[test]
fn ssh_identity_resolution_and_rbac_with_pusher_ssh_user() {
let dir = tempfile::tempdir().unwrap();
let alice_sk = SigningKey::from_bytes(&[1u8; 32]);
let bob_sk = SigningKey::from_bytes(&[2u8; 32]);
let carol_sk = SigningKey::from_bytes(&[3u8; 32]);
let alice_blob = build_ssh_ed25519_public_blob(alice_sk.verifying_key().as_bytes());
let bob_blob = build_ssh_ed25519_public_blob(bob_sk.verifying_key().as_bytes());
let carol_blob = build_ssh_ed25519_public_blob(carol_sk.verifying_key().as_bytes());
let alice_b64 =
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &alice_blob);
let bob_b64 = base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &bob_blob);
let carol_b64 =
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &carol_blob);
let ak = dir.path().join("authorized_keys");
std::fs::write(
&ak,
format!(
"# alice (laptop)\nssh-ed25519 {alice_b64} alice@example.invalid\n\
# bob (reader-key)\nssh-ed25519 {bob_b64} bob@example.invalid\n\
# carol (collab-key)\nssh-ed25519 {carol_b64} carol@example.invalid\n"
),
)
.unwrap();
let challenge = b"ssh-userauth-challenge";
let alice_sig = sign_ssh_ed25519(
&HostEd25519 {
signing: alice_sk,
public_blob: alice_blob.clone(),
},
challenge,
);
let comment_user =
verify_publickey_against_authorized(&ak, &alice_blob, challenge, &alice_sig).unwrap();
assert_eq!(comment_user.as_deref(), Some("alice"));
let mut store = ForgeStore {
visibility: "private".into(),
..Default::default()
};
store.users.push(crate::web_ui::store::UserAccount {
username: "alice".into(),
password_hash: "x".into(),
role: "admin".into(),
ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
title: "laptop".into(),
public_key: format!("ssh-ed25519 {alice_b64} alice@example.invalid"),
added_at: 1,
fingerprint: String::new(),
}],
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
external_ids: Vec::new(),
});
store.users.push(crate::web_ui::store::UserAccount {
username: "bob".into(),
password_hash: "x".into(),
role: "reader".into(),
ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
title: "reader-key".into(),
public_key: format!("ssh-ed25519 {bob_b64} bob@example.invalid"),
added_at: 1,
fingerprint: String::new(),
}],
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
external_ids: Vec::new(),
});
store.users.push(crate::web_ui::store::UserAccount {
username: "carol".into(),
password_hash: "x".into(),
role: "reader".into(),
ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
title: "collab-key".into(),
public_key: format!("ssh-ed25519 {carol_b64} carol@example.invalid"),
added_at: 1,
fingerprint: String::new(),
}],
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
external_ids: Vec::new(),
});
store.collaborators.push("carol".into());
let alice_id = SshAuthIdentity {
request_user: "git".into(),
key_comment_user: Some("alice".into()),
public_blob: alice_blob,
};
let resolved_alice = resolve_ssh_identity(&store, &alice_id);
assert_eq!(resolved_alice.as_deref(), Some("alice"));
let pusher = Pusher::ssh_user(resolved_alice.as_deref().unwrap());
assert_eq!(pusher.transport, "ssh");
assert_eq!(pusher.verified_user.as_deref(), Some("alice"));
assert!(check_ssh_repo_rbac(&store, resolved_alice.as_deref(), false).is_ok());
assert!(check_ssh_repo_rbac(&store, resolved_alice.as_deref(), true).is_ok());
let spoof_id = SshAuthIdentity {
request_user: "alice".into(),
key_comment_user: Some("bob".into()),
public_blob: bob_blob,
};
let resolved_bob = resolve_ssh_identity(&store, &spoof_id);
assert_eq!(resolved_bob.as_deref(), Some("bob"));
assert!(check_ssh_repo_rbac(&store, resolved_bob.as_deref(), false).is_err());
assert!(check_ssh_repo_rbac(&store, resolved_bob.as_deref(), true).is_err());
let carol_id = SshAuthIdentity {
request_user: "git".into(),
key_comment_user: Some("carol".into()),
public_blob: carol_blob,
};
let resolved_carol = resolve_ssh_identity(&store, &carol_id);
assert_eq!(resolved_carol.as_deref(), Some("carol"));
assert!(check_ssh_repo_rbac(&store, resolved_carol.as_deref(), false).is_ok());
assert!(check_ssh_repo_rbac(&store, resolved_carol.as_deref(), true).is_err());
}
#[test]
fn ssh_channel_pipe_bidirectional_window_adjust_over_2mib() {
let key_c2s = [0x11u8; 64];
let key_s2c = [0x22u8; 64];
let payload_len = (2 * 1024 * 1024) + (512 * 1024);
{
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let expected: Vec<u8> = (0..payload_len).map(|i| (i % 251) as u8).collect();
let client_data = expected.clone();
let client = thread::spawn(move || -> u64 {
let mut sock = TcpStream::connect(addr).unwrap();
sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
sock.set_write_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
let mut remote_window: u32 = SSH_LOCAL_INITIAL_WINDOW;
let mut total_adjust_received: u64 = 0;
for chunk in client_data.chunks(16_384) {
while (remote_window as usize) < chunk.len() {
let msg = read_encrypted_packet(&mut sock, &mut s2c, 65_536).unwrap();
assert_eq!(msg.first().copied(), Some(93), "expected WINDOW_ADJUST");
let mut off = 1usize;
let _chan = read_u32(&msg, &mut off).unwrap();
let add = read_u32(&msg, &mut off).unwrap();
remote_window = remote_window.saturating_add(add);
total_adjust_received += u64::from(add);
}
let mut pkt = vec![94]; pkt.extend_from_slice(&0u32.to_be_bytes());
pkt.extend(ssh_string(chunk));
write_encrypted_packet(&mut sock, &mut c2s, &pkt).unwrap();
remote_window -= chunk.len() as u32;
}
let mut eof = vec![96];
eof.extend_from_slice(&0u32.to_be_bytes());
write_encrypted_packet(&mut sock, &mut c2s, &eof).unwrap();
let _ = sock.shutdown(std::net::Shutdown::Write);
while let Ok(msg) = read_encrypted_packet(&mut sock, &mut s2c, 65_536) {
if msg.first().copied() == Some(93) {
let mut off = 1usize;
let _chan = read_u32(&msg, &mut off).unwrap();
let add = read_u32(&msg, &mut off).unwrap();
total_adjust_received += u64::from(add);
}
}
total_adjust_received
});
let (mut srv_sock, _) = listener.accept().unwrap();
srv_sock
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
srv_sock
.set_write_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
let mut pipe = SshChannelPipe {
stream: &mut srv_sock,
c2s: &mut c2s,
s2c: &mut s2c,
peer_channel: 7,
max_data: 16_384,
local_window_remaining: SSH_LOCAL_INITIAL_WINDOW,
local_window_consumed: 0,
peer_window_remaining: 65_536,
inbox: VecDeque::new(),
eof: false,
closed: false,
};
let mut received = Vec::with_capacity(payload_len);
pipe.read_to_end(&mut received).unwrap();
assert_eq!(received.len(), expected.len());
assert_eq!(received, expected);
let total_adjust = client.join().unwrap();
assert!(
total_adjust >= 512 * 1024,
"server must send WINDOW_ADJUST during >2 MiB push (got {total_adjust})"
);
}
{
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let expected: Vec<u8> = (0..payload_len).map(|i| ((i * 7) % 251) as u8).collect();
let initial_peer_window: u32 = 128 * 1024;
let client = thread::spawn(move || -> Vec<u8> {
let mut sock = TcpStream::connect(addr).unwrap();
sock.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
sock.set_write_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
let mut got = Vec::with_capacity(payload_len);
let mut remaining_window: u32 = initial_peer_window;
let mut sent_interleaved_data = false;
while got.len() < payload_len {
let msg = read_encrypted_packet(&mut sock, &mut s2c, 65_536).unwrap();
assert_eq!(msg.first().copied(), Some(94), "expected CHANNEL_DATA");
let mut off = 1usize;
let _chan = read_u32(&msg, &mut off).unwrap();
let data = read_ssh_bytes(&msg, &mut off).unwrap();
assert!(
(data.len() as u32) <= remaining_window,
"server violated peer RFC 4254 window: sent {} with {} remaining",
data.len(),
remaining_window
);
remaining_window -= data.len() as u32;
got.extend_from_slice(&data);
if remaining_window == 0 && got.len() < payload_len {
if !sent_interleaved_data {
let mut inter = vec![94]; inter.extend_from_slice(&0u32.to_be_bytes());
inter.extend(ssh_string(b"interleaved-ping"));
write_encrypted_packet(&mut sock, &mut c2s, &inter).unwrap();
sent_interleaved_data = true;
}
let refill: u32 = 256 * 1024;
let mut adj = vec![93]; adj.extend_from_slice(&0u32.to_be_bytes());
adj.extend_from_slice(&refill.to_be_bytes());
write_encrypted_packet(&mut sock, &mut c2s, &adj).unwrap();
remaining_window += refill;
}
}
got
});
let (mut srv_sock, _) = listener.accept().unwrap();
srv_sock
.set_read_timeout(Some(Duration::from_secs(5)))
.unwrap();
srv_sock
.set_write_timeout(Some(Duration::from_secs(5)))
.unwrap();
let mut c2s = OpenSshChaCha::new(&key_c2s, 0).unwrap();
let mut s2c = OpenSshChaCha::new(&key_s2c, 0).unwrap();
let mut pipe = SshChannelPipe {
stream: &mut srv_sock,
c2s: &mut c2s,
s2c: &mut s2c,
peer_channel: 7,
max_data: 16_384,
local_window_remaining: SSH_LOCAL_INITIAL_WINDOW,
local_window_consumed: 0,
peer_window_remaining: initial_peer_window,
inbox: VecDeque::new(),
eof: false,
closed: false,
};
pipe.write_all(&expected).unwrap();
pipe.flush().unwrap();
let mut buffered = [0u8; 32];
let n = pipe.read(&mut buffered).unwrap();
assert_eq!(&buffered[..n], b"interleaved-ping");
let client_got = client.join().unwrap();
assert_eq!(client_got.len(), expected.len());
assert_eq!(client_got, expected);
}
}
#[test]
fn open_ssh_repo_multi_repo_hardening() {
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("repos");
let outside = dir.path().join("secret.git");
std::fs::create_dir_all(&root).unwrap();
for repo_dir in [
root.join("alpha.git"),
root.join("beta"),
root.join("gamma").join(".git"),
outside.clone(),
] {
std::fs::create_dir_all(repo_dir.join("objects")).unwrap();
std::fs::create_dir_all(repo_dir.join("refs/heads")).unwrap();
std::fs::write(repo_dir.join("HEAD"), "ref: refs/heads/main\n").unwrap();
}
assert!(open_ssh_repo(&root, "git-upload-pack '/alpha.git'").is_ok());
assert!(open_ssh_repo(&root, "git-upload-pack '/alpha'").is_ok());
assert!(open_ssh_repo(&root, "git-upload-pack '/beta'").is_ok());
assert!(open_ssh_repo(&root, "git-upload-pack '/gamma'").is_ok());
for bad in [
"git-upload-pack '/../secret.git'",
"git-upload-pack '/alpha/../../secret.git'",
"git-upload-pack '/alpha\0.git'",
"git-upload-pack '/.arks-global-auth'",
"git-upload-pack '/.git'",
"git-upload-pack '/..\\secret.git'",
"git-upload-pack '.'",
] {
assert!(
open_ssh_repo(&root, bad).is_err(),
"must reject traversal/invalid ssh path: {bad}"
);
}
#[cfg(unix)]
{
let link = root.join("escape.git");
std::os::unix::fs::symlink(&outside, &link).unwrap();
assert!(
open_ssh_repo(&root, "git-upload-pack '/escape.git'").is_err(),
"must reject symlink escaping multi-repo root"
);
}
}
#[test]
fn ssh_rbac_corrupt_store_fails_closed() {
let corrupt_store = ForgeStore {
corrupt: true,
..Default::default()
};
let auth = SshAuthIdentity {
request_user: "alice".into(),
key_comment_user: Some("alice".into()),
public_blob: Vec::new(),
};
assert_eq!(resolve_ssh_identity(&corrupt_store, &auth), None);
let read_err = check_ssh_repo_rbac(&corrupt_store, Some("alice"), false).unwrap_err();
assert!(read_err.contains("corrupted"), "{read_err}");
let write_err = check_ssh_repo_rbac(&corrupt_store, Some("alice"), true).unwrap_err();
assert!(write_err.contains("corrupted"), "{write_err}");
}
#[test]
fn ssh_identity_rejects_keyless_admin_request_user_spoofing() {
let attacker_sk = SigningKey::from_bytes(&[42u8; 32]);
let attacker_blob = build_ssh_ed25519_public_blob(attacker_sk.verifying_key().as_bytes());
let mut store = ForgeStore {
visibility: "private".into(),
..Default::default()
};
store.users.push(crate::web_ui::store::UserAccount {
username: "admin".into(),
password_hash: "x".into(),
role: "admin".into(),
ssh_keys: Vec::new(),
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
external_ids: Vec::new(),
});
let spoof = SshAuthIdentity {
request_user: "admin".into(),
key_comment_user: None,
public_blob: attacker_blob.clone(),
};
assert_eq!(resolve_ssh_identity(&store, &spoof), None);
assert!(check_ssh_repo_rbac(&store, None, false).is_err());
assert!(check_ssh_repo_rbac(&store, None, true).is_err());
let annotated = SshAuthIdentity {
request_user: "git".into(),
key_comment_user: Some("admin".into()),
public_blob: attacker_blob,
};
assert_eq!(
resolve_ssh_identity(&store, &annotated).as_deref(),
Some("admin")
);
assert!(check_ssh_repo_rbac(&store, Some("admin"), true).is_ok());
}
#[test]
fn ssh_reader_collaborator_upload_allowed_receive_denied_and_multi_repo_global_auth_syncs() {
let mut store = ForgeStore {
visibility: "private".into(),
..Default::default()
};
store.users.push(crate::web_ui::store::UserAccount {
username: "reader_collab".into(),
password_hash: "x".into(),
role: "reader".into(),
ssh_keys: Vec::new(),
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
external_ids: Vec::new(),
});
store.users.push(crate::web_ui::store::UserAccount {
username: "maint1".into(),
password_hash: "x".into(),
role: "maintainer".into(),
ssh_keys: Vec::new(),
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
external_ids: Vec::new(),
});
store.collaborators.push("reader_collab".into());
assert!(check_ssh_repo_rbac(&store, Some("reader_collab"), false).is_ok());
let err = check_ssh_repo_rbac(&store, Some("reader_collab"), true).unwrap_err();
assert!(err.contains("cannot push"), "{err}");
assert!(check_ssh_repo_rbac(&store, Some("maint1"), false).is_ok());
assert!(check_ssh_repo_rbac(&store, Some("maint1"), true).is_ok());
let dir = tempfile::tempdir().unwrap();
let root = dir.path().join("multi");
let child = root.join("demo.git");
let global = root.join(".arks-global-auth");
std::fs::create_dir_all(child.join("objects")).unwrap();
std::fs::create_dir_all(child.join("refs/heads")).unwrap();
std::fs::write(child.join("HEAD"), "ref: refs/heads/main\n").unwrap();
std::fs::create_dir_all(&global).unwrap();
let admin_sk = SigningKey::from_bytes(&[77u8; 32]);
let admin_blob = build_ssh_ed25519_public_blob(admin_sk.verifying_key().as_bytes());
let admin_b64 =
base64::Engine::encode(&base64::engine::general_purpose::STANDARD, &admin_blob);
let mut gstore = ForgeStore::load(&global);
gstore.users.push(crate::web_ui::store::UserAccount {
username: "global_admin".into(),
password_hash: "x".into(),
role: "admin".into(),
ssh_keys: vec![crate::web_ui::store::SshKeyRecord {
title: "deploy".into(),
public_key: format!("ssh-ed25519 {admin_b64} global-admin@example.invalid"),
added_at: 1,
fingerprint: String::new(),
}],
created_at: 1,
totp_secret_b32: None,
recovery_codes: Vec::new(),
external_ids: Vec::new(),
});
gstore.save(&global).unwrap();
let repo = open_ssh_repo(&root, "git-receive-pack '/demo.git'").unwrap();
assert_ne!(repo.common_dir(), root.as_path());
crate::web_ui::sync_global_auth_into_repo(&root, repo.common_dir());
let synced = ForgeStore::load_shared(repo.common_dir());
let id = SshAuthIdentity {
request_user: "git".into(),
key_comment_user: None,
public_blob: admin_blob,
};
let resolved = resolve_ssh_identity(&synced, &id);
assert_eq!(resolved.as_deref(), Some("global_admin"));
assert!(check_ssh_repo_rbac(&synced, resolved.as_deref(), true).is_ok());
}
#[test]
fn parse_openssh_ed25519_bin_rejects_truncated_inputs_without_panic() {
assert!(parse_openssh_ed25519_bin(b"").is_err());
assert!(parse_openssh_ed25519_bin(b"openssh-key-v1\0").is_err());
let mut short_nkeys = b"openssh-key-v1\0".to_vec();
short_nkeys.extend(ssh_string(b"none"));
short_nkeys.extend(ssh_string(b"none"));
short_nkeys.extend(ssh_string(b""));
short_nkeys.extend_from_slice(&[0u8, 1u8]);
assert!(parse_openssh_ed25519_bin(&short_nkeys).is_err());
let mut short_priv = b"openssh-key-v1\0".to_vec();
short_priv.extend(ssh_string(b"none"));
short_priv.extend(ssh_string(b"none"));
short_priv.extend(ssh_string(b""));
short_priv.extend_from_slice(&1u32.to_be_bytes());
short_priv.extend(ssh_string(b"pub"));
short_priv.extend(ssh_string(b"abc"));
assert!(parse_openssh_ed25519_bin(&short_priv).is_err());
let mut off = 2usize;
assert!(read_u32(&[1, 2, 3], &mut off).is_err());
let mut max_off = usize::MAX;
assert!(read_u32(&[1, 2, 3, 4], &mut max_off).is_err());
}
}