use std::fmt::Write as _;
use std::io::{Error, Read, Write};
use std::path::{Path, PathBuf};
use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
use getrandom::SysRng;
use rsa::hazmat::{rsa_decrypt_and_check, rsa_encrypt};
use rsa::rand_core::TryCryptoRng;
use rsa::traits::{PrivateKeyParts, PublicKeyParts};
use rsa::{BoxedUint, PrivateKey, PublicKey};
use sha1::{Digest, Sha1};
use zeroize::Zeroizing;
use crate::error::{ErrorExt, printable};
use crate::io::{ReadExt, WriteExt};
use crate::pbo::PBO;
pub struct BIPrivateKey {
name: String,
length: u32,
exponent: u32,
key: PrivateKey,
}
#[derive(Debug)]
pub struct BIPublicKey {
name: String,
length: u32,
exponent: u32,
key: PublicKey,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum BISignVersion {
V2,
V3,
}
#[derive(Debug)]
pub struct BISign {
version: BISignVersion,
name: String,
length: u32,
exponent: u32,
n: BoxedUint,
sig1: BoxedUint,
sig2: BoxedUint,
sig3: BoxedUint,
}
impl std::fmt::Debug for BIPrivateKey {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BIPrivateKey")
.field("name", &self.name)
.field("length", &self.length)
.finish_non_exhaustive()
}
}
fn write_uint<O: Write>(output: &mut O, value: &BoxedUint, size: usize) -> Result<(), Error> {
let trimmed = Zeroizing::new(value.to_be_bytes_trimmed_vartime().into_vec());
if trimmed.len() > size {
return Err(error!("Key component does not fit into {size} bytes."));
}
let mut vec = Zeroizing::new(vec![0u8; size]);
for (dst, src) in vec.iter_mut().zip(trimmed.iter().rev()) {
*dst = *src;
}
output.write_all(&vec)
}
fn read_uint<I: Read>(input: &mut I, size: usize) -> Result<BoxedUint, Error> {
let mut buffer = Zeroizing::new(vec![0; size]);
input.read_exact(&mut buffer)?;
uint_from_le(&buffer)
}
fn uint_from_le(bytes: &[u8]) -> Result<BoxedUint, Error> {
let bits = u32::try_from(bytes.len())
.ok()
.and_then(|len| len.checked_mul(8))
.ok_or_else(|| error!("Key component is too large."))?;
BoxedUint::from_le_slice(bytes, bits).map_err(|_| error!("Invalid key data."))
}
fn same_value(a: &BoxedUint, b: &BoxedUint) -> bool {
let a = Zeroizing::new(a.to_be_bytes_trimmed_vartime().into_vec());
let b = Zeroizing::new(b.to_be_bytes_trimmed_vartime().into_vec());
*a == *b
}
fn is_trivial(value: &BoxedUint) -> bool {
value.bit_width_vartime() <= 1
}
#[expect(
clippy::needless_pass_by_value,
reason = "used as a map_err closure; the error is formatted, not stored"
)]
fn key_err(err: rsa::Error) -> Error {
error!("{err}")
}
type NameFilePair<'a> = (Vec<u8>, &'a [u8]);
const MIN_KEY_BITS: u32 = 288;
const MIN_SIGN_BITS: u32 = 384;
const MAX_KEY_BITS: u32 = 16384;
const PRIVATE_BLOB: u32 = 0x0207;
const PUBLIC_BLOB: u32 = 0x0206;
const KEY_ALG: u32 = 0x2400;
const PRIVATE_MAGIC: [u8; 4] = *b"RSA2";
const PUBLIC_MAGIC: [u8; 4] = *b"RSA1";
fn check_blob_header<I: Read>(
input: &mut I,
blob: u32,
magic: [u8; 4],
file: &str,
kind: &str,
) -> Result<(), Error> {
let found_blob = input.read_u32::<LittleEndian>()?;
let found_alg = input.read_u32::<LittleEndian>()?;
let mut found_magic = [0; 4];
input.read_exact(&mut found_magic)?;
if found_blob != blob || found_alg != KEY_ALG || found_magic != magic {
return Err(error!(
"Invalid {file} file (bad header: not a {kind} key blob)."
));
}
Ok(())
}
fn check_key_length(length: u32) -> Result<(), Error> {
if !(MIN_KEY_BITS..=MAX_KEY_BITS).contains(&length) {
return Err(error!(
"Invalid key length: {length} (supported: {MIN_KEY_BITS} to {MAX_KEY_BITS} bits)."
));
}
Ok(())
}
fn check_sign_length(length: u32) -> Result<(), Error> {
if length < MIN_SIGN_BITS {
return Err(error!(
"A {length}-bit key is smaller than the {MIN_SIGN_BITS}-bit CryptoAPI minimum and cannot sign."
));
}
Ok(())
}
pub fn signature_path(pbo_path: &Path, key_name: &str) -> Result<PathBuf, Error> {
if key_name.is_empty()
|| key_name
.chars()
.any(|c| matches!(c, '/' | '\\' | ':') || c.is_control())
{
return Err(error!(
"The key name {key_name:?} cannot be used in a file name; pass the signature path explicitly."
));
}
let mut path = pbo_path.to_path_buf();
path.set_extension(format!("pbo.{key_name}.bisign"));
Ok(path)
}
fn namehash(pbo: &PBO) -> [u8; 20] {
let mut files_sorted: Vec<NameFilePair<'_>> = pbo
.entries()
.map(|(a, b)| (pbo.name_bytes(a).to_ascii_lowercase(), b))
.collect();
files_sorted.sort_by(|a, b| a.0.cmp(&b.0));
let mut h = Sha1::new();
for (name, data) in &files_sorted {
if data.is_empty() {
continue;
}
h.update(name);
}
h.finalize().into()
}
fn filehash(pbo: &PBO, version: BISignVersion) -> [u8; 20] {
let mut h = Sha1::new();
let mut nothing = true;
for (name, data) in pbo.entries() {
let ext = name.split('.').next_back().unwrap_or("");
match version {
BISignVersion::V2 => {
if ext == "paa"
|| ext == "jpg"
|| ext == "p3d"
|| ext == "tga"
|| ext == "rvmat"
|| ext == "lip"
|| ext == "ogg"
|| ext == "wss"
|| ext == "png"
|| ext == "rtm"
|| ext == "pac"
|| ext == "fxy"
|| ext == "wrp"
{
continue;
}
}
BISignVersion::V3 => {
if ext != "sqf"
&& ext != "c"
&& ext != "inc"
&& ext != "bikb"
&& ext != "ext"
&& ext != "fsm"
&& ext != "sqm"
&& ext != "hpp"
&& ext != "cfg"
&& ext != "sqs"
&& ext != "h"
{
continue;
}
}
}
h.update(data);
nothing = false;
}
match version {
BISignVersion::V2 => {
if nothing {
h.update(b"nothing");
}
}
BISignVersion::V3 => {
if nothing {
h.update(b"gnihton");
}
}
}
h.finalize().into()
}
fn generate_hashes(
pbo: &PBO,
version: BISignVersion,
length: u32,
signing: bool,
) -> Result<[Vec<u8>; 3], Error> {
let checksum = pbo.trailer_checksum(signing)?;
let hash1 = &checksum[..];
let namehash = namehash(pbo);
let mut suffix = Vec::new();
if let Some(prefix) = pbo.prefix() {
suffix.extend(pbo.extension_bytes(prefix));
if !prefix.ends_with('\\') {
suffix.push(b'\\');
}
}
let mut h = Sha1::new();
h.update(hash1);
h.update(namehash);
h.update(&suffix);
let hash2 = h.finalize();
let mut h = Sha1::new();
h.update(filehash(pbo, version));
h.update(namehash);
h.update(&suffix);
let hash3 = h.finalize();
let size = usize::try_from(length / 8).map_err(|_| error!("Invalid key length: {length}."))?;
Ok([
pad_hash(hash1, size)?,
pad_hash(&hash2, size)?,
pad_hash(&hash3, size)?,
])
}
fn pad_hash(hash: &[u8], size: usize) -> Result<Vec<u8>, Error> {
if size < 36 {
return Err(error!("Key length too small: {size} bytes."));
}
let mut vec: Vec<u8> = Vec::new();
vec.push(0);
vec.push(1);
vec.resize(size - 36, 255);
vec.extend(b"\x00\x30\x21\x30\x09\x06\x05\x2b");
vec.extend(b"\x0e\x03\x02\x1a\x05\x00\x04\x14");
vec.extend(hash);
Ok(vec)
}
fn trim_zeros(bytes: &[u8]) -> &[u8] {
let start = bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len());
bytes.get(start..).unwrap_or_default()
}
fn hex(bytes: &[u8]) -> String {
if bytes.is_empty() {
return "0".to_string();
}
let mut out = String::with_capacity(bytes.len() * 2);
for b in bytes {
let _ = write!(out, "{b:02x}");
}
out
}
fn display_hashes(signed: &[u8], real: &[u8]) -> (String, String) {
let hex_signed = hex(signed);
let hex_real = hex(real);
if hex_signed.len() != hex_real.len() || hex_signed.len() <= 40 {
return (hex_signed, hex_real);
}
let (signed_padding, signed_hash) = hex_signed.split_at(hex_signed.len() - 40);
let (real_padding, real_hash) = hex_real.split_at(hex_real.len() - 40);
if signed_padding == real_padding {
(signed_hash.to_string(), real_hash.to_string())
} else {
(hex_signed, hex_real)
}
}
impl BIPrivateKey {
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
pub fn read<I: Read>(input: &mut I) -> Result<BIPrivateKey, Error> {
let name = input.read_cstring()?;
let temp = input.read_u32::<LittleEndian>()?;
check_blob_header(input, PRIVATE_BLOB, PRIVATE_MAGIC, "private key", "private")?;
let length = input.read_u32::<LittleEndian>()?;
let exponent = input.read_u32::<LittleEndian>()?;
check_key_length(length)?;
if temp != length / 16 * 9 + 20 {
return Err(error!("Invalid private key file (bad length field)."));
}
if length % 16 != 0 {
return Err(error!(
"Invalid private key file (the length {length} is not a multiple of 16)."
));
}
let full = (length / 8) as usize;
let half = (length / 16) as usize;
let n = read_uint(input, full)?;
let p = Zeroizing::new(read_uint(input, half)?);
let q = Zeroizing::new(read_uint(input, half)?);
let exp_p = Zeroizing::new(read_uint(input, half)?);
let exp_q = Zeroizing::new(read_uint(input, half)?);
let iqmp = Zeroizing::new(read_uint(input, half)?);
let d = Zeroizing::new(read_uint(input, full)?);
for value in [&n, &*p, &*q, &*exp_p, &*exp_q, &*iqmp, &*d] {
if is_trivial(value) {
return Err(error!("Invalid private key (a component is zero or one)."));
}
}
if n.bit_width_vartime() != length {
return Err(error!(
"Invalid private key file (the modulus is not {length} bits wide)."
));
}
let key = PrivateKey::from_components(
n,
BoxedUint::from(u64::from(exponent)),
(*d).clone(),
vec![(*p).clone(), (*q).clone()],
)
.map_err(key_err)
.prepend_error("Invalid private key:")?;
let consistent = match (
key.dp(),
key.dq(),
key.crt_coefficient().map(Zeroizing::new),
) {
(Some(dp), Some(dq), Some(qinv)) => {
same_value(dp, &exp_p) && same_value(dq, &exp_q) && same_value(&qinv, &iqmp)
}
_ => false,
};
if !consistent {
return Err(error!(
"Invalid private key (CRT values do not match the primes)."
));
}
Ok(BIPrivateKey {
name,
length,
exponent,
key,
})
}
pub fn generate(length: u32, name: String) -> Result<BIPrivateKey, Error> {
Self::generate_with_rng(length, name, &mut SysRng)
}
pub(crate) fn generate_with_rng<R: TryCryptoRng + ?Sized>(
length: u32,
name: String,
rng: &mut R,
) -> Result<BIPrivateKey, Error> {
check_sign_length(length)?;
check_key_length(length)?;
if !length.is_multiple_of(16) {
return Err(error!(
"Invalid key length: {length} (it must be a multiple of 16)."
));
}
let exponent = 65537;
let bits = usize::try_from(length).map_err(|_| error!("Invalid key length: {length}."))?;
let key =
PrivateKey::new_with_exp_unchecked(rng, bits, BoxedUint::from(u64::from(exponent)))
.map_err(key_err)
.prepend_error("Failed to generate keypair:")?;
if key.n().as_ref().bit_width_vartime() != length {
return Err(error!(
"Failed to generate keypair: the modulus is not {length} bits wide."
));
}
Ok(BIPrivateKey {
name,
length,
exponent,
key,
})
}
pub fn to_public_key(&self) -> Result<BIPublicKey, Error> {
Ok(BIPublicKey {
name: self.name.clone(),
length: self.length,
exponent: self.exponent,
key: self.key.to_public_key(),
})
}
pub fn sign(&self, pbo: &PBO, version: BISignVersion) -> Result<BISign, Error> {
check_sign_length(self.length)?;
let hashes = generate_hashes(pbo, version, self.length, true)?;
let n = self.key.n().as_ref();
let precision = n.bits_precision();
let mut rng = SysRng;
let mut sign_one = |padded: &[u8]| -> Result<BoxedUint, Error> {
let m = BoxedUint::from_be_slice(padded, precision)
.map_err(|_| error!("The hash does not fit the key."))?;
rsa_decrypt_and_check(&self.key, Some(&mut rng), &m).map_err(key_err)
};
let [h1, h2, h3] = &hashes;
let (sig1, sig2, sig3) = (sign_one(h1)?, sign_one(h2)?, sign_one(h3)?);
Ok(BISign {
version,
name: self.name.clone(),
length: self.length,
exponent: self.exponent,
n: n.clone(),
sig1,
sig2,
sig3,
})
}
pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
output
.write_cstring(&self.name)
.prepend_error("Key name:")?;
output.write_u32::<LittleEndian>(self.length / 16 * 9 + 20)?;
output.write_all(b"\x07\x02\x00\x00\x00\x24\x00\x00")?;
output.write_all(b"RSA2")?;
output.write_u32::<LittleEndian>(self.length)?;
output.write_u32::<LittleEndian>(self.exponent)?;
let full = (self.length / 8) as usize;
let half = (self.length / 16) as usize;
let primes = self.key.primes();
let (Some(p), Some(q)) = (primes.first(), primes.get(1)) else {
return Err(error!("Invalid private key (missing primes)."));
};
let (Some(exp_p), Some(exp_q), Some(iqmp)) = (
self.key.dp(),
self.key.dq(),
self.key.crt_coefficient().map(Zeroizing::new),
) else {
return Err(error!("Invalid private key (missing CRT values)."));
};
write_uint(output, self.key.n().as_ref(), full)?;
write_uint(output, p.as_ref(), half)?;
write_uint(output, q.as_ref(), half)?;
write_uint(output, exp_p, half)?;
write_uint(output, exp_q, half)?;
write_uint(output, &iqmp, half)?;
write_uint(output, self.key.d(), full)?;
Ok(())
}
}
impl BIPublicKey {
#[must_use]
pub fn name(&self) -> &str {
&self.name
}
pub fn read<I: Read>(input: &mut I) -> Result<BIPublicKey, Error> {
let name = input.read_cstring()?;
let temp = input.read_u32::<LittleEndian>()?;
check_blob_header(input, PUBLIC_BLOB, PUBLIC_MAGIC, "public key", "public")?;
let length = input.read_u32::<LittleEndian>()?;
let exponent = input.read_u32::<LittleEndian>()?;
check_key_length(length)?;
if temp != length / 8 + 20 {
return Err(error!("Invalid public key file (bad length field)."));
}
let n = read_uint(input, (length / 8) as usize)?;
let length_bits = length as usize;
let key = PublicKey::new_with_size_limits(
n,
BoxedUint::from(u64::from(exponent)),
length_bits..=length_bits,
)
.map_err(key_err)
.prepend_error("Invalid public key:")?;
Ok(BIPublicKey {
name,
length,
exponent,
key,
})
}
pub fn verify(&self, pbo: &PBO, signature: &BISign) -> Result<(), Error> {
let n = self.key.n().as_ref();
if signature.length != self.length || !same_value(&signature.n, n) {
return Err(error!(
"The signature was made with a different key (signature: {}, {} bits; this key: {}, {} bits).",
printable(&signature.name),
signature.length,
printable(&self.name),
self.length
));
}
let hashes = generate_hashes(pbo, signature.version, self.length, false)?;
let precision = n.bits_precision();
let values = [&signature.sig1, &signature.sig2, &signature.sig3];
let mut signed = Vec::with_capacity(values.len());
for (i, value) in values.into_iter().enumerate() {
let number = i + 1;
let value = BoxedUint::from_be_slice(&value.to_be_bytes_trimmed_vartime(), precision)
.ok()
.filter(|value| value < n)
.ok_or_else(|| error!("Signature {number} is not smaller than the modulus."))?;
signed.push(rsa_encrypt(&self.key, &value).map_err(key_err)?);
}
for (i, (signed, real)) in signed.iter().zip(&hashes).enumerate() {
let signed = signed.to_be_bytes_trimmed_vartime();
let real = trim_zeros(real);
if *signed != *real {
let (s, r) = display_hashes(&signed, real);
return Err(error!(
"Hash {} doesn't match\nSigned hash: {}\nReal hash: {}",
i + 1,
s,
r
));
}
}
Ok(())
}
pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
output
.write_cstring(&self.name)
.prepend_error("Key name:")?;
output.write_u32::<LittleEndian>(self.length / 8 + 20)?;
output.write_all(b"\x06\x02\x00\x00\x00\x24\x00\x00")?;
output.write_all(b"RSA1")?;
output.write_u32::<LittleEndian>(self.length)?;
output.write_u32::<LittleEndian>(self.exponent)?;
write_uint(output, self.key.n().as_ref(), (self.length / 8) as usize)?;
Ok(())
}
}
impl From<BISignVersion> for u32 {
fn from(val: BISignVersion) -> Self {
match val {
BISignVersion::V2 => 2,
BISignVersion::V3 => 3,
}
}
}
impl BISign {
pub fn read<I: Read>(input: &mut I) -> Result<BISign, Error> {
let name = input.read_cstring()?;
let temp = input.read_u32::<LittleEndian>()?;
check_blob_header(input, PUBLIC_BLOB, PUBLIC_MAGIC, "signature", "public")?;
let length = input.read_u32::<LittleEndian>()?;
let exponent = input.read_u32::<LittleEndian>()?;
check_key_length(length)?;
if temp != length / 8 + 20 {
return Err(error!("Invalid signature file (bad length field)."));
}
let size = (length / 8) as usize;
let n = read_uint(input, size)?;
if n.bit_width_vartime() != length {
return Err(error!(
"Invalid signature file (the modulus is not {length} bits wide)."
));
}
input.read_u32::<LittleEndian>()?;
let sig1 = read_uint(input, size)?;
let version = match input.read_u32::<LittleEndian>()? {
2 => BISignVersion::V2,
3 => BISignVersion::V3,
_ => {
return Err(error!("Unknown BISign version."));
}
};
input.read_u32::<LittleEndian>()?;
let sig2 = read_uint(input, size)?;
input.read_u32::<LittleEndian>()?;
let sig3 = read_uint(input, size)?;
Ok(BISign {
version,
name,
length,
exponent,
n,
sig1,
sig2,
sig3,
})
}
pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
output
.write_cstring(&self.name)
.prepend_error("Key name:")?;
output.write_u32::<LittleEndian>(self.length / 8 + 20)?;
output.write_all(b"\x06\x02\x00\x00\x00\x24\x00\x00")?;
output.write_all(b"RSA1")?;
output.write_u32::<LittleEndian>(self.length)?;
output.write_u32::<LittleEndian>(self.exponent)?;
write_uint(output, &self.n, (self.length / 8) as usize)?;
output.write_u32::<LittleEndian>(self.length / 8)?;
write_uint(output, &self.sig1, (self.length / 8) as usize)?;
output.write_u32::<LittleEndian>(self.version.into())?;
output.write_u32::<LittleEndian>(self.length / 8)?;
write_uint(output, &self.sig2, (self.length / 8) as usize)?;
output.write_u32::<LittleEndian>(self.length / 8)?;
write_uint(output, &self.sig3, (self.length / 8) as usize)?;
Ok(())
}
}
#[cfg(test)]
mod tests {
#![expect(
clippy::many_single_char_names,
reason = "the names of the RSA numbers: n, e, d, p, q"
)]
use std::fs;
use std::io::Cursor;
use num_bigint::BigUint;
use rand_chacha::ChaCha20Rng;
use rand_core::SeedableRng;
use super::*;
fn seeded(seed: u64, bits: u32) -> BIPrivateKey {
let mut rng = ChaCha20Rng::seed_from_u64(seed);
BIPrivateKey::generate_with_rng(bits, "gen".to_string(), &mut rng).unwrap()
}
fn bn(value: &BoxedUint) -> BigUint {
BigUint::from_bytes_be(&value.to_be_bytes_trimmed_vartime())
}
fn file(key: &BIPrivateKey) -> Vec<u8> {
let mut out = Vec::new();
key.write(&mut out).unwrap();
out
}
#[test]
fn generated_key_is_valid() {
for (seed, bits) in [(1u64, 384u32), (2, 1024)] {
let key = seeded(seed, bits);
assert_eq!((key.length, key.exponent), (bits, 65537));
let n = bn(key.key.n().as_ref());
assert_eq!(n.bits(), u64::from(bits));
let primes = key.key.primes();
let (p, q) = (bn(&primes[0]), bn(&primes[1]));
let (d, e) = (bn(key.key.d()), BigUint::from(65537u32));
let one = BigUint::from(1u32);
assert_eq!(&p * &q, n);
let (p1, q1) = (&p - &one, &q - &one);
let phi = &p1 * &q1;
assert_eq!((&e * &d) % &phi, one, "e * d mod phi(n)");
assert_eq!(&d % &p1, bn(key.key.dp().unwrap()));
assert_eq!(&d % &q1, bn(key.key.dq().unwrap()));
let qinv = key.key.crt_coefficient().unwrap();
assert_eq!((bn(&qinv) * &q) % &p, one, "qinv * q mod p");
let bytes = file(&key);
let again = BIPrivateKey::read(&mut Cursor::new(&bytes)).unwrap();
assert_eq!(file(&again), bytes);
assert_eq!(again.name(), "gen");
}
}
#[test]
fn generated_key_signs_and_verifies() {
let pbo_bytes = fs::read(concat!(
env!("CARGO_MANIFEST_DIR"),
"/../../tests/fixtures/bi/sign/testsig.pbo"
))
.unwrap();
let pbo = PBO::read(&mut Cursor::new(pbo_bytes)).unwrap();
let key = seeded(3, 1024);
let public = key.to_public_key().unwrap();
for version in [BISignVersion::V2, BISignVersion::V3] {
let signature = key.sign(&pbo, version).unwrap();
public.verify(&pbo, &signature).unwrap();
let hashes = generate_hashes(&pbo, version, 1024, false).unwrap();
let n = bn(key.key.n().as_ref());
let e = BigUint::from(65537u32);
for (sig, hash) in [&signature.sig1, &signature.sig2, &signature.sig3]
.into_iter()
.zip(&hashes)
{
let back = bn(sig).modpow(&e, &n);
assert_eq!(back.to_bytes_be(), trim_zeros(hash));
}
}
}
#[test]
fn seeded_generation_is_deterministic() {
assert_eq!(file(&seeded(4, 512)), file(&seeded(4, 512)));
assert_ne!(file(&seeded(4, 512)), file(&seeded(5, 512)));
}
#[test]
fn generation_with_the_os_rng_is_not_deterministic() {
let a = BIPrivateKey::generate(384, "a".to_string()).unwrap();
let b = BIPrivateKey::generate(384, "a".to_string()).unwrap();
assert_ne!(file(&a), file(&b));
}
#[test]
fn unusable_lengths_are_refused() {
for bits in [0, 288, 368, 383, 392, 400 + 8, MAX_KEY_BITS + 16] {
assert!(
BIPrivateKey::generate(bits, "x".to_string()).is_err(),
"{bits}"
);
}
}
}