core: decode stored keys with upstream's simple_asn1 shape plus scalar left-padding; deterministic and malformed-input tests
This commit is contained in:
1 parent
456041bfde
commit
ba4c7ec2af
5 files changed
+106
-83
No files matched your search
Generated
+1
@@ -1878,6 +1878,7 @@ dependencies = [
|
||||
"serde",
|
||||
"serde_json",
|
||||
"sha-1",
|
||||
"simple_asn1",
|
||||
"thiserror 2.0.21",
|
||||
"tokio",
|
||||
"tracing",
|
||||
|
||||
@@ -22,6 +22,8 @@ num-traits = "0.2"
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = { version = "1", features = ["raw_value", "preserve_order"] }
|
||||
sha-1 = "0.10"
|
||||
# Same DER decoder tsproto-types uses for keys (already in the lock through it).
|
||||
simple_asn1 = "0.6"
|
||||
thiserror = "2"
|
||||
tokio = { version = "1", features = ["rt", "macros", "io-std", "io-util", "sync", "time"] }
|
||||
tracing = "0.1"
|
||||
|
||||
+81
-74
@@ -3,10 +3,13 @@
|
||||
//! 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
|
||||
//! 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 sha1::{Digest, Sha1};
|
||||
use simple_asn1::{ASN1Block, BigInt};
|
||||
use tsclientlib::Identity;
|
||||
use tsproto_types::crypto::EccKeyPrivP256;
|
||||
|
||||
@@ -16,68 +19,36 @@ const IDENTITY_OBFUSCATION: &[u8; 128] = b"b9dfaa7bee6ac57ac7b65f1094a1c155\
|
||||
e747327bc2fe5d51c512023fe54a280201004e90ad1daaae1075d53b7d571c30e063b5a\
|
||||
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,
|
||||
/// 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> {
|
||||
let mut i = 0;
|
||||
let (tag, seq) = tlv(der, &mut i).ok_or("truncated DER")?;
|
||||
if tag != 0x30 || i != der.len() {
|
||||
let blocks = simple_asn1::from_der(der).map_err(|e| format!("invalid DER: {e}"))?;
|
||||
let [ASN1Block::Sequence(_, items)] = blocks.as_slice() else {
|
||||
return Err("expected a single DER SEQUENCE".into());
|
||||
}
|
||||
let mut j = 0;
|
||||
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 {
|
||||
};
|
||||
let Some(ASN1Block::BitString(_, bit_count, flags)) = items.first() else {
|
||||
return Err("expected BIT STRING".into());
|
||||
}
|
||||
let bit_count = (bits.len() - 1) * 8 - bits[0] as usize;
|
||||
if bits[1] & 0x80 == 0 {
|
||||
};
|
||||
if !flags.first().is_some_and(|f| f & 0x80 != 0) {
|
||||
return Err("key has no private part".into());
|
||||
}
|
||||
let priv_index = match bit_count {
|
||||
1 => 4,
|
||||
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")?;
|
||||
if it != 0x02 {
|
||||
return Err("expected INTEGER".into());
|
||||
let Some(ASN1Block::Integer(_, scalar)) = items.get(priv_index) else {
|
||||
return Err("missing private INTEGER".into());
|
||||
};
|
||||
if *scalar < BigInt::default() {
|
||||
return Err("negative private scalar".into());
|
||||
}
|
||||
let digits: &[u8] = {
|
||||
let first_nonzero = int.iter().position(|b| *b != 0).unwrap_or(int.len());
|
||||
&int[first_nonzero..]
|
||||
};
|
||||
let (_, digits) = scalar.to_bytes_be();
|
||||
if digits.len() > 32 {
|
||||
return Err("private scalar longer than 32 bytes".into());
|
||||
}
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -117,39 +88,39 @@ pub fn identity_from_ts_str(value: &str) -> Result<Identity, String> {
|
||||
#[cfg(test)]
|
||||
pub mod tests {
|
||||
use super::*;
|
||||
use simple_asn1::{to_der, ASN1Block::*};
|
||||
|
||||
/// A key whose private scalar starts with 0x00 (expected after ~256 draws).
|
||||
pub fn zero_leading_key() -> EccKeyPrivP256 {
|
||||
for _ in 0..100_000 {
|
||||
let k = EccKeyPrivP256::create();
|
||||
if k.to_short()[0] == 0 {
|
||||
return k;
|
||||
}
|
||||
/// Valid P-256 scalars (non-zero, below the group order) covering every DER length case.
|
||||
pub const ONE_LEADING_ZERO: [u8; 32] = scalar(1, 0x5a);
|
||||
const THREE_LEADING_ZEROS: [u8; 32] = scalar(3, 0x5a);
|
||||
/// Top bit set: DER needs a 0x00 sign byte (33 content bytes).
|
||||
const SIGN_PADDED: [u8; 32] = scalar(0, 0x80);
|
||||
/// 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]
|
||||
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());
|
||||
}
|
||||
pub fn key(s: &[u8; 32]) -> EccKeyPrivP256 { EccKeyPrivP256::from_short(s).unwrap() }
|
||||
|
||||
#[test]
|
||||
fn many_random_keys_roundtrip() {
|
||||
for _ in 0..2000 {
|
||||
let k = EccKeyPrivP256::create();
|
||||
assert_eq!(private_key_from_ts(&k.to_ts()).unwrap().to_short(), k.to_short());
|
||||
let id = identity_from_ts_str(&format!("1V{}", k.to_ts_obfuscated())).unwrap();
|
||||
assert_eq!(id.key().to_short(), k.to_short());
|
||||
fn fixed_scalars_roundtrip_in_every_stored_form() {
|
||||
for s in [ONE_LEADING_ZERO, THREE_LEADING_ZEROS, SIGN_PADDED, FULL_WIDTH] {
|
||||
let k = key(&s);
|
||||
let ts = k.to_ts();
|
||||
assert_eq!(private_key_from_ts(&ts).unwrap().to_short().as_slice(), s.as_slice());
|
||||
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("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
@@ -390,7 +390,7 @@ pub mod tests {
|
||||
fn zero_leading_private_key_loads_and_imports() {
|
||||
let dir = TempDir::new("zerolead");
|
||||
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);
|
||||
identity.upgrade_level(NEW_IDENTITY_LEVEL);
|
||||
let uid = store.write_identity(&identity).unwrap();
|
||||
|
||||
@@ -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
|
||||
`Identity::new_from_ts_str` (ini import). Affected users would have had a permanently refused
|
||||
identity (the core never regenerates).
|
||||
- Fix (`core/src/keyfmt.rs`): the core parses the libtomcrypt DER itself and left-pads the scalar
|
||||
to 32 bytes; the import path de-obfuscates (same constant as tsproto-types) and then parses
|
||||
the same way. The stored format is unchanged, so already-written affected files now load.
|
||||
- Tests: a zero-leading key round-trips (and is asserted to still fail upstream); 2000 random keys
|
||||
round-trip as plain DER and obfuscated; profile write → load → export → import with a
|
||||
zero-leading key; upstream test vector. 37 unit + 3 smoke pass. Concurrent stress
|
||||
6×40: 0 failures. Release `0.1.2`: 8984064 bytes, SHA256
|
||||
`db045fc505db09854a4f0495340acf56cec60f1ba0f2f67212fe7f7a36b2106e`, imports only system DLLs.
|
||||
- Fix (`core/src/keyfmt.rs`): upstream's own decoder shape — the same `simple_asn1::from_der`
|
||||
(already in the lock through tsproto-types), the same SEQUENCE / BIT STRING / INTEGER positions —
|
||||
with the single difference that the non-negative scalar is left-padded to 32 bytes. The import
|
||||
path de-obfuscates (same constant as tsproto-types) and then parses the same way. The stored
|
||||
format is unchanged, so already-written affected files now load; no identity is regenerated.
|
||||
Malformed input returns an error, never panics. (A first hand-written TLV parser from the same
|
||||
day was replaced by this after review.)
|
||||
- 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).
|
||||
Reference in new issue
Block a user