Skip to content

A cross-platform desktop All-in-One assistant for Claude Code, Codex, OpenCode,DeepSeek Harness and more. Only official website: ccswitch.io

10.6 KB
Raw Blame
//! AES-256-GCM encryption/decryption for cloud sync artifacts (WebDAV / S3).
//!
//! File format: `HEADER(15) || SALT(16) || NONCE(12) || CIPHERTEXT+TAG(variable)`
//! - Header: `CCSWITCH ENC v2`
//! - Key derivation: PBKDF2-HMAC-SHA256 (600,000 iterations) -> 256-bit AES key
//! - AAD: `HEADER || SALT` (authenticates format version and salt)
//! - Uses `ring` crate (already a transitive dependency via rustls).

use std::num::NonZeroU32;

use ring::aead::{
    Aad, BoundKey, Nonce, NonceSequence, OpeningKey, SealingKey, UnboundKey, AES_256_GCM, NONCE_LEN,
};
use ring::error::Unspecified;
use ring::hmac;
use ring::pbkdf2;
use ring::rand::{SecureRandom, SystemRandom};

const SALT_LEN: usize = 16;
const KEY_LEN: usize = 32;
const TAG_LEN: usize = 16;
const HMAC_LEN: usize = 32;
const HEADER_PREFIX: &[u8] = b"CCSWITCH ENC ";
const HEADER: &[u8] = b"CCSWITCH ENC v2";
const KEY_CHECK_MESSAGE: &[u8] = b"cc-switch-sync-key-check-v2";
const PBKDF2_ITERATIONS: NonZeroU32 = NonZeroU32::new(600_000).unwrap();

/// Encryption format version recorded in remote sync manifests.
pub const FORMAT_VERSION: u32 = 2;

/// Byte overhead added by [`encrypt`] (`HEADER || SALT || NONCE || TAG`).
pub const ENCRYPTION_OVERHEAD: usize = HEADER.len() + SALT_LEN + NONCE_LEN + TAG_LEN;

/// Result of checking a local passphrase against a remote manifest's encryption metadata.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum KeyCheckResult {
    Matched,
    Mismatched,
    UnsupportedVersion,
    MalformedMetadata,
}

/// A simple nonce sequence that returns the nonce once then errors.
struct SingleNonce {
    nonce: Option<[u8; NONCE_LEN]>,
}

impl SingleNonce {
    fn new(nonce_bytes: [u8; NONCE_LEN]) -> Self {
        Self {
            nonce: Some(nonce_bytes),
        }
    }
}

impl NonceSequence for SingleNonce {
    fn advance(&mut self) -> Result<Nonce, Unspecified> {
        let bytes = self.nonce.take().ok_or(Unspecified)?;
        Ok(Nonce::assume_unique_for_key(bytes))
    }
}

/// Derive a 256-bit AES key from a passphrase using PBKDF2-HMAC-SHA256.
fn derive_key(salt: &[u8], passphrase: &str) -> [u8; KEY_LEN] {
    let mut key = [0u8; KEY_LEN];
    pbkdf2::derive(
        pbkdf2::PBKDF2_HMAC_SHA256,
        PBKDF2_ITERATIONS,
        salt,
        passphrase.as_bytes(),
        &mut key,
    );
    key
}

fn build_aad(header: &[u8], salt: &[u8]) -> [u8; HEADER.len() + SALT_LEN] {
    let mut aad = [0u8; HEADER.len() + SALT_LEN];
    aad[..HEADER.len()].copy_from_slice(header);
    aad[HEADER.len()..].copy_from_slice(salt);
    aad
}

/// Encrypt data with a passphrase. Returns `header || salt || nonce || ciphertext+tag`.
pub fn encrypt(data: &[u8], passphrase: &str) -> Result<Vec<u8>, String> {
    let rng = SystemRandom::new();

    let mut salt = [0u8; SALT_LEN];
    rng.fill(&mut salt).map_err(|_| "Failed to generate salt")?;

    let mut nonce_bytes = [0u8; NONCE_LEN];
    rng.fill(&mut nonce_bytes)
        .map_err(|_| "Failed to generate nonce")?;

    let key_bytes = derive_key(&salt, passphrase);
    let unbound_key = UnboundKey::new(&AES_256_GCM, &key_bytes)
        .map_err(|e| format!("Failed to create key: {e}"))?;
    let mut sealing_key = SealingKey::new(unbound_key, SingleNonce::new(nonce_bytes));

    let aad = build_aad(HEADER, &salt);
    let mut ciphertext = data.to_vec();
    sealing_key
        .seal_in_place_append_tag(Aad::from(&aad), &mut ciphertext)
        .map_err(|e| format!("Encryption failed: {e}"))?;

    let mut output = Vec::with_capacity(HEADER.len() + SALT_LEN + NONCE_LEN + ciphertext.len());
    output.extend_from_slice(HEADER);
    output.extend_from_slice(&salt);
    output.extend_from_slice(&nonce_bytes);
    output.extend(ciphertext);
    Ok(output)
}

