From 83bfa98a38ee04a5bce354d246c9af6e4fce5818 Mon Sep 17 00:00:00 2001 From: Alex Page Date: Fri, 23 Jun 2023 02:24:40 -0400 Subject: [PATCH 01/10] Reorganize crate as lib --- Cargo.toml | 4 ++++ src/{ => bin/xpkey}/cli.rs | 4 ++-- src/bin/xpkey/main.rs | 7 +++++++ src/bink1998.rs | 9 ++++----- src/bink2002.rs | 37 ++++++++++++++++++++++++------------- src/confid/black_box.rs | 4 ++-- src/crypto.rs | 12 ++++++++++++ src/lib.rs | 7 +++++++ src/main.rs | 14 -------------- 9 files changed, 62 insertions(+), 36 deletions(-) rename src/{ => bin/xpkey}/cli.rs (99%) create mode 100644 src/bin/xpkey/main.rs create mode 100644 src/lib.rs delete mode 100644 src/main.rs diff --git a/Cargo.toml b/Cargo.toml index f622acf..84db26a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,10 @@ name = "umskt" version = "0.1.0" edition = "2021" +crate-type = ["lib"] + +[[bin]] +name = "xpkey" # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/src/cli.rs b/src/bin/xpkey/cli.rs similarity index 99% rename from src/cli.rs rename to src/bin/xpkey/cli.rs index a422deb..f7e00a9 100644 --- a/src/cli.rs +++ b/src/bin/xpkey/cli.rs @@ -9,7 +9,7 @@ use openssl::{ }; use serde_json::{from_reader, from_str}; -use crate::{ +use umskt::{ bink1998, bink2002, confid, crypto::initialize_elliptic_curve, key::P_KEY_CHARSET, PK_LENGTH, }; @@ -156,7 +156,7 @@ impl Cli { keys } else { - from_str(std::include_str!("../keys.json"))? + from_str(std::include_str!("../../../keys.json"))? } }; diff --git a/src/bin/xpkey/main.rs b/src/bin/xpkey/main.rs new file mode 100644 index 0000000..5e60ce0 --- /dev/null +++ b/src/bin/xpkey/main.rs @@ -0,0 +1,7 @@ +use anyhow::Result; + +mod cli; + +fn main() -> Result<()> { + cli::Cli::new()?.run() +} diff --git a/src/bink1998.rs b/src/bink1998.rs index 1c9f12b..9d3f4ee 100644 --- a/src/bink1998.rs +++ b/src/bink1998.rs @@ -6,7 +6,10 @@ use openssl::{ sha::sha1, }; -use crate::key::{base24_decode, base24_encode}; +use crate::{ + crypto::bitmask, + key::{base24_decode, base24_encode}, +}; const FIELD_BITS: i32 = 384; const FIELD_BYTES: usize = 48; @@ -185,10 +188,6 @@ fn pack(p_key: ProductKey) -> Vec { .collect() } -fn bitmask(n: u64) -> u64 { - (1 << n) - 1 -} - #[cfg(test)] mod tests { use std::{fs::File, io::BufReader}; diff --git a/src/bink2002.rs b/src/bink2002.rs index ce5655c..1f3f46d 100644 --- a/src/bink2002.rs +++ b/src/bink2002.rs @@ -6,7 +6,10 @@ use openssl::{ sha::sha1, }; -use crate::key::{base24_decode, base24_encode}; +use crate::{ + crypto::{bitmask, by_dword, next_sn_bits}, + key::{base24_decode, base24_encode}, +}; const FIELD_BITS: i32 = 512; const FIELD_BYTES: usize = 64; @@ -262,22 +265,11 @@ fn pack(p_key: ProductKey) -> Vec { .collect() } -fn bitmask(n: u64) -> u64 { - (1 << n) - 1 -} - -fn next_sn_bits(field: u64, n: u32, offset: u32) -> u64 { - (field >> offset) & ((1u64 << n) - 1) -} - -fn by_dword(n: &[u8]) -> u32 { - (n[0] as u32) | (n[1] as u32) << 8 | (n[2] as u32) << 16 | (n[3] as u32) << 24 -} - #[cfg(test)] mod tests { use std::{fs::File, io::BufReader}; + use openssl::bn::{BigNum, BigNumContext}; use serde_json::from_reader; use crate::crypto::initialize_elliptic_curve; @@ -308,4 +300,23 @@ mod tests { assert!(super::verify(&e_curve, &gen_point, &pub_point, product_key, true).unwrap()); } + + #[test] + fn prime_test() { + let mut ctx = BigNumContext::new().unwrap(); + let p = BigNum::from_dec_str("9759712359818460653").unwrap(); + let mut p2 = BigNum::new().unwrap(); + let _ = p2.sqr(&p, &mut ctx); + println!("p2: {:?}", p2); + } + + #[test] + fn sqrt_test() { + let mut ctx = BigNumContext::new().unwrap(); + let s = BigNum::from_dec_str("95251985346393225982548498694509186409").unwrap(); + let p = BigNum::from_dec_str("9362780380393422053").unwrap(); + let mut out = BigNum::new().unwrap(); + out.mod_sqrt(&s, &p, &mut ctx).unwrap(); + assert_eq!(out, BigNum::from_dec_str("8965848400968383453").unwrap()); + } } diff --git a/src/confid/black_box.rs b/src/confid/black_box.rs index af491ea..688552d 100644 --- a/src/confid/black_box.rs +++ b/src/confid/black_box.rs @@ -79,8 +79,8 @@ fn umul128(a: u64, b: u64, hi: &mut u64) -> u64 { r as u64 } -/// `hi:lo * ceil(2**170/MOD) >> (64 + 64 + 42)` fn ui128_quotient_mod(lo: u64, hi: u64) -> u64 { + // hi:lo * ceil(2**170/MOD) >> (64 + 64 + 42) let mut prod1: u64 = 0; umul128(lo, 0x604fa6a1c6346a87_i64 as u64, &mut prod1); let mut part1hi: u64 = 0; @@ -286,7 +286,6 @@ unsafe fn find_divisor_v(d: *mut TDivisor) -> i32 { 1_i32 } -/// generic short slow code unsafe fn polynomial_mul( adeg: i32, a: *const u64, @@ -295,6 +294,7 @@ unsafe fn polynomial_mul( mut resultprevdeg: i32, result: *mut u64, ) -> i32 { + // generic short slow code if adeg < 0_i32 || bdeg < 0_i32 { return resultprevdeg; } diff --git a/src/crypto.rs b/src/crypto.rs index ce406c3..530824b 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -35,3 +35,15 @@ pub fn initialize_elliptic_curve( (c_curve, gen_point, pub_point) } + +pub fn bitmask(n: u64) -> u64 { + (1 << n) - 1 +} + +pub fn next_sn_bits(field: u64, n: u32, offset: u32) -> u64 { + (field >> offset) & ((1u64 << n) - 1) +} + +pub fn by_dword(n: &[u8]) -> u32 { + (n[0] as u32) | (n[1] as u32) << 8 | (n[2] as u32) << 16 | (n[3] as u32) << 24 +} diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..ecf24a8 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,7 @@ +pub mod bink1998; +pub mod bink2002; +pub mod confid; +pub mod crypto; +pub mod key; + +pub const PK_LENGTH: usize = 25; diff --git a/src/main.rs b/src/main.rs deleted file mode 100644 index 1a5ccb1..0000000 --- a/src/main.rs +++ /dev/null @@ -1,14 +0,0 @@ -use anyhow::Result; - -mod bink1998; -mod bink2002; -mod cli; -mod confid; -mod crypto; -mod key; - -const PK_LENGTH: usize = 25; - -fn main() -> Result<()> { - cli::Cli::new()?.run() -} From 61d875757ddda4a9dc23d24c9f630ef03b73441b Mon Sep 17 00:00:00 2001 From: Alex Page Date: Fri, 23 Jun 2023 16:57:12 -0400 Subject: [PATCH 02/10] Redesign lib public interface --- src/bin/xpkey/cli.rs | 222 ++++++-------------- src/bink1998.rs | 335 +++++++++++++++++------------- src/bink2002.rs | 472 ++++++++++++++++++++++++------------------- src/crypto.rs | 88 ++++---- src/key.rs | 32 ++- src/lib.rs | 5 +- src/math.rs | 11 + 7 files changed, 603 insertions(+), 562 deletions(-) create mode 100644 src/math.rs diff --git a/src/bin/xpkey/cli.rs b/src/bin/xpkey/cli.rs index f7e00a9..5046fbd 100644 --- a/src/bin/xpkey/cli.rs +++ b/src/bin/xpkey/cli.rs @@ -2,24 +2,20 @@ use std::{fs::File, io::BufReader, path::Path}; use anyhow::{anyhow, Result}; use clap::Parser; -use openssl::{ - bn::{BigNum, MsbOption}, - ec::{EcGroup, EcPoint}, - rand::rand_bytes, -}; use serde_json::{from_reader, from_str}; use umskt::{ - bink1998, bink2002, confid, crypto::initialize_elliptic_curve, key::P_KEY_CHARSET, PK_LENGTH, + bink1998, bink2002, confid, + crypto::{EllipticCurve, PrivateKey}, }; #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum Mode { Bink1998Generate, Bink2002Generate, - ConfirmationId, Bink1998Validate, Bink2002Validate, + ConfirmationId, } impl Default for Mode { @@ -37,7 +33,7 @@ pub struct Options { /// Number of keys to generate #[arg(short = 'n', long = "number", default_value = "1")] - num_keys: i32, + num_keys: u64, /// Specify which keys file to load #[arg(short = 'f', long = "file")] @@ -69,12 +65,15 @@ pub struct Options { pub struct Cli { options: Options, - private_key: BigNum, - gen_order: BigNum, - gen_point: EcPoint, - pub_point: EcPoint, - e_curve: EcGroup, - count: u32, + p: String, + a: String, + b: String, + gx: String, + gy: String, + kx: String, + ky: String, + n: String, + k: String, } impl Cli { @@ -85,11 +84,11 @@ impl Cli { let bink = &keys["BINK"][&options.binkid]; // We cannot produce a valid key without knowing the private key k. The reason for this is that // we need the result of the function K(x; y) = kG(x; y). - let private_key = BigNum::from_dec_str(bink["priv"].as_str().unwrap()).unwrap(); + let private_key = bink["priv"].as_str().unwrap(); // We can, however, validate any given key using the available public key: {p, a, b, G, K}. // genOrder the order of the generator G, a value we have to reverse -> Schoof's Algorithm. - let gen_order = BigNum::from_dec_str(bink["n"].as_str().unwrap()).unwrap(); + let gen_order = bink["n"].as_str().unwrap(); let p = bink["p"].as_str().unwrap(); let a = bink["a"].as_str().unwrap(); @@ -98,8 +97,6 @@ impl Cli { let gy = bink["g"]["y"].as_str().unwrap(); let kx = bink["pub"]["x"].as_str().unwrap(); let ky = bink["pub"]["y"].as_str().unwrap(); - let n = bink["n"].as_str().unwrap(); - let k = bink["priv"].as_str().unwrap(); if options.verbose { println!("-----------------------------------------------------------"); @@ -115,21 +112,22 @@ impl Cli { println!("Gy: {gy}"); println!("Kx: {kx}"); println!("Ky: {ky}"); - println!(" n: {n}"); - println!(" k: {k}"); + println!(" n: {gen_order}"); + println!(" k: {private_key}"); println!(); } - let (e_curve, gen_point, pub_point) = initialize_elliptic_curve(p, a, b, gx, gy, kx, ky); - Ok(Self { options, - private_key, - gen_order, - gen_point, - pub_point, - e_curve, - count: 0, + p: p.to_owned(), + a: a.to_owned(), + b: b.to_owned(), + gx: gx.to_owned(), + gy: gy.to_owned(), + kx: kx.to_owned(), + ky: ky.to_owned(), + n: gen_order.to_owned(), + k: private_key.to_owned(), }) } @@ -205,134 +203,71 @@ impl Cli { match self.options.application_mode { Mode::Bink1998Generate => self.bink1998_generate(), Mode::Bink2002Generate => self.bink2002_generate(), - Mode::ConfirmationId => self.confirmation_id(), Mode::Bink1998Validate => self.bink1998_validate(), Mode::Bink2002Validate => self.bink2002_validate(), + Mode::ConfirmationId => self.confirmation_id(), } } fn bink1998_generate(&mut self) -> Result<()> { - let mut n_raw = self.options.channel_id * 1_000_000; // <- change - - let mut bn_rand = BigNum::new()?; - bn_rand.rand(19, MsbOption::MAYBE_ZERO, false)?; - - let o_raw: u32 = u32::from_be_bytes(bn_rand.to_vec_padded(4)?.try_into().unwrap()); - n_raw += o_raw % 999999; - - if self.options.verbose { - println!("> PID: {n_raw:09}"); - } - - let private_key = &self.gen_order - &self.private_key; - - let upgrade = false; + let curve = EllipticCurve::new( + &self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky, + )?; + let private_key = PrivateKey::new(&self.n, &self.k)?; for _ in 0..self.options.num_keys { - let p_key = bink1998::generate( - &self.e_curve, - &self.gen_point, - &self.gen_order, + let product_key = bink1998::ProductKey::new( + &curve, &private_key, - n_raw, - upgrade, + self.options.channel_id, + None, + None, )?; - Cli::print_key(&p_key); - - if bink1998::verify( - &self.e_curve, - &self.gen_point, - &self.pub_point, - &p_key, - self.options.verbose, - )? { - self.count += 1; - } + println!("{product_key}"); } - - println!("Success count: {}/{}", self.count, self.options.num_keys); Ok(()) } fn bink2002_generate(&mut self) -> Result<()> { - let p_channel_id = self.options.channel_id; - - if self.options.verbose { - println!("> Channel ID: {p_channel_id:03}"); - } + let curve = EllipticCurve::new( + &self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky, + )?; + let private_key = PrivateKey::new(&self.n, &self.k)?; for _ in 0..self.options.num_keys { - let mut p_auth_info_bytes = [0_u8; 4]; - rand_bytes(&mut p_auth_info_bytes)?; - let p_auth_info = u32::from_ne_bytes(p_auth_info_bytes) & ((1 << 10) - 1); - - if self.options.verbose { - println!("> AuthInfo: {p_auth_info}"); - } - - let p_key = bink2002::generate( - &self.e_curve, - &self.gen_point, - &self.gen_order, - &self.private_key, - p_channel_id, - p_auth_info, - false, + let product_key = bink2002::ProductKey::new( + &curve, + &private_key, + self.options.channel_id, + None, + None, + None, )?; - Cli::print_key(&p_key); - println!("\n"); - - if bink2002::verify( - &self.e_curve, - &self.gen_point, - &self.pub_point, - &p_key, - self.options.verbose, - )? { - self.count += 1; - } + println!("{product_key}"); } - - println!("Success count: {}/{}", self.count, self.options.num_keys); Ok(()) } fn bink1998_validate(&mut self) -> Result<()> { - let Ok(key) = Self::strip_key(self.options.key_to_check.as_ref().unwrap()) else { - return Err(anyhow!("Product key is in an incorrect format!")); - }; - - Self::print_key(&key); - if !bink1998::verify( - &self.e_curve, - &self.gen_point, - &self.pub_point, - &key, - self.options.verbose, - )? { - return Err(anyhow!("Product key is invalid! Wrong BINK ID?")); - } + let curve = EllipticCurve::new( + &self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky, + )?; + let product_key = + bink1998::ProductKey::from_key(&curve, self.options.key_to_check.as_ref().unwrap())?; + println!("{product_key}"); println!("Key validated successfully!"); Ok(()) } fn bink2002_validate(&mut self) -> Result<()> { - let Ok(key) = Self::strip_key(self.options.key_to_check.as_ref().unwrap()) else { - return Err(anyhow!("Product key is in an incorrect format!")); - }; - - Self::print_key(&key); - if !bink2002::verify( - &self.e_curve, - &self.gen_point, - &self.pub_point, - &key, - self.options.verbose, - )? { - return Err(anyhow!("Product key is invalid! Wrong BINK ID?")); - } + let curve = EllipticCurve::new( + &self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky, + )?; + let product_key = + bink2002::ProductKey::from_key(&curve, self.options.key_to_check.as_ref().unwrap())?; + println!("{product_key}"); println!("Key validated successfully!"); Ok(()) } @@ -344,39 +279,4 @@ impl Cli { }; Ok(()) } - - fn print_key(pk: &str) { - assert!(pk.len() >= PK_LENGTH); - println!( - "{}", - pk.chars() - .enumerate() - .fold(String::new(), |mut acc: String, (i, c)| { - if i > 0 && i % 5 == 0 { - acc.push('-'); - } - acc.push(c); - acc - }) - ); - } - - fn strip_key(in_key: &str) -> Result { - let out_key: String = in_key - .chars() - .filter_map(|c| { - let c = c.to_ascii_uppercase(); - if P_KEY_CHARSET.into_iter().any(|x| x == c) { - Some(c) - } else { - None - } - }) - .collect(); - if out_key.len() == PK_LENGTH { - Ok(out_key) - } else { - Err(anyhow!("Invalid key length")) - } - } } diff --git a/src/bink1998.rs b/src/bink1998.rs index 9d3f4ee..981315a 100644 --- a/src/bink1998.rs +++ b/src/bink1998.rs @@ -1,4 +1,6 @@ -use anyhow::Result; +use std::fmt::{Display, Formatter}; + +use anyhow::{bail, Result}; use bitreader::BitReader; use openssl::{ bn::{BigNum, BigNumContext, MsbOption}, @@ -7,112 +9,171 @@ use openssl::{ }; use crate::{ - crypto::bitmask, - key::{base24_decode, base24_encode}, + crypto::{EllipticCurve, PrivateKey}, + key::{base24_decode, base24_encode, strip_key}, + math::bitmask, }; const FIELD_BITS: i32 = 384; const FIELD_BYTES: usize = 48; const SHA_MSG_LENGTH: usize = 4 + 2 * FIELD_BYTES; -#[derive(Clone, Copy, Debug)] -struct ProductKey { +const HASH_LENGTH_BITS: u8 = 28; +const SERIAL_LENGTH_BITS: u8 = 30; +const UPGRADE_LENGTH_BITS: u8 = 1; +const EVERYTHING_ELSE: u8 = HASH_LENGTH_BITS + SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ProductKey { upgrade: bool, serial: u32, hash: u32, signature: u64, } -pub fn verify( - e_curve: &EcGroup, - base_point: &EcPoint, - public_key: &EcPoint, - p_key: &str, - verbose: bool, -) -> Result { - let mut num_context = BigNumContext::new()?; +impl ProductKey { + pub fn new( + curve: &EllipticCurve, + private_key: &PrivateKey, + channel_id: u32, + sequence: Option, + upgrade: Option, + ) -> Result { + // Generate random sequence if none supplied + let sequence = match sequence { + Some(serial) => serial, + None => { + let mut bn_rand = BigNum::new()?; + bn_rand.rand(19, MsbOption::MAYBE_ZERO, false)?; + let o_raw = u32::from_be_bytes(bn_rand.to_vec_padded(4)?.try_into().unwrap()); + o_raw % 999999 + } + }; - let p_raw = base24_decode(p_key); - let product_key = unpack(&p_raw)?; + // Default to upgrade=false + let upgrade = upgrade.unwrap_or(false); - let p_data = product_key.serial << 1 | product_key.upgrade as u32; + // Generate a new random key + let product_key = Self::generate( + &curve.curve, + &curve.gen_point, + &private_key.gen_order, + &private_key.private_key, + channel_id * 1_000_000 + sequence, + upgrade, + )?; - if verbose { - println!("Validation results:"); - println!(" Upgrade: {}", product_key.upgrade); - println!(" Serial: {}", product_key.serial); - println!(" Hash: {}", product_key.hash); - println!(" Signature: {}", product_key.signature); - println!(); + // Make sure the key is valid + product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?; + + // Ship it + Ok(product_key) } - let e = BigNum::from_u32(product_key.hash)?; - let s = BigNum::from_slice(&product_key.signature.to_be_bytes())?; - let mut x = BigNum::new()?; - let mut y = BigNum::new()?; + pub fn from_key(curve: &EllipticCurve, key: &str) -> Result { + let key = strip_key(key)?; + let Ok(p_raw) = base24_decode(&key) else { + bail!("Product key is in an incorrect format!") + }; + let product_key = Self::from_packed(&p_raw)?; + product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?; + Ok(product_key) + } - let mut t = EcPoint::new(e_curve)?; - let mut p = EcPoint::new(e_curve)?; - let mut p_2 = EcPoint::new(e_curve)?; + fn generate( + e_curve: &EcGroup, + base_point: &EcPoint, + gen_order: &BigNum, + private_key: &BigNum, + p_serial: u32, + p_upgrade: bool, + ) -> Result { + let mut num_context = BigNumContext::new().unwrap(); - t.mul(e_curve, base_point, &s, &num_context)?; - p.mul(e_curve, public_key, &e, &num_context)?; - p_2.mul(e_curve, public_key, &e, &num_context)?; + let mut c = BigNum::new()?; + let mut s = BigNum::new()?; + let mut s_2 = BigNum::new()?; + let mut x = BigNum::new()?; + let mut y = BigNum::new()?; - p.add(e_curve, &t, &p_2, &mut num_context)?; + let p_data = p_serial << 1 | p_upgrade as u32; - p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; + let product_key = loop { + let mut r = EcPoint::new(e_curve)?; - let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH]; + // Generate a random number c consisting of 384 bits without any constraints. + c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?; - let mut x_bin = x.to_vec_padded(FIELD_BYTES as i32)?; - x_bin.reverse(); - let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?; - y_bin.reverse(); + // Pick a random derivative of the base point on the elliptic curve. + // R = cG; + r.mul(e_curve, base_point, &c, &num_context)?; - msg_buffer[0..4].copy_from_slice(&p_data.to_le_bytes()); - msg_buffer[4..4 + FIELD_BYTES].copy_from_slice(&x_bin); - msg_buffer[4 + FIELD_BYTES..4 + FIELD_BYTES * 2].copy_from_slice(&y_bin); + // Acquire its coordinates. + // x = R.x; y = R.y; + r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; - let msg_digest = sha1(&msg_buffer); + let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH]; - let hash: u32 = - u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32; + let mut x_bin = x.to_vec_padded(FIELD_BYTES as i32)?; + x_bin.reverse(); + let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?; + y_bin.reverse(); - Ok(hash == product_key.hash) -} + msg_buffer[0..4].copy_from_slice(&p_data.to_le_bytes()); + msg_buffer[4..4 + FIELD_BYTES].copy_from_slice(&x_bin); + msg_buffer[4 + FIELD_BYTES..4 + FIELD_BYTES * 2].copy_from_slice(&y_bin); -pub fn generate( - e_curve: &EcGroup, - base_point: &EcPoint, - gen_order: &BigNum, - private_key: &BigNum, - p_serial: u32, - p_upgrade: bool, -) -> Result { - let mut num_context = BigNumContext::new().unwrap(); + let msg_digest = sha1(&msg_buffer); - let mut c = BigNum::new()?; - let mut s = BigNum::new()?; - let mut s_2 = BigNum::new()?; - let mut x = BigNum::new()?; - let mut y = BigNum::new()?; + let p_hash: u32 = + u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32; - let p_data = p_serial << 1 | p_upgrade as u32; + s_2.copy_from_slice(&private_key.to_vec())?; + s_2.mul_word(p_hash)?; - let p_raw = loop { - let mut r = EcPoint::new(e_curve)?; + s.mod_add(&s_2, &c, gen_order, &mut num_context)?; - // Generate a random number c consisting of 384 bits without any constraints. - c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?; + let p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap()); - // Pick a random derivative of the base point on the elliptic curve. - // R = cG; - r.mul(e_curve, base_point, &c, &num_context)?; + if p_signature <= bitmask(55) { + break Self { + upgrade: p_upgrade, + serial: p_serial, + hash: p_hash, + signature: p_signature, + }; + } + }; - // Acquire its coordinates. - // x = R.x; y = R.y; - r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; + Ok(product_key) + } + + fn verify( + &self, + e_curve: &EcGroup, + base_point: &EcPoint, + public_key: &EcPoint, + ) -> Result { + let mut num_context = BigNumContext::new()?; + + let p_data = self.serial << 1 | self.upgrade as u32; + + let e = BigNum::from_u32(self.hash)?; + let s = BigNum::from_slice(&self.signature.to_be_bytes())?; + let mut x = BigNum::new()?; + let mut y = BigNum::new()?; + + let mut t = EcPoint::new(e_curve)?; + let mut p = EcPoint::new(e_curve)?; + let mut p_2 = EcPoint::new(e_curve)?; + + t.mul(e_curve, base_point, &s, &num_context)?; + p.mul(e_curve, public_key, &e, &num_context)?; + p_2.mul(e_curve, public_key, &e, &num_context)?; + + p.add(e_curve, &t, &p_2, &mut num_context)?; + + p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH]; @@ -127,65 +188,61 @@ pub fn generate( let msg_digest = sha1(&msg_buffer); - let p_hash: u32 = + let hash: u32 = u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32; - s_2.copy_from_slice(&private_key.to_vec())?; - s_2.mul_word(p_hash)?; + Ok(hash == self.hash) + } - s.mod_add(&s_2, &c, gen_order, &mut num_context)?; + fn from_packed(p_raw: &[u8]) -> Result { + let mut reader = BitReader::new(p_raw); + // The signature length is unknown, but everything else is, so we can calculate it + let signature_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE; - let p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap()); + let p_signature = reader.read_u64(signature_length_bits)?; + let p_hash = reader.read_u32(HASH_LENGTH_BITS)?; + let p_serial = reader.read_u32(SERIAL_LENGTH_BITS)?; + let p_upgrade = reader.read_bool()?; - if p_signature <= bitmask(55) { - break pack(ProductKey { - upgrade: p_upgrade, - serial: p_serial, - hash: p_hash, - signature: p_signature, + Ok(Self { + upgrade: p_upgrade, + serial: p_serial, + hash: p_hash, + signature: p_signature, + }) + } + + fn pack(&self) -> Vec { + let mut p_raw: u128 = 0; + + p_raw |= (self.signature as u128) << EVERYTHING_ELSE; + p_raw |= (self.hash as u128) << (SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS); + p_raw |= (self.serial as u128) << UPGRADE_LENGTH_BITS; + p_raw |= self.upgrade as u128; + + p_raw + .to_be_bytes() + .into_iter() + .skip_while(|&x| x == 0) + .collect() + } +} + +impl Display for ProductKey { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let pk = base24_encode(&self.pack()).unwrap(); + let key = pk + .chars() + .enumerate() + .fold(String::new(), |mut acc: String, (i, c)| { + if i > 0 && i % 5 == 0 { + acc.push('-'); + } + acc.push(c); + acc }); - } - }; - - Ok(base24_encode(&p_raw)) -} - -const HASH_LENGTH_BITS: u8 = 28; -const SERIAL_LENGTH_BITS: u8 = 30; -const UPGRADE_LENGTH_BITS: u8 = 1; -const EVERYTHING_ELSE: u8 = HASH_LENGTH_BITS + SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS; - -fn unpack(p_raw: &[u8]) -> Result { - let mut reader = BitReader::new(p_raw); - // The signature length is unknown, but everything else is, so we can calculate it - let signature_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE; - - let p_signature = reader.read_u64(signature_length_bits)?; - let p_hash = reader.read_u32(HASH_LENGTH_BITS)?; - let p_serial = reader.read_u32(SERIAL_LENGTH_BITS)?; - let p_upgrade = reader.read_bool()?; - - Ok(ProductKey { - upgrade: p_upgrade, - serial: p_serial, - hash: p_hash, - signature: p_signature, - }) -} - -fn pack(p_key: ProductKey) -> Vec { - let mut p_raw: u128 = 0; - - p_raw |= (p_key.signature as u128) << EVERYTHING_ELSE; - p_raw |= (p_key.hash as u128) << (SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS); - p_raw |= (p_key.serial as u128) << UPGRADE_LENGTH_BITS; - p_raw |= p_key.upgrade as u128; - - p_raw - .to_be_bytes() - .into_iter() - .skip_while(|&x| x == 0) - .collect() + write!(f, "{}", key) + } } #[cfg(test)] @@ -194,7 +251,7 @@ mod tests { use serde_json::from_reader; - use crate::crypto::initialize_elliptic_curve; + use crate::crypto::EllipticCurve; #[test] fn verify_test() { @@ -218,35 +275,21 @@ mod tests { let kx = bink["pub"]["x"].as_str().unwrap(); let ky = bink["pub"]["y"].as_str().unwrap(); - let (e_curve, gen_point, pub_point) = initialize_elliptic_curve(p, a, b, gx, gy, kx, ky); + let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky).unwrap(); - assert!(super::verify(&e_curve, &gen_point, &pub_point, product_key, true).unwrap()); - assert!(!super::verify( - &e_curve, - &gen_point, - &pub_point, - "11111-R6BG2-39J83-RYKHF-W47TT", - true - ) - .unwrap()); + assert!(super::ProductKey::from_key(&curve, product_key).is_ok()); + assert!(super::ProductKey::from_key(&curve, "11111-R6BG2-39J83-RYKHF-W47TT").is_err()); } #[test] fn pack_test() { - let p_key = super::ProductKey { + let key = super::ProductKey { upgrade: false, serial: 640010550, hash: 39185432, signature: 6939952665262054, }; - let p_raw = super::pack(p_key); - - assert_eq!( - p_raw, - vec![ - 0xC5, 0x3E, 0xCD, 0x2A, 0xF7, 0xBF, 0x31, 0x2A, 0xF6, 0x0C, 0x4C, 0x4B, 0x92, 0x6C - ] - ); + assert_eq!(key.to_string(), "D9924-R6BG2-39J83-RYKHF-W47TT"); } } diff --git a/src/bink2002.rs b/src/bink2002.rs index 1f3f46d..2a1aaad 100644 --- a/src/bink2002.rs +++ b/src/bink2002.rs @@ -1,22 +1,33 @@ -use anyhow::Result; +use std::fmt::{Display, Formatter}; + +use anyhow::{bail, Result}; use bitreader::BitReader; use openssl::{ bn::{BigNum, BigNumContext, MsbOption}, ec::{EcGroup, EcPoint}, + rand::rand_bytes, sha::sha1, }; use crate::{ - crypto::{bitmask, by_dword, next_sn_bits}, - key::{base24_decode, base24_encode}, + crypto::{EllipticCurve, PrivateKey}, + key::{base24_decode, base24_encode, strip_key}, + math::{bitmask, by_dword, next_sn_bits}, }; const FIELD_BITS: i32 = 512; const FIELD_BYTES: usize = 64; const SHA_MSG_LENGTH: usize = 3 + 2 * FIELD_BYTES; -#[derive(Clone, Copy, Debug)] -struct ProductKey { +const SIGNATURE_LENGTH_BITS: u8 = 62; +const HASH_LENGTH_BITS: u8 = 31; +const CHANNEL_ID_LENGTH_BITS: u8 = 10; +const UPGRADE_LENGTH_BITS: u8 = 1; +const EVERYTHING_ELSE: u8 = + SIGNATURE_LENGTH_BITS + HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct ProductKey { upgrade: bool, channel_id: u32, hash: u32, @@ -24,117 +35,231 @@ struct ProductKey { auth_info: u32, } -pub fn verify( - e_curve: &EcGroup, - base_point: &EcPoint, - public_key: &EcPoint, - cd_key: &str, - verbose: bool, -) -> Result { - let mut num_context = BigNumContext::new()?; +impl ProductKey { + pub fn new( + curve: &EllipticCurve, + private_key: &PrivateKey, + channel_id: u32, + sequence: Option, + auth_info: Option, + upgrade: Option, + ) -> Result { + // Generate random sequence if none supplied + let sequence = match sequence { + Some(serial) => serial, + None => { + let mut bn_rand = BigNum::new()?; + bn_rand.rand(19, MsbOption::MAYBE_ZERO, false)?; + let o_raw = u32::from_be_bytes(bn_rand.to_vec_padded(4)?.try_into().unwrap()); + o_raw % 999999 + } + }; - let b_key = base24_decode(cd_key); - let product_key = unpack(&b_key)?; + // Generate random auth info if none supplied + let auth_info = match auth_info { + Some(auth_info) => auth_info, + None => { + let mut p_auth_info_bytes = [0_u8; 4]; + rand_bytes(&mut p_auth_info_bytes)?; + u32::from_ne_bytes(p_auth_info_bytes) & ((1 << 10) - 1) + } + }; - let p_data = product_key.channel_id << 1 | product_key.upgrade as u32; + // Default to upgrade=false + let upgrade = upgrade.unwrap_or(false); - if verbose { - println!("Validation results:"); - println!(" Upgrade: {}", product_key.upgrade); - println!("Channel ID: {}", product_key.channel_id); - println!(" Hash: {}", product_key.hash); - println!(" Signature: {}", product_key.signature); - println!(" AuthInfo: {}", product_key.auth_info); - println!(); + // Generate a new random key + let product_key = Self::generate( + &curve.curve, + &curve.gen_point, + &private_key.gen_order, + &private_key.private_key, + channel_id * 1_000_000 + sequence, + auth_info, + upgrade, + )?; + + // Make sure the key is valid + product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?; + + // Ship it + Ok(product_key) } - let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH]; + pub fn from_key(curve: &EllipticCurve, key: &str) -> Result { + let key = strip_key(key)?; + let Ok(p_raw) = base24_decode(&key) else { + bail!("Product key is in an incorrect format!") + }; + let product_key = Self::from_packed(&p_raw)?; + let verified = product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?; + if !verified { + bail!("Product key is invalid! Wrong BINK ID?"); + } + Ok(product_key) + } - msg_buffer[0x00] = 0x5D; - msg_buffer[0x01] = (p_data & 0x00FF) as u8; - msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; - msg_buffer[0x03] = (product_key.hash & 0x000000FF) as u8; - msg_buffer[0x04] = ((product_key.hash & 0x0000FF00) >> 8) as u8; - msg_buffer[0x05] = ((product_key.hash & 0x00FF0000) >> 16) as u8; - msg_buffer[0x06] = ((product_key.hash & 0xFF000000) >> 24) as u8; - msg_buffer[0x07] = (product_key.auth_info & 0x00FF) as u8; - msg_buffer[0x08] = ((product_key.auth_info & 0xFF00) >> 8) as u8; - msg_buffer[0x09] = 0x00; - msg_buffer[0x0A] = 0x00; + fn generate( + e_curve: &EcGroup, + base_point: &EcPoint, + gen_order: &BigNum, + private_key: &BigNum, + p_channel_id: u32, + p_auth_info: u32, + p_upgrade: bool, + ) -> Result { + let mut num_context = BigNumContext::new().unwrap(); - let msg_digest = sha1(&msg_buffer[..=0x0A]); + let mut c = BigNum::new()?; + let mut x = BigNum::new()?; + let mut y = BigNum::new()?; - let i_signature = next_sn_bits(by_dword(&msg_digest[4..8]) as u64, 30, 2) << 32 - | by_dword(&msg_digest[0..4]) as u64; + let p_data = p_channel_id << 1 | p_upgrade as u32; - let e = BigNum::from_slice(&i_signature.to_be_bytes())?; - let s = BigNum::from_slice(&product_key.signature.to_be_bytes())?; + let mut no_square = false; + let key = loop { + let mut r = EcPoint::new(e_curve)?; - let mut x = BigNum::new()?; - let mut y = BigNum::new()?; + c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?; - let mut p = EcPoint::new(e_curve)?; - let mut t = EcPoint::new(e_curve)?; + r.mul(e_curve, base_point, &c, &num_context)?; - t.mul(e_curve, base_point, &s, &num_context)?; - p.mul(e_curve, public_key, &e, &num_context)?; - let p_2 = p.to_owned(e_curve)?; + r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; - p.add(e_curve, &t, &p_2, &mut num_context)?; - let p_2 = p.to_owned(e_curve)?; + let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH]; - p.mul(e_curve, &p_2, &s, &num_context)?; + let mut x_bin = x.to_vec_padded(FIELD_BYTES as i32)?; + x_bin.reverse(); + let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?; + y_bin.reverse(); - p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; + msg_buffer[0x00] = 0x79; + msg_buffer[0x01] = (p_data & 0x00FF) as u8; + msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; - let mut x_bin = x.to_vec_padded(FIELD_BYTES as i32)?; - x_bin.reverse(); - let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?; - y_bin.reverse(); + msg_buffer[3..3 + FIELD_BYTES].copy_from_slice(&x_bin); + msg_buffer[3 + FIELD_BYTES..3 + FIELD_BYTES * 2].copy_from_slice(&y_bin); - msg_buffer[0x00] = 0x79; - msg_buffer[0x01] = (p_data & 0x00FF) as u8; - msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; + let msg_digest = sha1(&msg_buffer); - msg_buffer[3..3 + FIELD_BYTES].copy_from_slice(&x_bin); - msg_buffer[3 + FIELD_BYTES..3 + FIELD_BYTES * 2].copy_from_slice(&y_bin); + let p_hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32; - let msg_digest = sha1(&msg_buffer); + msg_buffer[0x00] = 0x5D; + msg_buffer[0x01] = (p_data & 0x00FF) as u8; + msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; + msg_buffer[0x03] = (p_hash & 0x000000FF) as u8; + msg_buffer[0x04] = ((p_hash & 0x0000FF00) >> 8) as u8; + msg_buffer[0x05] = ((p_hash & 0x00FF0000) >> 16) as u8; + msg_buffer[0x06] = ((p_hash & 0xFF000000) >> 24) as u8; + msg_buffer[0x07] = (p_auth_info & 0x00FF) as u8; + msg_buffer[0x08] = ((p_auth_info & 0xFF00) >> 8) as u8; + msg_buffer[0x09] = 0x00; + msg_buffer[0x0A] = 0x00; - let hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32; + let msg_digest = sha1(&msg_buffer[..=0x0A]); - Ok(hash == product_key.hash) -} + let i_signature = next_sn_bits(by_dword(&msg_digest[4..8]) as u64, 30, 2) << 32 + | by_dword(&msg_digest[0..4]) as u64; -pub fn generate( - e_curve: &EcGroup, - base_point: &EcPoint, - gen_order: &BigNum, - private_key: &BigNum, - p_channel_id: u32, - p_auth_info: u32, - p_upgrade: bool, -) -> Result { - let mut num_context = BigNumContext::new().unwrap(); + let mut e = BigNum::from_slice(&i_signature.to_be_bytes())?; - let mut c = BigNum::new()?; - let mut x = BigNum::new()?; - let mut y = BigNum::new()?; + let e_2 = e.to_owned()?; + e.mod_mul(&e_2, private_key, gen_order, &mut num_context)?; - let p_data = p_channel_id << 1 | p_upgrade as u32; + let mut s = e.to_owned()?; - let mut no_square = false; - let p_raw: Vec = loop { - let mut r = EcPoint::new(e_curve)?; + let s_2 = s.to_owned()?; + s.mod_sqr(&s_2, gen_order, &mut num_context)?; - c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?; + let c_2 = c.to_owned()?; + c.lshift(&c_2, 2)?; - r.mul(e_curve, base_point, &c, &num_context)?; + s = &s + &c; - r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; + let s_2 = s.to_owned()?; + if s.mod_sqrt(&s_2, gen_order, &mut num_context).is_err() { + no_square = true; + }; + + let s_2 = s.to_owned()?; + s.mod_sub(&s_2, &e, gen_order, &mut num_context)?; + + if s.is_bit_set(0) { + s = &s + gen_order; + } + + let s_2 = s.to_owned()?; + s.rshift1(&s_2)?; + + let p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap()); + + let product_key = Self { + upgrade: p_upgrade, + channel_id: p_channel_id, + hash: p_hash, + signature: p_signature, + auth_info: p_auth_info, + }; + + if p_signature <= bitmask(62) && !no_square { + break product_key; + } + + no_square = false; + }; + + Ok(key) + } + + fn verify( + &self, + e_curve: &EcGroup, + base_point: &EcPoint, + public_key: &EcPoint, + ) -> Result { + let mut num_context = BigNumContext::new()?; + + let p_data = self.channel_id << 1 | self.upgrade as u32; let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH]; + msg_buffer[0x00] = 0x5D; + msg_buffer[0x01] = (p_data & 0x00FF) as u8; + msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; + msg_buffer[0x03] = (self.hash & 0x000000FF) as u8; + msg_buffer[0x04] = ((self.hash & 0x0000FF00) >> 8) as u8; + msg_buffer[0x05] = ((self.hash & 0x00FF0000) >> 16) as u8; + msg_buffer[0x06] = ((self.hash & 0xFF000000) >> 24) as u8; + msg_buffer[0x07] = (self.auth_info & 0x00FF) as u8; + msg_buffer[0x08] = ((self.auth_info & 0xFF00) >> 8) as u8; + msg_buffer[0x09] = 0x00; + msg_buffer[0x0A] = 0x00; + + let msg_digest = sha1(&msg_buffer[..=0x0A]); + + let i_signature = next_sn_bits(by_dword(&msg_digest[4..8]) as u64, 30, 2) << 32 + | by_dword(&msg_digest[0..4]) as u64; + + let e = BigNum::from_slice(&i_signature.to_be_bytes())?; + let s = BigNum::from_slice(&self.signature.to_be_bytes())?; + + let mut x = BigNum::new()?; + let mut y = BigNum::new()?; + + let mut p = EcPoint::new(e_curve)?; + let mut t = EcPoint::new(e_curve)?; + + t.mul(e_curve, base_point, &s, &num_context)?; + p.mul(e_curve, public_key, &e, &num_context)?; + let p_2 = p.to_owned(e_curve)?; + + p.add(e_curve, &t, &p_2, &mut num_context)?; + let p_2 = p.to_owned(e_curve)?; + + p.mul(e_curve, &p_2, &s, &num_context)?; + + p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; + let mut x_bin = x.to_vec_padded(FIELD_BYTES as i32)?; x_bin.reverse(); let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?; @@ -149,130 +274,75 @@ pub fn generate( let msg_digest = sha1(&msg_buffer); - let p_hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32; + let hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32; - msg_buffer[0x00] = 0x5D; - msg_buffer[0x01] = (p_data & 0x00FF) as u8; - msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; - msg_buffer[0x03] = (p_hash & 0x000000FF) as u8; - msg_buffer[0x04] = ((p_hash & 0x0000FF00) >> 8) as u8; - msg_buffer[0x05] = ((p_hash & 0x00FF0000) >> 16) as u8; - msg_buffer[0x06] = ((p_hash & 0xFF000000) >> 24) as u8; - msg_buffer[0x07] = (p_auth_info & 0x00FF) as u8; - msg_buffer[0x08] = ((p_auth_info & 0xFF00) >> 8) as u8; - msg_buffer[0x09] = 0x00; - msg_buffer[0x0A] = 0x00; + Ok(hash == self.hash) + } - let msg_digest = sha1(&msg_buffer[..=0x0A]); + fn from_packed(p_raw: &[u8]) -> Result { + let mut reader = BitReader::new(p_raw); + let auth_info_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE; - let i_signature = next_sn_bits(by_dword(&msg_digest[4..8]) as u64, 30, 2) << 32 - | by_dword(&msg_digest[0..4]) as u64; + let p_auth_info = reader.read_u32(auth_info_length_bits)?; + let p_signature = reader.read_u64(SIGNATURE_LENGTH_BITS)?; + let p_hash = reader.read_u32(HASH_LENGTH_BITS)?; + let p_channel_id = reader.read_u32(CHANNEL_ID_LENGTH_BITS)?; + let p_upgrade = reader.read_bool()?; - let mut e = BigNum::from_slice(&i_signature.to_be_bytes())?; - - let e_2 = e.to_owned()?; - e.mod_mul(&e_2, private_key, gen_order, &mut num_context)?; - - let mut s = e.to_owned()?; - - let s_2 = s.to_owned()?; - s.mod_sqr(&s_2, gen_order, &mut num_context)?; - - let c_2 = c.to_owned()?; - c.lshift(&c_2, 2)?; - - s = &s + &c; - - let s_2 = s.to_owned()?; - if s.mod_sqrt(&s_2, gen_order, &mut num_context).is_err() { - no_square = true; - }; - - let s_2 = s.to_owned()?; - s.mod_sub(&s_2, &e, gen_order, &mut num_context)?; - - if s.is_bit_set(0) { - s = &s + gen_order; - } - - let s_2 = s.to_owned()?; - s.rshift1(&s_2)?; - - let p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap()); - - let product_key = ProductKey { + Ok(Self { upgrade: p_upgrade, channel_id: p_channel_id, hash: p_hash, signature: p_signature, auth_info: p_auth_info, - }; + }) + } - if p_signature <= bitmask(62) && !no_square { - break pack(product_key); - } + fn pack(&self) -> Vec { + let mut p_raw: u128 = 0; - no_square = false; - }; + p_raw |= (self.auth_info as u128) + << (SIGNATURE_LENGTH_BITS + + HASH_LENGTH_BITS + + CHANNEL_ID_LENGTH_BITS + + UPGRADE_LENGTH_BITS); + p_raw |= (self.signature as u128) + << (HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS); + p_raw |= (self.hash as u128) << (CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS); + p_raw |= (self.channel_id as u128) << UPGRADE_LENGTH_BITS; + p_raw |= self.upgrade as u128; - Ok(base24_encode(&p_raw)) + p_raw + .to_be_bytes() + .into_iter() + .skip_while(|&x| x == 0) + .collect() + } } -const SIGNATURE_LENGTH_BITS: u8 = 62; -const HASH_LENGTH_BITS: u8 = 31; -const CHANNEL_ID_LENGTH_BITS: u8 = 10; -const UPGRADE_LENGTH_BITS: u8 = 1; -const EVERYTHING_ELSE: u8 = - SIGNATURE_LENGTH_BITS + HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS; - -fn unpack(p_raw: &[u8]) -> Result { - let mut reader = BitReader::new(p_raw); - let auth_info_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE; - - let p_auth_info = reader.read_u32(auth_info_length_bits)?; - let p_signature = reader.read_u64(SIGNATURE_LENGTH_BITS)?; - let p_hash = reader.read_u32(HASH_LENGTH_BITS)?; - let p_channel_id = reader.read_u32(CHANNEL_ID_LENGTH_BITS)?; - let p_upgrade = reader.read_bool()?; - - Ok(ProductKey { - upgrade: p_upgrade, - channel_id: p_channel_id, - hash: p_hash, - signature: p_signature, - auth_info: p_auth_info, - }) -} - -fn pack(p_key: ProductKey) -> Vec { - let mut p_raw: u128 = 0; - - p_raw |= (p_key.auth_info as u128) - << (SIGNATURE_LENGTH_BITS - + HASH_LENGTH_BITS - + CHANNEL_ID_LENGTH_BITS - + UPGRADE_LENGTH_BITS); - p_raw |= (p_key.signature as u128) - << (HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS); - p_raw |= (p_key.hash as u128) << (CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS); - p_raw |= (p_key.channel_id as u128) << UPGRADE_LENGTH_BITS; - p_raw |= p_key.upgrade as u128; - - p_raw - .to_be_bytes() - .into_iter() - .skip_while(|&x| x == 0) - .collect() +impl Display for ProductKey { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + let pk = base24_encode(&self.pack()).unwrap(); + let key = pk + .chars() + .enumerate() + .fold(String::new(), |mut acc: String, (i, c)| { + if i > 0 && i % 5 == 0 { + acc.push('-'); + } + acc.push(c); + acc + }); + write!(f, "{}", key) + } } #[cfg(test)] mod tests { + use serde_json::from_reader; use std::{fs::File, io::BufReader}; - use openssl::bn::{BigNum, BigNumContext}; - use serde_json::from_reader; - - use crate::crypto::initialize_elliptic_curve; + use crate::crypto::EllipticCurve; #[test] fn verify_test() { @@ -296,27 +366,9 @@ mod tests { let kx = bink["pub"]["x"].as_str().unwrap(); let ky = bink["pub"]["y"].as_str().unwrap(); - let (e_curve, gen_point, pub_point) = initialize_elliptic_curve(p, a, b, gx, gy, kx, ky); + let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky).unwrap(); - assert!(super::verify(&e_curve, &gen_point, &pub_point, product_key, true).unwrap()); - } - - #[test] - fn prime_test() { - let mut ctx = BigNumContext::new().unwrap(); - let p = BigNum::from_dec_str("9759712359818460653").unwrap(); - let mut p2 = BigNum::new().unwrap(); - let _ = p2.sqr(&p, &mut ctx); - println!("p2: {:?}", p2); - } - - #[test] - fn sqrt_test() { - let mut ctx = BigNumContext::new().unwrap(); - let s = BigNum::from_dec_str("95251985346393225982548498694509186409").unwrap(); - let p = BigNum::from_dec_str("9362780380393422053").unwrap(); - let mut out = BigNum::new().unwrap(); - out.mod_sqrt(&s, &p, &mut ctx).unwrap(); - assert_eq!(out, BigNum::from_dec_str("8965848400968383453").unwrap()); + assert!(super::ProductKey::from_key(&curve, product_key).is_ok()); + assert!(super::ProductKey::from_key(&curve, "11111-YRGC8-4KYTG-C3FCC-JCFDY").is_err()); } } diff --git a/src/crypto.rs b/src/crypto.rs index 530824b..831971a 100644 --- a/src/crypto.rs +++ b/src/crypto.rs @@ -1,49 +1,63 @@ +use anyhow::Result; use openssl::{ bn::{BigNum, BigNumContext}, ec::{EcGroup, EcPoint}, }; -pub fn initialize_elliptic_curve( - p_sel: &str, - a_sel: &str, - b_sel: &str, - generator_x_sel: &str, - generator_y_sel: &str, - public_key_x_sel: &str, - public_key_y_sel: &str, -) -> (EcGroup, EcPoint, EcPoint) { - let mut context = BigNumContext::new().unwrap(); - - let p = BigNum::from_dec_str(p_sel).unwrap(); - let a = BigNum::from_dec_str(a_sel).unwrap(); - let b = BigNum::from_dec_str(b_sel).unwrap(); - let generator_x = BigNum::from_dec_str(generator_x_sel).unwrap(); - let generator_y = BigNum::from_dec_str(generator_y_sel).unwrap(); - - let public_key_x = BigNum::from_dec_str(public_key_x_sel).unwrap(); - let public_key_y = BigNum::from_dec_str(public_key_y_sel).unwrap(); - - let c_curve = EcGroup::from_components(p, a, b, &mut context).unwrap(); - - let mut gen_point = EcPoint::new(&c_curve).unwrap(); - let _ = - gen_point.set_affine_coordinates_gfp(&c_curve, &generator_x, &generator_y, &mut context); - - let mut pub_point = EcPoint::new(&c_curve).unwrap(); - let _ = - pub_point.set_affine_coordinates_gfp(&c_curve, &public_key_x, &public_key_y, &mut context); - - (c_curve, gen_point, pub_point) +pub struct EllipticCurve { + pub curve: EcGroup, + pub gen_point: EcPoint, + pub pub_point: EcPoint, } -pub fn bitmask(n: u64) -> u64 { - (1 << n) - 1 +pub struct PrivateKey { + pub gen_order: BigNum, + pub private_key: BigNum, } -pub fn next_sn_bits(field: u64, n: u32, offset: u32) -> u64 { - (field >> offset) & ((1u64 << n) - 1) +impl PrivateKey { + pub fn new(gen_order: &str, private_key: &str) -> Result { + let gen_order = BigNum::from_dec_str(gen_order)?; + let private_key = &gen_order - &BigNum::from_dec_str(private_key)?; + Ok(Self { + gen_order, + private_key, + }) + } } -pub fn by_dword(n: &[u8]) -> u32 { - (n[0] as u32) | (n[1] as u32) << 8 | (n[2] as u32) << 16 | (n[3] as u32) << 24 +impl EllipticCurve { + pub fn new( + p: &str, + a: &str, + b: &str, + generator_x: &str, + generator_y: &str, + public_key_x: &str, + public_key_y: &str, + ) -> Result { + let mut context = BigNumContext::new()?; + + let p = BigNum::from_dec_str(p)?; + let a = BigNum::from_dec_str(a)?; + let b = BigNum::from_dec_str(b)?; + let generator_x = BigNum::from_dec_str(generator_x)?; + let generator_y = BigNum::from_dec_str(generator_y)?; + let public_key_x = BigNum::from_dec_str(public_key_x)?; + let public_key_y = BigNum::from_dec_str(public_key_y)?; + + let curve = EcGroup::from_components(p, a, b, &mut context)?; + + let mut gen_point = EcPoint::new(&curve)?; + gen_point.set_affine_coordinates_gfp(&curve, &generator_x, &generator_y, &mut context)?; + + let mut pub_point = EcPoint::new(&curve)?; + pub_point.set_affine_coordinates_gfp(&curve, &public_key_x, &public_key_y, &mut context)?; + + Ok(Self { + curve, + gen_point, + pub_point, + }) + } } diff --git a/src/key.rs b/src/key.rs index 8e0f678..838c308 100644 --- a/src/key.rs +++ b/src/key.rs @@ -1,5 +1,6 @@ use std::collections::VecDeque; +use anyhow::{anyhow, Result}; use openssl::bn::BigNum; use crate::PK_LENGTH; @@ -10,7 +11,7 @@ pub const P_KEY_CHARSET: [char; 24] = [ '4', '6', '7', '8', '9', ]; -pub fn base24_decode(cd_key: &str) -> Vec { +pub(crate) fn base24_decode(cd_key: &str) -> Result> { let p_decoded_key: Vec = cd_key .chars() .filter_map(|c| P_KEY_CHARSET.iter().position(|&x| x == c).map(|i| i as u8)) @@ -23,14 +24,33 @@ pub fn base24_decode(cd_key: &str) -> Vec { y.add_word(i.into()).unwrap(); } - y.to_vec() + Ok(y.to_vec()) } -pub fn base24_encode(byte_seq: &[u8]) -> String { +pub(crate) fn base24_encode(byte_seq: &[u8]) -> Result { let mut z = BigNum::from_slice(byte_seq).unwrap(); let mut out: VecDeque = VecDeque::new(); (0..=24).for_each(|_| out.push_front(P_KEY_CHARSET[z.div_word(24).unwrap() as usize])); - out.iter().collect() + Ok(out.iter().collect()) +} + +pub(crate) fn strip_key(in_key: &str) -> Result { + let out_key: String = in_key + .chars() + .filter_map(|c| { + let c = c.to_ascii_uppercase(); + if P_KEY_CHARSET.into_iter().any(|x| x == c) { + Some(c) + } else { + None + } + }) + .collect(); + if out_key.len() == PK_LENGTH { + Ok(out_key) + } else { + Err(anyhow!("Invalid key length")) + } } #[cfg(test)] @@ -38,9 +58,9 @@ mod tests { #[test] fn test_base24() { let input = "JTW3TJ7PFJ7V9CCMX84V9PFT8"; - let unbase24 = super::base24_decode(input); + let unbase24 = super::base24_decode(input).unwrap(); println!("{:?}", unbase24); - let base24 = super::base24_encode(&unbase24); + let base24 = super::base24_encode(&unbase24).unwrap(); println!("{}", base24); assert_eq!(input, base24); } diff --git a/src/lib.rs b/src/lib.rs index ecf24a8..a9d9f1b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -2,6 +2,7 @@ pub mod bink1998; pub mod bink2002; pub mod confid; pub mod crypto; -pub mod key; +mod key; +mod math; -pub const PK_LENGTH: usize = 25; +const PK_LENGTH: usize = 25; diff --git a/src/math.rs b/src/math.rs new file mode 100644 index 0000000..9573f87 --- /dev/null +++ b/src/math.rs @@ -0,0 +1,11 @@ +pub(crate) fn bitmask(n: u64) -> u64 { + (1 << n) - 1 +} + +pub(crate) fn next_sn_bits(field: u64, n: u32, offset: u32) -> u64 { + (field >> offset) & ((1u64 << n) - 1) +} + +pub(crate) fn by_dword(n: &[u8]) -> u32 { + (n[0] as u32) | (n[1] as u32) << 8 | (n[2] as u32) << 16 | (n[3] as u32) << 24 +} From d00fbb98822781497c86da88b8be378f14cbb97f Mon Sep 17 00:00:00 2001 From: Alex Page Date: Fri, 23 Jun 2023 16:59:02 -0400 Subject: [PATCH 03/10] Add upfront length checks to confid --- src/confid/mod.rs | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/src/confid/mod.rs b/src/confid/mod.rs index 397a938..63dc290 100644 --- a/src/confid/mod.rs +++ b/src/confid/mod.rs @@ -21,6 +21,12 @@ pub enum ConfirmationIdError { } pub fn generate(installation_id: &str) -> Result { + if installation_id.len() < 54 { + return Err(ConfirmationIdError::TooShort); + } + if installation_id.len() > 54 { + return Err(ConfirmationIdError::TooLarge); + } let inst_id = CString::new(installation_id).unwrap(); let conf_id = [0u8; 49]; let result = unsafe { black_box::generate(inst_id.as_ptr(), conf_id.as_ptr() as *mut i8) }; From 7bd191e6beacc27b7cbdbfdb438e0644c38d2c21 Mon Sep 17 00:00:00 2001 From: Alex Page Date: Fri, 23 Jun 2023 17:04:34 -0400 Subject: [PATCH 04/10] Add tests to confid --- src/confid/mod.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/src/confid/mod.rs b/src/confid/mod.rs index 63dc290..077c2f5 100644 --- a/src/confid/mod.rs +++ b/src/confid/mod.rs @@ -4,7 +4,7 @@ use thiserror::Error; mod black_box; -#[derive(Error, Debug)] +#[derive(Error, Debug, PartialEq, Eq)] pub enum ConfirmationIdError { #[error("Installation ID is too short.")] TooShort, @@ -47,3 +47,32 @@ pub fn generate(installation_id: &str) -> Result { .to_string()) } } + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_generate() { + assert_eq!( + generate("334481558826870862843844566221823392794862457401103810").unwrap(), + "110281-200130-887120-647974-697175-027544-252733" + ); + assert!( + generate("33448155882687086284384456622182339279486245740110381") + .is_err_and(|err| err == ConfirmationIdError::TooShort), + ); + assert!( + generate("3344815588268708628438445662218233927948624574011038100") + .is_err_and(|err| err == ConfirmationIdError::TooLarge), + ); + assert!( + generate("33448155882687086284384456622182339279486245740110381!") + .is_err_and(|err| err == ConfirmationIdError::InvalidCharacter), + ); + assert!( + generate("334481558826870862843844566221823392794862457401103811") + .is_err_and(|err| err == ConfirmationIdError::InvalidCheckDigit), + ); + } +} From b73401cefb19fa5a91b10bcf1a630754e1a86247 Mon Sep 17 00:00:00 2001 From: Alex Page Date: Fri, 23 Jun 2023 20:29:13 -0400 Subject: [PATCH 05/10] Cleanup --- src/bink1998.rs | 52 +++++++++++++++++++++++++------------------------ src/bink2002.rs | 27 ++++++++++++------------- src/key.rs | 2 +- src/lib.rs | 2 -- 4 files changed, 42 insertions(+), 41 deletions(-) diff --git a/src/bink1998.rs b/src/bink1998.rs index 981315a..94cc4c9 100644 --- a/src/bink1998.rs +++ b/src/bink1998.rs @@ -92,10 +92,11 @@ impl ProductKey { let mut c = BigNum::new()?; let mut s = BigNum::new()?; - let mut s_2 = BigNum::new()?; let mut x = BigNum::new()?; let mut y = BigNum::new()?; + let mut ek: BigNum; + let p_data = p_serial << 1 | p_upgrade as u32; let product_key = loop { @@ -128,10 +129,10 @@ impl ProductKey { let p_hash: u32 = u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32; - s_2.copy_from_slice(&private_key.to_vec())?; - s_2.mul_word(p_hash)?; + ek = (*private_key).to_owned()?; + ek.mul_word(p_hash)?; - s.mod_add(&s_2, &c, gen_order, &mut num_context)?; + s.mod_add(&ek, &c, gen_order, &mut num_context)?; let p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap()); @@ -154,9 +155,7 @@ impl ProductKey { base_point: &EcPoint, public_key: &EcPoint, ) -> Result { - let mut num_context = BigNumContext::new()?; - - let p_data = self.serial << 1 | self.upgrade as u32; + let mut ctx = BigNumContext::new()?; let e = BigNum::from_u32(self.hash)?; let s = BigNum::from_slice(&self.signature.to_be_bytes())?; @@ -165,15 +164,16 @@ impl ProductKey { let mut t = EcPoint::new(e_curve)?; let mut p = EcPoint::new(e_curve)?; - let mut p_2 = EcPoint::new(e_curve)?; - t.mul(e_curve, base_point, &s, &num_context)?; - p.mul(e_curve, public_key, &e, &num_context)?; - p_2.mul(e_curve, public_key, &e, &num_context)?; + t.mul(e_curve, base_point, &s, &ctx)?; + p.mul(e_curve, public_key, &e, &ctx)?; - p.add(e_curve, &t, &p_2, &mut num_context)?; + { + let p_copy = p.to_owned(e_curve)?; + p.add(e_curve, &t, &p_copy, &mut ctx)?; + } - p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; + p.affine_coordinates(e_curve, &mut x, &mut y, &mut ctx)?; let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH]; @@ -182,6 +182,8 @@ impl ProductKey { let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?; y_bin.reverse(); + let p_data = self.serial << 1 | self.upgrade as u32; + msg_buffer[0..4].copy_from_slice(&p_data.to_le_bytes()); msg_buffer[4..4 + FIELD_BYTES].copy_from_slice(&x_bin); msg_buffer[4 + FIELD_BYTES..4 + FIELD_BYTES * 2].copy_from_slice(&y_bin); @@ -194,21 +196,21 @@ impl ProductKey { Ok(hash == self.hash) } - fn from_packed(p_raw: &[u8]) -> Result { - let mut reader = BitReader::new(p_raw); - // The signature length is unknown, but everything else is, so we can calculate it - let signature_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE; + fn from_packed(packed_key: &[u8]) -> Result { + let mut reader = BitReader::new(packed_key); + // The signature length isn't known, but everything else is, so we can calculate it + let signature_length_bits = (packed_key.len() * 8) as u8 - EVERYTHING_ELSE; - let p_signature = reader.read_u64(signature_length_bits)?; - let p_hash = reader.read_u32(HASH_LENGTH_BITS)?; - let p_serial = reader.read_u32(SERIAL_LENGTH_BITS)?; - let p_upgrade = reader.read_bool()?; + let signature = reader.read_u64(signature_length_bits)?; + let hash = reader.read_u32(HASH_LENGTH_BITS)?; + let serial = reader.read_u32(SERIAL_LENGTH_BITS)?; + let upgrade = reader.read_bool()?; Ok(Self { - upgrade: p_upgrade, - serial: p_serial, - hash: p_hash, - signature: p_signature, + upgrade, + serial, + hash, + signature, }) } diff --git a/src/bink2002.rs b/src/bink2002.rs index 2a1aaad..b822542 100644 --- a/src/bink2002.rs +++ b/src/bink2002.rs @@ -279,22 +279,23 @@ impl ProductKey { Ok(hash == self.hash) } - fn from_packed(p_raw: &[u8]) -> Result { - let mut reader = BitReader::new(p_raw); - let auth_info_length_bits = (p_raw.len() * 8) as u8 - EVERYTHING_ELSE; + fn from_packed(packed_key: &[u8]) -> Result { + let mut reader = BitReader::new(packed_key); + // The auth info length isn't known, but everything else is, so we can calculate it + let auth_info_length_bits = (packed_key.len() * 8) as u8 - EVERYTHING_ELSE; - let p_auth_info = reader.read_u32(auth_info_length_bits)?; - let p_signature = reader.read_u64(SIGNATURE_LENGTH_BITS)?; - let p_hash = reader.read_u32(HASH_LENGTH_BITS)?; - let p_channel_id = reader.read_u32(CHANNEL_ID_LENGTH_BITS)?; - let p_upgrade = reader.read_bool()?; + let auth_info = reader.read_u32(auth_info_length_bits)?; + let signature = reader.read_u64(SIGNATURE_LENGTH_BITS)?; + let hash = reader.read_u32(HASH_LENGTH_BITS)?; + let channel_id = reader.read_u32(CHANNEL_ID_LENGTH_BITS)?; + let upgrade = reader.read_bool()?; Ok(Self { - upgrade: p_upgrade, - channel_id: p_channel_id, - hash: p_hash, - signature: p_signature, - auth_info: p_auth_info, + upgrade, + channel_id, + hash, + signature, + auth_info, }) } diff --git a/src/key.rs b/src/key.rs index 838c308..d470090 100644 --- a/src/key.rs +++ b/src/key.rs @@ -3,7 +3,7 @@ use std::collections::VecDeque; use anyhow::{anyhow, Result}; use openssl::bn::BigNum; -use crate::PK_LENGTH; +const PK_LENGTH: usize = 25; /// The allowed character set in a product key. pub const P_KEY_CHARSET: [char; 24] = [ diff --git a/src/lib.rs b/src/lib.rs index a9d9f1b..2910152 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,5 +4,3 @@ pub mod confid; pub mod crypto; mod key; mod math; - -const PK_LENGTH: usize = 25; From 49ce9a47f3c8fca6e049a4848dcd79f0d20a4aca Mon Sep 17 00:00:00 2001 From: Alex Page Date: Fri, 23 Jun 2023 20:36:45 -0400 Subject: [PATCH 06/10] Use correct channel_id for bink2002 --- src/bin/xpkey/cli.rs | 1 - src/bink1998.rs | 44 +++++++++--------- src/bink2002.rs | 104 ++++++++++++++++++++----------------------- src/key.rs | 12 ++--- 4 files changed, 76 insertions(+), 85 deletions(-) diff --git a/src/bin/xpkey/cli.rs b/src/bin/xpkey/cli.rs index 5046fbd..86dfa98 100644 --- a/src/bin/xpkey/cli.rs +++ b/src/bin/xpkey/cli.rs @@ -241,7 +241,6 @@ impl Cli { self.options.channel_id, None, None, - None, )?; println!("{product_key}"); } diff --git a/src/bink1998.rs b/src/bink1998.rs index 94cc4c9..2527c97 100644 --- a/src/bink1998.rs +++ b/src/bink1998.rs @@ -72,10 +72,10 @@ impl ProductKey { pub fn from_key(curve: &EllipticCurve, key: &str) -> Result { let key = strip_key(key)?; - let Ok(p_raw) = base24_decode(&key) else { + let Ok(packed_key) = base24_decode(&key) else { bail!("Product key is in an incorrect format!") }; - let product_key = Self::from_packed(&p_raw)?; + let product_key = Self::from_packed(&packed_key)?; product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?; Ok(product_key) } @@ -85,8 +85,8 @@ impl ProductKey { base_point: &EcPoint, gen_order: &BigNum, private_key: &BigNum, - p_serial: u32, - p_upgrade: bool, + serial: u32, + upgrade: bool, ) -> Result { let mut num_context = BigNumContext::new().unwrap(); @@ -97,7 +97,7 @@ impl ProductKey { let mut ek: BigNum; - let p_data = p_serial << 1 | p_upgrade as u32; + let data = serial << 1 | upgrade as u32; let product_key = loop { let mut r = EcPoint::new(e_curve)?; @@ -120,28 +120,28 @@ impl ProductKey { let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?; y_bin.reverse(); - msg_buffer[0..4].copy_from_slice(&p_data.to_le_bytes()); + msg_buffer[0..4].copy_from_slice(&data.to_le_bytes()); msg_buffer[4..4 + FIELD_BYTES].copy_from_slice(&x_bin); msg_buffer[4 + FIELD_BYTES..4 + FIELD_BYTES * 2].copy_from_slice(&y_bin); let msg_digest = sha1(&msg_buffer); - let p_hash: u32 = + let hash: u32 = u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32; ek = (*private_key).to_owned()?; - ek.mul_word(p_hash)?; + ek.mul_word(hash)?; s.mod_add(&ek, &c, gen_order, &mut num_context)?; - let p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap()); + let signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap()); - if p_signature <= bitmask(55) { + if signature <= bitmask(55) { break Self { - upgrade: p_upgrade, - serial: p_serial, - hash: p_hash, - signature: p_signature, + upgrade, + serial, + hash, + signature, }; } }; @@ -182,9 +182,9 @@ impl ProductKey { let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?; y_bin.reverse(); - let p_data = self.serial << 1 | self.upgrade as u32; + let data = self.serial << 1 | self.upgrade as u32; - msg_buffer[0..4].copy_from_slice(&p_data.to_le_bytes()); + msg_buffer[0..4].copy_from_slice(&data.to_le_bytes()); msg_buffer[4..4 + FIELD_BYTES].copy_from_slice(&x_bin); msg_buffer[4 + FIELD_BYTES..4 + FIELD_BYTES * 2].copy_from_slice(&y_bin); @@ -215,14 +215,14 @@ impl ProductKey { } fn pack(&self) -> Vec { - let mut p_raw: u128 = 0; + let mut packed_key: u128 = 0; - p_raw |= (self.signature as u128) << EVERYTHING_ELSE; - p_raw |= (self.hash as u128) << (SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS); - p_raw |= (self.serial as u128) << UPGRADE_LENGTH_BITS; - p_raw |= self.upgrade as u128; + packed_key |= (self.signature as u128) << EVERYTHING_ELSE; + packed_key |= (self.hash as u128) << (SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS); + packed_key |= (self.serial as u128) << UPGRADE_LENGTH_BITS; + packed_key |= self.upgrade as u128; - p_raw + packed_key .to_be_bytes() .into_iter() .skip_while(|&x| x == 0) diff --git a/src/bink2002.rs b/src/bink2002.rs index b822542..173e763 100644 --- a/src/bink2002.rs +++ b/src/bink2002.rs @@ -40,28 +40,16 @@ impl ProductKey { curve: &EllipticCurve, private_key: &PrivateKey, channel_id: u32, - sequence: Option, auth_info: Option, upgrade: Option, ) -> Result { - // Generate random sequence if none supplied - let sequence = match sequence { - Some(serial) => serial, - None => { - let mut bn_rand = BigNum::new()?; - bn_rand.rand(19, MsbOption::MAYBE_ZERO, false)?; - let o_raw = u32::from_be_bytes(bn_rand.to_vec_padded(4)?.try_into().unwrap()); - o_raw % 999999 - } - }; - // Generate random auth info if none supplied let auth_info = match auth_info { Some(auth_info) => auth_info, None => { - let mut p_auth_info_bytes = [0_u8; 4]; - rand_bytes(&mut p_auth_info_bytes)?; - u32::from_ne_bytes(p_auth_info_bytes) & ((1 << 10) - 1) + let mut auth_info_bytes = [0_u8; 4]; + rand_bytes(&mut auth_info_bytes)?; + u32::from_ne_bytes(auth_info_bytes) & ((1 << 10) - 1) } }; @@ -74,7 +62,7 @@ impl ProductKey { &curve.gen_point, &private_key.gen_order, &private_key.private_key, - channel_id * 1_000_000 + sequence, + channel_id, auth_info, upgrade, )?; @@ -88,10 +76,10 @@ impl ProductKey { pub fn from_key(curve: &EllipticCurve, key: &str) -> Result { let key = strip_key(key)?; - let Ok(p_raw) = base24_decode(&key) else { + let Ok(packed_key) = base24_decode(&key) else { bail!("Product key is in an incorrect format!") }; - let product_key = Self::from_packed(&p_raw)?; + let product_key = Self::from_packed(&packed_key)?; let verified = product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?; if !verified { bail!("Product key is invalid! Wrong BINK ID?"); @@ -104,9 +92,9 @@ impl ProductKey { base_point: &EcPoint, gen_order: &BigNum, private_key: &BigNum, - p_channel_id: u32, - p_auth_info: u32, - p_upgrade: bool, + channel_id: u32, + auth_info: u32, + upgrade: bool, ) -> Result { let mut num_context = BigNumContext::new().unwrap(); @@ -114,7 +102,7 @@ impl ProductKey { let mut x = BigNum::new()?; let mut y = BigNum::new()?; - let p_data = p_channel_id << 1 | p_upgrade as u32; + let data = channel_id << 1 | upgrade as u32; let mut no_square = false; let key = loop { @@ -134,25 +122,25 @@ impl ProductKey { y_bin.reverse(); msg_buffer[0x00] = 0x79; - msg_buffer[0x01] = (p_data & 0x00FF) as u8; - msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; + msg_buffer[0x01] = (data & 0x00FF) as u8; + msg_buffer[0x02] = ((data & 0xFF00) >> 8) as u8; msg_buffer[3..3 + FIELD_BYTES].copy_from_slice(&x_bin); msg_buffer[3 + FIELD_BYTES..3 + FIELD_BYTES * 2].copy_from_slice(&y_bin); let msg_digest = sha1(&msg_buffer); - let p_hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32; + let hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32; msg_buffer[0x00] = 0x5D; - msg_buffer[0x01] = (p_data & 0x00FF) as u8; - msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; - msg_buffer[0x03] = (p_hash & 0x000000FF) as u8; - msg_buffer[0x04] = ((p_hash & 0x0000FF00) >> 8) as u8; - msg_buffer[0x05] = ((p_hash & 0x00FF0000) >> 16) as u8; - msg_buffer[0x06] = ((p_hash & 0xFF000000) >> 24) as u8; - msg_buffer[0x07] = (p_auth_info & 0x00FF) as u8; - msg_buffer[0x08] = ((p_auth_info & 0xFF00) >> 8) as u8; + msg_buffer[0x01] = (data & 0x00FF) as u8; + msg_buffer[0x02] = ((data & 0xFF00) >> 8) as u8; + msg_buffer[0x03] = (hash & 0x000000FF) as u8; + msg_buffer[0x04] = ((hash & 0x0000FF00) >> 8) as u8; + msg_buffer[0x05] = ((hash & 0x00FF0000) >> 16) as u8; + msg_buffer[0x06] = ((hash & 0xFF000000) >> 24) as u8; + msg_buffer[0x07] = (auth_info & 0x00FF) as u8; + msg_buffer[0x08] = ((auth_info & 0xFF00) >> 8) as u8; msg_buffer[0x09] = 0x00; msg_buffer[0x0A] = 0x00; @@ -191,17 +179,17 @@ impl ProductKey { let s_2 = s.to_owned()?; s.rshift1(&s_2)?; - let p_signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap()); + let signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap()); let product_key = Self { - upgrade: p_upgrade, - channel_id: p_channel_id, - hash: p_hash, - signature: p_signature, - auth_info: p_auth_info, + upgrade, + channel_id, + hash, + signature, + auth_info, }; - if p_signature <= bitmask(62) && !no_square { + if signature <= bitmask(62) && !no_square { break product_key; } @@ -219,13 +207,13 @@ impl ProductKey { ) -> Result { let mut num_context = BigNumContext::new()?; - let p_data = self.channel_id << 1 | self.upgrade as u32; + let data = self.channel_id << 1 | self.upgrade as u32; let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH]; msg_buffer[0x00] = 0x5D; - msg_buffer[0x01] = (p_data & 0x00FF) as u8; - msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; + msg_buffer[0x01] = (data & 0x00FF) as u8; + msg_buffer[0x02] = ((data & 0xFF00) >> 8) as u8; msg_buffer[0x03] = (self.hash & 0x000000FF) as u8; msg_buffer[0x04] = ((self.hash & 0x0000FF00) >> 8) as u8; msg_buffer[0x05] = ((self.hash & 0x00FF0000) >> 16) as u8; @@ -251,12 +239,16 @@ impl ProductKey { t.mul(e_curve, base_point, &s, &num_context)?; p.mul(e_curve, public_key, &e, &num_context)?; - let p_2 = p.to_owned(e_curve)?; - p.add(e_curve, &t, &p_2, &mut num_context)?; - let p_2 = p.to_owned(e_curve)?; + { + let p_2 = p.to_owned(e_curve)?; + p.add(e_curve, &t, &p_2, &mut num_context)?; + } - p.mul(e_curve, &p_2, &s, &num_context)?; + { + let p_2 = p.to_owned(e_curve)?; + p.mul(e_curve, &p_2, &s, &num_context)?; + } p.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?; @@ -266,8 +258,8 @@ impl ProductKey { y_bin.reverse(); msg_buffer[0x00] = 0x79; - msg_buffer[0x01] = (p_data & 0x00FF) as u8; - msg_buffer[0x02] = ((p_data & 0xFF00) >> 8) as u8; + msg_buffer[0x01] = (data & 0x00FF) as u8; + msg_buffer[0x02] = ((data & 0xFF00) >> 8) as u8; msg_buffer[3..3 + FIELD_BYTES].copy_from_slice(&x_bin); msg_buffer[3 + FIELD_BYTES..3 + FIELD_BYTES * 2].copy_from_slice(&y_bin); @@ -300,20 +292,20 @@ impl ProductKey { } fn pack(&self) -> Vec { - let mut p_raw: u128 = 0; + let mut packed_key: u128 = 0; - p_raw |= (self.auth_info as u128) + packed_key |= (self.auth_info as u128) << (SIGNATURE_LENGTH_BITS + HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS); - p_raw |= (self.signature as u128) + packed_key |= (self.signature as u128) << (HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS); - p_raw |= (self.hash as u128) << (CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS); - p_raw |= (self.channel_id as u128) << UPGRADE_LENGTH_BITS; - p_raw |= self.upgrade as u128; + packed_key |= (self.hash as u128) << (CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS); + packed_key |= (self.channel_id as u128) << UPGRADE_LENGTH_BITS; + packed_key |= self.upgrade as u128; - p_raw + packed_key .to_be_bytes() .into_iter() .skip_while(|&x| x == 0) diff --git a/src/key.rs b/src/key.rs index d470090..978ade9 100644 --- a/src/key.rs +++ b/src/key.rs @@ -6,20 +6,20 @@ use openssl::bn::BigNum; const PK_LENGTH: usize = 25; /// The allowed character set in a product key. -pub const P_KEY_CHARSET: [char; 24] = [ +pub const KEY_CHARSET: [char; 24] = [ 'B', 'C', 'D', 'F', 'G', 'H', 'J', 'K', 'M', 'P', 'Q', 'R', 'T', 'V', 'W', 'X', 'Y', '2', '3', '4', '6', '7', '8', '9', ]; pub(crate) fn base24_decode(cd_key: &str) -> Result> { - let p_decoded_key: Vec = cd_key + let decoded_key: Vec = cd_key .chars() - .filter_map(|c| P_KEY_CHARSET.iter().position(|&x| x == c).map(|i| i as u8)) + .filter_map(|c| KEY_CHARSET.iter().position(|&x| x == c).map(|i| i as u8)) .collect(); let mut y = BigNum::from_u32(0).unwrap(); - for i in p_decoded_key { + for i in decoded_key { y.mul_word((PK_LENGTH - 1) as u32).unwrap(); y.add_word(i.into()).unwrap(); } @@ -30,7 +30,7 @@ pub(crate) fn base24_decode(cd_key: &str) -> Result> { pub(crate) fn base24_encode(byte_seq: &[u8]) -> Result { let mut z = BigNum::from_slice(byte_seq).unwrap(); let mut out: VecDeque = VecDeque::new(); - (0..=24).for_each(|_| out.push_front(P_KEY_CHARSET[z.div_word(24).unwrap() as usize])); + (0..=24).for_each(|_| out.push_front(KEY_CHARSET[z.div_word(24).unwrap() as usize])); Ok(out.iter().collect()) } @@ -39,7 +39,7 @@ pub(crate) fn strip_key(in_key: &str) -> Result { .chars() .filter_map(|c| { let c = c.to_ascii_uppercase(); - if P_KEY_CHARSET.into_iter().any(|x| x == c) { + if KEY_CHARSET.into_iter().any(|x| x == c) { Some(c) } else { None From c380be1eaee76e9bc4e4b88949be8beb42d96beb Mon Sep 17 00:00:00 2001 From: Alex Page Date: Fri, 23 Jun 2023 20:44:46 -0400 Subject: [PATCH 07/10] Separate channel_id and sequence in bink1998 --- src/bink1998.rs | 29 +++++++++++++++++++++-------- 1 file changed, 21 insertions(+), 8 deletions(-) diff --git a/src/bink1998.rs b/src/bink1998.rs index 2527c97..d4dc575 100644 --- a/src/bink1998.rs +++ b/src/bink1998.rs @@ -26,7 +26,8 @@ const EVERYTHING_ELSE: u8 = HASH_LENGTH_BITS + SERIAL_LENGTH_BITS + UPGRADE_LENG #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct ProductKey { upgrade: bool, - serial: u32, + channel_id: u32, + sequence: u32, hash: u32, signature: u64, } @@ -59,7 +60,8 @@ impl ProductKey { &curve.gen_point, &private_key.gen_order, &private_key.private_key, - channel_id * 1_000_000 + sequence, + channel_id, + sequence, upgrade, )?; @@ -85,7 +87,8 @@ impl ProductKey { base_point: &EcPoint, gen_order: &BigNum, private_key: &BigNum, - serial: u32, + channel_id: u32, + sequence: u32, upgrade: bool, ) -> Result { let mut num_context = BigNumContext::new().unwrap(); @@ -97,6 +100,7 @@ impl ProductKey { let mut ek: BigNum; + let serial = channel_id * 1_000_000 + sequence; let data = serial << 1 | upgrade as u32; let product_key = loop { @@ -139,7 +143,8 @@ impl ProductKey { if signature <= bitmask(55) { break Self { upgrade, - serial, + channel_id, + sequence, hash, signature, }; @@ -182,7 +187,8 @@ impl ProductKey { let mut y_bin = y.to_vec_padded(FIELD_BYTES as i32)?; y_bin.reverse(); - let data = self.serial << 1 | self.upgrade as u32; + let serial = self.channel_id * 1_000_000 + self.sequence; + let data = serial << 1 | self.upgrade as u32; msg_buffer[0..4].copy_from_slice(&data.to_le_bytes()); msg_buffer[4..4 + FIELD_BYTES].copy_from_slice(&x_bin); @@ -206,9 +212,13 @@ impl ProductKey { let serial = reader.read_u32(SERIAL_LENGTH_BITS)?; let upgrade = reader.read_bool()?; + let sequence = serial % 1_000_000; + let channel_id = serial / 1_000_000; + Ok(Self { upgrade, - serial, + channel_id, + sequence, hash, signature, }) @@ -217,9 +227,11 @@ impl ProductKey { fn pack(&self) -> Vec { let mut packed_key: u128 = 0; + let serial = self.channel_id * 1_000_000 + self.sequence; + packed_key |= (self.signature as u128) << EVERYTHING_ELSE; packed_key |= (self.hash as u128) << (SERIAL_LENGTH_BITS + UPGRADE_LENGTH_BITS); - packed_key |= (self.serial as u128) << UPGRADE_LENGTH_BITS; + packed_key |= (serial as u128) << UPGRADE_LENGTH_BITS; packed_key |= self.upgrade as u128; packed_key @@ -287,7 +299,8 @@ mod tests { fn pack_test() { let key = super::ProductKey { upgrade: false, - serial: 640010550, + channel_id: 640, + sequence: 10550, hash: 39185432, signature: 6939952665262054, }; From 72d4db7af6c33098fb8b3c43e75c11cf3f22ef1b Mon Sep 17 00:00:00 2001 From: Alex Page Date: Sat, 24 Jun 2023 00:28:18 -0400 Subject: [PATCH 08/10] Re-add verbose logging of key fields --- src/bin/xpkey/cli.rs | 12 ++++++++++++ 1 file changed, 12 insertions(+) diff --git a/src/bin/xpkey/cli.rs b/src/bin/xpkey/cli.rs index 86dfa98..18f492c 100644 --- a/src/bin/xpkey/cli.rs +++ b/src/bin/xpkey/cli.rs @@ -223,6 +223,9 @@ impl Cli { None, None, )?; + if self.options.verbose { + println!("{:?}", product_key); + } println!("{product_key}"); } Ok(()) @@ -242,6 +245,9 @@ impl Cli { None, None, )?; + if self.options.verbose { + println!("{:?}", product_key); + } println!("{product_key}"); } Ok(()) @@ -254,6 +260,9 @@ impl Cli { let product_key = bink1998::ProductKey::from_key(&curve, self.options.key_to_check.as_ref().unwrap())?; + if self.options.verbose { + println!("{:?}", product_key); + } println!("{product_key}"); println!("Key validated successfully!"); Ok(()) @@ -266,6 +275,9 @@ impl Cli { let product_key = bink2002::ProductKey::from_key(&curve, self.options.key_to_check.as_ref().unwrap())?; + if self.options.verbose { + println!("{:?}", product_key); + } println!("{product_key}"); println!("Key validated successfully!"); Ok(()) From 42f2fa5f804eed376092bc2051d408b3dc5a8154 Mon Sep 17 00:00:00 2001 From: Alex Page Date: Sat, 24 Jun 2023 01:01:40 -0400 Subject: [PATCH 09/10] Pare down xpkey --- src/bin/xpkey.rs | 253 ++++++++++++++++++++++++++++++++++++ src/bin/xpkey/cli.rs | 293 ------------------------------------------ src/bin/xpkey/main.rs | 7 - 3 files changed, 253 insertions(+), 300 deletions(-) create mode 100644 src/bin/xpkey.rs delete mode 100644 src/bin/xpkey/cli.rs delete mode 100644 src/bin/xpkey/main.rs diff --git a/src/bin/xpkey.rs b/src/bin/xpkey.rs new file mode 100644 index 0000000..cde93dc --- /dev/null +++ b/src/bin/xpkey.rs @@ -0,0 +1,253 @@ +use std::{fs::File, io::BufReader, path::Path}; + +use anyhow::{anyhow, Result}; +use clap::Parser; +use serde_json::{from_reader, from_str}; + +use umskt::{ + bink1998, bink2002, confid, + crypto::{EllipticCurve, PrivateKey}, +}; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Mode { + Bink1998Generate, + Bink2002Generate, + Bink1998Validate, + Bink2002Validate, + ConfirmationId, +} + +impl Default for Mode { + fn default() -> Self { + Self::Bink1998Generate + } +} + +#[derive(Parser, Debug)] +#[command(author, about, long_about = None)] +pub struct Options { + /// Enable verbose output + #[arg(short, long)] + verbose: bool, + + /// Number of keys to generate + #[arg(short = 'n', long = "number", default_value = "1")] + num_keys: u64, + + /// Specify which keys file to load + #[arg(short = 'f', long = "file")] + keys_filename: Option, + + /// Installation ID used to generate confirmation ID + #[arg(short, long)] + instid: Option, + + /// Specify which BINK identifier to load + #[arg(short, long, default_value = "2E")] + binkid: String, + + /// Show which products/binks can be loaded + #[arg(short, long)] + list: bool, + + /// Specify which Channel Identifier to use + #[arg(short = 'c', long = "channel", default_value = "640")] + channel_id: u32, + + /// Product key to validate signature + #[arg(short = 'V', long = "validate")] + key_to_check: Option, + + #[clap(skip)] + application_mode: Mode, +} + +fn main() -> Result<()> { + let mut options = parse_command_line(); + let keys = validate_command_line(&mut options)?; + + let bink = &keys["BINK"][&options.binkid]; + // We cannot produce a valid key without knowing the private key k. The reason for this is that + // we need the result of the function K(x; y) = kG(x; y). + let private_key = bink["priv"].as_str().unwrap(); + + // We can, however, validate any given key using the available public key: {p, a, b, G, K}. + // genOrder the order of the generator G, a value we have to reverse -> Schoof's Algorithm. + let gen_order = bink["n"].as_str().unwrap(); + + let p = bink["p"].as_str().unwrap(); + let a = bink["a"].as_str().unwrap(); + let b = bink["b"].as_str().unwrap(); + let gx = bink["g"]["x"].as_str().unwrap(); + let gy = bink["g"]["y"].as_str().unwrap(); + let kx = bink["pub"]["x"].as_str().unwrap(); + let ky = bink["pub"]["y"].as_str().unwrap(); + + if options.verbose { + println!("-----------------------------------------------------------"); + println!( + "Loaded the following elliptic curve parameters: BINK[{}]", + options.binkid + ); + println!("-----------------------------------------------------------"); + println!(" P: {p}"); + println!(" a: {a}"); + println!(" b: {b}"); + println!("Gx: {gx}"); + println!("Gy: {gy}"); + println!("Kx: {kx}"); + println!("Ky: {ky}"); + println!(" n: {gen_order}"); + println!(" k: {private_key}"); + println!(); + } + + let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky)?; + + match options.application_mode { + Mode::Bink1998Generate => { + let private_key = PrivateKey::new(gen_order, private_key)?; + bink1998_generate(&options, &curve, &private_key)?; + } + Mode::Bink2002Generate => { + let private_key = PrivateKey::new(gen_order, private_key)?; + bink2002_generate(&options, &curve, &private_key)?; + } + Mode::Bink1998Validate => bink1998_validate(&options, &curve)?, + Mode::Bink2002Validate => bink2002_validate(&options, &curve)?, + Mode::ConfirmationId => confirmation_id(&options)?, + } + + Ok(()) +} + +fn parse_command_line() -> Options { + let mut args = Options::parse(); + if args.instid.is_some() { + args.application_mode = Mode::ConfirmationId; + } + args +} + +fn validate_command_line(options: &mut Options) -> Result { + let keys = { + if let Some(filename) = &options.keys_filename { + if options.verbose { + println!("Loading keys file {}", filename); + } + + let keys = load_json(filename)?; + + if options.verbose { + println!("Loaded keys from {} successfully", filename); + } + + keys + } else { + from_str(std::include_str!("../../keys.json"))? + } + }; + + if options.list { + let products = keys["Products"] + .as_object() + .ok_or(anyhow!("`Products` object not found in keys",))?; + for (key, value) in products.iter() { + println!("{}: {}", key, value["BINK"]); + } + + println!("\n\n** Please note: any BINK ID other than 2E is considered experimental at this time **\n"); + } + + let bink_id = u32::from_str_radix(&options.binkid, 16)?; + + if options.key_to_check.is_some() { + options.application_mode = Mode::Bink1998Validate; + } + + if bink_id >= 0x40 { + if options.key_to_check.is_some() { + options.application_mode = Mode::Bink2002Validate; + } else { + options.application_mode = Mode::Bink2002Generate; + } + } + + if options.channel_id > 999 { + return Err(anyhow!( + "Refusing to create a key with a Channel ID greater than 999" + )); + } + + Ok(keys) +} + +fn load_json>(path: P) -> Result { + let file = File::open(path)?; + let reader = BufReader::new(file); + let json = from_reader(reader)?; + Ok(json) +} + +fn bink1998_generate( + options: &Options, + curve: &EllipticCurve, + private_key: &PrivateKey, +) -> Result<()> { + for _ in 0..options.num_keys { + let product_key = + bink1998::ProductKey::new(curve, private_key, options.channel_id, None, None)?; + if options.verbose { + println!("{:?}", product_key); + } + println!("{product_key}"); + } + Ok(()) +} + +fn bink2002_generate( + options: &Options, + curve: &EllipticCurve, + private_key: &PrivateKey, +) -> Result<()> { + for _ in 0..options.num_keys { + let product_key = + bink2002::ProductKey::new(curve, private_key, options.channel_id, None, None)?; + if options.verbose { + println!("{:?}", product_key); + } + println!("{product_key}"); + } + Ok(()) +} + +fn bink1998_validate(options: &Options, curve: &EllipticCurve) -> Result<()> { + let product_key = + bink1998::ProductKey::from_key(curve, options.key_to_check.as_ref().unwrap())?; + if options.verbose { + println!("{:?}", product_key); + } + println!("{product_key}"); + println!("Key validated successfully!"); + Ok(()) +} + +fn bink2002_validate(options: &Options, curve: &EllipticCurve) -> Result<()> { + let product_key = + bink2002::ProductKey::from_key(curve, options.key_to_check.as_ref().unwrap())?; + if options.verbose { + println!("{:?}", product_key); + } + println!("{product_key}"); + println!("Key validated successfully!"); + Ok(()) +} + +fn confirmation_id(options: &Options) -> Result<()> { + if let Some(instid) = &options.instid { + let confirmation_id = confid::generate(instid)?; + println!("Confirmation ID: {confirmation_id}"); + }; + Ok(()) +} diff --git a/src/bin/xpkey/cli.rs b/src/bin/xpkey/cli.rs deleted file mode 100644 index 18f492c..0000000 --- a/src/bin/xpkey/cli.rs +++ /dev/null @@ -1,293 +0,0 @@ -use std::{fs::File, io::BufReader, path::Path}; - -use anyhow::{anyhow, Result}; -use clap::Parser; -use serde_json::{from_reader, from_str}; - -use umskt::{ - bink1998, bink2002, confid, - crypto::{EllipticCurve, PrivateKey}, -}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Mode { - Bink1998Generate, - Bink2002Generate, - Bink1998Validate, - Bink2002Validate, - ConfirmationId, -} - -impl Default for Mode { - fn default() -> Self { - Self::Bink1998Generate - } -} - -#[derive(Parser, Debug)] -#[command(author, about, long_about = None)] -pub struct Options { - /// Enable verbose output - #[arg(short, long)] - verbose: bool, - - /// Number of keys to generate - #[arg(short = 'n', long = "number", default_value = "1")] - num_keys: u64, - - /// Specify which keys file to load - #[arg(short = 'f', long = "file")] - keys_filename: Option, - - /// Installation ID used to generate confirmation ID - #[arg(short, long)] - instid: Option, - - /// Specify which BINK identifier to load - #[arg(short, long, default_value = "2E")] - binkid: String, - - /// Show which products/binks can be loaded - #[arg(short, long)] - list: bool, - - /// Specify which Channel Identifier to use - #[arg(short = 'c', long = "channel", default_value = "640")] - channel_id: u32, - - /// Product key to validate signature - #[arg(short = 'V', long = "validate")] - key_to_check: Option, - - #[clap(skip)] - application_mode: Mode, -} - -pub struct Cli { - options: Options, - p: String, - a: String, - b: String, - gx: String, - gy: String, - kx: String, - ky: String, - n: String, - k: String, -} - -impl Cli { - pub fn new() -> Result { - let mut options = Self::parse_command_line(); - let keys = Self::validate_command_line(&mut options)?; - - let bink = &keys["BINK"][&options.binkid]; - // We cannot produce a valid key without knowing the private key k. The reason for this is that - // we need the result of the function K(x; y) = kG(x; y). - let private_key = bink["priv"].as_str().unwrap(); - - // We can, however, validate any given key using the available public key: {p, a, b, G, K}. - // genOrder the order of the generator G, a value we have to reverse -> Schoof's Algorithm. - let gen_order = bink["n"].as_str().unwrap(); - - let p = bink["p"].as_str().unwrap(); - let a = bink["a"].as_str().unwrap(); - let b = bink["b"].as_str().unwrap(); - let gx = bink["g"]["x"].as_str().unwrap(); - let gy = bink["g"]["y"].as_str().unwrap(); - let kx = bink["pub"]["x"].as_str().unwrap(); - let ky = bink["pub"]["y"].as_str().unwrap(); - - if options.verbose { - println!("-----------------------------------------------------------"); - println!( - "Loaded the following elliptic curve parameters: BINK[{}]", - options.binkid - ); - println!("-----------------------------------------------------------"); - println!(" P: {p}"); - println!(" a: {a}"); - println!(" b: {b}"); - println!("Gx: {gx}"); - println!("Gy: {gy}"); - println!("Kx: {kx}"); - println!("Ky: {ky}"); - println!(" n: {gen_order}"); - println!(" k: {private_key}"); - println!(); - } - - Ok(Self { - options, - p: p.to_owned(), - a: a.to_owned(), - b: b.to_owned(), - gx: gx.to_owned(), - gy: gy.to_owned(), - kx: kx.to_owned(), - ky: ky.to_owned(), - n: gen_order.to_owned(), - k: private_key.to_owned(), - }) - } - - fn parse_command_line() -> Options { - let mut args = Options::parse(); - if args.instid.is_some() { - args.application_mode = Mode::ConfirmationId; - } - args - } - - fn validate_command_line(options: &mut Options) -> Result { - let keys = { - if let Some(filename) = &options.keys_filename { - if options.verbose { - println!("Loading keys file {}", filename); - } - - let keys = Self::load_json(filename)?; - - if options.verbose { - println!("Loaded keys from {} successfully", filename); - } - - keys - } else { - from_str(std::include_str!("../../../keys.json"))? - } - }; - - if options.list { - let products = keys["Products"] - .as_object() - .ok_or(anyhow!("`Products` object not found in keys",))?; - for (key, value) in products.iter() { - println!("{}: {}", key, value["BINK"]); - } - - println!("\n\n** Please note: any BINK ID other than 2E is considered experimental at this time **\n"); - } - - let bink_id = u32::from_str_radix(&options.binkid, 16)?; - - if options.key_to_check.is_some() { - options.application_mode = Mode::Bink1998Validate; - } - - if bink_id >= 0x40 { - if options.key_to_check.is_some() { - options.application_mode = Mode::Bink2002Validate; - } else { - options.application_mode = Mode::Bink2002Generate; - } - } - - if options.channel_id > 999 { - return Err(anyhow!( - "Refusing to create a key with a Channel ID greater than 999" - )); - } - - Ok(keys) - } - - fn load_json>(path: P) -> Result { - let file = File::open(path)?; - let reader = BufReader::new(file); - let json = from_reader(reader)?; - Ok(json) - } - - pub fn run(&mut self) -> Result<()> { - match self.options.application_mode { - Mode::Bink1998Generate => self.bink1998_generate(), - Mode::Bink2002Generate => self.bink2002_generate(), - Mode::Bink1998Validate => self.bink1998_validate(), - Mode::Bink2002Validate => self.bink2002_validate(), - Mode::ConfirmationId => self.confirmation_id(), - } - } - - fn bink1998_generate(&mut self) -> Result<()> { - let curve = EllipticCurve::new( - &self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky, - )?; - let private_key = PrivateKey::new(&self.n, &self.k)?; - - for _ in 0..self.options.num_keys { - let product_key = bink1998::ProductKey::new( - &curve, - &private_key, - self.options.channel_id, - None, - None, - )?; - if self.options.verbose { - println!("{:?}", product_key); - } - println!("{product_key}"); - } - Ok(()) - } - - fn bink2002_generate(&mut self) -> Result<()> { - let curve = EllipticCurve::new( - &self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky, - )?; - let private_key = PrivateKey::new(&self.n, &self.k)?; - - for _ in 0..self.options.num_keys { - let product_key = bink2002::ProductKey::new( - &curve, - &private_key, - self.options.channel_id, - None, - None, - )?; - if self.options.verbose { - println!("{:?}", product_key); - } - println!("{product_key}"); - } - Ok(()) - } - - fn bink1998_validate(&mut self) -> Result<()> { - let curve = EllipticCurve::new( - &self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky, - )?; - - let product_key = - bink1998::ProductKey::from_key(&curve, self.options.key_to_check.as_ref().unwrap())?; - if self.options.verbose { - println!("{:?}", product_key); - } - println!("{product_key}"); - println!("Key validated successfully!"); - Ok(()) - } - - fn bink2002_validate(&mut self) -> Result<()> { - let curve = EllipticCurve::new( - &self.p, &self.a, &self.b, &self.gx, &self.gy, &self.kx, &self.ky, - )?; - - let product_key = - bink2002::ProductKey::from_key(&curve, self.options.key_to_check.as_ref().unwrap())?; - if self.options.verbose { - println!("{:?}", product_key); - } - println!("{product_key}"); - println!("Key validated successfully!"); - Ok(()) - } - - fn confirmation_id(&mut self) -> Result<()> { - if let Some(instid) = &self.options.instid { - let confirmation_id = confid::generate(instid)?; - println!("Confirmation ID: {confirmation_id}"); - }; - Ok(()) - } -} diff --git a/src/bin/xpkey/main.rs b/src/bin/xpkey/main.rs deleted file mode 100644 index 5e60ce0..0000000 --- a/src/bin/xpkey/main.rs +++ /dev/null @@ -1,7 +0,0 @@ -use anyhow::Result; - -mod cli; - -fn main() -> Result<()> { - cli::Cli::new()?.run() -} From b6707e34b87cd69632a0361adef0cff75961c61c Mon Sep 17 00:00:00 2001 From: Alex Page Date: Sat, 24 Jun 2023 03:49:50 -0400 Subject: [PATCH 10/10] Restructure CLI to use subcommands --- Cargo.lock | 15 +++ Cargo.toml | 1 + src/bin/xpkey.rs | 253 ------------------------------------ src/bin/xpkey/keys.rs | 36 ++++++ src/bin/xpkey/main.rs | 289 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 341 insertions(+), 253 deletions(-) delete mode 100644 src/bin/xpkey.rs create mode 100644 src/bin/xpkey/keys.rs create mode 100644 src/bin/xpkey/main.rs diff --git a/Cargo.lock b/Cargo.lock index 253065e..9d3db39 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -311,6 +311,20 @@ name = "serde" version = "1.0.164" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e8c8cf938e98f769bc164923b06dce91cea1751522f46f8466461af04c9027d" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.164" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9735b638ccc51c28bf6914d90a2e9725b377144fc612c49a611fddd1b631d68" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] [[package]] name = "serde_json" @@ -368,6 +382,7 @@ dependencies = [ "bitreader", "clap", "openssl", + "serde", "serde_json", "thiserror", ] diff --git a/Cargo.toml b/Cargo.toml index 84db26a..aeeec04 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -14,5 +14,6 @@ anyhow = "1.0.71" bitreader = "0.3.7" clap = { version = "4.3.4", features = ["derive"] } openssl = { git = "https://github.com/anpage/rust-openssl.git" } +serde = { version = "1.0.164", features = ["derive"] } serde_json = "1.0" thiserror = "1.0.40" diff --git a/src/bin/xpkey.rs b/src/bin/xpkey.rs deleted file mode 100644 index cde93dc..0000000 --- a/src/bin/xpkey.rs +++ /dev/null @@ -1,253 +0,0 @@ -use std::{fs::File, io::BufReader, path::Path}; - -use anyhow::{anyhow, Result}; -use clap::Parser; -use serde_json::{from_reader, from_str}; - -use umskt::{ - bink1998, bink2002, confid, - crypto::{EllipticCurve, PrivateKey}, -}; - -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub enum Mode { - Bink1998Generate, - Bink2002Generate, - Bink1998Validate, - Bink2002Validate, - ConfirmationId, -} - -impl Default for Mode { - fn default() -> Self { - Self::Bink1998Generate - } -} - -#[derive(Parser, Debug)] -#[command(author, about, long_about = None)] -pub struct Options { - /// Enable verbose output - #[arg(short, long)] - verbose: bool, - - /// Number of keys to generate - #[arg(short = 'n', long = "number", default_value = "1")] - num_keys: u64, - - /// Specify which keys file to load - #[arg(short = 'f', long = "file")] - keys_filename: Option, - - /// Installation ID used to generate confirmation ID - #[arg(short, long)] - instid: Option, - - /// Specify which BINK identifier to load - #[arg(short, long, default_value = "2E")] - binkid: String, - - /// Show which products/binks can be loaded - #[arg(short, long)] - list: bool, - - /// Specify which Channel Identifier to use - #[arg(short = 'c', long = "channel", default_value = "640")] - channel_id: u32, - - /// Product key to validate signature - #[arg(short = 'V', long = "validate")] - key_to_check: Option, - - #[clap(skip)] - application_mode: Mode, -} - -fn main() -> Result<()> { - let mut options = parse_command_line(); - let keys = validate_command_line(&mut options)?; - - let bink = &keys["BINK"][&options.binkid]; - // We cannot produce a valid key without knowing the private key k. The reason for this is that - // we need the result of the function K(x; y) = kG(x; y). - let private_key = bink["priv"].as_str().unwrap(); - - // We can, however, validate any given key using the available public key: {p, a, b, G, K}. - // genOrder the order of the generator G, a value we have to reverse -> Schoof's Algorithm. - let gen_order = bink["n"].as_str().unwrap(); - - let p = bink["p"].as_str().unwrap(); - let a = bink["a"].as_str().unwrap(); - let b = bink["b"].as_str().unwrap(); - let gx = bink["g"]["x"].as_str().unwrap(); - let gy = bink["g"]["y"].as_str().unwrap(); - let kx = bink["pub"]["x"].as_str().unwrap(); - let ky = bink["pub"]["y"].as_str().unwrap(); - - if options.verbose { - println!("-----------------------------------------------------------"); - println!( - "Loaded the following elliptic curve parameters: BINK[{}]", - options.binkid - ); - println!("-----------------------------------------------------------"); - println!(" P: {p}"); - println!(" a: {a}"); - println!(" b: {b}"); - println!("Gx: {gx}"); - println!("Gy: {gy}"); - println!("Kx: {kx}"); - println!("Ky: {ky}"); - println!(" n: {gen_order}"); - println!(" k: {private_key}"); - println!(); - } - - let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky)?; - - match options.application_mode { - Mode::Bink1998Generate => { - let private_key = PrivateKey::new(gen_order, private_key)?; - bink1998_generate(&options, &curve, &private_key)?; - } - Mode::Bink2002Generate => { - let private_key = PrivateKey::new(gen_order, private_key)?; - bink2002_generate(&options, &curve, &private_key)?; - } - Mode::Bink1998Validate => bink1998_validate(&options, &curve)?, - Mode::Bink2002Validate => bink2002_validate(&options, &curve)?, - Mode::ConfirmationId => confirmation_id(&options)?, - } - - Ok(()) -} - -fn parse_command_line() -> Options { - let mut args = Options::parse(); - if args.instid.is_some() { - args.application_mode = Mode::ConfirmationId; - } - args -} - -fn validate_command_line(options: &mut Options) -> Result { - let keys = { - if let Some(filename) = &options.keys_filename { - if options.verbose { - println!("Loading keys file {}", filename); - } - - let keys = load_json(filename)?; - - if options.verbose { - println!("Loaded keys from {} successfully", filename); - } - - keys - } else { - from_str(std::include_str!("../../keys.json"))? - } - }; - - if options.list { - let products = keys["Products"] - .as_object() - .ok_or(anyhow!("`Products` object not found in keys",))?; - for (key, value) in products.iter() { - println!("{}: {}", key, value["BINK"]); - } - - println!("\n\n** Please note: any BINK ID other than 2E is considered experimental at this time **\n"); - } - - let bink_id = u32::from_str_radix(&options.binkid, 16)?; - - if options.key_to_check.is_some() { - options.application_mode = Mode::Bink1998Validate; - } - - if bink_id >= 0x40 { - if options.key_to_check.is_some() { - options.application_mode = Mode::Bink2002Validate; - } else { - options.application_mode = Mode::Bink2002Generate; - } - } - - if options.channel_id > 999 { - return Err(anyhow!( - "Refusing to create a key with a Channel ID greater than 999" - )); - } - - Ok(keys) -} - -fn load_json>(path: P) -> Result { - let file = File::open(path)?; - let reader = BufReader::new(file); - let json = from_reader(reader)?; - Ok(json) -} - -fn bink1998_generate( - options: &Options, - curve: &EllipticCurve, - private_key: &PrivateKey, -) -> Result<()> { - for _ in 0..options.num_keys { - let product_key = - bink1998::ProductKey::new(curve, private_key, options.channel_id, None, None)?; - if options.verbose { - println!("{:?}", product_key); - } - println!("{product_key}"); - } - Ok(()) -} - -fn bink2002_generate( - options: &Options, - curve: &EllipticCurve, - private_key: &PrivateKey, -) -> Result<()> { - for _ in 0..options.num_keys { - let product_key = - bink2002::ProductKey::new(curve, private_key, options.channel_id, None, None)?; - if options.verbose { - println!("{:?}", product_key); - } - println!("{product_key}"); - } - Ok(()) -} - -fn bink1998_validate(options: &Options, curve: &EllipticCurve) -> Result<()> { - let product_key = - bink1998::ProductKey::from_key(curve, options.key_to_check.as_ref().unwrap())?; - if options.verbose { - println!("{:?}", product_key); - } - println!("{product_key}"); - println!("Key validated successfully!"); - Ok(()) -} - -fn bink2002_validate(options: &Options, curve: &EllipticCurve) -> Result<()> { - let product_key = - bink2002::ProductKey::from_key(curve, options.key_to_check.as_ref().unwrap())?; - if options.verbose { - println!("{:?}", product_key); - } - println!("{product_key}"); - println!("Key validated successfully!"); - Ok(()) -} - -fn confirmation_id(options: &Options) -> Result<()> { - if let Some(instid) = &options.instid { - let confirmation_id = confid::generate(instid)?; - println!("Confirmation ID: {confirmation_id}"); - }; - Ok(()) -} diff --git a/src/bin/xpkey/keys.rs b/src/bin/xpkey/keys.rs new file mode 100644 index 0000000..583b0cc --- /dev/null +++ b/src/bin/xpkey/keys.rs @@ -0,0 +1,36 @@ +use std::collections::HashMap; + +use serde::{Deserialize, Serialize}; + +#[derive(Serialize, Deserialize)] +pub struct Keys { + #[serde(rename = "Products")] + pub products: HashMap, + #[serde(rename = "BINK")] + pub bink: HashMap, +} + +#[derive(Serialize, Deserialize)] +pub struct Product { + #[serde(rename = "BINK")] + pub bink: Vec, +} + +#[derive(Serialize, Deserialize)] +pub struct Bink { + pub p: String, + pub a: String, + pub b: String, + pub g: Point, + #[serde(rename = "pub")] + pub public: Point, + pub n: String, + #[serde(rename = "priv")] + pub private: String, +} + +#[derive(Serialize, Deserialize)] +pub struct Point { + pub x: String, + pub y: String, +} diff --git a/src/bin/xpkey/main.rs b/src/bin/xpkey/main.rs new file mode 100644 index 0000000..3a28017 --- /dev/null +++ b/src/bin/xpkey/main.rs @@ -0,0 +1,289 @@ +mod keys; + +use std::{fs::File, io::BufReader, path::Path}; + +use anyhow::{anyhow, Result}; +use clap::{Args, Parser, Subcommand}; +use keys::{Bink, Keys}; +use serde_json::{from_reader, from_str}; + +use umskt::{ + bink1998, bink2002, confid, + crypto::{EllipticCurve, PrivateKey}, +}; + +#[derive(Parser, Debug)] +#[command(author, about, version, long_about = None)] +struct Cli { + /// Enable verbose output + #[arg(short, long)] + verbose: bool, + + #[command(subcommand)] + command: Commands, +} + +#[derive(Subcommand, Clone, Debug)] +enum Commands { + /// Show which products/binks can be loaded + List(ListArgs), + /// Generate new product keys + Generate(GenerateArgs), + /// Validate a product key + Validate(ValidateArgs), + /// Generate a phone activation Confirmation ID from an Installation ID + Confid(ConfirmationIdArgs), +} + +#[derive(Args, Clone, Debug)] +struct ListArgs { + /// Specify which keys file to load + #[arg(short = 'f', long = "file")] + keys_path: Option, +} + +#[derive(Args, Clone, Debug)] +struct GenerateArgs { + /// Specify which BINK identifier to load + #[arg(short, long, default_value = "2E")] + binkid: String, + + /// Specify which Channel Identifier to use + #[arg(short = 'c', long = "channel", default_value = "640")] + channel_id: u32, + + /// Number of keys to generate + #[arg(short = 'n', long = "number", default_value = "1")] + num_keys: u64, + + /// Specify which keys file to load + #[arg(short = 'f', long = "file")] + keys_path: Option, +} + +#[derive(Args, Clone, Debug)] +struct ValidateArgs { + /// Specify which BINK identifier to load + #[arg(short, long, default_value = "2E")] + binkid: String, + + /// Specify which keys file to load + #[arg(short = 'f', long = "file")] + keys_path: Option, + + /// Product key to validate signature + key_to_check: String, +} + +#[derive(Args, Clone, Debug)] +struct ConfirmationIdArgs { + /// Installation ID used to generate confirmation ID + instid: String, +} + +fn main() -> Result<()> { + let args = Cli::parse(); + + match &args.command { + Commands::List(list_args) => { + let keys = load_keys(list_args.keys_path.as_ref(), args.verbose)?; + for (key, value) in keys.products.iter() { + println!("{}: {:?}", key, value.bink); + } + + println!("\n\n** Please note: any BINK ID other than 2E is considered experimental at this time **\n"); + } + Commands::Generate(generate_args) => { + if generate_args.channel_id > 999 { + return Err(anyhow!("Channel ID must be 3 digits or fewer")); + } + let keys = load_keys(generate_args.keys_path.as_ref(), args.verbose)?; + generate( + &keys, + &generate_args.binkid, + generate_args.channel_id, + generate_args.num_keys, + args.verbose, + )?; + } + Commands::Validate(validate_args) => { + let keys = load_keys(validate_args.keys_path.as_ref(), args.verbose)?; + validate( + &keys, + &validate_args.binkid, + &validate_args.key_to_check, + args.verbose, + )?; + } + Commands::Confid(confirmation_id_args) => { + confirmation_id(&confirmation_id_args.instid)?; + } + } + + Ok(()) +} + +fn load_keys + std::fmt::Display>(path: Option

