1use std::collections::HashSet;
6use std::str::FromStr;
7use std::sync::LazyLock;
8
9use anyhow::Result;
10use cryptoki::object::{Attribute, AttributeInfo, ObjectHandle};
11use cryptoki::session::Session;
12use indexmap::IndexMap;
13use serde::{Deserialize, Serialize};
14use strum::IntoEnumIterator;
15
16use super::AttributeError;
17use super::AttributeType;
18use super::CertificateType;
19use super::Date;
20use super::KeyType;
21use super::MechanismType;
22use super::ObjectClass;
23use super::{AttrData, Redacted};
24
25fn into_kv(attr: &Attribute) -> Result<(AttributeType, AttrData)> {
29 match attr {
30 Attribute::AlwaysAuthenticate(b)
32 | Attribute::AlwaysSensitive(b)
33 | Attribute::Copyable(b)
34 | Attribute::Decrypt(b)
35 | Attribute::Derive(b)
36 | Attribute::Destroyable(b)
37 | Attribute::Encrypt(b)
38 | Attribute::Extractable(b)
39 | Attribute::Local(b)
40 | Attribute::Modifiable(b)
41 | Attribute::NeverExtractable(b)
42 | Attribute::Private(b)
43 | Attribute::Sensitive(b)
44 | Attribute::Sign(b)
45 | Attribute::SignRecover(b)
46 | Attribute::Token(b)
47 | Attribute::Trusted(b)
48 | Attribute::Unwrap(b)
49 | Attribute::Verify(b)
50 | Attribute::VerifyRecover(b)
51 | Attribute::Wrap(b)
52 | Attribute::WrapWithTrusted(b) => Ok((
53 AttributeType::from(attr.attribute_type()),
54 AttrData::from(*b),
55 )),
56 Attribute::ModulusBits(val) | Attribute::ValueLen(val) => Ok((
58 AttributeType::from(attr.attribute_type()),
59 AttrData::from(*val),
60 )),
61 Attribute::Application(bytes) | Attribute::Label(bytes) | Attribute::Url(bytes) => Ok((
63 AttributeType::from(attr.attribute_type()),
64 AttrData::from_ascii_bytes(bytes.as_slice()),
65 )),
66 Attribute::AcIssuer(bytes)
68 | Attribute::AttrTypes(bytes)
69 | Attribute::Base(bytes)
70 | Attribute::CheckValue(bytes)
71 | Attribute::Coefficient(bytes)
72 | Attribute::EcParams(bytes)
73 | Attribute::EcPoint(bytes)
74 | Attribute::Exponent1(bytes)
75 | Attribute::Exponent2(bytes)
76 | Attribute::HashOfIssuerPublicKey(bytes)
77 | Attribute::HashOfSubjectPublicKey(bytes)
78 | Attribute::Issuer(bytes)
79 | Attribute::ObjectId(bytes)
80 | Attribute::Prime(bytes)
81 | Attribute::Prime1(bytes)
82 | Attribute::Prime2(bytes)
83 | Attribute::PrivateExponent(bytes)
84 | Attribute::PublicExponent(bytes)
85 | Attribute::PublicKeyInfo(bytes)
86 | Attribute::Modulus(bytes)
87 | Attribute::Owner(bytes)
88 | Attribute::SerialNumber(bytes)
89 | Attribute::Subject(bytes)
90 | Attribute::Value(bytes)
91 | Attribute::Id(bytes) => Ok((
92 AttributeType::from(attr.attribute_type()),
93 AttrData::from(bytes.as_slice()),
94 )),
95 Attribute::CertificateType(certificate_type) => {
97 let val = CertificateType::from(*certificate_type);
98 Ok((
99 AttributeType::from(attr.attribute_type()),
100 AttrData::from(val),
101 ))
102 }
103 Attribute::Class(object_class) => {
104 let val = ObjectClass::from(*object_class);
105 Ok((
106 AttributeType::from(attr.attribute_type()),
107 AttrData::from(val),
108 ))
109 }
110 Attribute::KeyGenMechanism(mech) => {
111 let val = MechanismType::from(*mech);
112 Ok((
113 AttributeType::from(attr.attribute_type()),
114 AttrData::from(val),
115 ))
116 }
117 Attribute::KeyType(key_type) => {
118 let val = KeyType::from(*key_type);
119 Ok((
120 AttributeType::from(attr.attribute_type()),
121 AttrData::from(val),
122 ))
123 }
124 Attribute::AllowedMechanisms(mechanisms) => {
125 let val = mechanisms
126 .iter()
127 .map(|m| AttrData::from(MechanismType::from(*m)))
128 .collect::<Vec<_>>();
129 Ok((
130 AttributeType::from(attr.attribute_type()),
131 AttrData::List(val),
132 ))
133 }
134 Attribute::EndDate(date) | Attribute::StartDate(date) => {
135 let val = Date::from(*date);
136 Ok((
137 AttributeType::from(attr.attribute_type()),
138 AttrData::Str(val.into()),
139 ))
140 }
141 _ => Err(AttributeError::UnknownAttribute(attr.clone()).into()),
142 }
143}
144
145fn from_kv(atype: AttributeType, data: &AttrData) -> Result<Attribute> {
149 match atype {
150 AttributeType::AcIssuer => Ok(Attribute::AcIssuer(data.try_into()?)),
151 AttributeType::AllowedMechanisms => match data {
152 AttrData::List(v) => {
153 let mechs = v
154 .iter()
155 .map(|a| Ok(MechanismType::try_from(a)?.try_into()?))
156 .collect::<Result<Vec<cryptoki::mechanism::MechanismType>>>()?;
157 Ok(Attribute::AllowedMechanisms(mechs))
158 }
159 _ => Err(AttributeError::InvalidDataType.into()),
160 },
161 AttributeType::AlwaysAuthenticate => Ok(Attribute::AlwaysAuthenticate(data.try_into()?)),
162 AttributeType::AlwaysSensitive => Ok(Attribute::AlwaysSensitive(data.try_into()?)),
163 AttributeType::Application => Ok(Attribute::Application(data.try_into()?)),
164 AttributeType::AttrTypes => Ok(Attribute::AttrTypes(data.try_into()?)),
165 AttributeType::Base => Ok(Attribute::Base(data.try_into()?)),
166 AttributeType::CertificateType => Ok(Attribute::CertificateType(
167 CertificateType::try_from(data)?.try_into()?,
168 )),
169 AttributeType::CheckValue => Ok(Attribute::CheckValue(data.try_into()?)),
170 AttributeType::Class => Ok(Attribute::Class(ObjectClass::try_from(data)?.try_into()?)),
171 AttributeType::Coefficient => Ok(Attribute::Coefficient(data.try_into()?)),
172 AttributeType::Copyable => Ok(Attribute::Copyable(data.try_into()?)),
173 AttributeType::Decrypt => Ok(Attribute::Decrypt(data.try_into()?)),
174 AttributeType::Derive => Ok(Attribute::Derive(data.try_into()?)),
175 AttributeType::Destroyable => Ok(Attribute::Destroyable(data.try_into()?)),
176 AttributeType::EcParams => Ok(Attribute::EcParams(data.try_into()?)),
177 AttributeType::EcPoint => Ok(Attribute::EcPoint(data.try_into()?)),
178 AttributeType::Encrypt => Ok(Attribute::Encrypt(data.try_into()?)),
179 AttributeType::EndDate => Ok(Attribute::EndDate(Date::try_from(data)?.try_into()?)),
180 AttributeType::Exponent1 => Ok(Attribute::Exponent1(data.try_into()?)),
181 AttributeType::Exponent2 => Ok(Attribute::Exponent2(data.try_into()?)),
182 AttributeType::Extractable => Ok(Attribute::Extractable(data.try_into()?)),
183 AttributeType::HashOfIssuerPublicKey => {
184 Ok(Attribute::HashOfIssuerPublicKey(data.try_into()?))
185 }
186 AttributeType::HashOfSubjectPublicKey => {
187 Ok(Attribute::HashOfSubjectPublicKey(data.try_into()?))
188 }
189 AttributeType::Id => Ok(Attribute::Id(data.try_into()?)),
190 AttributeType::Issuer => Ok(Attribute::Issuer(data.try_into()?)),
191 AttributeType::KeyGenMechanism => Ok(Attribute::KeyGenMechanism(
192 MechanismType::try_from(data)?.try_into()?,
193 )),
194 AttributeType::KeyType => Ok(Attribute::KeyType(KeyType::try_from(data)?.try_into()?)),
195 AttributeType::Label => Ok(Attribute::Label(data.try_into()?)),
196 AttributeType::Local => Ok(Attribute::Local(data.try_into()?)),
197 AttributeType::Modifiable => Ok(Attribute::Modifiable(data.try_into()?)),
198 AttributeType::Modulus => Ok(Attribute::Modulus(data.try_into()?)),
199 AttributeType::ModulusBits => Ok(Attribute::ModulusBits(data.try_into()?)),
200 AttributeType::NeverExtractable => Ok(Attribute::NeverExtractable(data.try_into()?)),
201 AttributeType::ObjectId => Ok(Attribute::ObjectId(data.try_into()?)),
202 AttributeType::Owner => Ok(Attribute::Owner(data.try_into()?)),
203 AttributeType::Prime => Ok(Attribute::Prime(data.try_into()?)),
204 AttributeType::Prime1 => Ok(Attribute::Prime1(data.try_into()?)),
205 AttributeType::Prime2 => Ok(Attribute::Prime2(data.try_into()?)),
206 AttributeType::Private => Ok(Attribute::Private(data.try_into()?)),
207 AttributeType::PrivateExponent => Ok(Attribute::PrivateExponent(data.try_into()?)),
208 AttributeType::PublicExponent => Ok(Attribute::PublicExponent(data.try_into()?)),
209 AttributeType::PublicKeyInfo => Ok(Attribute::PublicKeyInfo(data.try_into()?)),
210 AttributeType::Sensitive => Ok(Attribute::Sensitive(data.try_into()?)),
211 AttributeType::SerialNumber => Ok(Attribute::SerialNumber(data.try_into()?)),
212 AttributeType::Sign => Ok(Attribute::Sign(data.try_into()?)),
213 AttributeType::SignRecover => Ok(Attribute::SignRecover(data.try_into()?)),
214 AttributeType::StartDate => Ok(Attribute::StartDate(Date::try_from(data)?.try_into()?)),
215 AttributeType::Subject => Ok(Attribute::Subject(data.try_into()?)),
216 AttributeType::Token => Ok(Attribute::Token(data.try_into()?)),
217 AttributeType::Trusted => Ok(Attribute::Trusted(data.try_into()?)),
218 AttributeType::Unwrap => Ok(Attribute::Unwrap(data.try_into()?)),
219 AttributeType::Url => Ok(Attribute::Url(data.try_into()?)),
220 AttributeType::Value => Ok(Attribute::Value(data.try_into()?)),
221 AttributeType::ValueLen => Ok(Attribute::ValueLen(data.try_into()?)),
222 AttributeType::Verify => Ok(Attribute::Verify(data.try_into()?)),
223 AttributeType::VerifyRecover => Ok(Attribute::VerifyRecover(data.try_into()?)),
224 AttributeType::Wrap => Ok(Attribute::Wrap(data.try_into()?)),
225 AttributeType::WrapWithTrusted => Ok(Attribute::WrapWithTrusted(data.try_into()?)),
226 _ => Err(AttributeError::UnknownAttributeType(atype).into()),
227 }
228}
229
230#[derive(Clone, Debug, Default, Serialize, Deserialize)]
231pub struct AttributeMap(IndexMap<AttributeType, AttrData>);
232
233impl From<&[Attribute]> for AttributeMap {
234 fn from(a: &[Attribute]) -> Self {
235 AttributeMap(
236 a.iter()
237 .map(|a| into_kv(a).expect("convert from attribute"))
238 .collect(),
239 )
240 }
241}
242
243impl AttributeMap {
244 pub fn all() -> &'static [cryptoki::object::AttributeType] {
250 static VALID_TYPES: LazyLock<Vec<cryptoki::object::AttributeType>> = LazyLock::new(|| {
251 AttributeType::iter()
252 .map(|a| Ok(a.try_into()?))
253 .filter(|a| a.is_ok())
254 .collect::<Result<Vec<_>>>()
255 .unwrap()
256 });
257
258 VALID_TYPES.as_slice()
259 }
260
261 pub fn insert(&mut self, key: AttributeType, value: AttrData) -> Option<AttrData> {
264 self.0.insert(key, value)
265 }
266
267 pub fn get(&self, key: &AttributeType) -> Option<&AttrData> {
269 self.0.get(key)
270 }
271
272 pub fn is_empty(&self) -> bool {
274 self.0.is_empty()
275 }
276
277 pub fn to_vec(&self) -> Result<Vec<Attribute>> {
279 self.0.iter().map(|(k, v)| from_kv(*k, v)).collect()
280 }
281
282 pub fn merge(&mut self, other: AttributeMap) {
284 for (k, v) in other.0 {
285 self.insert(k, v);
286 }
287 }
288
289 pub fn redact(&mut self, redactions: &HashSet<AttributeType>) {
290 for (k, v) in self.0.iter_mut() {
291 if redactions.contains(k) && !matches!(v, AttrData::Redacted(_)) {
292 *v = AttrData::Redacted(Redacted::RedactedByTool);
293 }
294 }
295 }
296
297 pub fn from_object(session: &Session, object: ObjectHandle) -> Result<Self> {
299 let all = Self::all();
300 let info = session.get_attribute_info(object, all)?;
301 let mut atypes = Vec::new();
302 for (&a, i) in all.iter().zip(info.iter()) {
303 if a == cryptoki::object::AttributeType::AllowedMechanisms {
306 continue;
307 }
308 if a == cryptoki::object::AttributeType::Value {
313 continue;
314 }
315 if matches!(i, AttributeInfo::Available(_)) {
316 atypes.push(a);
317 }
318 }
319
320 let attrs = session.get_attributes(object, &atypes)?;
321 let mut map = AttributeMap::from(attrs.as_slice());
322
323 let sensitive = map.get(&AttributeType::Sensitive);
324 if sensitive.is_none() || matches!(sensitive, Some(AttrData::Bool(false))) {
325 let value = session
327 .get_attributes(object, &[cryptoki::object::AttributeType::Value])?
328 .remove(0);
329 let (ty, val) = into_kv(&value)?;
330 map.insert(ty, val);
331 } else {
332 map.insert(
334 AttributeType::Value,
335 AttrData::Redacted(Redacted::RedactedByHsm),
336 );
337 }
338
339 for (&a, i) in all.iter().zip(info.iter()) {
340 if matches!(i, AttributeInfo::Sensitive) {
341 map.insert(a.into(), AttrData::Redacted(Redacted::RedactedByHsm));
342 }
343 }
344 Ok(map)
345 }
346}
347
348impl FromStr for AttributeMap {
349 type Err = anyhow::Error;
350
351 fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
353 if let Some(path) = s.strip_prefix('@') {
354 let data = std::fs::read_to_string(path)?;
355 Ok(serde_annotate::from_str(&data)?)
356 } else {
357 Ok(serde_annotate::from_str(s)?)
358 }
359 }
360}
361
362#[cfg(test)]
363mod tests {
364 use super::*;
365
366 #[test]
367 fn test_attribute_to_kv() -> Result<()> {
368 let a = Attribute::Copyable(true);
369 let (ty, data) = into_kv(&a)?;
370 assert_eq!(ty, AttributeType::Copyable);
371 assert_eq!(data, AttrData::Bool(true));
372 Ok(())
373 }
374
375 #[test]
376 fn test_kv_to_attribute() -> Result<()> {
377 let a = from_kv(AttributeType::Copyable, &AttrData::Bool(true))?;
378 assert!(matches!(a, Attribute::Copyable(true)));
379 Ok(())
380 }
381
382 const ATTR_MAP: &str = r#"{
383 "CKA_COPYABLE": true,
384 "CKA_MODULUS_BITS": 3072,
385 "CKA_LABEL": "foo",
386 "CKA_OBJECT_ID": "12:34:56:78",
387 "CKA_CERTIFICATE_TYPE": "CKC_X_509",
388 "CKA_CLASS": "CKO_CERTIFICATE",
389 "CKA_KEY_TYPE": "CKK_RSA",
390 "CKA_KEY_GEN_MECHANISM": "CKM_RSA_PKCS",
391 "CKA_ALLOWED_MECHANISMS": [
392 "CKM_RSA_PKCS",
393 "CKM_RSA_PKCS_KEY_PAIR_GEN"
394 ],
395 "CKA_START_DATE": "2023-02-15"
396}"#;
397
398 #[test]
399 fn test_to_attribute_map() -> Result<()> {
400 let a = [
401 Attribute::Copyable(true),
402 Attribute::ModulusBits(3072u64.into()),
403 Attribute::Label(vec![b'f', b'o', b'o']),
404 Attribute::ObjectId(vec![0x12, 0x34, 0x56, 0x78]),
405 Attribute::CertificateType(CertificateType::X509.try_into()?),
406 Attribute::Class(ObjectClass::Certificate.try_into()?),
407 Attribute::KeyType(KeyType::Rsa.try_into()?),
408 Attribute::KeyGenMechanism(MechanismType::RsaPkcs.try_into()?),
409 Attribute::AllowedMechanisms(vec![
410 MechanismType::RsaPkcs.try_into()?,
411 MechanismType::RsaPkcsKeyPairGen.try_into()?,
412 ]),
413 Attribute::StartDate(Date::from("2023-02-15").try_into()?),
414 ];
415 let am = AttributeMap::from(a.as_slice());
416 let json = serde_json::to_string_pretty(&am)?;
417 assert_eq!(json, ATTR_MAP);
418 Ok(())
419 }
420
421 #[test]
422 fn test_from_attribute_map() -> Result<()> {
423 let map = serde_json::from_str::<AttributeMap>(ATTR_MAP)?;
424 let a = map.to_vec()?;
425 let result = format!("{:x?}", a);
428 assert_eq!(
429 result,
430 "[Copyable(true), ModulusBits(Ulong { val: c00 }), Label([66, 6f, 6f]), ObjectId([12, 34, 56, 78]), CertificateType(CertificateType { val: 0 }), Class(ObjectClass { val: 1 }), KeyType(KeyType { val: 0 }), KeyGenMechanism(MechanismType { val: 1 }), AllowedMechanisms([MechanismType { val: 1 }, MechanismType { val: 0 }]), StartDate(Date { date: CK_DATE { year: [32, 30, 32, 33], month: [30, 32], day: [31, 35] } })]"
431 );
432 Ok(())
433 }
434}