Restructure into a workspace

This commit is contained in:
Alex Page 2023-06-24 17:11:37 -04:00
parent 589f0bb52b
commit fe08910831
16 changed files with 534 additions and 39 deletions

472
umskt/Cargo.lock generated Normal file
View file

@ -0,0 +1,472 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "anstream"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "0ca84f3628370c59db74ee214b3263d58f9aadd9b4fe7e711fd87dc452b7f163"
dependencies = [
"anstyle",
"anstyle-parse",
"anstyle-query",
"anstyle-wincon",
"colorchoice",
"is-terminal",
"utf8parse",
]
[[package]]
name = "anstyle"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "41ed9a86bf92ae6580e0a31281f65a1b1d867c0cc68d5346e2ae128dddfa6a7d"
[[package]]
name = "anstyle-parse"
version = "0.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e765fd216e48e067936442276d1d57399e37bce53c264d6fefbe298080cb57ee"
dependencies = [
"utf8parse",
]
[[package]]
name = "anstyle-query"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5ca11d4be1bab0c8bc8734a9aa7bf4ee8316d462a08c6ac5052f888fef5b494b"
dependencies = [
"windows-sys",
]
[[package]]
name = "anstyle-wincon"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "180abfa45703aebe0093f79badacc01b8fd4ea2e35118747e5811127f926e188"
dependencies = [
"anstyle",
"windows-sys",
]
[[package]]
name = "anyhow"
version = "1.0.71"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "9c7d0618f0e0b7e8ff11427422b64564d5fb0be1940354bfe2e0529b18a9d9b8"
[[package]]
name = "bitflags"
version = "1.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
[[package]]
name = "bitreader"
version = "0.3.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f10043e4864d975e7f197f993ec4018636ad93946724b2571c4474d51845869b"
dependencies = [
"cfg-if",
]
[[package]]
name = "cc"
version = "1.0.79"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "50d30906286121d95be3d479533b458f87493b30a4b5f79a607db8f5d11aa91f"
[[package]]
name = "cfg-if"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "clap"
version = "4.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "80672091db20273a15cf9fdd4e47ed43b5091ec9841bf4c6145c9dfbbcae09ed"
dependencies = [
"clap_builder",
"clap_derive",
"once_cell",
]
[[package]]
name = "clap_builder"
version = "4.3.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "c1458a1df40e1e2afebb7ab60ce55c1fa8f431146205aa5f4887e0b111c27636"
dependencies = [
"anstream",
"anstyle",
"bitflags",
"clap_lex",
"strsim",
]
[[package]]
name = "clap_derive"
version = "4.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b8cd2b2a819ad6eec39e8f1d6b53001af1e5469f8c177579cdaeb313115b825f"
dependencies = [
"heck",
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "clap_lex"
version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "2da6da31387c7e4ef160ffab6d5e7f00c42626fe39aea70a7b0f1773f7dd6c1b"
[[package]]
name = "colorchoice"
version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "acbf1af155f9b9ef647e42cdc158db4b64a1b61f743629225fde6f3e0be2a7c7"
[[package]]
name = "errno"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4bcfec3a70f97c962c307b2d2c56e358cf1d00b558d74262b5f929ee8cc7e73a"
dependencies = [
"errno-dragonfly",
"libc",
"windows-sys",
]
[[package]]
name = "errno-dragonfly"
version = "0.1.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "aa68f1b12764fab894d2755d2518754e71b4fd80ecfb822714a1206c2aab39bf"
dependencies = [
"cc",
"libc",
]
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "heck"
version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8"
[[package]]
name = "hermit-abi"
version = "0.3.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "fed44880c466736ef9a5c5b5facefb5ed0785676d0c02d612db14e54f0d84286"
[[package]]
name = "io-lifetimes"
version = "1.0.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2"
dependencies = [
"hermit-abi",
"libc",
"windows-sys",
]
[[package]]
name = "is-terminal"
version = "0.4.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "adcf93614601c8129ddf72e2d5633df827ba6551541c6d8c59520a371475be1f"
dependencies = [
"hermit-abi",
"io-lifetimes",
"rustix",
"windows-sys",
]
[[package]]
name = "itoa"
version = "1.0.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "453ad9f582a441959e5f0d088b02ce04cfe8d51a8eaf077f12ac6d3e94164ca6"
[[package]]
name = "libc"
version = "0.2.146"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f92be4933c13fd498862a9e02a3055f8a8d9c039ce33db97306fd5a6caa7f29b"
[[package]]
name = "linux-raw-sys"
version = "0.3.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ef53942eb7bf7ff43a617b3e2c1c4a5ecf5944a7c1bc12d7ee39bbb15e5c1519"
[[package]]
name = "once_cell"
version = "1.18.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dd8b5dd2ae5ed71462c540258bedcb51965123ad7e7ccf4b9a8cafaa4a63576d"
[[package]]
name = "openssl"
version = "0.10.55"
source = "git+https://github.com/anpage/rust-openssl.git#a50639888f80f0a935ec621c328d761428aff32a"
dependencies = [
"bitflags",
"cfg-if",
"foreign-types",
"libc",
"once_cell",
"openssl-macros",
"openssl-sys",
]
[[package]]
name = "openssl-macros"
version = "0.1.1"
source = "git+https://github.com/anpage/rust-openssl.git#a50639888f80f0a935ec621c328d761428aff32a"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "openssl-sys"
version = "0.9.90"
source = "git+https://github.com/anpage/rust-openssl.git#a50639888f80f0a935ec621c328d761428aff32a"
dependencies = [
"cc",
"libc",
"pkg-config",
"vcpkg",
]
[[package]]
name = "pkg-config"
version = "0.3.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "26072860ba924cbfa98ea39c8c19b4dd6a4a25423dbdf219c1eca91aa0cf6964"
[[package]]
name = "proc-macro2"
version = "1.0.60"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "dec2b086b7a862cf4de201096214fa870344cf922b2b30c167badb3af3195406"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quote"
version = "1.0.28"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1b9ab9c7eadfd8df19006f1cf1a4aed13540ed5cbc047010ece5826e10825488"
dependencies = [
"proc-macro2",
]
[[package]]
name = "rustix"
version = "0.37.20"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b96e891d04aa506a6d1f318d2771bcb1c7dfda84e126660ace067c9b474bb2c0"
dependencies = [
"bitflags",
"errno",
"io-lifetimes",
"libc",
"linux-raw-sys",
"windows-sys",
]
[[package]]
name = "ryu"
version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f91339c0467de62360649f8d3e185ca8de4224ff281f66000de5eb2a77a79041"
[[package]]
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"
version = "1.0.97"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "bdf3bf93142acad5821c99197022e170842cdbc1c30482b98750c688c640842a"
dependencies = [
"itoa",
"ryu",
"serde",
]
[[package]]
name = "strsim"
version = "0.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "73473c0e59e6d5812c5dfe2a064a6444949f089e20eec9a2e5506596494e4623"
[[package]]
name = "syn"
version = "2.0.18"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "32d41677bcbe24c20c52e7c70b0d8db04134c5d1066bf98662e2871ad200ea3e"
dependencies = [
"proc-macro2",
"quote",
"unicode-ident",
]
[[package]]
name = "thiserror"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "978c9a314bd8dc99be594bc3c175faaa9794be04a5a5e153caba6915336cebac"
dependencies = [
"thiserror-impl",
]
[[package]]
name = "thiserror-impl"
version = "1.0.40"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f9456a42c5b0d803c8cd86e73dd7cc9edd429499f37a3550d286d5e86720569f"
dependencies = [
"proc-macro2",
"quote",
"syn",
]
[[package]]
name = "umskt"
version = "0.1.0"
dependencies = [
"anyhow",
"bitreader",
"clap",
"openssl",
"serde",
"serde_json",
"thiserror",
]
[[package]]
name = "unicode-ident"
version = "1.0.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b15811caf2415fb889178633e7724bad2509101cde276048e013b9def5e51fa0"
[[package]]
name = "utf8parse"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "711b9620af191e0cdc7468a8d14e709c3dcdb115b36f838e601583af800a370a"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "windows-sys"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
dependencies = [
"windows-targets",
]
[[package]]
name = "windows-targets"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7b1eb6f0cd7c80c79759c929114ef071b87354ce476d9d94271031c0497adfd5"
dependencies = [
"windows_aarch64_gnullvm",
"windows_aarch64_msvc",
"windows_i686_gnu",
"windows_i686_msvc",
"windows_x86_64_gnu",
"windows_x86_64_gnullvm",
"windows_x86_64_msvc",
]
[[package]]
name = "windows_aarch64_gnullvm"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "91ae572e1b79dba883e0d315474df7305d12f569b400fcf90581b06062f7e1bc"
[[package]]
name = "windows_aarch64_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b2ef27e0d7bdfcfc7b868b317c1d32c641a6fe4629c171b8928c7b08d98d7cf3"
[[package]]
name = "windows_i686_gnu"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "622a1962a7db830d6fd0a69683c80a18fda201879f0f447f065a3b7467daa241"
[[package]]
name = "windows_i686_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4542c6e364ce21bf45d69fdd2a8e455fa38d316158cfd43b3ac1c5b1b19f8e00"
[[package]]
name = "windows_x86_64_gnu"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ca2b8a661f7628cbd23440e50b05d705db3686f894fc9580820623656af974b1"
[[package]]
name = "windows_x86_64_gnullvm"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7896dbc1f41e08872e9d5e8f8baa8fdd2677f29468c4e156210174edc7f7b953"
[[package]]
name = "windows_x86_64_msvc"
version = "0.48.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "1a515f5799fe4961cb532f983ce2b23082366b898e52ffbce459c86f67c8378a"

14
umskt/Cargo.toml Normal file
View file

@ -0,0 +1,14 @@
[package]
name = "umskt"
version = "0.1.0"
edition = "2021"
crate-type = ["lib"]
[dependencies]
anyhow = "1.0.71"
bitreader = "0.3.7"
openssl = { git = "https://github.com/anpage/rust-openssl.git" }
thiserror = "1.0.40"
[dev-dependencies]
serde_json = "1.0"

310
umskt/src/bink1998.rs Normal file
View file

@ -0,0 +1,310 @@
use std::fmt::{Display, Formatter};
use anyhow::{bail, Result};
use bitreader::BitReader;
use openssl::{
bn::{BigNum, BigNumContext, MsbOption},
ec::{EcGroup, EcPoint},
sha::sha1,
};
use crate::{
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;
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,
channel_id: u32,
sequence: u32,
hash: u32,
signature: u64,
}
impl ProductKey {
pub fn new(
curve: &EllipticCurve,
private_key: &PrivateKey,
channel_id: u32,
sequence: Option<u32>,
upgrade: Option<bool>,
) -> Result<Self> {
// 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
}
};
// Default to upgrade=false
let upgrade = upgrade.unwrap_or(false);
// 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,
sequence,
upgrade,
)?;
// Make sure the key is valid
product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?;
// Ship it
Ok(product_key)
}
pub fn from_key(curve: &EllipticCurve, key: &str) -> Result<Self> {
let key = strip_key(key)?;
let Ok(packed_key) = base24_decode(&key) else {
bail!("Product key is in an incorrect format!")
};
let product_key = Self::from_packed(&packed_key)?;
product_key.verify(&curve.curve, &curve.gen_point, &curve.pub_point)?;
Ok(product_key)
}
fn generate(
e_curve: &EcGroup,
base_point: &EcPoint,
gen_order: &BigNum,
private_key: &BigNum,
channel_id: u32,
sequence: u32,
upgrade: bool,
) -> Result<Self> {
let mut num_context = BigNumContext::new().unwrap();
let mut c = BigNum::new()?;
let mut s = BigNum::new()?;
let mut x = BigNum::new()?;
let mut y = BigNum::new()?;
let mut ek: BigNum;
let serial = channel_id * 1_000_000 + sequence;
let data = serial << 1 | upgrade as u32;
let product_key = loop {
let mut r = EcPoint::new(e_curve)?;
// Generate a random number c consisting of 384 bits without any constraints.
c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?;
// Pick a random derivative of the base point on the elliptic curve.
// R = cG;
r.mul(e_curve, base_point, &c, &num_context)?;
// Acquire its coordinates.
// x = R.x; y = R.y;
r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
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[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 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(hash)?;
s.mod_add(&ek, &c, gen_order, &mut num_context)?;
let signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap());
if signature <= bitmask(55) {
break Self {
upgrade,
channel_id,
sequence,
hash,
signature,
};
}
};
Ok(product_key)
}
fn verify(
&self,
e_curve: &EcGroup,
base_point: &EcPoint,
public_key: &EcPoint,
) -> Result<bool> {
let mut ctx = BigNumContext::new()?;
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)?;
t.mul(e_curve, base_point, &s, &ctx)?;
p.mul(e_curve, public_key, &e, &ctx)?;
{
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 ctx)?;
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
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();
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);
msg_buffer[4 + FIELD_BYTES..4 + FIELD_BYTES * 2].copy_from_slice(&y_bin);
let msg_digest = sha1(&msg_buffer);
let hash: u32 =
u32::from_le_bytes(msg_digest[0..4].try_into().unwrap()) >> 4 & bitmask(28) as u32;
Ok(hash == self.hash)
}
fn from_packed(packed_key: &[u8]) -> Result<Self> {
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 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()?;
let sequence = serial % 1_000_000;
let channel_id = serial / 1_000_000;
Ok(Self {
upgrade,
channel_id,
sequence,
hash,
signature,
})
}
fn pack(&self) -> Vec<u8> {
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 |= (serial as u128) << UPGRADE_LENGTH_BITS;
packed_key |= self.upgrade as u128;
packed_key
.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 std::{fs::File, io::BufReader};
use serde_json::from_reader;
use crate::crypto::EllipticCurve;
#[test]
fn verify_test() {
// Example product key and its BINK ID
let product_key = "D9924-R6BG2-39J83-RYKHF-W47TT";
let bink_id = "2E";
// Load keys.json
let path = "keys.json";
let file = File::open(path).unwrap();
let reader = BufReader::new(file);
let keys: serde_json::Value = from_reader(reader).unwrap();
let bink = &keys["BINK"][&bink_id];
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();
let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky).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 key = super::ProductKey {
upgrade: false,
channel_id: 640,
sequence: 10550,
hash: 39185432,
signature: 6939952665262054,
};
assert_eq!(key.to_string(), "D9924-R6BG2-39J83-RYKHF-W47TT");
}
}

