navid/veins / 83508482911f348af86cb892949a35bdce0d6b2f949b4a0faab7cba9a499fb82 / veinsrs/src/crypto.rs

crypto.rs

← veinsrs/src · 16625 bytes · raw · download

use std::fs;
use std::os::unix::fs::PermissionsExt;

use ring::signature::KeyPair;

pub type PublicKey = [u8; 32];
pub type Signature = [u8; 64];

pub fn ed25519_public_from_seed(seed: &[u8]) -> Option<PublicKey> {
    if seed.len() != 32 {
        return None;
    }
    let pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(seed).ok()?;
    let public = pair.public_key().as_ref();
    if public.len() != 32 {
        return None;
    }
    let mut output = [0u8; 32];
    output.copy_from_slice(public);
    Some(output)
}

pub fn ed25519_sign(seed: &[u8], message: &[u8]) -> Option<Signature> {
    if seed.len() != 32 {
        return None;
    }
    let pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(seed).ok()?;
    let signature = pair.sign(message);
    let bytes = signature.as_ref();
    if bytes.len() != 64 {
        return None;
    }
    let mut output = [0u8; 64];
    output.copy_from_slice(bytes);
    Some(output)
}

pub fn ed25519_verify(public_key: &PublicKey, message: &[u8], signature: &[u8]) -> bool {
    if signature.len() != 64 {
        return false;
    }
    ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key)
        .verify(message, signature)
        .is_ok()
}

pub fn key_fingerprint_bytes(public_key: &PublicKey) -> [u8; 16] {
    let mut hasher = blake3::Hasher::new();
    hasher.update(b"veins/key/1\0");
    hasher.update(public_key);
    let digest = hasher.finalize();
    let mut output = [0u8; 16];
    output.copy_from_slice(&digest.as_bytes()[..16]);
    output
}

pub fn base32_text(raw: &[u8]) -> String {
    const ALPHABET: &[u8; 32] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZ234567";
    let mut output = String::with_capacity(raw.len() * 8 / 5 + 2);
    let mut bits = 0u64;
    let mut count = 0usize;
    for byte in raw {
        bits = (bits << 8) | *byte as u64;
        count += 8;
        while count >= 5 {
            count -= 5;
            output.push(ALPHABET[((bits >> count) & 31) as usize] as char);
        }
    }
    if count > 0 {
        output.push(ALPHABET[((bits << (5 - count)) & 31) as usize] as char);
    }
    output
}

pub fn key_fingerprint(public_key: &PublicKey) -> String {
    base32_text(&key_fingerprint_bytes(public_key))
}

pub fn base64url_encode(raw: &[u8]) -> String {
    const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
    let mut output = String::with_capacity(raw.len() * 4 / 3 + 4);
    let mut accumulator = 0u32;
    let mut bits = 0usize;
    for byte in raw {
        accumulator = (accumulator << 8) | *byte as u32;
        bits += 8;
        while bits >= 6 {
            bits -= 6;
            output.push(ALPHABET[((accumulator >> bits) & 63) as usize] as char);
        }
    }
    if bits > 0 {
        output.push(ALPHABET[((accumulator << (6 - bits)) & 63) as usize] as char);
    }
    output
}

pub fn base64url_decode(text: &str) -> Option<Vec<u8>> {
    if text.is_empty() {
        return None;
    }
    let value = |character: u8| -> Option<u32> {
        match character {
            b'A'..=b'Z' => Some((character - b'A') as u32),
            b'a'..=b'z' => Some((character - b'a' + 26) as u32),
            b'0'..=b'9' => Some((character - b'0' + 52) as u32),
            b'-' => Some(62),
            b'_' => Some(63),
            _ => None,
        }
    };
    let mut output = Vec::with_capacity(text.len() * 6 / 8);
    let mut accumulator = 0u32;
    let mut bits = 0usize;
    for character in text.bytes() {
        accumulator = (accumulator << 6) | value(character)?;
        bits += 6;
        if bits >= 8 {
            bits -= 8;
            output.push(((accumulator >> bits) & 255) as u8);
        }
    }
    Some(output)
}

pub fn format_public_key(public_key: &PublicKey) -> String {
    format!("ed25519:{}", base64url_encode(public_key))
}

