1use crate::clusters::generated::tls_certificate_management as spec_tls;
27use crate::dm::spec::{Conforming, Optional};
28use crate::dm::{Resolved, ResolvedCommand};
29use crate::im::{ClusterHandler, ClusterId, CommandId, InteractionContext, Status, StatusIb};
30use crate::msg::FabricIndex;
31use crate::tlv::{Tag, TlvWriter, ToTlv};
32
33use super::{
34 CERTIFICATE_MAX, ClientEntry, FINGERPRINT_FIELD_MAX, INTERMEDIATES_MAX, NONCE_LEN, RootEntry,
35 Slot, TlsCaid, TlsCcdid, TlsCertificateHooks, TlsTables, clear_client, fingerprint, visible,
36};
37use crate::clusters::Cluster;
38
39pub use spec_tls::attribute::{
40 MAX_CLIENT_CERTIFICATES, MAX_ROOT_CERTIFICATES, PROVISIONED_CLIENT_CERTIFICATES,
41 PROVISIONED_ROOT_CERTIFICATES,
42};
43pub use spec_tls::command::{
44 CLIENT_CSR, CLIENT_CSR_RESPONSE, FIND_CLIENT_CERTIFICATE, FIND_CLIENT_CERTIFICATE_RESPONSE,
45 FIND_ROOT_CERTIFICATE, FIND_ROOT_CERTIFICATE_RESPONSE, LOOKUP_CLIENT_CERTIFICATE,
46 LOOKUP_CLIENT_CERTIFICATE_RESPONSE, LOOKUP_ROOT_CERTIFICATE, LOOKUP_ROOT_CERTIFICATE_RESPONSE,
47 PROVISION_CLIENT_CERTIFICATE, PROVISION_ROOT_CERTIFICATE, PROVISION_ROOT_CERTIFICATE_RESPONSE,
48 REMOVE_CLIENT_CERTIFICATE, REMOVE_ROOT_CERTIFICATE,
49};
50pub use spec_tls::{ID, PICS, REVISION};
51
52#[derive(Debug)]
54pub struct CertificateManagement<
55 'a,
56 H: TlsCertificateHooks,
57 const R: usize,
58 const C: usize,
59 const E: usize,
60> {
61 tables: &'a TlsTables<R, C, E>,
62 hooks: &'a H,
63}
64
65impl<'a, H: TlsCertificateHooks, const R: usize, const C: usize, const E: usize>
66 CertificateManagement<'a, H, R, C, E>
67{
68 #[must_use]
70 pub const fn new(tables: &'a TlsTables<R, C, E>, hooks: &'a H) -> Self {
71 Self { tables, hooks }
72 }
73
74 pub fn conforming(
76 feature_map: u32,
77 optional: &Optional<'_>,
78 ) -> crate::error::Result<Conforming<4, 9, 6, 0>> {
79 Conforming::new(&spec_tls::CLUSTER, feature_map, optional)
80 }
81
82 #[must_use]
84 pub const fn tables(&self) -> &'a TlsTables<R, C, E> {
85 self.tables
86 }
87}
88
89fn find_root<const R: usize, const C: usize, const E: usize>(
94 tables: &TlsTables<R, C, E>,
95 fabric: FabricIndex,
96 caid: TlsCaid,
97) -> Result<RootEntry, Status> {
98 tables
99 .roots()
100 .iter()
101 .find(|r| r.caid == caid && r.fabric_index == fabric)
102 .copied()
103 .ok_or(Status::NotFound)
104}
105
106fn find_client<const R: usize, const C: usize, const E: usize>(
107 tables: &TlsTables<R, C, E>,
108 fabric: FabricIndex,
109 ccdid: TlsCcdid,
110) -> Result<ClientEntry, Status> {
111 tables
112 .clients()
113 .iter()
114 .find(|c| c.ccdid == ccdid && c.fabric_index == fabric)
115 .copied()
116 .ok_or(Status::NotFound)
117}
118
119impl<H: TlsCertificateHooks, const R: usize, const C: usize, const E: usize> ClusterHandler
120 for CertificateManagement<'_, H, R, C, E>
121{
122 fn on_lifecycle(&self, event: crate::im::Lifecycle) {
126 if let crate::im::Lifecycle::FabricRemoved(fabric) = event {
127 self.tables.remove_fabric(fabric, self.hooks);
128 }
129 }
130 fn read(
131 &self,
132 resolved: &Resolved<'_>,
133 ctx: &InteractionContext<'_>,
134 w: &mut TlvWriter<'_>,
135 tag: Tag,
136 ) -> Result<(), Status> {
137 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
138 match resolved.attribute {
139 MAX_ROOT_CERTIFICATES => full(w.unsigned(tag, u64::from(self.tables.max_roots()))),
140 MAX_CLIENT_CERTIFICATES => full(w.unsigned(tag, u64::from(self.tables.max_clients()))),
141 PROVISIONED_ROOT_CERTIFICATES => {
142 let roots = self.tables.roots();
143 full(w.start_array(tag))?;
144 for root in roots.iter().filter(|r| visible(ctx, r.fabric_index)) {
145 full(w.start_structure(Tag::Anonymous))?;
146 full(w.unsigned(Tag::Context(0), u64::from(root.caid)))?;
147 if ctx.large_messages {
152 self.hooks.write_certificate(
153 Slot::Root {
154 fabric_index: root.fabric_index,
155 caid: root.caid,
156 },
157 w,
158 Tag::Context(1),
159 )?;
160 }
161 full(w.unsigned(Tag::Context(254), u64::from(root.fabric_index.0)))?;
162 full(w.end_container())?;
163 }
164 full(w.end_container())
165 }
166 PROVISIONED_CLIENT_CERTIFICATES => {
167 let clients = self.tables.clients();
168 full(w.start_array(tag))?;
169 for client in clients.iter().filter(|c| visible(ctx, c.fabric_index)) {
170 full(w.start_structure(Tag::Anonymous))?;
171 full(w.unsigned(Tag::Context(0), u64::from(client.ccdid)))?;
172 self.write_client_certificate(client, ctx.large_messages, w)?;
173 full(w.unsigned(Tag::Context(254), u64::from(client.fabric_index.0)))?;
174 full(w.end_container())?;
175 }
176 full(w.end_container())
177 }
178 _ => Err(Status::UnsupportedAttribute),
179 }
180 }
181
182 fn invoke(
183 &self,
184 resolved: &ResolvedCommand<'_>,
185 fields: Option<&[u8]>,
186 ctx: &InteractionContext<'_>,
187 w: &mut TlvWriter<'_>,
188 tag: Tag,
189 ) -> Result<Option<CommandId>, StatusIb> {
190 let fabric = ctx
193 .fabric_index
194 .filter(|f| f.0 != 0)
195 .ok_or(StatusIb::from(Status::UnsupportedAccess))?;
196 let payload = fields.ok_or(StatusIb::from(Status::InvalidCommand))?;
197 match resolved.command.id {
198 PROVISION_ROOT_CERTIFICATE => self.provision_root(fabric, payload, w, tag),
199 FIND_ROOT_CERTIFICATE => self.find_roots(fabric, payload, w, tag),
200 LOOKUP_ROOT_CERTIFICATE => self.lookup_root(fabric, payload, w, tag),
201 REMOVE_ROOT_CERTIFICATE => self.remove_root(fabric, payload),
202 CLIENT_CSR => self.client_csr(fabric, payload, w, tag),
203 PROVISION_CLIENT_CERTIFICATE => self.provision_client(fabric, payload),
204 FIND_CLIENT_CERTIFICATE => self.find_clients(fabric, payload, w, tag),
205 LOOKUP_CLIENT_CERTIFICATE => self.lookup_client(fabric, payload, w, tag),
206 REMOVE_CLIENT_CERTIFICATE => self.remove_client(fabric, payload),
207 _ => Err(Status::UnsupportedCommand.into()),
208 }
209 }
210}
211
212impl<H: TlsCertificateHooks, const R: usize, const C: usize, const E: usize>
213 CertificateManagement<'_, H, R, C, E>
214{
215 fn provision_root(
217 &self,
218 fabric: FabricIndex,
219 payload: &[u8],
220 w: &mut TlvWriter<'_>,
221 tag: Tag,
222 ) -> Result<Option<CommandId>, StatusIb> {
223 let decoded: spec_tls::ProvisionRootCertificateFields<'_> =
224 crate::clusters::decode_fields(payload)?;
225 if decoded.certificate.len() > CERTIFICATE_MAX {
226 return Err(Status::ConstraintError.into());
227 }
228 if !self.tables.time_known() {
231 return Err(Status::InvalidInState.into());
232 }
233 if !self.hooks.is_valid_certificate(decoded.certificate) {
234 return Err(Status::DynamicConstraintError.into());
235 }
236 let print = fingerprint(decoded.certificate);
237 if self
240 .tables
241 .roots()
242 .iter()
243 .any(|r| r.fabric_index == fabric && r.fingerprint == print)
244 {
245 return Err(Status::AlreadyExists.into());
246 }
247
248 let caid = match decoded.caid.0 {
249 None => {
250 if self.tables.count_roots(fabric) >= usize::from(self.tables.max_roots()) {
251 return Err(Status::ResourceExhausted.into());
252 }
253 let taken =
254 |candidate: TlsCaid| self.tables.roots().iter().any(|r| r.caid == candidate);
255 let caid = TlsTables::<R, C, E>::allocate(&self.tables.next_caid, taken)
256 .ok_or(StatusIb::from(Status::ResourceExhausted))?;
257 self.hooks.save(
258 Slot::Root {
259 fabric_index: fabric,
260 caid,
261 },
262 decoded.certificate,
263 )?;
264 self.tables
265 .roots
266 .borrow_mut()
267 .push(RootEntry {
268 fabric_index: fabric,
269 caid,
270 fingerprint: print,
271 })
272 .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
273 caid
274 }
275 Some(caid) => {
276 let existing = find_root(self.tables, fabric, caid)?;
277 self.hooks.save(
278 Slot::Root {
279 fabric_index: fabric,
280 caid: existing.caid,
281 },
282 decoded.certificate,
283 )?;
284 if let Some(entry) = self
285 .tables
286 .roots
287 .borrow_mut()
288 .iter_mut()
289 .find(|r| r.caid == caid && r.fabric_index == fabric)
290 {
291 entry.fingerprint = print;
292 }
293 caid
294 }
295 };
296 spec_tls::ProvisionRootCertificateResponseFields { caid }
297 .to_tlv(w, tag)
298 .map_err(|_| StatusIb::from(Status::Failure))?;
299 Ok(Some(PROVISION_ROOT_CERTIFICATE_RESPONSE))
300 }
301
302 fn find_roots(
305 &self,
306 fabric: FabricIndex,
307 payload: &[u8],
308 w: &mut TlvWriter<'_>,
309 tag: Tag,
310 ) -> Result<Option<CommandId>, StatusIb> {
311 let decoded: spec_tls::FindRootCertificateFields = crate::clusters::decode_fields(payload)?;
312 if self.tables.roots().is_empty() {
313 return Err(Status::NotFound.into());
314 }
315 let wanted = decoded.caid.0;
316 let matches: heapless::Vec<RootEntry, R> = self
317 .tables
318 .roots()
319 .iter()
320 .filter(|r| r.fabric_index == fabric && wanted.is_none_or(|caid| r.caid == caid))
321 .copied()
322 .collect();
323 if matches.is_empty() {
326 return Err(Status::NotFound.into());
327 }
328 let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
329 full(w.start_structure(tag))?;
330 full(w.start_array(Tag::Context(0)))?;
331 for root in &matches {
332 full(w.start_structure(Tag::Anonymous))?;
333 full(w.unsigned(Tag::Context(0), u64::from(root.caid)))?;
334 self.hooks.write_certificate(
335 Slot::Root {
336 fabric_index: root.fabric_index,
337 caid: root.caid,
338 },
339 w,
340 Tag::Context(1),
341 )?;
342 full(w.unsigned(Tag::Context(254), u64::from(root.fabric_index.0)))?;
343 full(w.end_container())?;
344 }
345 full(w.end_container())?;
346 full(w.end_container())?;
347 Ok(Some(FIND_ROOT_CERTIFICATE_RESPONSE))
348 }
349
350 fn lookup_root(
352 &self,
353 fabric: FabricIndex,
354 payload: &[u8],
355 w: &mut TlvWriter<'_>,
356 tag: Tag,
357 ) -> Result<Option<CommandId>, StatusIb> {
358 let decoded: spec_tls::LookupRootCertificateFields<'_> =
359 crate::clusters::decode_fields(payload)?;
360 if decoded.fingerprint.len() > FINGERPRINT_FIELD_MAX {
361 return Err(Status::ConstraintError.into());
362 }
363 if self.tables.roots().is_empty() {
364 return Err(Status::NotFound.into());
365 }
366 let caid = self
367 .tables
368 .roots()
369 .iter()
370 .find(|r| r.fabric_index == fabric && r.fingerprint.as_slice() == decoded.fingerprint)
371 .map(|r| r.caid)
372 .ok_or(StatusIb::from(Status::NotFound))?;
373 spec_tls::LookupRootCertificateResponseFields { caid }
374 .to_tlv(w, tag)
375 .map_err(|_| StatusIb::from(Status::Failure))?;
376 Ok(Some(LOOKUP_ROOT_CERTIFICATE_RESPONSE))
377 }
378
379 fn remove_root(
381 &self,
382 fabric: FabricIndex,
383 payload: &[u8],
384 ) -> Result<Option<CommandId>, StatusIb> {
385 let decoded: spec_tls::RemoveRootCertificateFields =
386 crate::clusters::decode_fields(payload)?;
387 if self.tables.roots().is_empty() {
388 return Err(Status::NotFound.into());
389 }
390 let entry = find_root(self.tables, fabric, decoded.caid)?;
391 if self
395 .tables
396 .endpoints()
397 .iter()
398 .any(|e| e.caid == decoded.caid)
399 {
400 return Err(Status::InvalidInState.into());
401 }
402 self.hooks.clear(Slot::Root {
403 fabric_index: entry.fabric_index,
404 caid: entry.caid,
405 });
406 self.tables
407 .roots
408 .borrow_mut()
409 .retain(|r| !(r.caid == entry.caid && r.fabric_index == fabric));
410 Ok(None)
411 }
412
413 fn client_csr(
415 &self,
416 fabric: FabricIndex,
417 payload: &[u8],
418 w: &mut TlvWriter<'_>,
419 tag: Tag,
420 ) -> Result<Option<CommandId>, StatusIb> {
421 let decoded: spec_tls::ClientCSRFields<'_> = crate::clusters::decode_fields(payload)?;
422 if decoded.nonce.len() != NONCE_LEN {
424 return Err(Status::ConstraintError.into());
425 }
426 let ccdid = match decoded.ccdid.0 {
427 None => {
428 if self.tables.count_clients(fabric) >= usize::from(self.tables.max_clients()) {
429 return Err(Status::ResourceExhausted.into());
430 }
431 let taken = |candidate: TlsCcdid| {
432 self.tables.clients().iter().any(|c| c.ccdid == candidate)
433 };
434 let ccdid = TlsTables::<R, C, E>::allocate(&self.tables.next_ccdid, taken)
435 .ok_or(StatusIb::from(Status::ResourceExhausted))?;
436 self.hooks.generate_key(ccdid)?;
439 self.tables
440 .clients
441 .borrow_mut()
442 .push(ClientEntry {
443 fabric_index: fabric,
444 ccdid,
445 fingerprint: None,
448 intermediates: 0,
449 })
450 .map_err(|_| StatusIb::from(Status::ResourceExhausted))?;
451 ccdid
452 }
453 Some(ccdid) => find_client(self.tables, fabric, ccdid)?.ccdid,
454 };
455 let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
456 full(w.start_structure(tag))?;
457 full(w.unsigned(Tag::Context(0), u64::from(ccdid)))?;
458 self.hooks
459 .write_csr(ccdid, decoded.nonce, w, Tag::Context(1), Tag::Context(2))?;
460 full(w.end_container())?;
461 Ok(Some(CLIENT_CSR_RESPONSE))
462 }
463
464 fn provision_client(
466 &self,
467 fabric: FabricIndex,
468 payload: &[u8],
469 ) -> Result<Option<CommandId>, StatusIb> {
470 let decoded: spec_tls::ProvisionClientCertificateFields<'_> =
471 crate::clusters::decode_fields(payload)?;
472 if decoded.client_certificate.len() > CERTIFICATE_MAX {
473 return Err(Status::ConstraintError.into());
474 }
475 if self.tables.clients().is_empty() {
476 return Err(Status::NotFound.into());
477 }
478 let print = fingerprint(decoded.client_certificate);
479 if self
480 .tables
481 .clients()
482 .iter()
483 .any(|c| c.fabric_index == fabric && c.fingerprint == Some(print))
484 {
485 return Err(Status::AlreadyExists.into());
486 }
487 let entry = find_client(self.tables, fabric, decoded.ccdid)?;
488 if !self.hooks.is_valid_certificate(decoded.client_certificate) {
489 return Err(Status::DynamicConstraintError.into());
490 }
491 if !self
495 .hooks
496 .key_matches(entry.ccdid, decoded.client_certificate)
497 {
498 return Err(Status::DynamicConstraintError.into());
499 }
500
501 let mut count = 0u8;
505 for intermediate in decoded.intermediate_certificates.iter() {
506 let der = intermediate.map_err(|_| StatusIb::from(Status::InvalidCommand))?;
507 if der.len() > CERTIFICATE_MAX || usize::from(count) >= INTERMEDIATES_MAX {
508 return Err(Status::ConstraintError.into());
509 }
510 if !self.hooks.is_valid_certificate(der) {
511 return Err(Status::DynamicConstraintError.into());
512 }
513 count = count.saturating_add(1);
514 }
515
516 clear_client(self.hooks, fabric, entry.ccdid, entry.intermediates);
519 self.hooks.save(
520 Slot::Client {
521 fabric_index: fabric,
522 ccdid: entry.ccdid,
523 },
524 decoded.client_certificate,
525 )?;
526 let mut index = 0u8;
527 for intermediate in decoded.intermediate_certificates.iter() {
528 let der = intermediate.map_err(|_| StatusIb::from(Status::InvalidCommand))?;
529 self.hooks.save(
530 Slot::Intermediate {
531 fabric_index: fabric,
532 ccdid: entry.ccdid,
533 index,
534 },
535 der,
536 )?;
537 index = index.saturating_add(1);
538 }
539 if let Some(stored) = self
540 .tables
541 .clients
542 .borrow_mut()
543 .iter_mut()
544 .find(|c| c.ccdid == entry.ccdid && c.fabric_index == fabric)
545 {
546 stored.fingerprint = Some(print);
547 stored.intermediates = count;
548 }
549 Ok(None)
550 }
551
552 fn find_clients(
554 &self,
555 fabric: FabricIndex,
556 payload: &[u8],
557 w: &mut TlvWriter<'_>,
558 tag: Tag,
559 ) -> Result<Option<CommandId>, StatusIb> {
560 let decoded: spec_tls::FindClientCertificateFields =
561 crate::clusters::decode_fields(payload)?;
562 if self.tables.clients().is_empty() {
563 return Err(Status::NotFound.into());
564 }
565 let wanted = decoded.ccdid.0;
566 let matches: heapless::Vec<ClientEntry, C> = self
567 .tables
568 .clients()
569 .iter()
570 .filter(|c| c.fabric_index == fabric && wanted.is_none_or(|ccdid| c.ccdid == ccdid))
571 .copied()
572 .collect();
573 if matches.is_empty() {
574 return Err(Status::NotFound.into());
575 }
576 let full = |r: crate::error::Result<()>| r.map_err(|_| StatusIb::from(Status::Failure));
577 full(w.start_structure(tag))?;
578 full(w.start_array(Tag::Context(0)))?;
579 for client in &matches {
580 full(w.start_structure(Tag::Anonymous))?;
581 full(w.unsigned(Tag::Context(0), u64::from(client.ccdid)))?;
582 self.write_client_certificate(client, true, w)?;
584 full(w.unsigned(Tag::Context(254), u64::from(client.fabric_index.0)))?;
585 full(w.end_container())?;
586 }
587 full(w.end_container())?;
588 full(w.end_container())?;
589 Ok(Some(FIND_CLIENT_CERTIFICATE_RESPONSE))
590 }
591
592 fn lookup_client(
594 &self,
595 fabric: FabricIndex,
596 payload: &[u8],
597 w: &mut TlvWriter<'_>,
598 tag: Tag,
599 ) -> Result<Option<CommandId>, StatusIb> {
600 let decoded: spec_tls::LookupClientCertificateFields<'_> =
601 crate::clusters::decode_fields(payload)?;
602 if decoded.fingerprint.len() > FINGERPRINT_FIELD_MAX {
603 return Err(Status::ConstraintError.into());
604 }
605 if self.tables.clients().is_empty() {
606 return Err(Status::NotFound.into());
607 }
608 let ccdid = self
609 .tables
610 .clients()
611 .iter()
612 .find(|c| {
613 c.fabric_index == fabric
614 && c.fingerprint
615 .is_some_and(|print| print.as_slice() == decoded.fingerprint)
616 })
617 .map(|c| c.ccdid)
618 .ok_or(StatusIb::from(Status::NotFound))?;
619 spec_tls::LookupClientCertificateResponseFields { ccdid }
620 .to_tlv(w, tag)
621 .map_err(|_| StatusIb::from(Status::Failure))?;
622 Ok(Some(LOOKUP_CLIENT_CERTIFICATE_RESPONSE))
623 }
624
625 fn remove_client(
627 &self,
628 fabric: FabricIndex,
629 payload: &[u8],
630 ) -> Result<Option<CommandId>, StatusIb> {
631 let decoded: spec_tls::RemoveClientCertificateFields =
632 crate::clusters::decode_fields(payload)?;
633 if self.tables.clients().is_empty() {
634 return Err(Status::NotFound.into());
635 }
636 let entry = find_client(self.tables, fabric, decoded.ccdid)?;
637 if self
638 .tables
639 .endpoints()
640 .iter()
641 .any(|e| e.ccdid == Some(decoded.ccdid))
642 {
643 return Err(Status::InvalidInState.into());
644 }
645 clear_client(self.hooks, fabric, entry.ccdid, entry.intermediates);
646 self.hooks.remove_key(entry.ccdid);
649 self.tables
650 .clients
651 .borrow_mut()
652 .retain(|c| !(c.ccdid == entry.ccdid && c.fabric_index == fabric));
653 Ok(None)
654 }
655
656 fn write_client_certificate(
671 &self,
672 client: &ClientEntry,
673 large: bool,
674 w: &mut TlvWriter<'_>,
675 ) -> Result<(), Status> {
676 let full = |r: crate::error::Result<()>| r.map_err(|_| Status::ResourceExhausted);
677 match client.fingerprint {
678 None => full(w.null(Tag::Context(1)))?,
679 Some(_) if !large => {}
680 Some(_) => self.hooks.write_certificate(
681 Slot::Client {
682 fabric_index: client.fabric_index,
683 ccdid: client.ccdid,
684 },
685 w,
686 Tag::Context(1),
687 )?,
688 }
689 if !large && client.intermediates > 0 {
690 return Ok(());
691 }
692 full(w.start_array(Tag::Context(2)))?;
693 for index in 0..client.intermediates {
694 self.hooks.write_certificate(
695 Slot::Intermediate {
696 fabric_index: client.fabric_index,
697 ccdid: client.ccdid,
698 index,
699 },
700 w,
701 Tag::Anonymous,
702 )?;
703 }
704 full(w.end_container())
705 }
706}
707
708impl<H: TlsCertificateHooks, const R: usize, const C: usize, const E: usize> Cluster
710 for CertificateManagement<'_, H, R, C, E>
711{
712 const ID: ClusterId = ID;
713}