/// Decrypt data with a passphrase. Expects `header || salt || nonce || ciphertext+tag`.
pub fn decrypt(data: &[u8], passphrase: &str) -> Result<Vec<u8>, String> {
    let header_len = HEADER.len();
    if data.len() < header_len || &data[..header_len] != HEADER {
        return Err(
            "Unsupported or invalid encryption header — expected CCSWITCH ENC v2".to_string(),
        );
    }

    let min_len = header_len + SALT_LEN + NONCE_LEN + TAG_LEN;
    if data.len() < min_len {
        return Err("Data too short to be a valid encrypted artifact".to_string());
    }

    let salt = &data[header_len..header_len + SALT_LEN];
    let nonce_bytes: [u8; NONCE_LEN] = data
        [header_len + SALT_LEN..header_len + SALT_LEN + NONCE_LEN]
        .try_into()
        .map_err(|_| "Invalid nonce length")?;
    let mut ciphertext = data[header_len + SALT_LEN + NONCE_LEN..].to_vec();

    let key_bytes = derive_key(salt, passphrase);
    let unbound_key = UnboundKey::new(&AES_256_GCM, &key_bytes)
        .map_err(|e| format!("Failed to create key: {e}"))?;
    let mut opening_key = OpeningKey::new(unbound_key, SingleNonce::new(nonce_bytes));

    let aad = build_aad(HEADER, salt);
    let plaintext = opening_key
        .open_in_place(Aad::from(&aad), &mut ciphertext)
        .map_err(|e| format!("Decryption failed (wrong key?): {e}"))?;
    Ok(plaintext.to_vec())
}

/// Check if data starts with a CC Switch encryption header (`CCSWITCH ENC ...`).
pub fn is_encrypted(data: &[u8]) -> bool {
    data.starts_with(HEADER_PREFIX)
}

/// Compute a random salt and HMAC-SHA256 key-check token derived via PBKDF2-HMAC-SHA256.
///
/// Returned as `(salt_hex, key_check_hex)`. Stored in `manifest.json` so other devices
/// can detect whether a remote snapshot is encrypted and verify key equality before
/// overwriting or downloading, without ever storing or revealing the key itself.
pub fn compute_key_check(passphrase: &str) -> Result<(String, String), String> {
    let rng = SystemRandom::new();
    let mut salt = [0u8; SALT_LEN];
    rng.fill(&mut salt)
        .map_err(|_| "Failed to generate key-check salt")?;

    let derived = derive_key(&salt, passphrase);
    let mac_key = hmac::Key::new(hmac::HMAC_SHA256, &derived);
    let tag = hmac::sign(&mac_key, KEY_CHECK_MESSAGE);
    Ok((hex_encode(&salt), hex_encode(tag.as_ref())))
}

/// Verify a passphrase against a remote manifest's `(version, salt_hex, key_check_hex)`.
pub fn verify_key_check(
    passphrase: &str,
    version: u32,
    salt_hex: &str,
    key_check_hex: &str,
) -> KeyCheckResult {
    if version != FORMAT_VERSION {
        return KeyCheckResult::UnsupportedVersion;
    }

    let Some(salt) = hex_decode(salt_hex) else {
        return KeyCheckResult::MalformedMetadata;
    };
    let Some(expected_tag) = hex_decode(key_check_hex) else {
        return KeyCheckResult::MalformedMetadata;
    };
    if salt.len() != SALT_LEN || expected_tag.len() != HMAC_LEN {
        return KeyCheckResult::MalformedMetadata;
    }

    let derived = derive_key(&salt, passphrase);
    let mac_key = hmac::Key::new(hmac::HMAC_SHA256, &derived);
    match hmac::verify(&mac_key, KEY_CHECK_MESSAGE, &expected_tag) {
        Ok(()) => KeyCheckResult::Matched,
        Err(_) => KeyCheckResult::Mismatched,
    }
}

