Skip to main content

dayzmake_core/
sign.rs

1//! Functions for creating and working with BI keys and signatures
2
3use std::fmt::Write as _;
4use std::io::{Error, Read, Write};
5use std::path::{Path, PathBuf};
6
7use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
8use getrandom::SysRng;
9use rsa::hazmat::{rsa_decrypt_and_check, rsa_encrypt};
10use rsa::rand_core::TryCryptoRng;
11use rsa::traits::{PrivateKeyParts, PublicKeyParts};
12use rsa::{BoxedUint, PrivateKey, PublicKey};
13use sha1::{Digest, Sha1};
14use zeroize::Zeroizing;
15
16use crate::error::{ErrorExt, printable};
17use crate::io::{ReadExt, WriteExt};
18use crate::pbo::PBO;
19
20/// BI private key (.biprivatekey)
21pub struct BIPrivateKey {
22    name: String,
23    length: u32,
24    exponent: u32,
25    /// The validated key: `n`, `e`, `d`, `p`, `q` and the CRT values, checked against each other on creation.
26    key: PrivateKey,
27}
28
29/// BI public key (.bikey)
30#[derive(Debug)]
31pub struct BIPublicKey {
32    name: String,
33    length: u32,
34    exponent: u32,
35    key: PublicKey,
36}
37
38/// BI signature version
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40#[non_exhaustive]
41pub enum BISignVersion {
42    /// Version 2
43    V2,
44    /// Version 3
45    V3,
46}
47
48/// BI signature (.bisign)
49#[derive(Debug)]
50pub struct BISign {
51    version: BISignVersion,
52    name: String,
53    length: u32,
54    exponent: u32,
55    n: BoxedUint,
56    sig1: BoxedUint,
57    sig2: BoxedUint,
58    sig3: BoxedUint,
59}
60
61impl std::fmt::Debug for BIPrivateKey {
62    /// Prints the name and length only, never any key material.
63    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64        f.debug_struct("BIPrivateKey")
65            .field("name", &self.name)
66            .field("length", &self.length)
67            .finish_non_exhaustive()
68    }
69}
70
71/// Writes `value` little-endian, zero-padded to `size` bytes.
72///
73/// # Errors
74///
75/// Returns an error if the value does not fit into `size` bytes, or on I/O failure.
76fn write_uint<O: Write>(output: &mut O, value: &BoxedUint, size: usize) -> Result<(), Error> {
77    // Both buffers can hold secret key bytes: they are wiped on drop, and the output buffer is allocated at its
78    // final size so that no reallocation leaves a copy behind.
79    let trimmed = Zeroizing::new(value.to_be_bytes_trimmed_vartime().into_vec());
80    if trimmed.len() > size {
81        return Err(error!("Key component does not fit into {size} bytes."));
82    }
83    let mut vec = Zeroizing::new(vec![0u8; size]);
84    for (dst, src) in vec.iter_mut().zip(trimmed.iter().rev()) {
85        *dst = *src;
86    }
87
88    output.write_all(&vec)
89}
90
91/// Reads a key component of `size` little-endian bytes.
92fn read_uint<I: Read>(input: &mut I, size: usize) -> Result<BoxedUint, Error> {
93    // The buffer can hold a secret key component: wiped on drop, also on the error paths.
94    let mut buffer = Zeroizing::new(vec![0; size]);
95    input.read_exact(&mut buffer)?;
96    uint_from_le(&buffer)
97}
98
99/// Converts little-endian bytes into an integer wide enough for them.
100fn uint_from_le(bytes: &[u8]) -> Result<BoxedUint, Error> {
101    let bits = u32::try_from(bytes.len())
102        .ok()
103        .and_then(|len| len.checked_mul(8))
104        .ok_or_else(|| error!("Key component is too large."))?;
105    BoxedUint::from_le_slice(bytes, bits).map_err(|_| error!("Invalid key data."))
106}
107
108/// Whether two integers have the same value, whatever their storage widths.
109///
110/// Variable time: used only to check a key file against itself, where the file's owner knows every value.
111fn same_value(a: &BoxedUint, b: &BoxedUint) -> bool {
112    let a = Zeroizing::new(a.to_be_bytes_trimmed_vartime().into_vec());
113    let b = Zeroizing::new(b.to_be_bytes_trimmed_vartime().into_vec());
114    *a == *b
115}
116
117/// Whether `value` is zero or one: no key component can be.
118fn is_trivial(value: &BoxedUint) -> bool {
119    value.bit_width_vartime() <= 1
120}
121
122/// Maps an `rsa` error onto a message that carries no key material.
123///
124/// `rsa` errors name the kind of defect only; they never contain a value.
125#[expect(
126    clippy::needless_pass_by_value,
127    reason = "used as a map_err closure; the error is formatted, not stored"
128)]
129fn key_err(err: rsa::Error) -> Error {
130    error!("{err}")
131}
132
133/// A PBO entry's lowercased raw name bytes paired with its contents.
134type NameFilePair<'a> = (Vec<u8>, &'a [u8]);
135
136/// Smallest key length accepted, in bits.
137const MIN_KEY_BITS: u32 = 288;
138/// Smallest key length that `sign` and `generate` accept, in bits: the minimum of the Windows `CryptoAPI` RSA
139/// signature key (BI's tools and the game cannot use smaller ones). PKCS#1 v1.5 padding of a `SHA-1` hash needs
140/// 368 bits at least. Smaller keys can still be read, and signatures made with them verified.
141const MIN_SIGN_BITS: u32 = 384;
142/// Largest key length accepted, in bits: the largest RSA key the Windows `CryptoAPI` (which BI's key format comes
143/// from) handles. Bigger keys would only make hostile files expensive to read.
144const MAX_KEY_BITS: u32 = 16384;
145
146/// bType, bVersion and reserved of a private key blob (`PRIVATEKEYBLOB`, version 2), as a little-endian word.
147const PRIVATE_BLOB: u32 = 0x0207;
148/// The same for a public key blob (`PUBLICKEYBLOB`).
149const PUBLIC_BLOB: u32 = 0x0206;
150/// `aiKeyAlg` of every key: `CALG_RSA_SIGN`.
151const KEY_ALG: u32 = 0x2400;
152/// Magic of a private key blob.
153const PRIVATE_MAGIC: [u8; 4] = *b"RSA2";
154/// Magic of a public key blob.
155const PUBLIC_MAGIC: [u8; 4] = *b"RSA1";
156
157/// Reads and checks the 12 bytes of a `CryptoAPI` key blob header that follow the blob length: type and
158/// version, key algorithm and magic.
159///
160/// # Errors
161///
162/// Returns an error on I/O failure or if the header is not the one of a `kind` key. `file` names the kind of file
163/// ("private key", "public key", "signature") in the message.
164fn check_blob_header<I: Read>(
165    input: &mut I,
166    blob: u32,
167    magic: [u8; 4],
168    file: &str,
169    kind: &str,
170) -> Result<(), Error> {
171    let found_blob = input.read_u32::<LittleEndian>()?;
172    let found_alg = input.read_u32::<LittleEndian>()?;
173    let mut found_magic = [0; 4];
174    input.read_exact(&mut found_magic)?;
175    if found_blob != blob || found_alg != KEY_ALG || found_magic != magic {
176        return Err(error!(
177            "Invalid {file} file (bad header: not a {kind} key blob)."
178        ));
179    }
180    Ok(())
181}
182
183/// Validates a key length read from a key or signature file.
184///
185/// # Errors
186///
187/// Returns an error if the length is not a sane RSA key length.
188fn check_key_length(length: u32) -> Result<(), Error> {
189    if !(MIN_KEY_BITS..=MAX_KEY_BITS).contains(&length) {
190        return Err(error!(
191            "Invalid key length: {length} (supported: {MIN_KEY_BITS} to {MAX_KEY_BITS} bits)."
192        ));
193    }
194    Ok(())
195}
196
197/// Refuses key lengths that cannot sign.
198///
199/// # Errors
200///
201/// Returns an error if `length` is below the 384-bit `CryptoAPI` minimum.
202fn check_sign_length(length: u32) -> Result<(), Error> {
203    if length < MIN_SIGN_BITS {
204        return Err(error!(
205            "A {length}-bit key is smaller than the {MIN_SIGN_BITS}-bit CryptoAPI minimum and cannot sign."
206        ));
207    }
208    Ok(())
209}
210
211/// The default signature file of `pbo_path`: `<pbo>.<key name>.bisign`.
212///
213/// The key name is read from the (untrusted) key file, so it must be a plain file name part:
214/// `Path::set_extension` panics on a path separator, and a name must not steer the file elsewhere.
215///
216/// # Errors
217///
218/// Returns an error if the key name is empty or contains a path separator, `:` or a control
219/// character.
220pub fn signature_path(pbo_path: &Path, key_name: &str) -> Result<PathBuf, Error> {
221    if key_name.is_empty()
222        || key_name
223            .chars()
224            .any(|c| matches!(c, '/' | '\\' | ':') || c.is_control())
225    {
226        return Err(error!(
227            "The key name {key_name:?} cannot be used in a file name; pass the signature path explicitly."
228        ));
229    }
230    let mut path = pbo_path.to_path_buf();
231    path.set_extension(format!("pbo.{key_name}.bisign"));
232    Ok(path)
233}
234
235/// SHA-1 of the lowercased names of the non-empty entries, in byte order.
236fn namehash(pbo: &PBO) -> [u8; 20] {
237    let mut files_sorted: Vec<NameFilePair<'_>> = pbo
238        .entries()
239        .map(|(a, b)| (pbo.name_bytes(a).to_ascii_lowercase(), b))
240        .collect();
241    files_sorted.sort_by(|a, b| a.0.cmp(&b.0));
242
243    let mut h = Sha1::new();
244
245    for (name, data) in &files_sorted {
246        if data.is_empty() {
247            continue;
248        }
249
250        h.update(name);
251    }
252
253    h.finalize().into()
254}
255
256/// SHA-1 of the entries the signature `version` covers.
257fn filehash(pbo: &PBO, version: BISignVersion) -> [u8; 20] {
258    let mut h = Sha1::new();
259    let mut nothing = true;
260
261    for (name, data) in pbo.entries() {
262        // file names are never empty, so there is always at least one (possibly empty) part
263        let ext = name.split('.').next_back().unwrap_or("");
264
265        match version {
266            BISignVersion::V2 => {
267                if ext == "paa"
268                    || ext == "jpg"
269                    || ext == "p3d"
270                    || ext == "tga"
271                    || ext == "rvmat"
272                    || ext == "lip"
273                    || ext == "ogg"
274                    || ext == "wss"
275                    || ext == "png"
276                    || ext == "rtm"
277                    || ext == "pac"
278                    || ext == "fxy"
279                    || ext == "wrp"
280                {
281                    continue;
282                }
283            }
284            BISignVersion::V3 => {
285                // "c": DayZ's DSSignFile also hashes Enforce Script files (verified against DSSignFile.exe
286                // from DayZ Tools); without it a DayZ server rejects the signature of a script mod
287                if ext != "sqf"
288                    && ext != "c"
289                    && ext != "inc"
290                    && ext != "bikb"
291                    && ext != "ext"
292                    && ext != "fsm"
293                    && ext != "sqm"
294                    && ext != "hpp"
295                    && ext != "cfg"
296                    && ext != "sqs"
297                    && ext != "h"
298                {
299                    continue;
300                }
301            }
302        }
303
304        h.update(data);
305        nothing = false;
306    }
307
308    match version {
309        BISignVersion::V2 => {
310            if nothing {
311                h.update(b"nothing");
312            }
313        }
314        BISignVersion::V3 => {
315            if nothing {
316                h.update(b"gnihton");
317            }
318        }
319    }
320
321    h.finalize().into()
322}
323
324/// The three padded hashes that BI signs, big-endian, `length / 8` bytes each.
325fn generate_hashes(
326    pbo: &PBO,
327    version: BISignVersion,
328    length: u32,
329    signing: bool,
330) -> Result<[Vec<u8>; 3], Error> {
331    // the SHA-1 of the PBO's contents: computed while reading for a PBO that was read (a stored trailer that
332    // differs is an error), the one `PBO::write` would produce for one that was not read
333    let checksum = pbo.trailer_checksum(signing)?;
334    let hash1 = &checksum[..];
335
336    let namehash = namehash(pbo);
337    // the prefix part both of the following hashes end with
338    let mut suffix = Vec::new();
339    if let (Some(prefix), Some(prefix_bytes)) = (pbo.prefix(), pbo.prefix_bytes()) {
340        suffix.extend(prefix_bytes);
341        if !prefix.ends_with('\\') {
342            suffix.push(b'\\');
343        }
344    }
345
346    let mut h = Sha1::new();
347    h.update(hash1);
348    h.update(namehash);
349    h.update(&suffix);
350    let hash2 = h.finalize();
351
352    let mut h = Sha1::new();
353    h.update(filehash(pbo, version));
354    h.update(namehash);
355    h.update(&suffix);
356    let hash3 = h.finalize();
357
358    let size = usize::try_from(length / 8).map_err(|_| error!("Invalid key length: {length}."))?;
359    Ok([
360        pad_hash(hash1, size)?,
361        pad_hash(&hash2, size)?,
362        pad_hash(&hash3, size)?,
363    ])
364}
365
366/// The PKCS#1 v1.5 (`SHA-1`) padded block of `hash`, `size` bytes big-endian.
367fn pad_hash(hash: &[u8], size: usize) -> Result<Vec<u8>, Error> {
368    if size < 36 {
369        return Err(error!("Key length too small: {size} bytes."));
370    }
371    let mut vec: Vec<u8> = Vec::new();
372
373    vec.push(0);
374    vec.push(1);
375    vec.resize(size - 36, 255);
376    vec.extend(b"\x00\x30\x21\x30\x09\x06\x05\x2b");
377    vec.extend(b"\x0e\x03\x02\x1a\x05\x00\x04\x14");
378    vec.extend(hash);
379
380    Ok(vec)
381}
382
383/// `bytes` without its leading zero bytes.
384fn trim_zeros(bytes: &[u8]) -> &[u8] {
385    let start = bytes.iter().position(|&b| b != 0).unwrap_or(bytes.len());
386    bytes.get(start..).unwrap_or_default()
387}
388
389/// Lowercase hex of a number (`0` for zero).
390fn hex(bytes: &[u8]) -> String {
391    if bytes.is_empty() {
392        return "0".to_string();
393    }
394    let mut out = String::with_capacity(bytes.len() * 2);
395    for b in bytes {
396        // writing into a String cannot fail
397        let _ = write!(out, "{b:02x}");
398    }
399    out
400}
401
402/// The two numbers as hex, reduced to the hashes if their padding is the same.
403fn display_hashes(signed: &[u8], real: &[u8]) -> (String, String) {
404    let hex_signed = hex(signed);
405    let hex_real = hex(real);
406
407    if hex_signed.len() != hex_real.len() || hex_signed.len() <= 40 {
408        return (hex_signed, hex_real);
409    }
410
411    let (signed_padding, signed_hash) = hex_signed.split_at(hex_signed.len() - 40);
412    let (real_padding, real_hash) = hex_real.split_at(hex_real.len() - 40);
413
414    if signed_padding == real_padding {
415        (signed_hash.to_string(), real_hash.to_string())
416    } else {
417        (hex_signed, hex_real)
418    }
419}
420
421impl BIPrivateKey {
422    /// The key name, as stored in the key file.
423    #[must_use]
424    pub fn name(&self) -> &str {
425        &self.name
426    }
427
428    /// Reads a private key from the given input.
429    ///
430    /// # Errors
431    ///
432    /// Returns an error if the input is not a valid private key.
433    pub fn read<I: Read>(input: &mut I) -> Result<BIPrivateKey, Error> {
434        let name = input.read_cstring()?;
435        let temp = input.read_u32::<LittleEndian>()?;
436        check_blob_header(input, PRIVATE_BLOB, PRIVATE_MAGIC, "private key", "private")?;
437        let length = input.read_u32::<LittleEndian>()?;
438        let exponent = input.read_u32::<LittleEndian>()?;
439
440        check_key_length(length)?;
441        if temp != length / 16 * 9 + 20 {
442            return Err(error!("Invalid private key file (bad length field)."));
443        }
444        if length % 16 != 0 {
445            return Err(error!(
446                "Invalid private key file (the length {length} is not a multiple of 16)."
447            ));
448        }
449
450        let full = (length / 8) as usize;
451        let half = (length / 16) as usize;
452        // Everything but `n` is secret: wiped on drop, also on the error returns below.
453        let n = read_uint(input, full)?;
454        let p = Zeroizing::new(read_uint(input, half)?);
455        let q = Zeroizing::new(read_uint(input, half)?);
456        let exp_p = Zeroizing::new(read_uint(input, half)?);
457        let exp_q = Zeroizing::new(read_uint(input, half)?);
458        let iqmp = Zeroizing::new(read_uint(input, half)?);
459        let d = Zeroizing::new(read_uint(input, full)?);
460
461        // `rsa` would reject most of these, but some values would reach its arithmetic first (a modulus of
462        // one, a prime of zero), so every component is checked here.
463        for value in [&n, &*p, &*q, &*exp_p, &*exp_q, &*iqmp, &*d] {
464            if is_trivial(value) {
465                return Err(error!("Invalid private key (a component is zero or one)."));
466            }
467        }
468        if n.bit_width_vartime() != length {
469            return Err(error!(
470                "Invalid private key file (the modulus is not {length} bits wide)."
471            ));
472        }
473        // `from_components` takes its numbers by value: the key owns (and wipes) copies, ours are wiped here.
474        let key = PrivateKey::from_components(
475            n,
476            BoxedUint::from(u64::from(exponent)),
477            (*d).clone(),
478            vec![(*p).clone(), (*q).clone()],
479        )
480        .map_err(key_err)
481        .prepend_error("Invalid private key:")?;
482
483        // `rsa` recomputes the CRT values from `d`, `p` and `q`; the file's copies must agree.
484        let consistent = match (
485            key.dp(),
486            key.dq(),
487            key.crt_coefficient().map(Zeroizing::new),
488        ) {
489            (Some(dp), Some(dq), Some(qinv)) => {
490                same_value(dp, &exp_p) && same_value(dq, &exp_q) && same_value(&qinv, &iqmp)
491            }
492            _ => false,
493        };
494        if !consistent {
495            return Err(error!(
496                "Invalid private key (CRT values do not match the primes)."
497            ));
498        }
499
500        Ok(BIPrivateKey {
501            name,
502            length,
503            exponent,
504            key,
505        })
506    }
507
508    /// Generate a new private key with the given name and bitlength, with the exponent 65537.
509    ///
510    /// Arma 3 uses 1024 bit keys. The length must be a multiple of 16 (the key file layout) between 384 bits (the
511    /// `CryptoAPI` minimum, see [`BIPrivateKey::sign`]) and 16384 bits. Primes come from the operating system's
512    /// random number generator.
513    ///
514    /// # Errors
515    ///
516    /// Returns an error if `length` is not usable or the keypair cannot be generated.
517    pub fn generate(length: u32, name: String) -> Result<BIPrivateKey, Error> {
518        Self::generate_with_rng(length, name, &mut SysRng)
519    }
520
521    /// [`generate`](Self::generate) with a caller-supplied random number generator (seeded ones in tests).
522    pub(crate) fn generate_with_rng<R: TryCryptoRng + ?Sized>(
523        length: u32,
524        name: String,
525        rng: &mut R,
526    ) -> Result<BIPrivateKey, Error> {
527        check_sign_length(length)?;
528        check_key_length(length)?;
529        if !length.is_multiple_of(16) {
530            return Err(error!(
531                "Invalid key length: {length} (it must be a multiple of 16)."
532            ));
533        }
534        let exponent = 65537;
535        // `rsa` refuses anything below 1024 bits by default; BI keys may be smaller (down to 384 bits for
536        // signing), so the unchecked variant is used and the size limits are ours.
537        let bits = usize::try_from(length).map_err(|_| error!("Invalid key length: {length}."))?;
538        let key =
539            PrivateKey::new_with_exp_unchecked(rng, bits, BoxedUint::from(u64::from(exponent)))
540                .map_err(key_err)
541                .prepend_error("Failed to generate keypair:")?;
542        if key.n().as_ref().bit_width_vartime() != length {
543            return Err(error!(
544                "Failed to generate keypair: the modulus is not {length} bits wide."
545            ));
546        }
547
548        Ok(BIPrivateKey {
549            name,
550            length,
551            exponent,
552            key,
553        })
554    }
555
556    /// Returns the public key for this private key.
557    ///
558    /// # Errors
559    ///
560    /// Returns an error if the key material is invalid.
561    pub fn to_public_key(&self) -> Result<BIPublicKey, Error> {
562        Ok(BIPublicKey {
563            name: self.name.clone(),
564            length: self.length,
565            exponent: self.exponent,
566            key: self.key.to_public_key(),
567        })
568    }
569
570    /// Signs the given PBO with this private key.
571    ///
572    /// # Errors
573    ///
574    /// Returns an error if the key is below 384 bits (the `CryptoAPI` minimum), the PBO's stored SHA-1 trailer does
575    /// not match its contents (a checksum mismatch: repack the PBO first), hashing fails or the RSA operation
576    /// fails.
577    pub fn sign(&self, pbo: &PBO, version: BISignVersion) -> Result<BISign, Error> {
578        check_sign_length(self.length)?;
579        let hashes = generate_hashes(pbo, version, self.length, true)?;
580        let n = self.key.n().as_ref();
581        let precision = n.bits_precision();
582
583        // Blinding (base, exponent and CRT modulus) uses the OS RNG; it changes the computation, never the
584        // result, so signatures stay deterministic. The result is checked against the public key, which
585        // catches a faulty CRT computation before a bad signature is written.
586        let mut rng = SysRng;
587        let mut sign_one = |padded: &[u8]| -> Result<BoxedUint, Error> {
588            let m = BoxedUint::from_be_slice(padded, precision)
589                .map_err(|_| error!("The hash does not fit the key."))?;
590            rsa_decrypt_and_check(&self.key, Some(&mut rng), &m).map_err(key_err)
591        };
592        let [h1, h2, h3] = &hashes;
593        let (sig1, sig2, sig3) = (sign_one(h1)?, sign_one(h2)?, sign_one(h3)?);
594
595        Ok(BISign {
596            version,
597            name: self.name.clone(),
598            length: self.length,
599            exponent: self.exponent,
600            n: n.clone(),
601            sig1,
602            sig2,
603            sig3,
604        })
605    }
606
607    /// Write private key to output.
608    ///
609    /// # Errors
610    ///
611    /// Returns an error on I/O failure.
612    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
613        output
614            .write_cstring(&self.name)
615            .prepend_error("Key name:")?;
616        output.write_u32::<LittleEndian>(self.length / 16 * 9 + 20)?;
617        output.write_all(b"\x07\x02\x00\x00\x00\x24\x00\x00")?;
618        output.write_all(b"RSA2")?;
619        output.write_u32::<LittleEndian>(self.length)?;
620        output.write_u32::<LittleEndian>(self.exponent)?;
621        let full = (self.length / 8) as usize;
622        let half = (self.length / 16) as usize;
623        let primes = self.key.primes();
624        let (Some(p), Some(q)) = (primes.first(), primes.get(1)) else {
625            return Err(error!("Invalid private key (missing primes)."));
626        };
627        // The CRT values are recomputed from `d`, `p` and `q`; `read` checks that the file holds the same.
628        let (Some(exp_p), Some(exp_q), Some(iqmp)) = (
629            self.key.dp(),
630            self.key.dq(),
631            self.key.crt_coefficient().map(Zeroizing::new),
632        ) else {
633            return Err(error!("Invalid private key (missing CRT values)."));
634        };
635        write_uint(output, self.key.n().as_ref(), full)?;
636        write_uint(output, p.as_ref(), half)?;
637        write_uint(output, q.as_ref(), half)?;
638        write_uint(output, exp_p, half)?;
639        write_uint(output, exp_q, half)?;
640        write_uint(output, &iqmp, half)?;
641        write_uint(output, self.key.d(), full)?;
642        Ok(())
643    }
644}
645
646impl BIPublicKey {
647    /// The key name, as stored in the key file.
648    #[must_use]
649    pub fn name(&self) -> &str {
650        &self.name
651    }
652
653    /// Reads a public key from the given input.
654    ///
655    /// # Errors
656    ///
657    /// Returns an error if the input is not a valid public key.
658    pub fn read<I: Read>(input: &mut I) -> Result<BIPublicKey, Error> {
659        let name = input.read_cstring()?;
660        let temp = input.read_u32::<LittleEndian>()?;
661        check_blob_header(input, PUBLIC_BLOB, PUBLIC_MAGIC, "public key", "public")?;
662        let length = input.read_u32::<LittleEndian>()?;
663        let exponent = input.read_u32::<LittleEndian>()?;
664
665        check_key_length(length)?;
666        if temp != length / 8 + 20 {
667            return Err(error!("Invalid public key file (bad length field)."));
668        }
669
670        let n = read_uint(input, (length / 8) as usize)?;
671        // The modulus must be exactly `length` bits wide (a key frame bigger than its number, or a length that is
672        // no multiple of 8, is rejected). BI keys down to 288 bits are accepted, `rsa`'s default limits (1024 to
673        // 8192 bits) are widened to exactly this size.
674        let length_bits = length as usize;
675        let key = PublicKey::new_with_size_limits(
676            n,
677            BoxedUint::from(u64::from(exponent)),
678            length_bits..=length_bits,
679        )
680        .map_err(key_err)
681        .prepend_error("Invalid public key:")?;
682
683        Ok(BIPublicKey {
684            name,
685            length,
686            exponent,
687            key,
688        })
689    }
690
691    /// Verifies a signature against this public key.
692    ///
693    /// # Errors
694    ///
695    /// Returns an error if the signature was made with a different key, a signature value is not smaller than the
696    /// modulus, the PBO's stored SHA-1 trailer does not match its contents (a checksum mismatch), hashing fails or
697    /// one of the signature hashes doesn't match.
698    pub fn verify(&self, pbo: &PBO, signature: &BISign) -> Result<(), Error> {
699        let n = self.key.n().as_ref();
700        // a signature carries the public key it was made with: compare before anything else, so that a wrong key
701        // is reported as such and not as a defect of the signature values
702        if signature.length != self.length || !same_value(&signature.n, n) {
703            return Err(error!(
704                "The signature was made with a different key (signature: {}, {} bits; this key: {}, {} bits).",
705                printable(&signature.name),
706                signature.length,
707                printable(&self.name),
708                self.length
709            ));
710        }
711        let hashes = generate_hashes(pbo, signature.version, self.length, false)?;
712        let precision = n.bits_precision();
713
714        let values = [&signature.sig1, &signature.sig2, &signature.sig3];
715        let mut signed = Vec::with_capacity(values.len());
716        for (i, value) in values.into_iter().enumerate() {
717            let number = i + 1;
718            // a signature value is below n; a bigger one (or one too wide for the key) is no signature
719            let value = BoxedUint::from_be_slice(&value.to_be_bytes_trimmed_vartime(), precision)
720                .ok()
721                .filter(|value| value < n)
722                .ok_or_else(|| error!("Signature {number} is not smaller than the modulus."))?;
723            signed.push(rsa_encrypt(&self.key, &value).map_err(key_err)?);
724        }
725
726        // Plain `==` on the trimmed bytes: both sides are public (the recovered block and the hashes of the
727        // PBO), so no constant-time comparison is needed.
728        for (i, (signed, real)) in signed.iter().zip(&hashes).enumerate() {
729            let signed = signed.to_be_bytes_trimmed_vartime();
730            let real = trim_zeros(real);
731            if *signed != *real {
732                let (s, r) = display_hashes(&signed, real);
733                return Err(error!(
734                    "Hash {} doesn't match\nSigned hash: {}\nReal hash:   {}",
735                    i + 1,
736                    s,
737                    r
738                ));
739            }
740        }
741
742        Ok(())
743    }
744
745    /// Write public key to output.
746    ///
747    /// # Errors
748    ///
749    /// Returns an error on I/O failure.
750    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
751        output
752            .write_cstring(&self.name)
753            .prepend_error("Key name:")?;
754        output.write_u32::<LittleEndian>(self.length / 8 + 20)?;
755        output.write_all(b"\x06\x02\x00\x00\x00\x24\x00\x00")?;
756        output.write_all(b"RSA1")?;
757        output.write_u32::<LittleEndian>(self.length)?;
758        output.write_u32::<LittleEndian>(self.exponent)?;
759        write_uint(output, self.key.n().as_ref(), (self.length / 8) as usize)?;
760        Ok(())
761    }
762}
763
764impl From<BISignVersion> for u32 {
765    fn from(val: BISignVersion) -> Self {
766        match val {
767            BISignVersion::V2 => 2,
768            BISignVersion::V3 => 3,
769        }
770    }
771}
772
773/// BI signature (.bisign)
774impl BISign {
775    /// Reads a signature from the given input.
776    ///
777    /// # Errors
778    ///
779    /// Returns an error if the input is not a valid signature.
780    pub fn read<I: Read>(input: &mut I) -> Result<BISign, Error> {
781        let name = input.read_cstring()?;
782        let temp = input.read_u32::<LittleEndian>()?;
783        check_blob_header(input, PUBLIC_BLOB, PUBLIC_MAGIC, "signature", "public")?;
784        let length = input.read_u32::<LittleEndian>()?;
785        let exponent = input.read_u32::<LittleEndian>()?;
786
787        check_key_length(length)?;
788        if temp != length / 8 + 20 {
789            return Err(error!("Invalid signature file (bad length field)."));
790        }
791
792        let size = (length / 8) as usize;
793        let n = read_uint(input, size)?;
794        if n.bit_width_vartime() != length {
795            return Err(error!(
796                "Invalid signature file (the modulus is not {length} bits wide)."
797            ));
798        }
799
800        input.read_u32::<LittleEndian>()?;
801        let sig1 = read_uint(input, size)?;
802
803        let version = match input.read_u32::<LittleEndian>()? {
804            2 => BISignVersion::V2,
805            3 => BISignVersion::V3,
806            _ => {
807                return Err(error!("Unknown BISign version."));
808            }
809        };
810
811        input.read_u32::<LittleEndian>()?;
812        let sig2 = read_uint(input, size)?;
813
814        input.read_u32::<LittleEndian>()?;
815        let sig3 = read_uint(input, size)?;
816
817        Ok(BISign {
818            version,
819            name,
820            length,
821            exponent,
822            n,
823            sig1,
824            sig2,
825            sig3,
826        })
827    }
828
829    /// Writes the signature to the given output.
830    ///
831    /// # Errors
832    ///
833    /// Returns an error on I/O failure.
834    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
835        output
836            .write_cstring(&self.name)
837            .prepend_error("Key name:")?;
838        output.write_u32::<LittleEndian>(self.length / 8 + 20)?;
839        output.write_all(b"\x06\x02\x00\x00\x00\x24\x00\x00")?;
840        output.write_all(b"RSA1")?;
841        output.write_u32::<LittleEndian>(self.length)?;
842        output.write_u32::<LittleEndian>(self.exponent)?;
843        write_uint(output, &self.n, (self.length / 8) as usize)?;
844        output.write_u32::<LittleEndian>(self.length / 8)?;
845        write_uint(output, &self.sig1, (self.length / 8) as usize)?;
846        output.write_u32::<LittleEndian>(self.version.into())?;
847        output.write_u32::<LittleEndian>(self.length / 8)?;
848        write_uint(output, &self.sig2, (self.length / 8) as usize)?;
849        output.write_u32::<LittleEndian>(self.length / 8)?;
850        write_uint(output, &self.sig3, (self.length / 8) as usize)?;
851        Ok(())
852    }
853}
854
855#[cfg(test)]
856mod tests {
857    //! Key generation is tested here because the seeded entry point `generate_with_rng` is private to the crate.
858    #![expect(
859        clippy::many_single_char_names,
860        reason = "the names of the RSA numbers: n, e, d, p, q"
861    )]
862
863    use std::fs;
864    use std::io::Cursor;
865
866    use num_bigint::BigUint;
867    use rand_chacha::ChaCha20Rng;
868    use rand_core::SeedableRng;
869
870    use super::*;
871
872    fn seeded(seed: u64, bits: u32) -> BIPrivateKey {
873        let mut rng = ChaCha20Rng::seed_from_u64(seed);
874        BIPrivateKey::generate_with_rng(bits, "gen".to_string(), &mut rng).unwrap()
875    }
876
877    fn bn(value: &BoxedUint) -> BigUint {
878        BigUint::from_bytes_be(&value.to_be_bytes_trimmed_vartime())
879    }
880
881    fn file(key: &BIPrivateKey) -> Vec<u8> {
882        let mut out = Vec::new();
883        key.write(&mut out).unwrap();
884        out
885    }
886
887    #[test]
888    fn generated_key_is_valid() {
889        for (seed, bits) in [(1u64, 384u32), (2, 1024)] {
890            let key = seeded(seed, bits);
891            assert_eq!((key.length, key.exponent), (bits, 65537));
892            let n = bn(key.key.n().as_ref());
893            assert_eq!(n.bits(), u64::from(bits));
894            let primes = key.key.primes();
895            let (p, q) = (bn(&primes[0]), bn(&primes[1]));
896            let (d, e) = (bn(key.key.d()), BigUint::from(65537u32));
897            let one = BigUint::from(1u32);
898
899            // p * q = n
900            assert_eq!(&p * &q, n);
901
902            // e * d = 1 mod phi(n); `rsa` computes d from phi (not from lambda)
903            let (p1, q1) = (&p - &one, &q - &one);
904            let phi = &p1 * &q1;
905            assert_eq!((&e * &d) % &phi, one, "e * d mod phi(n)");
906
907            // CRT values
908            assert_eq!(&d % &p1, bn(key.key.dp().unwrap()));
909            assert_eq!(&d % &q1, bn(key.key.dq().unwrap()));
910            let qinv = key.key.crt_coefficient().unwrap();
911            assert_eq!((bn(&qinv) * &q) % &p, one, "qinv * q mod p");
912
913            // the key file round-trips byte for byte
914            let bytes = file(&key);
915            let again = BIPrivateKey::read(&mut Cursor::new(&bytes)).unwrap();
916            assert_eq!(file(&again), bytes);
917            assert_eq!(again.name(), "gen");
918        }
919    }
920
921    #[test]
922    fn generated_key_signs_and_verifies() {
923        let pbo_bytes = fs::read(concat!(
924            env!("CARGO_MANIFEST_DIR"),
925            "/../../tests/fixtures/bi/sign/testsig.pbo"
926        ))
927        .unwrap();
928        let pbo = PBO::read(&mut Cursor::new(pbo_bytes)).unwrap();
929        let key = seeded(3, 1024);
930        let public = key.to_public_key().unwrap();
931        for version in [BISignVersion::V2, BISignVersion::V3] {
932            let signature = key.sign(&pbo, version).unwrap();
933            public.verify(&pbo, &signature).unwrap();
934
935            // the independent side: num-bigint's modular exponentiation recovers the padded hashes
936            let hashes = generate_hashes(&pbo, version, 1024, false).unwrap();
937            let n = bn(key.key.n().as_ref());
938            let e = BigUint::from(65537u32);
939            for (sig, hash) in [&signature.sig1, &signature.sig2, &signature.sig3]
940                .into_iter()
941                .zip(&hashes)
942            {
943                let back = bn(sig).modpow(&e, &n);
944                assert_eq!(back.to_bytes_be(), trim_zeros(hash));
945            }
946        }
947    }
948
949    #[test]
950    fn seeded_generation_is_deterministic() {
951        assert_eq!(file(&seeded(4, 512)), file(&seeded(4, 512)));
952        assert_ne!(file(&seeded(4, 512)), file(&seeded(5, 512)));
953    }
954
955    #[test]
956    fn generation_with_the_os_rng_is_not_deterministic() {
957        let a = BIPrivateKey::generate(384, "a".to_string()).unwrap();
958        let b = BIPrivateKey::generate(384, "a".to_string()).unwrap();
959        assert_ne!(file(&a), file(&b));
960    }
961
962    #[test]
963    fn unusable_lengths_are_refused() {
964        for bits in [0, 288, 368, 383, 392, 400 + 8, MAX_KEY_BITS + 16] {
965            assert!(
966                BIPrivateKey::generate(bits, "x".to_string()).is_err(),
967                "{bits}"
968            );
969        }
970    }
971}