367
umskt/src/bink2002.rs Normal file
View file

@ -0,0 +1,367 @@
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::{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;
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,
signature: u64,
auth_info: u32,
}
impl ProductKey {
pub fn new(
curve: &EllipticCurve,
private_key: &PrivateKey,
channel_id: u32,
auth_info: Option<u32>,
upgrade: Option<bool>,
) -> Result<Self> {
// Generate random auth info if none supplied
let auth_info = match auth_info {
Some(auth_info) => auth_info,
None => {
let mut auth_info_bytes = [0_u8; 4];
rand_bytes(&mut auth_info_bytes)?;
u32::from_ne_bytes(auth_info_bytes) & ((1 << 10) - 1)
}
};
// Default to upgrade=false
let upgrade = upgrade.unwrap_or(false);
// 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,
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)
}
pub fn from_key(curve: &EllipticCurve, key: &str) -> Result<Self> {
let key = strip_key(key)?;
let Ok(packed_key) = base24_decode(&key) else {
bail!("Product key is in an incorrect format!")
};
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?");
}
Ok(product_key)
}
fn generate(
e_curve: &EcGroup,
base_point: &EcPoint,
gen_order: &BigNum,
private_key: &BigNum,
channel_id: u32,
auth_info: u32,
upgrade: bool,
) -> Result<Self> {
let mut num_context = BigNumContext::new().unwrap();
let mut c = BigNum::new()?;
let mut x = BigNum::new()?;
let mut y = BigNum::new()?;
let data = channel_id << 1 | upgrade as u32;
let mut no_square = false;
let key = loop {
let mut r = EcPoint::new(e_curve)?;
c.rand(FIELD_BITS, MsbOption::MAYBE_ZERO, false)?;
r.mul(e_curve, base_point, &c, &num_context)?;
r.affine_coordinates(e_curve, &mut x, &mut y, &mut num_context)?;
let mut msg_buffer: [u8; SHA_MSG_LENGTH] = [0; SHA_MSG_LENGTH];
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[0x00] = 0x79;
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 hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32;
msg_buffer[0x00] = 0x5D;
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;
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 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 signature = u64::from_be_bytes(s.to_vec_padded(8)?.try_into().unwrap());
let product_key = Self {
upgrade,
channel_id,
hash,
signature,
auth_info,
};
if 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<bool> {
let mut num_context = BigNumContext::new()?;
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] = (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;
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)?;
y_bin.reverse();
msg_buffer[0x00] = 0x79;
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 hash: u32 = by_dword(&msg_digest[0..4]) & bitmask(31) as u32;
Ok(hash == self.hash)
}
fn from_packed(packed_key: &[u8]) -> Result<Self> {
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 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,
channel_id,
hash,
signature,
auth_info,
})
}
fn pack(&self) -> Vec<u8> {
let mut packed_key: u128 = 0;
packed_key |= (self.auth_info as u128)
<< (SIGNATURE_LENGTH_BITS
+ HASH_LENGTH_BITS
+ CHANNEL_ID_LENGTH_BITS
+ UPGRADE_LENGTH_BITS);
packed_key |= (self.signature as u128)
<< (HASH_LENGTH_BITS + CHANNEL_ID_LENGTH_BITS + UPGRADE_LENGTH_BITS);
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;
packed_key
.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 crate::crypto::EllipticCurve;
#[test]
fn verify_test() {
// Example product key and its BINK ID
let product_key = "R882X-YRGC8-4KYTG-C3FCC-JCFDY";
let bink_id = "54";
// Load keys.json
let path = "keys.json";
let file = File::open(path).unwrap();
let reader = BufReader::new(file);
let keys: serde_json::Value = from_reader(reader).unwrap();
let bink = &keys["BINK"][&bink_id];
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();
let curve = EllipticCurve::new(p, a, b, gx, gy, kx, ky).unwrap();
assert!(super::ProductKey::from_key(&curve, product_key).is_ok());
assert!(super::ProductKey::from_key(&curve, "11111-YRGC8-4KYTG-C3FCC-JCFDY").is_err());
}
}