pub fn parse_public_key(text: &str) -> Option<PublicKey> {
    let value = text.strip_prefix("ed25519:")?;
    let decoded = base64url_decode(value)?;
    if decoded.len() != 32 {
        return None;
    }
    let mut output = [0u8; 32];
    output.copy_from_slice(&decoded);
    Some(output)
}

pub fn secure_random(count: usize) -> Vec<u8> {
    use ring::rand::SecureRandom;
    let mut output = vec![0u8; count];
    let random = ring::rand::SystemRandom::new();
    if random.fill(&mut output).is_err() {
        return Vec::new();
    }
    output
}

pub struct Key {
    pub name: String,
    pub seed: Vec<u8>,
    pub public_key: PublicKey,
    pub fingerprint: String,
}

pub fn key_dir() -> std::path::PathBuf {
    if let Ok(value) = std::env::var("XDG_CONFIG_HOME")
        && !value.is_empty()
    {
        return std::path::PathBuf::from(value).join("veins").join("keys");
    }
    if let Ok(home) = std::env::var("HOME")
        && !home.is_empty()
    {
        return std::path::PathBuf::from(home)
            .join(".config")
            .join("veins")
            .join("keys");
    }
    std::path::PathBuf::from(".veins-keys")
}

fn valid_key_name(name: &str) -> bool {
    !name.is_empty() && name.len() <= 128 && !name.contains(['/', '\\', '\0'])
}

pub fn key_path(name: &str) -> std::path::PathBuf {
    key_dir().join(format!("{name}.key"))
}

pub fn load_key(name: &str) -> Option<Key> {
    if !valid_key_name(name) {
        return None;
    }
    let path = key_path(name);
    let metadata = fs::metadata(&path).ok()?;
    if metadata.permissions().mode() & 63 != 0 {
        return None;
    }
    let data = fs::read(path).ok()?;
    if data.len() != 33 || data[0] != 1 {
        return None;
    }
    let seed = data[1..].to_vec();
    let public_key = ed25519_public_from_seed(&seed)?;
    Some(Key {
        name: name.to_string(),
        fingerprint: key_fingerprint(&public_key),
        seed,
        public_key,
    })
}

pub fn generate_key(name: &str) -> Option<Key> {
    if !valid_key_name(name) {
        return None;
    }
    let directory = key_dir();
    fs::create_dir_all(&directory).ok()?;
    let _ = fs::set_permissions(&directory, fs::Permissions::from_mode(0o700));
    let seed = secure_random(32);
    if seed.len() != 32 {
        return None;
    }
    let public_key = ed25519_public_from_seed(&seed)?;
    let mut body = Vec::with_capacity(33);
    body.push(1);
    body.extend_from_slice(&seed);
    let path = key_path(name);
    fs::write(&path, &body).ok()?;
    let _ = fs::set_permissions(&path, fs::Permissions::from_mode(0o600));
    Some(Key {
        name: name.to_string(),
        fingerprint: key_fingerprint(&public_key),
        seed,
        public_key,
    })
}

pub fn list_key_names() -> Vec<String> {
    let directory = key_dir();
    let mut output = Vec::new();
    for name in crate::core::list_directory(&directory) {
        let text = String::from_utf8_lossy(&name);
        if let Some(stem) = text.strip_suffix(".key") {
            output.push(stem.to_string());
        }
    }
    output
}

pub fn auth_dir() -> std::path::PathBuf {
    let directory = key_dir();
    match directory.parent() {
        Some(parent) => parent.join("auth"),
        None => std::path::PathBuf::from(".veins-auth"),
    }
}

fn authority_of(input: &str) -> Option<String> {
    let text = crate::core::trim_str(input);
    let mut start = 0;
    if let Some(scheme) = text.find("://") {
        start = scheme + 3;
    }
    if start >= text.len() {
        return None;
    }
    let end = text[start..]
        .find('/')
        .map(|offset| start + offset)
        .unwrap_or(text.len());
    if end <= start {
        return None;
    }
    let raw = &text[start..end];
    let host = raw.rsplit('@').next().unwrap_or(raw);
    if host.is_empty() {
        return None;
    }
    Some(host.to_ascii_lowercase())
}

