core: decode stored keys with upstream's simple_asn1 shape plus scalar left-padding; deterministic and malformed-input tests

This commit is contained in:
omar committed 2026-10-24 06:18:41 +03:00
1 parent 456041bfde
commit ba4c7ec2af
5 files changed
+106 -83

No files matched your search

+1
View File
@@ -1878,6 +1878,7 @@ dependencies = [
"serde", "serde",
"serde_json", "serde_json",
"sha-1", "sha-1",
"simple_asn1",
"thiserror 2.0.21", "thiserror 2.0.21",
"tokio", "tokio",
"tracing", "tracing",
+2
View File
@@ -22,6 +22,8 @@ num-traits = "0.2"
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = { version = "1", features = ["raw_value", "preserve_order"] } serde_json = { version = "1", features = ["raw_value", "preserve_order"] }
sha-1 = "0.10" sha-1 = "0.10"
# Same DER decoder tsproto-types uses for keys (already in the lock through it).
simple_asn1 = "0.6"
thiserror = "2" thiserror = "2"
tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync", "time"] } tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync", "time"] }
tracing = "0.1" tracing = "0.1"
+81 -74
View File
@@ -3,10 +3,13 @@
//! Upstream `tsproto_types::crypto::EccKeyPrivP256::from_tomcrypt` passes the DER integer's //! Upstream `tsproto_types::crypto::EccKeyPrivP256::from_tomcrypt` passes the DER integer's
//! minimal big-endian bytes to `from_short`, which requires exactly 32 bytes. A private scalar //! minimal big-endian bytes to `from_short`, which requires exactly 32 bytes. A private scalar
//! whose top byte is 0x00 (about 1 key in 256) is therefore written fine by `to_ts` but can never //! whose top byte is 0x00 (about 1 key in 256) is therefore written fine by `to_ts` but can never
//! be read back. This module parses the libtomcrypt DER itself and left-pads the scalar. //! be read back. `private_key_from_tomcrypt` is upstream's decoder — the same `simple_asn1`
//! parser and the same block positions — with the single difference that the scalar is
//! left-padded to 32 bytes. The stored format is unchanged.
use base64::prelude::*; use base64::prelude::*;
use sha1::{Digest, Sha1}; use sha1::{Digest, Sha1};
use simple_asn1::{ASN1Block, BigInt};
use tsclientlib::Identity; use tsclientlib::Identity;
use tsproto_types::crypto::EccKeyPrivP256; use tsproto_types::crypto::EccKeyPrivP256;
@@ -16,68 +19,36 @@ const IDENTITY_OBFUSCATION: &[u8; 128] = b"b9dfaa7bee6ac57ac7b65f1094a1c155\
e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a\ e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a\
62a4a017bb394833aa0983e6e"; 62a4a017bb394833aa0983e6e";
fn tlv<'a>(d: &'a [u8], i: &mut usize) -> Option<(u8, &'a [u8])> {
let tag = *d.get(*i)?;
let first = *d.get(*i + 1)? as usize;
*i += 2;
let len = if first & 0x80 == 0 {
first
} else {
let n = first & 0x7f;
if n == 0 || n > 4 {
return None;
}
let mut l = 0usize;
for _ in 0..n {
l = (l << 8) | *d.get(*i)? as usize;
*i += 1;
}
l
};
let v = d.get(*i..i.checked_add(len)?)?;
*i += len;
Some((tag, v))
}
/// Private key from libtomcrypt DER: `SEQUENCE { BIT STRING flags, INTEGER size, INTEGER x, /// Private key from libtomcrypt DER: `SEQUENCE { BIT STRING flags, INTEGER size, INTEGER x,
/// INTEGER y, INTEGER priv }`, or the 2-bit variant `{ BIT STRING, INTEGER size, INTEGER priv }`. /// INTEGER y, INTEGER priv }`, or the 2-bit variant `{ BIT STRING, INTEGER size, INTEGER priv }`.
pub fn private_key_from_tomcrypt(der: &[u8]) -> Result<EccKeyPrivP256, String> { pub fn private_key_from_tomcrypt(der: &[u8]) -> Result<EccKeyPrivP256, String> {
let mut i = 0; let blocks = simple_asn1::from_der(der).map_err(|e| format!("invalid DER: {e}"))?;
let (tag, seq) = tlv(der, &mut i).ok_or("truncated DER")?; let [ASN1Block::Sequence(_, items)] = blocks.as_slice() else {
if tag != 0x30 || i != der.len() {
return Err("expected a single DER SEQUENCE".into()); return Err("expected a single DER SEQUENCE".into());
} };
let mut j = 0; let Some(ASN1Block::BitString(_, bit_count, flags)) = items.first() else {
let mut items = Vec::new();
while j < seq.len() {
items.push(tlv(seq, &mut j).ok_or("truncated DER element")?);
}
let (bt, bits) = *items.first().ok_or("empty sequence")?;
if bt != 0x03 || bits.len() < 2 {
return Err("expected BIT STRING".into()); return Err("expected BIT STRING".into());
} };
let bit_count = (bits.len() - 1) * 8 - bits[0] as usize; if !flags.first().is_some_and(|f| f & 0x80 != 0) {
if bits[1] & 0x80 == 0 {
return Err("key has no private part".into()); return Err("key has no private part".into());
} }
let priv_index = match bit_count { let priv_index = match bit_count {
1 => 4, 1 => 4,
2 => 2, 2 => 2,
_ => return Err(format!("unexpected flag bit count {bit_count}")), n => return Err(format!("unexpected flag bit count {n}")),
}; };
let (it, int) = *items.get(priv_index).ok_or("missing private INTEGER")?; let Some(ASN1Block::Integer(_, scalar)) = items.get(priv_index) else {
if it != 0x02 { return Err("missing private INTEGER".into());
return Err("expected INTEGER".into()); };
if *scalar < BigInt::default() {
return Err("negative private scalar".into());
} }
let digits: &[u8] = { let (_, digits) = scalar.to_bytes_be();
let first_nonzero = int.iter().position(|b| *b != 0).unwrap_or(int.len());
&int[first_nonzero..]
};
if digits.len() > 32 { if digits.len() > 32 {
return Err("private scalar longer than 32 bytes".into()); return Err("private scalar longer than 32 bytes".into());
} }
let mut short = [0u8; 32]; let mut short = [0u8; 32];
short[32 - digits.len()..].copy_from_slice(digits); short[32 - digits.len()..].copy_from_slice(&digits);
EccKeyPrivP256::from_short(&short).map_err(|e| e.to_string()) EccKeyPrivP256::from_short(&short).map_err(|e| e.to_string())
} }
@@ -117,39 +88,39 @@ pub fn identity_from_ts_str(value: &str) -> Result<Identity, String> {
#[cfg(test)] #[cfg(test)]
pub mod tests { pub mod tests {
use super::*; use super::*;
use simple_asn1::{to_der, ASN1Block::*};
/// A key whose private scalar starts with 0x00 (expected after ~256 draws). /// Valid P-256 scalars (non-zero, below the group order) covering every DER length case.
pub fn zero_leading_key() -> EccKeyPrivP256 { pub const ONE_LEADING_ZERO: [u8; 32] = scalar(1, 0x5a);
for _ in 0..100_000 { const THREE_LEADING_ZEROS: [u8; 32] = scalar(3, 0x5a);
let k = EccKeyPrivP256::create(); /// Top bit set: DER needs a 0x00 sign byte (33 content bytes).
if k.to_short()[0] == 0 { const SIGN_PADDED: [u8; 32] = scalar(0, 0x80);
return k; /// Full width without sign byte (32 content bytes).
} const FULL_WIDTH: [u8; 32] = scalar(0, 0x7f);
const fn scalar(zeros: usize, first: u8) -> [u8; 32] {
let mut s = [0x5au8; 32];
let mut i = 0;
while i < zeros {
s[i] = 0;
i += 1;
} }
panic!("no zero-leading key found"); s[zeros] = first;
s
} }
#[test] pub fn key(s: &[u8; 32]) -> EccKeyPrivP256 { EccKeyPrivP256::from_short(s).unwrap() }
fn zero_leading_scalar_roundtrips_where_upstream_fails() {
let k = zero_leading_key();
let ts = k.to_ts();
assert!(EccKeyPrivP256::from_ts(&ts).is_err(), "upstream bug fixed? then this workaround can go");
let back = private_key_from_ts(&ts).unwrap();
assert_eq!(back.to_short(), k.to_short());
let id = identity_from_ts_str(&format!("42V{}", k.to_ts_obfuscated())).unwrap();
assert_eq!(id.key().to_short(), k.to_short());
assert_eq!(id.counter(), 42);
let plain = identity_from_ts_str(&format!("7V{ts}")).unwrap();
assert_eq!(plain.key().to_short(), k.to_short());
}
#[test] #[test]
fn many_random_keys_roundtrip() { fn fixed_scalars_roundtrip_in_every_stored_form() {
for _ in 0..2000 { for s in [ONE_LEADING_ZERO, THREE_LEADING_ZEROS, SIGN_PADDED, FULL_WIDTH] {
let k = EccKeyPrivP256::create(); let k = key(&s);
assert_eq!(private_key_from_ts(&k.to_ts()).unwrap().to_short(), k.to_short()); let ts = k.to_ts();
let id = identity_from_ts_str(&format!("1V{}", k.to_ts_obfuscated())).unwrap(); assert_eq!(private_key_from_ts(&ts).unwrap().to_short().as_slice(), s.as_slice());
assert_eq!(id.key().to_short(), k.to_short()); let id = identity_from_ts_str(&format!("42V{}", k.to_ts_obfuscated())).unwrap();
assert_eq!(id.key().to_short().as_slice(), s.as_slice());
assert_eq!(id.counter(), 42);
assert_eq!(identity_from_ts_str(&format!("7V{ts}")).unwrap().key().to_short().as_slice(), s.as_slice());
} }
} }
@@ -165,4 +136,40 @@ pub mod tests {
assert!(identity_from_ts_str("xVabc").is_err()); assert!(identity_from_ts_str("xVabc").is_err());
assert!(identity_from_ts_str("1Vgarbage").is_err()); assert!(identity_from_ts_str("1Vgarbage").is_err());
} }
fn int(v: &[u8]) -> ASN1Block { Integer(0, BigInt::from_signed_bytes_be(v)) }
/// libtomcrypt layout with a 1-bit flag string; `priv_value` goes into the private slot.
fn der_with(flags: ASN1Block, priv_value: ASN1Block) -> Vec<u8> {
to_der(&Sequence(0, vec![flags, int(&[32]), int(&[1]), int(&[2]), priv_value])).unwrap()
}
#[test]
fn malformed_keys_are_errors_not_panics() {
let good = key(&ONE_LEADING_ZERO).to_tomcrypt();
assert!(private_key_from_tomcrypt(&good).is_ok());
let private_flag = || BitString(0, 1, vec![0x80]);
let mut cases: Vec<(&str, Vec<u8>)> = vec![
("truncated", good[..good.len() - 1].to_vec()),
("trailing block", [good.clone(), vec![0x05, 0x00]].concat()),
("not a sequence", to_der(&int(&[1])).unwrap()),
("empty sequence", to_der(&Sequence(0, vec![])).unwrap()),
("first item not a BIT STRING", to_der(&Sequence(0, vec![int(&[1]), int(&[1])])).unwrap()),
("public-only flag", der_with(BitString(0, 1, vec![0x00]), int(&ONE_LEADING_ZERO))),
("empty BIT STRING", der_with(BitString(0, 0, vec![]), int(&ONE_LEADING_ZERO))),
("3-bit flags", der_with(BitString(0, 3, vec![0x80]), int(&ONE_LEADING_ZERO))),
("private slot missing", to_der(&Sequence(0, vec![private_flag(), int(&[32])])).unwrap()),
("private slot not INTEGER", der_with(private_flag(), OctetString(0, ONE_LEADING_ZERO.to_vec()))),
("negative scalar", der_with(private_flag(), int(&[0xff]))),
("zero scalar", der_with(private_flag(), int(&[0]))),
("scalar above the group order", der_with(private_flag(), int(&[[0u8].as_slice(), &[0xff; 32]].concat()))),
("33-byte scalar", der_with(private_flag(), int(&[[0x01u8].as_slice(), &[0x5a; 32]].concat()))),
];
// Raw BIT STRING whose unused-bit count exceeds its length, and one with an empty INTEGER.
cases.push(("unused bits > length", vec![0x30, 0x04, 0x03, 0x02, 0x09, 0x80]));
cases.push(("empty INTEGER", vec![0x30, 0x0f, 0x03, 0x02, 0x07, 0x80, 0x02, 0x01, 0x20, 0x02, 0x01, 0x01, 0x02, 0x01, 0x02, 0x02, 0x00]));
for (name, der) in cases {
assert!(private_key_from_tomcrypt(&der).is_err(), "{name}");
}
}
} }
+1 -1
View File
@@ -390,7 +390,7 @@ pub mod tests {
fn zero_leading_private_key_loads_and_imports() { fn zero_leading_private_key_loads_and_imports() {
let dir = TempDir::new("zerolead"); let dir = TempDir::new("zerolead");
let store = Store::new(&dir.0); let store = Store::new(&dir.0);
let key = crate::keyfmt::tests::zero_leading_key(); let key = crate::keyfmt::tests::key(&crate::keyfmt::tests::ONE_LEADING_ZERO);
let mut identity = Identity::new(key, 0); let mut identity = Identity::new(key, 0);
identity.upgrade_level(NEW_IDENTITY_LEVEL); identity.upgrade_level(NEW_IDENTITY_LEVEL);
let uid = store.write_identity(&identity).unwrap(); let uid = store.write_identity(&identity).unwrap();
+21 -8
View File
@@ -110,11 +110,24 @@ initserver, dropping command")` would Debug-print a whole command if one arrived
(~1 in 256 keys) is written by `to_ts` but cannot be read back. The same applies to (~1 in 256 keys) is written by `to_ts` but cannot be read back. The same applies to
`Identity::new_from_ts_str` (ini import). Affected users would have had a permanently refused `Identity::new_from_ts_str` (ini import). Affected users would have had a permanently refused
identity (the core never regenerates). identity (the core never regenerates).
- Fix (`core/src/keyfmt.rs`): the core parses the libtomcrypt DER itself and left-pads the scalar - Fix (`core/src/keyfmt.rs`): upstream's own decoder shape — the same `simple_asn1::from_der`
to 32 bytes; the import path de-obfuscates (same constant as tsproto-types) and then parses (already in the lock through tsproto-types), the same SEQUENCE / BIT STRING / INTEGER positions —
the same way. The stored format is unchanged, so already-written affected files now load. with the single difference that the non-negative scalar is left-padded to 32 bytes. The import
- Tests: a zero-leading key round-trips (and is asserted to still fail upstream); 2000 random keys path de-obfuscates (same constant as tsproto-types) and then parses the same way. The stored
round-trip as plain DER and obfuscated; profile write → load → export → import with a format is unchanged, so already-written affected files now load; no identity is regenerated.
zero-leading key; upstream test vector. 37 unit + 3 smoke pass. Concurrent stress Malformed input returns an error, never panics. (A first hand-written TLV parser from the same
6×40: 0 failures. Release `0.1.2`: 8984064 bytes, SHA256 day was replaced by this after review.)
`db045fc505db09854a4f0495340acf56cec60f1ba0f2f67212fe7f7a36b2106e`, imports only system DLLs. - Permanent tests are deterministic: fixed scalars with one and three leading zero bytes, a
sign-padded scalar (top bit set, 33-byte DER INTEGER) and a full-width one round-trip as plain
DER, obfuscated `…V…` and plain `…V…`; profile write → load → export → import with the
one-zero scalar; upstream test vector (known UID); malformed inputs (truncated, trailing block,
non-SEQUENCE, empty SEQUENCE, wrong first item, public-only flag, empty / 3-bit / unused-bits >
length BIT STRING, missing or non-INTEGER private slot, negative, zero, empty, ≥ group order and
33-byte scalars) are errors. `cargo test --locked`: 37 unit + 3 stdio smoke pass.
- Throwaway evidence (not kept as tests): upstream `from_ts` fails on the fixed one-zero scalar;
100 000 random keys all round-trip through the fix, 387 had a zero top byte and exactly those
387 fail upstream.
- Release `0.1.2` (root `.cargo/config.toml`, static CRT, `-j 2`): 8969216 bytes, SHA256
`6c04f1e6595740f50628374b23216d00b9e7a5bfa5c8c5cba18a8b053eb9bb57`; imports only system DLLs
(ADVAPI32, IPHLPAPI, KERNEL32, api-ms-win-core-synch, bcrypt, bcryptprimitives, ntdll, oleaut32,
ws2_32); `npm run smoke:core` passes (create → restart → same UID).