File diff suppressed because it is too large Load diff

78
umskt/src/confid/mod.rs Normal file
View file

@ -0,0 +1,78 @@
use std::ffi::{CStr, CString};
use thiserror::Error;
mod black_box;
#[derive(Error, Debug, PartialEq, Eq)]
pub enum ConfirmationIdError {
#[error("Installation ID is too short.")]
TooShort,
#[error("Installation ID is too long.")]
TooLarge,
#[error("Invalid character in installation ID.")]
InvalidCharacter,
#[error("Installation ID checksum failed. Please check that it is typed correctly.")]
InvalidCheckDigit,
#[error("Unknown installation ID version.")]
UnknownVersion,
#[error("Unable to generate valid confirmation ID.")]
Unlucky,
}
pub fn generate(installation_id: &str) -> Result<String, ConfirmationIdError> {
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) };
match result {
0 => {}
1 => return Err(ConfirmationIdError::TooShort),
2 => return Err(ConfirmationIdError::TooLarge),
3 => return Err(ConfirmationIdError::InvalidCharacter),
4 => return Err(ConfirmationIdError::InvalidCheckDigit),
5 => return Err(ConfirmationIdError::UnknownVersion),
6 => return Err(ConfirmationIdError::Unlucky),
_ => panic!("Unknown error code: {}", result),
}
unsafe {
Ok(CStr::from_ptr(conf_id.as_ptr() as *const i8)
.to_str()
.unwrap()
.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),
);
}
}