fn hex_encode(bytes: &[u8]) -> String {
    const HEX: &[u8; 16] = b"0123456789abcdef";
    let mut out = String::with_capacity(bytes.len() * 2);
    for &b in bytes {
        out.push(HEX[(b >> 4) as usize] as char);
        out.push(HEX[(b & 0x0f) as usize] as char);
    }
    out
}

fn hex_decode(hex: &str) -> Option<Vec<u8>> {
    let bytes = hex.as_bytes();
    if bytes.len() % 2 != 0 {
        return None;
    }
    let mut out = Vec::with_capacity(bytes.len() / 2);
    for pair in bytes.chunks_exact(2) {
        let hi = hex_nibble(pair[0])?;
        let lo = hex_nibble(pair[1])?;
        out.push((hi << 4) | lo);
    }
    Some(out)
}

fn hex_nibble(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

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

    #[test]
    fn encrypt_decrypt_roundtrip() {
        let data = b"hello webdav encryption";
        let passphrase = "my-secret-key";
        let encrypted = encrypt(data, passphrase).unwrap();
        assert!(is_encrypted(&encrypted));
        assert!(encrypted.starts_with(b"CCSWITCH ENC v2"));
        let decrypted = decrypt(&encrypted, passphrase).unwrap();
        assert_eq!(decrypted, data);
    }

    #[test]
    fn empty_plaintext_roundtrip() {
        let encrypted = encrypt(b"", "passphrase").unwrap();
        assert!(is_encrypted(&encrypted));
        assert_eq!(decrypt(&encrypted, "passphrase").unwrap(), b"");
    }

    #[test]
    fn encrypt_produces_unique_ciphertexts() {
        let first = encrypt(b"same payload", "same-key").unwrap();
        let second = encrypt(b"same payload", "same-key").unwrap();
        assert_ne!(first, second);
    }

    #[test]
    fn wrong_key_fails() {
        let data = b"secret data";
        let encrypted = encrypt(data, "correct-key").unwrap();
        let result = decrypt(&encrypted, "wrong-key");
        assert!(result.is_err());
    }

    #[test]
    fn tampered_payload_fails() {
        let mut encrypted = encrypt(b"integrity test", "passphrase").unwrap();
        let last = encrypted.len() - 1;
        encrypted[last] ^= 0x01;
        assert!(decrypt(&encrypted, "passphrase").is_err());
    }

    #[test]
    fn unsupported_version_detected_as_encrypted_and_rejected() {
        let mut legacy = b"CCSWITCH ENC v1".to_vec();
        legacy.extend_from_slice(&[0u8; 64]);
        assert!(is_encrypted(&legacy));
        let err = decrypt(&legacy, "passphrase").unwrap_err();
        assert!(err.contains("CCSWITCH ENC v2"));
    }

    #[test]
    fn unencrypted_data_detected() {
        assert!(!is_encrypted(b"plain text"));
        assert!(!is_encrypted(b""));
    }

    #[test]
    fn key_check_roundtrip_and_mismatch() {
        let (salt, check) = compute_key_check("shared-passphrase").unwrap();
        assert_eq!(salt.len(), SALT_LEN * 2);
        assert_eq!(check.len(), HMAC_LEN * 2);

        assert_eq!(
            verify_key_check("shared-passphrase", FORMAT_VERSION, &salt, &check),
            KeyCheckResult::Matched
        );
        assert_eq!(
            verify_key_check("other-passphrase", FORMAT_VERSION, &salt, &check),
            KeyCheckResult::Mismatched
        );
        assert_eq!(
            verify_key_check("shared-passphrase", FORMAT_VERSION + 1, &salt, &check),
            KeyCheckResult::UnsupportedVersion
        );
        assert_eq!(
            verify_key_check("shared-passphrase", FORMAT_VERSION, "not-hex", &check),
            KeyCheckResult::MalformedMetadata
        );
        assert_eq!(
            verify_key_check("shared-passphrase", FORMAT_VERSION, &salt, "abcd"),
            KeyCheckResult::MalformedMetadata
        );
    }
}