pub fn normalize_target(target: &str) -> String {
    let text = crate::core::trim_str(target);
    if text.is_empty() || text == "default" {
        return "default".to_string();
    }
    if let Some(authority) = authority_of(text) {
        return authority;
    }
    let raw = text.split('/').next().unwrap_or(text);
    let host = raw.rsplit('@').next().unwrap_or(raw);
    if host.is_empty() {
        "default".to_string()
    } else {
        host.to_ascii_lowercase()
    }
}

fn hex_encode(data: &[u8]) -> String {
    let mut output = String::with_capacity(data.len() * 2);
    for byte in data {
        output.push_str(&format!("{byte:02x}"));
    }
    output
}

fn hex_decode(text: &str) -> Option<Vec<u8>> {
    if text.is_empty() || text.len() % 2 != 0 {
        return None;
    }
    let value = |character: u8| -> Option<u8> {
        match character {
            b'0'..=b'9' => Some(character - b'0'),
            b'a'..=b'f' => Some(character - b'a' + 10),
            _ => None,
        }
    };
    let mut output = Vec::with_capacity(text.len() / 2);
    for pair in text.as_bytes().chunks(2) {
        output.push((value(pair[0])? << 4) | value(pair[1])?);
    }
    Some(output)
}

fn target_path(directory: &std::path::Path, target: &str) -> std::path::PathBuf {
    directory.join(hex_encode(target.as_bytes()))
}

pub fn set_key(target: &str, key_name: &str) -> bool {
    if target.is_empty() || key_name.is_empty() {
        return false;
    }
    let directory = auth_dir();
    if !crate::core::ensure_directory(&directory) {
        return false;
    }
    crate::core::write_file(&target_path(&directory, target), key_name.as_bytes())
}

pub fn remove_key(target: &str) -> bool {
    crate::core::remove_file(&target_path(&auth_dir(), target))
}

pub fn list_credentials() -> Vec<String> {
    let directory = auth_dir();
    let mut output = Vec::new();
    for name in crate::core::list_directory(&directory) {
        let Some(decoded) = hex_decode(&String::from_utf8_lossy(&name)) else {
            continue;
        };
        let Ok(decoded) = String::from_utf8(decoded) else {
            continue;
        };
        let Some(data) = crate::core::read_file_opt(&target_path(&directory, &decoded), 0) else {
            continue;
        };
        let key = String::from_utf8_lossy(&data).trim().to_string();
        if !key.is_empty() {
            output.push(format!("{decoded}: {key}\n"));
        }
    }
    output
}

pub fn local_key_exists(name: &str) -> bool {
    !name.is_empty() && !name.starts_with("ed25519:") && load_key(name).is_some()
}

fn lookup_credential(directory: &std::path::Path, target: &str) -> Option<String> {
    let data = crate::core::read_file_opt(&target_path(directory, target), 0)?;
    let value = String::from_utf8_lossy(&data).trim().to_string();
    if value.is_empty() { None } else { Some(value) }
}

pub fn key_for_url(url: &str) -> Option<String> {
    let directory = auth_dir();
    if let Some(authority) = authority_of(url) {
        if let Some(key) = lookup_credential(&directory, &authority) {
            return Some(key);
        }
        if let Some((host, _)) = authority.rsplit_once(':')
            && let Some(key) = lookup_credential(&directory, host)
        {
            return Some(key);
        }
    }
    lookup_credential(&directory, "default")
}

#[derive(Clone)]
pub struct AccessEntry {
    pub public_key: PublicKey,
    pub name: String,
    pub role: u8,
}

#[derive(Clone)]
pub struct Access {
    pub valid: bool,
    pub error_line: i64,
    pub anonymous_read: bool,
    pub entries: Vec<AccessEntry>,
}

pub fn empty_access() -> Access {
    Access {
        valid: true,
        error_line: 0,
        anonymous_read: false,
        entries: Vec::new(),
    }
}

pub fn access_path(repo_root: &std::path::Path) -> std::path::PathBuf {
    crate::store::layout::veins_dir(repo_root).join("access")
}