, verbose: bool) -> Result { + let keys = { + if let Some(path) = path { + if verbose { + println!("Loading keys file {}", path); + } + + let file = File::open(&path)?; + let reader = BufReader::new(file); + let keys: Keys = from_reader(reader)?; + + if verbose { + println!("Loaded keys from {} successfully", path); + } + + keys + } else { + from_str(std::include_str!("../../../keys.json"))? + } + }; + + // let bink_id = u32::from_str_radix(&options.binkid, 16)?; + + // if bink_id >= 0x40 { + // if options.key_to_check.is_some() { + // options.application_mode = Commands::Bink2002Validate; + // } else { + // options.application_mode = Commands::Bink2002Generate; + // } + // } + + Ok(keys) +} + +fn generate(keys: &Keys, bink_id: &str, channel_id: u32, count: u64, verbose: bool) -> Result<()> { + let bink_id = bink_id.to_ascii_uppercase(); + let bink = &keys.bink[&bink_id]; + + // We cannot produce a valid key without knowing the private key k. The reason for this is that + // we need the result of the function K(x; y) = kG(x; y). + let private_key = &bink.private; + + // We can, however, validate any given key using the available public key: {p, a, b, G, K}. + // genOrder the order of the generator G, a value we have to reverse -> Schoof's Algorithm. + let gen_order = &bink.n; + + let curve = initialize_curve(bink, &bink_id, verbose)?; + if verbose { + println!(" n: {gen_order}"); + println!(" k: {private_key}"); + println!(); + } + let private_key = PrivateKey::new(gen_order, private_key)?; + + if u32::from_str_radix(&bink_id, 16)? < 0x40 { + bink1998_generate(&curve, &private_key, channel_id, count, verbose)?; + } else { + bink2002_generate(&curve, &private_key, channel_id, count, verbose)?; + } + + Ok(()) +} + +fn validate(keys: &Keys, bink_id: &str, key: &str, verbose: bool) -> Result<()> { + let bink_id = bink_id.to_ascii_uppercase(); + let bink = &keys.bink[&bink_id]; + let curve = initialize_curve(bink, &bink_id, verbose)?; + + if u32::from_str_radix(&bink_id, 16)? < 0x40 { + bink1998_validate(&curve, key, verbose)?; + } else { + bink2002_validate(&curve, key, verbose)?; + } + + Ok(()) +} + +fn initialize_curve(bink: &Bink, bink_id: &str, verbose: bool) -> Result { + let p = &bink.p; + let a = &bink.a; + let b = &bink.b; + let gx = &bink.g.x; + let gy = &bink.g.y; + let kx = &bink.public.x; + let ky = &bink.public.y; + + if verbose { + println!("-----------------------------------------------------------"); + println!( + "Loaded the following elliptic curve parameters: BINK[{}]", + bink_id + ); + println!("-----------------------------------------------------------"); + println!(" P: {p}"); + println!(" a: {a}"); + println!(" b: {b}"); + println!("Gx: {gx}"); + println!("Gy: {gy}"); + println!("Kx: {kx}"); + println!("Ky: {ky}"); + } + + EllipticCurve::new(p, a, b, gx, gy, kx, ky) +} + +fn bink1998_generate( + curve: &EllipticCurve, + private_key: &PrivateKey, + channel_id: u32, + count: u64, + verbose: bool, +) -> Result<()> { + for _ in 0..count { + let product_key = bink1998::ProductKey::new(curve, private_key, channel_id, None, None)?; + if verbose { + println!("{:?}", product_key); + } + println!("{product_key}"); + } + Ok(()) +} + +fn bink2002_generate( + curve: &EllipticCurve, + private_key: &PrivateKey, + channel_id: u32, + count: u64, + verbose: bool, +) -> Result<()> { + for _ in 0..count { + let product_key = bink2002::ProductKey::new(curve, private_key, channel_id, None, None)?; + if verbose { + println!("{:?}", product_key); + } + println!("{product_key}"); + } + Ok(()) +} + +fn bink1998_validate(curve: &EllipticCurve, key: &str, verbose: bool) -> Result<()> { + let product_key = bink1998::ProductKey::from_key(curve, key)?; + if verbose { + println!("{:?}", product_key); + } + println!("{product_key}"); + println!("Key validated successfully!"); + Ok(()) +} + +fn bink2002_validate(curve: &EllipticCurve, key: &str, verbose: bool) -> Result<()> { + let product_key = bink2002::ProductKey::from_key(curve, key)?; + if verbose { + println!("{:?}", product_key); + } + println!("{product_key}"); + println!("Key validated successfully!"); + Ok(()) +} + +fn confirmation_id(installation_id: &str) -> Result<()> { + let confirmation_id = confid::generate(installation_id)?; + println!("Confirmation ID: {confirmation_id}"); + Ok(()) +}