63
umskt/src/crypto.rs Normal file
View file

@ -0,0 +1,63 @@
use anyhow::Result;
use openssl::{
bn::{BigNum, BigNumContext},
ec::{EcGroup, EcPoint},
};
pub struct EllipticCurve {
pub curve: EcGroup,
pub gen_point: EcPoint,
pub pub_point: EcPoint,
}
pub struct PrivateKey {
pub gen_order: BigNum,
pub private_key: BigNum,
}
impl PrivateKey {
pub fn new(gen_order: &str, private_key: &str) -> Result<Self> {
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,
})
}
}
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<Self> {
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,
})
}
}

67
umskt/src/key.rs Normal file
View file

@ -0,0 +1,67 @@
use std::collections::VecDeque;
use anyhow::{anyhow, Result};
use openssl::bn::BigNum;
const PK_LENGTH: usize = 25;
/// The allowed character set in a product key.
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<Vec<u8>> {
let decoded_key: Vec<u8> = cd_key
.chars()
.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 decoded_key {
y.mul_word((PK_LENGTH - 1) as u32).unwrap();
y.add_word(i.into()).unwrap();
}
Ok(y.to_vec())
}
pub(crate) fn base24_encode(byte_seq: &[u8]) -> Result<String> {
let mut z = BigNum::from_slice(byte_seq).unwrap();
let mut out: VecDeque<char> = VecDeque::new();
(0..=24).for_each(|_| out.push_front(KEY_CHARSET[z.div_word(24).unwrap() as usize]));
Ok(out.iter().collect())
}
pub(crate) fn strip_key(in_key: &str) -> Result<String> {
let out_key: String = in_key
.chars()
.filter_map(|c| {
let c = c.to_ascii_uppercase();
if 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)]
mod tests {
#[test]
fn test_base24() {
let input = "JTW3TJ7PFJ7V9CCMX84V9PFT8";
let unbase24 = super::base24_decode(input).unwrap();
println!("{:?}", unbase24);
let base24 = super::base24_encode(&unbase24).unwrap();
println!("{}", base24);
assert_eq!(input, base24);
}
}

6
umskt/src/lib.rs Normal file
View file

@ -0,0 +1,6 @@
pub mod bink1998;
pub mod bink2002;
pub mod confid;
pub mod crypto;
mod key;
mod math;

11
umskt/src/math.rs Normal file
View file

@ -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
}