pub fn load_access(repo_root: &std::path::Path) -> Access {
    let path = access_path(repo_root);
    if let Ok(metadata) = fs::metadata(&path)
        && metadata.permissions().mode() & 18 != 0
    {
        return Access {
            valid: false,
            error_line: 0,
            anonymous_read: false,
            entries: Vec::new(),
        };
    }
    let Some(data) = crate::core::read_file_opt(&path, 0) else {
        return empty_access();
    };
    let text = String::from_utf8_lossy(&data);
    let mut access = empty_access();
    for (index, raw) in text.lines().enumerate() {
        let line = crate::core::trim_str(raw);
        if line.is_empty() || line.starts_with('#') {
            continue;
        }
        let tokens: Vec<&str> = line.split_whitespace().collect();
        let bad = if tokens.len() == 2 && tokens[0] == "anonymous" {
            if tokens[1] == "read" {
                access.anonymous_read = true;
                false
            } else {
                true
            }
        } else if tokens.len() >= 3 && tokens[0] == "allow" {
            let role = match tokens[1] {
                "read" => 1,
                "write" => 2,
                _ => 0,
            };
            match parse_public_key(tokens[2]) {
                Some(public_key) if role != 0 => {
                    if access
                        .entries
                        .iter()
                        .any(|entry| entry.public_key == public_key)
                    {
                        true
                    } else {
                        access.entries.push(AccessEntry {
                            public_key,
                            name: tokens.get(3).copied().unwrap_or("").to_string(),
                            role,
                        });
                        false
                    }
                }
                _ => true,
            }
        } else {
            true
        };
        if bad {
            return Access {
                valid: false,
                error_line: index as i64 + 1,
                anonymous_read: false,
                entries: Vec::new(),
            };
        }
    }
    access
}

fn set_mode(path: &std::path::Path, mode: u32) {
    let _ = fs::set_permissions(path, fs::Permissions::from_mode(mode));
}

pub fn write_access(repo_root: &std::path::Path, access: &Access) -> bool {
    let mut body = String::from("# veins access policy\n");
    if access.anonymous_read {
        body.push_str("anonymous read\n");
    }
    for entry in &access.entries {
        if entry.name.len() > 64 {
            return false;
        }
        body.push_str("allow ");
        body.push_str(if entry.role == 2 { "write" } else { "read" });
        body.push(' ');
        body.push_str(&format_public_key(&entry.public_key));
        if !entry.name.is_empty() {
            body.push(' ');
            body.push_str(&entry.name);
        }
        body.push('\n');
    }
    let path = access_path(repo_root);
    if !crate::core::write_file(&path, body.as_bytes()) {
        return false;
    }
    set_mode(&path, 0o600);
    true
}

pub fn role_for(access: &Access, public_key: Option<&PublicKey>) -> u8 {
    match public_key {
        None => {
            if access.anonymous_read {
                1
            } else {
                0
            }
        }
        Some(public_key) => access
            .entries
            .iter()
            .find(|entry| entry.public_key == *public_key)
            .map(|entry| entry.role)
            .unwrap_or(255),
    }
}

pub fn add_access(
    repo_root: &std::path::Path,
    role: u8,
    public_key: &PublicKey,
    name: &str,
) -> bool {
    let mut access = load_access(repo_root);
    if !access.valid
        || access
            .entries
            .iter()
            .any(|entry| entry.public_key == *public_key)
    {
        return false;
    }
    access.entries.push(AccessEntry {
        public_key: *public_key,
        name: name.to_string(),
        role,
    });
    write_access(repo_root, &access)
}

pub fn remove_access(repo_root: &std::path::Path, fingerprint: &str, name: &str) -> bool {
    let mut access = load_access(repo_root);
    if !access.valid {
        return false;
    }
    let before = access.entries.len();
    access.entries.retain(|entry| {
        let by_fingerprint =
            !fingerprint.is_empty() && key_fingerprint(&entry.public_key) == fingerprint;
        let by_name = !name.is_empty() && entry.name == name;
        !(by_fingerprint || by_name)
    });
    access.entries.len() != before && write_access(repo_root, &access)
}

pub fn set_anonymous(repo_root: &std::path::Path, enabled: bool) -> bool {
    let mut access = load_access(repo_root);
    if !access.valid {
        return false;
    }
    access.anonymous_read = enabled;
    write_access(repo_root, &access)
}