libadb 0.9.0

Low-level ADB protocol library for direct TCP and USB communication
Documentation
use alloc::vec::Vec;

use base64ct::{Base64, Encoding};
use rsa::traits::PublicKeyParts;
use rsa::{BigUint, RsaPublicKey};

use crate::base::protocol::command::MAX_PAYLOAD;

use super::KeyError;

const MODULUS_SIZE: usize = 256;
const MODULUS_WORDS: u32 = (MODULUS_SIZE / 4) as u32;
const ENCODED_SIZE: usize = 4 + 4 + MODULUS_SIZE + MODULUS_SIZE + 4;
const PREFIX_LEN: usize = ENCODED_SIZE.div_ceil(3) * 4 + 1;

/// The name a public key carries after its blob — `user@host` in the
/// `adbkey.pub` line `adb keygen` writes — checked once, where it
/// enters.
///
/// The line is a single line, NUL-terminated on the wire, and has to
/// fit the one AUTH packet that carries it. A name with a NUL, CR or
/// LF in it, or too long for that packet, is refused here rather than
/// by whatever builds the line later. The default is no name at all:
/// the line ends with the blob.
///
/// ```
/// use libadb::keys::{KeyError, KeyName};
///
/// assert_eq!(KeyName::new("user@host").unwrap().as_str(), "user@host");
/// assert!(matches!(KeyName::new("user\nhost"), Err(KeyError::InvalidName)));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct KeyName<'a>(&'a str);

impl<'a> KeyName<'a> {
    /// Check `name` against what the public-key line can carry.
    ///
    /// # Errors
    ///
    /// - [`KeyError::InvalidName`] for a NUL, CR or LF in `name`;
    /// - [`KeyError::NameTooLong`] when the line would not fit one AUTH
    ///   packet.
    pub fn new(name: &'a str) -> Result<Self, KeyError> {
        if name.bytes().any(|b| matches!(b, b'\0' | b'\r' | b'\n')) {
            return Err(KeyError::InvalidName);
        }
        if name.len() > MAX_PAYLOAD as usize - PREFIX_LEN - 1 {
            return Err(KeyError::NameTooLong(name.len()));
        }
        Ok(Self(name))
    }

    /// The name as it was given.
    pub fn as_str(&self) -> &'a str {
        self.0
    }
}

impl<'a> TryFrom<&'a str> for KeyName<'a> {
    type Error = KeyError;

    fn try_from(name: &'a str) -> Result<Self, KeyError> {
        Self::new(name)
    }
}

/// Encode a public key as the `adbkey.pub` line: base64 of the
/// mincrypt struct, then `" <name>"` when `name` is not empty.
///
/// No trailing NUL and no newline: the AUTH payload appends the NUL
/// (see [`AdbKey::public_key_wire`]), key files append their own
/// newline, if any.
///
/// The key is checked as far as the format demands, whichever
/// constructor built it: 2048 bits, an odd modulus, and an odd exponent
/// of at least 3 that fits the struct's 32-bit field. Encoding a
/// degenerate one would hand the device something it can only reject,
/// or, for `e = 1`, something anyone can forge signatures against.
///
/// [`AdbKey::public_key_wire`]: super::AdbKey::public_key_wire
pub fn encode_public_key(key: &RsaPublicKey, name: KeyName<'_>) -> Result<Vec<u8>, KeyError> {
    let blob = mincrypt_struct(key)?;
    let mut out = Base64::encode_string(&blob).into_bytes();
    if !name.0.is_empty() {
        out.push(b' ');
        out.extend_from_slice(name.0.as_bytes());
    }
    Ok(out)
}

fn mincrypt_struct(key: &RsaPublicKey) -> Result<[u8; ENCODED_SIZE], KeyError> {
    let n = key.n();
    let bits = n.bits();
    if bits != MODULUS_SIZE * 8 {
        return Err(KeyError::UnsupportedModulus(bits));
    }

    let mut n_le = n.to_bytes_le();
    n_le.resize(MODULUS_SIZE, 0);

    let n0 = u32::from_le_bytes(n_le[..4].try_into().unwrap());
    if n0 % 2 == 0 {
        return Err(KeyError::EvenModulus);
    }
    let n0inv = neg_inverse_mod_2_32(n0);

    let mut rr_le = ((BigUint::from(1u32) << (MODULUS_SIZE * 16)) % n).to_bytes_le();
    rr_le.resize(MODULUS_SIZE, 0);

    let e_le = key.e().to_bytes_le();
    if e_le.len() > 4 {
        return Err(KeyError::UnsupportedExponent);
    }
    let mut e_bytes = [0u8; 4];
    e_bytes[..e_le.len()].copy_from_slice(&e_le);
    let e = u32::from_le_bytes(e_bytes);
    if e < 3 || e % 2 == 0 {
        return Err(KeyError::UnsupportedExponent);
    }

    let mut out = [0u8; ENCODED_SIZE];
    out[0..4].copy_from_slice(&MODULUS_WORDS.to_le_bytes());
    out[4..8].copy_from_slice(&n0inv.to_le_bytes());
    out[8..8 + MODULUS_SIZE].copy_from_slice(&n_le);
    out[8 + MODULUS_SIZE..8 + 2 * MODULUS_SIZE].copy_from_slice(&rr_le);
    out[8 + 2 * MODULUS_SIZE..].copy_from_slice(&e_bytes);
    Ok(out)
}

fn neg_inverse_mod_2_32(n0: u32) -> u32 {
    let mut inv = n0;
    for _ in 0..4 {
        inv = inv.wrapping_mul(2u32.wrapping_sub(n0.wrapping_mul(inv)));
    }
    inv.wrapping_neg()
}