Skip to content

Commit 3453013

Browse files
authored
Merge pull request #10 from LinuxJedi/se050-strict-derive-read-policy
SE050Sim: enforce applet 7.2 read policy on symmetric key objects
2 parents f4ddf5e + 7cb780a commit 3453013

7 files changed

Lines changed: 339 additions & 22 deletions

File tree

‎SE050Sim/se050-sim/src/dispatch.rs‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -120,7 +120,8 @@ pub fn dispatch(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduResponse {
120120
ApduResponse::success_with_tlvs(
121121
&[crate::tlv::Tlv::new(crate::tlv::TAG_1, &curve_list)])
122122
}
123-
_ => handlers::object_mgmt::handle_read(apdu, store),
123+
_ => handlers::object_mgmt::handle_read(
124+
apdu, store, handlers::ec::strict_ecdh_from_env()),
124125
},
125126

126127
INS_CRYPTO => match (cred_type, apdu.p2) {

‎SE050Sim/se050-sim/src/handlers/aes.rs‎

Lines changed: 80 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
use crate::apdu::*;
2323
use crate::object_store::types::SecureObject;
2424
use crate::object_store::{CryptoObjectState, ObjectStore};
25-
use crate::tlv::{self, Tlv, TAG_1, TAG_2, TAG_3, TAG_4};
25+
use crate::tlv::{self, Tlv, TAG_1, TAG_2, TAG_3, TAG_4, TAG_POLICY};
2626

2727
use aes::cipher::{BlockEncrypt, BlockDecrypt, KeyInit};
2828
use aes::cipher::generic_array::GenericArray;
@@ -82,8 +82,10 @@ pub fn handle_write_aes_key(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduR
8282
}
8383

8484
/// Handle WRITE HMAC key command (WriteSymmKey with P1=HMAC).
85-
/// Tag1=obj_id(4B), Tag3=key_data. HMAC keys have no fixed length, so any
86-
/// non-empty Tag3 value is accepted as-is.
85+
/// Policy(opt), Tag1=obj_id(4B), Tag3=key_data. HMAC keys have no fixed
86+
/// length, so any non-empty Tag3 value is accepted as-is. An attached
87+
/// policy is recorded with the object; the applet 7.2 read-policy
88+
/// contract (see handle_read_object) keys off it.
8789
pub fn handle_write_hmac_key(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduResponse {
8890
let tlvs = match apdu.parse_tlvs() {
8991
Ok(t) => t,
@@ -99,9 +101,20 @@ pub fn handle_write_hmac_key(apdu: &ParsedApdu, store: &mut ObjectStore) -> Apdu
99101
_ => return ApduResponse::error(SW_WRONG_DATA),
100102
};
101103

104+
// A present but malformed (or empty) policy TLV is rejected up front,
105+
// like the applet would, rather than being recorded as "no policy" and
106+
// surfacing later as a strict-mode read denial.
107+
let policy = match tlv::find_tlv(&tlvs, TAG_POLICY) {
108+
Some(t) => match crate::policy::ar_header_union(&t.value) {
109+
Some(header) => Some(header),
110+
None => return ApduResponse::error(SW_WRONG_DATA),
111+
},
112+
None => None,
113+
};
114+
102115
match tlv::find_tlv(&tlvs, TAG_3) {
103116
Some(t) if !t.value.is_empty() => {
104-
store.insert(obj_id, SecureObject::HMACKey { key: t.value.clone() });
117+
store.insert(obj_id, SecureObject::HMACKey { key: t.value.clone(), policy });
105118
ApduResponse::success()
106119
}
107120
_ => ApduResponse::error(SW_WRONG_DATA),
@@ -441,11 +454,73 @@ mod hmac_write_tests {
441454
let resp = dispatch(&apdu, &mut store);
442455
assert_eq!(resp.sw, 0x9000);
443456
match store.get(&[0x00, 0x00, 0x00, 0x66]) {
444-
Some(SecureObject::HMACKey { key: stored }) => assert_eq!(stored, &key),
457+
Some(SecureObject::HMACKey { key: stored, policy }) => {
458+
assert_eq!(stored, &key);
459+
assert_eq!(*policy, None);
460+
}
461+
_ => panic!("HMACKey object not stored"),
462+
}
463+
}
464+
465+
#[test]
466+
fn test_write_hmac_key_records_policy() {
467+
// WriteSymmKey with a leading policy TLV, as sent by
468+
// sss_key_store_set_key when an sss_policy_t is attached. One
469+
// entry: len=8, authId=0, AR header granting read.
470+
let key = vec![0x5Au8; 32];
471+
let header: u32 = crate::policy::POLICY_OBJ_ALLOW_READ | 0x0014_0000;
472+
let mut data = vec![crate::tlv::TAG_POLICY, 0x09, 0x08, 0x00, 0x00, 0x00, 0x00];
473+
data.extend_from_slice(&header.to_be_bytes());
474+
data.extend_from_slice(&[TAG_1, 0x04, 0x00, 0x00, 0x00, 0x67]);
475+
data.push(TAG_3);
476+
data.push(key.len() as u8);
477+
data.extend_from_slice(&key);
478+
479+
let apdu = ParsedApdu {
480+
cla: 0x80,
481+
ins: 0x21,
482+
p1: P1_HMAC,
483+
p2: P2_DEFAULT,
484+
data,
485+
le: None,
486+
};
487+
let mut store = ObjectStore::new();
488+
let resp = dispatch(&apdu, &mut store);
489+
assert_eq!(resp.sw, 0x9000);
490+
match store.get(&[0x00, 0x00, 0x00, 0x67]) {
491+
Some(SecureObject::HMACKey { key: stored, policy }) => {
492+
assert_eq!(stored, &key);
493+
assert_eq!(*policy, Some(header));
494+
}
445495
_ => panic!("HMACKey object not stored"),
446496
}
447497
}
448498

499+
#[test]
500+
fn test_write_hmac_key_malformed_policy_rejected() {
501+
// A policy TLV that does not parse as an entry sequence must fail
502+
// the write with SW_WRONG_DATA, not be recorded as "no policy".
503+
let key = vec![0xA5u8; 32];
504+
let mut data = vec![crate::tlv::TAG_POLICY, 0x03, 0xDE, 0xAD, 0xBE];
505+
data.extend_from_slice(&[TAG_1, 0x04, 0x00, 0x00, 0x00, 0x68]);
506+
data.push(TAG_3);
507+
data.push(key.len() as u8);
508+
data.extend_from_slice(&key);
509+
510+
let apdu = ParsedApdu {
511+
cla: 0x80,
512+
ins: 0x21,
513+
p1: P1_HMAC,
514+
p2: P2_DEFAULT,
515+
data,
516+
le: None,
517+
};
518+
let mut store = ObjectStore::new();
519+
let resp = dispatch(&apdu, &mut store);
520+
assert_eq!(resp.sw, SW_WRONG_DATA);
521+
assert!(store.get(&[0x00, 0x00, 0x00, 0x68]).is_none());
522+
}
523+
449524
#[test]
450525
fn test_write_hmac_key_empty_value_rejected() {
451526
let data = vec![TAG_1, 0x04, 0x00, 0x00, 0x00, 0x66, TAG_3, 0x00];

‎SE050Sim/se050-sim/src/handlers/ec.rs‎

Lines changed: 37 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -463,7 +463,10 @@ pub fn handle_verify(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduResponse
463463

464464
/// Whether the applet 7.2 strict ECDH InObject contract is enforced.
465465
/// Off by default so hosts that predate the contract keep working; set
466-
/// SE050_SIM_STRICT_ECDH=1 to enforce it.
466+
/// SE050_SIM_STRICT_ECDH=1 to enforce it. Strict mode also enforces the
467+
/// derive-target read policy: ReadObject on an HMACKey object is refused
468+
/// with SW_COMMAND_NOT_ALLOWED unless the policy attached at creation
469+
/// grants POLICY_OBJ_ALLOW_READ (see object_mgmt::handle_read).
467470
pub fn strict_ecdh_from_env() -> bool {
468471
std::env::var("SE050_SIM_STRICT_ECDH").map(|v| v == "1").unwrap_or(false)
469472
}
@@ -518,9 +521,9 @@ pub fn handle_ecdh(apdu: &ParsedApdu, store: &mut ObjectStore, strict: bool) ->
518521
// On the real applet the Tag7 target must already exist as an HMACKey
519522
// object; the applet refuses to create it implicitly. In lenient mode a
520523
// missing (or non-HMACKey) target keeps the legacy implicit-create
521-
// behavior instead (target_len None).
522-
let target_len = match store.get(&output_id) {
523-
Some(SecureObject::HMACKey { key }) => Some(key.len()),
524+
// behavior instead (target None).
525+
let target = match store.get(&output_id) {
526+
Some(SecureObject::HMACKey { key, policy }) => Some((key.len(), *policy)),
524527
_ if strict => return ApduResponse::error(SW_CONDITIONS_NOT_SATISFIED),
525528
_ => None,
526529
};
@@ -543,12 +546,14 @@ pub fn handle_ecdh(apdu: &ParsedApdu, store: &mut ObjectStore, strict: bool) ->
543546

544547
match shared_secret {
545548
Some(secret) => {
546-
match target_len {
547-
Some(len) => {
549+
match target {
550+
Some((len, policy)) => {
548551
if secret.len() != len {
549552
return ApduResponse::error(SW_CONDITIONS_NOT_SATISFIED);
550553
}
551-
store.insert(output_id, SecureObject::HMACKey { key: secret });
554+
// The derive overwrites the object's value; the policy
555+
// attached at creation stays with the object.
556+
store.insert(output_id, SecureObject::HMACKey { key: secret, policy });
552557
}
553558
None => {
554559
// Legacy lenient behavior: implicitly create the target
@@ -726,7 +731,8 @@ mod tests {
726731
// HMACKey, in strict and lenient mode alike.
727732
for strict in [true, false] {
728733
let (apdu, mut store, _) = ecdh_inobject_fixture();
729-
store.insert([0, 0, 0, 0x66], SecureObject::HMACKey { key: vec![0u8; 16] });
734+
store.insert([0, 0, 0, 0x66],
735+
SecureObject::HMACKey { key: vec![0u8; 16], policy: None });
730736
let resp = handle_ecdh(&apdu, &mut store, strict);
731737
assert_eq!(resp.sw, SW_CONDITIONS_NOT_SATISFIED, "strict={}", strict);
732738
}
@@ -736,16 +742,37 @@ mod tests {
736742
fn test_ecdh_tag7_precreated_hmackey_succeeds_both_modes() {
737743
for strict in [true, false] {
738744
let (apdu, mut store, expected) = ecdh_inobject_fixture();
739-
store.insert([0, 0, 0, 0x66], SecureObject::HMACKey { key: vec![0u8; 32] });
745+
store.insert([0, 0, 0, 0x66],
746+
SecureObject::HMACKey { key: vec![0u8; 32], policy: None });
740747
let resp = handle_ecdh(&apdu, &mut store, strict);
741748
assert_eq!(resp.sw, 0x9000, "strict={}", strict);
742749
match store.get(&[0, 0, 0, 0x66]) {
743-
Some(SecureObject::HMACKey { key }) => assert_eq!(key, &expected),
750+
Some(SecureObject::HMACKey { key, .. }) => assert_eq!(key, &expected),
744751
other => panic!("expected HMACKey with shared secret, got {:?}", other.is_some()),
745752
}
746753
}
747754
}
748755

756+
#[test]
757+
fn test_ecdh_preserves_target_policy() {
758+
// The policy attached when the derive target was created must
759+
// survive the derive overwriting the value, or a subsequent
760+
// strict-mode ReadObject of the shared secret would be refused.
761+
let (apdu, mut store, expected) = ecdh_inobject_fixture();
762+
let policy = Some(crate::policy::POLICY_OBJ_ALLOW_READ);
763+
store.insert([0, 0, 0, 0x66],
764+
SecureObject::HMACKey { key: vec![0u8; 32], policy });
765+
let resp = handle_ecdh(&apdu, &mut store, true);
766+
assert_eq!(resp.sw, 0x9000);
767+
match store.get(&[0, 0, 0, 0x66]) {
768+
Some(SecureObject::HMACKey { key, policy: p }) => {
769+
assert_eq!(key, &expected);
770+
assert_eq!(*p, policy);
771+
}
772+
other => panic!("expected HMACKey, got {:?}", other.is_some()),
773+
}
774+
}
775+
749776
#[test]
750777
fn test_import_private_only_p256_derives_public() {
751778
// wc_ecc_use_key_id imports a private-only key pair and then reads

‎SE050Sim/se050-sim/src/handlers/object_mgmt.rs‎

Lines changed: 100 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -34,10 +34,12 @@ pub fn handle_write(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduResponse
3434
}
3535
}
3636

37-
/// Handle READ commands for objects.
38-
pub fn handle_read(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduResponse {
37+
/// Handle READ commands for objects. With `strict` (the applet 7.2
38+
/// contract, see ec::strict_ecdh_from_env) ReadObject enforces the
39+
/// symmetric key read policy; size/list/type reads are unaffected.
40+
pub fn handle_read(apdu: &ParsedApdu, store: &mut ObjectStore, strict: bool) -> ApduResponse {
3941
match apdu.p2 {
40-
P2_DEFAULT => handle_read_object(apdu, store),
42+
P2_DEFAULT => handle_read_object(apdu, store, strict),
4143
P2_SIZE => handle_read_size(apdu, store),
4244
P2_LIST => handle_read_id_list(apdu, store),
4345
P2_TYPE => handle_read_type(apdu, store),
@@ -190,7 +192,7 @@ fn handle_write_counter(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduRespo
190192
ApduResponse::success()
191193
}
192194

193-
fn handle_read_object(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduResponse {
195+
fn handle_read_object(apdu: &ParsedApdu, store: &mut ObjectStore, strict: bool) -> ApduResponse {
194196
let tlvs = match apdu.parse_tlvs() {
195197
Ok(t) => t,
196198
Err(_) => return ApduResponse::error(SW_WRONG_DATA),
@@ -238,7 +240,21 @@ fn handle_read_object(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduRespons
238240
SecureObject::AESKey { key } => key.clone(),
239241
SecureObject::UserID { value } => value.clone(),
240242
SecureObject::Counter { value } => value.to_be_bytes().to_vec(),
241-
SecureObject::HMACKey { key } => key.clone(),
243+
SecureObject::HMACKey { key, policy } => {
244+
// Applet 7.2 refuses to export a symmetric key object
245+
// unless the policy attached at creation grants
246+
// POLICY_OBJ_ALLOW_READ; an object created with no
247+
// policy attached is not readable. This is the ECDH
248+
// derive target readback contract, enforced only in
249+
// strict mode so hosts that predate it keep working.
250+
if strict
251+
&& policy.map_or(true,
252+
|p| p & crate::policy::POLICY_OBJ_ALLOW_READ == 0)
253+
{
254+
return ApduResponse::error(SW_COMMAND_NOT_ALLOWED);
255+
}
256+
key.clone()
257+
}
242258
};
243259
ApduResponse::success_with_tlvs(&[Tlv::new(TAG_1, &data)])
244260
}
@@ -347,3 +363,82 @@ fn handle_delete(apdu: &ParsedApdu, store: &mut ObjectStore) -> ApduResponse {
347363
store.remove(&obj_id);
348364
ApduResponse::success()
349365
}
366+
367+
#[cfg(test)]
368+
mod read_policy_tests {
369+
use super::*;
370+
use crate::policy::POLICY_OBJ_ALLOW_READ;
371+
372+
fn read_apdu(obj_id: [u8; 4]) -> ParsedApdu {
373+
ParsedApdu {
374+
cla: 0x80,
375+
ins: INS_READ,
376+
p1: P1_DEFAULT,
377+
p2: P2_DEFAULT,
378+
data: vec![TAG_1, 0x04, obj_id[0], obj_id[1], obj_id[2], obj_id[3]],
379+
le: None,
380+
}
381+
}
382+
383+
#[test]
384+
fn test_strict_read_hmackey_without_policy_returns_6986() {
385+
// Applet 7.2 behavior seen on SE05x hardware: an HMACKey object
386+
// created with no policy attached cannot be read back, so the
387+
// ECDH shared secret export fails unless the derive target was
388+
// created with a read policy.
389+
let mut store = ObjectStore::new();
390+
store.insert([0, 0, 0, 0x66],
391+
SecureObject::HMACKey { key: vec![0xAB; 32], policy: None });
392+
let resp = handle_read(&read_apdu([0, 0, 0, 0x66]), &mut store, true);
393+
assert_eq!(resp.sw, SW_COMMAND_NOT_ALLOWED);
394+
}
395+
396+
#[test]
397+
fn test_strict_read_hmackey_policy_without_read_returns_6986() {
398+
let mut store = ObjectStore::new();
399+
store.insert([0, 0, 0, 0x66],
400+
SecureObject::HMACKey { key: vec![0xAB; 32], policy: Some(0x0014_0000) });
401+
let resp = handle_read(&read_apdu([0, 0, 0, 0x66]), &mut store, true);
402+
assert_eq!(resp.sw, SW_COMMAND_NOT_ALLOWED);
403+
}
404+
405+
#[test]
406+
fn test_strict_read_hmackey_with_read_policy_succeeds() {
407+
let key = vec![0xABu8; 32];
408+
let mut store = ObjectStore::new();
409+
store.insert([0, 0, 0, 0x66],
410+
SecureObject::HMACKey {
411+
key: key.clone(),
412+
policy: Some(POLICY_OBJ_ALLOW_READ | 0x0014_0000),
413+
});
414+
let resp = handle_read(&read_apdu([0, 0, 0, 0x66]), &mut store, true);
415+
assert_eq!(resp.sw, 0x9000);
416+
let tlvs = crate::tlv::parse_tlvs(&resp.data).unwrap();
417+
assert_eq!(tlv::find_tlv(&tlvs, TAG_1).unwrap().value, key);
418+
}
419+
420+
#[test]
421+
fn test_lenient_read_hmackey_without_policy_succeeds() {
422+
// Hosts that predate the applet 7.2 contract keep working when
423+
// strict mode is off.
424+
let key = vec![0xABu8; 32];
425+
let mut store = ObjectStore::new();
426+
store.insert([0, 0, 0, 0x66],
427+
SecureObject::HMACKey { key: key.clone(), policy: None });
428+
let resp = handle_read(&read_apdu([0, 0, 0, 0x66]), &mut store, false);
429+
assert_eq!(resp.sw, 0x9000);
430+
}
431+
432+
#[test]
433+
fn test_strict_read_size_of_unreadable_hmackey_succeeds() {
434+
// Only the object content is policy-guarded; ReadSize must keep
435+
// working since sss_key_store_get_key sizes its buffer with it.
436+
let mut store = ObjectStore::new();
437+
store.insert([0, 0, 0, 0x66],
438+
SecureObject::HMACKey { key: vec![0xAB; 32], policy: None });
439+
let mut apdu = read_apdu([0, 0, 0, 0x66]);
440+
apdu.p2 = P2_SIZE;
441+
let resp = handle_read(&apdu, &mut store, true);
442+
assert_eq!(resp.sw, 0x9000);
443+
}
444+
}

‎SE050Sim/se050-sim/src/lib.rs‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ pub mod apdu;
2323
pub mod dispatch;
2424
pub mod handlers;
2525
pub mod object_store;
26+
pub mod policy;
2627
pub mod t1;
2728
pub mod tlv;
2829
pub mod transport;

‎SE050Sim/se050-sim/src/object_store/types.rs‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,12 @@ pub enum SecureObject {
110110
},
111111
HMACKey {
112112
key: Vec<u8>,
113+
/// Union of the AR headers from the TAG_POLICY TLV attached at
114+
/// creation; None when the object was created with no policy.
115+
/// The applet 7.2 read-policy contract keys off this (see
116+
/// crate::policy).
117+
#[serde(default)]
118+
policy: Option<u32>,
113119
},
114120
}
115121

@@ -166,7 +172,7 @@ impl SecureObject {
166172
SecureObject::Binary { data } => data.len(),
167173
SecureObject::UserID { value } => value.len(),
168174
SecureObject::Counter { .. } => 8,
169-
SecureObject::HMACKey { key } => key.len(),
175+
SecureObject::HMACKey { key, .. } => key.len(),
170176
}
171177
}
172178
}

0 commit comments

Comments
 (0)