1use crate::interface::InterfaceClass;
2use crate::obis::ObisCode;
3use crate::security::access_rights::ObjectListEntry;
4use crate::security::{gost3410, hls, signature, AuthMechanism, SecuritySuite};
5use crate::types::attrs::{AssociatedPartnersId, ContextName, ObjectListElement, User, XDLMSContextInfo};
6use crate::types::{BerError, CosemDataType};
7use aead::Aead;
8use aes_gcm::{Aes128Gcm, Aes256Gcm, KeyInit, Nonce};
9use rand::Rng;
10use serde::{Deserialize, Serialize};
11use std::any::Any;
12use subtle::ConstantTimeEq;
13
14#[derive(Clone, Serialize, Deserialize, Debug, PartialEq)]
16pub enum AssociationLnVersion {
17 Version0,
19 Version1,
21 Version2,
23}
24
25pub use crate::security::AuthMechanism as AuthenticationMechanism;
28
29#[derive(Clone, Serialize, Deserialize, Debug, Default)]
34pub struct HlsContext {
35 pub client_system_title: Vec<u8>,
37 pub server_system_title: Vec<u8>,
39 pub security_control_byte: u8,
41 pub server_invocation_counter: u32,
43 pub encryption_key: Vec<u8>,
45 pub authentication_key: Vec<u8>,
47 pub gost_key: Vec<u8>,
49 pub signing_key: Vec<u8>,
52 pub peer_public_key: Vec<u8>,
55}
56
57impl Drop for HlsContext {
58 fn drop(&mut self) {
61 use zeroize::Zeroize;
62 self.encryption_key.zeroize();
63 self.authentication_key.zeroize();
64 self.gost_key.zeroize();
65 self.signing_key.zeroize();
66 }
67}
68
69#[derive(Clone, Serialize, Deserialize, Debug)]
71pub struct AssociationLnConfig {
72 pub logical_name: ObisCode,
74 pub version: AssociationLnVersion,
76 pub object_list: Vec<ObjectListElement>,
78 pub associated_partners_id: AssociatedPartnersId,
80 pub application_context_name: ContextName,
82 pub xdlms_context_info: XDLMSContextInfo,
84 pub authentication_mechanism: AuthenticationMechanism,
86 pub secret: Vec<u8>,
88 pub association_status: u8,
90 pub security_setup_reference: ObisCode,
92 pub user_list: Vec<User>,
94 pub current_user: Option<User>,
96}
97
98#[derive(Clone, Serialize, Deserialize, Debug)]
102pub struct AssociationLn {
103 logical_name: ObisCode,
104 version: AssociationLnVersion,
105 object_list: Vec<ObjectListElement>,
106 associated_partners_id: AssociatedPartnersId,
107 application_context_name: ContextName,
108 xdlms_context_info: XDLMSContextInfo,
109 authentication_mechanism: AuthenticationMechanism,
110 secret: Vec<u8>,
111 association_status: u8,
112 security_setup_reference: ObisCode,
113 user_list: Vec<User>,
114 current_user: Option<User>,
115 #[serde(skip)]
117 parsed_object_list: Vec<ObjectListEntry>,
118 #[serde(skip)]
121 ctos: Option<Vec<u8>>,
122 #[serde(skip)]
124 stoc: Option<Vec<u8>>,
125 #[serde(skip)]
128 hls_context: Option<HlsContext>,
129 #[serde(skip)]
133 hls_handshake_mechanism: Option<AuthMechanism>,
134 #[serde(skip)]
137 hls_failures: u8,
138}
139
140const MAX_HLS_FAILURES: u8 = 5;
144
145impl AssociationLn {
146 pub fn new(config: AssociationLnConfig) -> Self {
148 AssociationLn {
149 logical_name: config.logical_name,
150 version: config.version,
151 object_list: config.object_list,
152 associated_partners_id: config.associated_partners_id,
153 application_context_name: config.application_context_name,
154 xdlms_context_info: config.xdlms_context_info,
155 authentication_mechanism: config.authentication_mechanism,
156 secret: config.secret,
157 association_status: config.association_status,
158 security_setup_reference: config.security_setup_reference,
159 user_list: config.user_list,
160 current_user: config.current_user,
161 parsed_object_list: Vec::new(),
162 ctos: None,
163 stoc: None,
164 hls_context: None,
165 hls_handshake_mechanism: None,
166 hls_failures: 0,
167 }
168 }
169
170 pub fn set_ctos(&mut self, ctos: Vec<u8>) {
172 self.ctos = Some(ctos);
173 }
174
175 pub fn set_stoc(&mut self, stoc: Vec<u8>) {
177 self.stoc = Some(stoc);
178 }
179
180 pub fn generate_stoc(&mut self, len: usize) -> Vec<u8> {
183 let mut rng = rand::rng();
184 let stoc: Vec<u8> = (0..len).map(|_| rng.random()).collect();
185 self.stoc = Some(stoc.clone());
186 stoc
187 }
188
189 pub fn set_hls_context(&mut self, ctx: HlsContext) {
191 self.hls_context = Some(ctx);
192 }
193
194 pub fn set_client_system_title(&mut self, title: Vec<u8>) {
196 if let Some(ctx) = self.hls_context.as_mut() {
197 ctx.client_system_title = title;
198 }
199 }
200
201 pub fn set_hls_handshake_mechanism(&mut self, mechanism: AuthMechanism) {
203 self.hls_handshake_mechanism = Some(mechanism);
204 }
205
206 fn hls_mechanism(&self) -> AuthMechanism {
207 self.hls_handshake_mechanism.unwrap_or(self.authentication_mechanism)
208 }
209
210 pub fn responding_ap_title_for_hls(&self) -> Option<Vec<u8>> {
212 self.hls_context.as_ref().map(|ctx| ctx.server_system_title.clone()).filter(|title| title.len() == 8)
213 }
214
215 pub fn authentication_mechanism(&self) -> AuthenticationMechanism {
217 self.authentication_mechanism
218 }
219
220 pub fn secret(&self) -> &[u8] {
222 &self.secret
223 }
224
225 pub fn set_association_status(&mut self, status: u8) {
228 self.association_status = status;
229 }
230
231 pub fn association_status(&self) -> u8 {
233 self.association_status
234 }
235
236 fn change_hls_secret(&mut self, data: CosemDataType) -> Result<CosemDataType, String> {
238 match data {
239 CosemDataType::OctetString(secret) => {
240 zeroize::Zeroize::zeroize(&mut self.secret);
242 self.secret = secret;
243 Ok(CosemDataType::Null)
244 }
245 _ => Err("Expected OctetString for HLS secret".to_string()),
246 }
247 }
248
249 fn reply_to_hls_authentication(&self, data: CosemDataType) -> Result<CosemDataType, String> {
262 let CosemDataType::OctetString(f_stoc) = data else {
263 return Err("Expected octet-string for f(StoC)".to_string());
264 };
265 let mechanism = self.hls_mechanism();
266
267 if mechanism == AuthMechanism::Lls {
270 return if self.secret.len() == f_stoc.len() && self.secret.ct_eq(f_stoc.as_slice()).into() {
271 Ok(CosemDataType::Null)
272 } else {
273 Err("LLS authentication failed".to_string())
274 };
275 }
276
277 let stoc = self.stoc.as_ref().ok_or("StoC challenge not set (Pass 2 missing)")?;
278 let ctos = self.ctos.as_ref().ok_or("CtoS challenge not set (Pass 1 missing)")?;
279
280 match mechanism {
281 AuthMechanism::HlsMd5 | AuthMechanism::HlsSha1 => {
283 let secret = self.secret_bytes();
284 let expected = hls::hash_legacy(mechanism, stoc, secret).ok_or("HLS hash computation failed")?;
285 if expected != f_stoc {
286 return Err("HLS authentication failed: f(StoC) mismatch".to_string());
287 }
288 let f_ctos = hls::hash_legacy(mechanism, ctos, secret).ok_or("HLS hash computation failed")?;
289 Ok(CosemDataType::OctetString(f_ctos))
290 }
291 AuthMechanism::HlsSha256 | AuthMechanism::HlsGostStreebog => {
293 let secret = self.secret_bytes();
294 let ctx = self.hls_context.as_ref().ok_or("HLS context (system titles) not set")?;
295 let expected = hls::hash_with_titles(
296 mechanism,
297 secret,
298 &ctx.client_system_title,
299 &ctx.server_system_title,
300 stoc,
301 ctos,
302 )
303 .ok_or("HLS hash computation failed")?;
304 if expected != f_stoc {
305 return Err("HLS authentication failed: f(StoC) mismatch".to_string());
306 }
307 let f_ctos = hls::hash_with_titles(
308 mechanism,
309 secret,
310 &ctx.server_system_title,
311 &ctx.client_system_title,
312 ctos,
313 stoc,
314 )
315 .ok_or("HLS hash computation failed")?;
316 Ok(CosemDataType::OctetString(f_ctos))
317 }
318 AuthMechanism::HlsGmac => {
320 let ctx = self.hls_context.as_ref().ok_or("HLS context not configured for GMAC")?;
321 if f_stoc.len() != 17 {
322 return Err("f(StoC) must be 17 octets (SC ‖ IC ‖ 12-octet tag)".to_string());
323 }
324 let sc = f_stoc[0];
325 if sc != ctx.security_control_byte {
326 return Err("f(StoC) security control byte mismatch".to_string());
327 }
328 let client_iv = build_iv(&ctx.client_system_title, &f_stoc[1..5])?;
329 let aad_stoc = [&[sc][..], &ctx.authentication_key, stoc].concat();
330 if gmac_tag(&ctx.encryption_key, &client_iv, &aad_stoc)? != f_stoc[5..17] {
331 return Err("HLS authentication failed: GMAC f(StoC) mismatch".to_string());
332 }
333 let server_ic = ctx.server_invocation_counter.to_be_bytes();
334 let server_iv = build_iv(&ctx.server_system_title, &server_ic)?;
335 let aad_ctos = [&[ctx.security_control_byte][..], &ctx.authentication_key, ctos].concat();
336 let tag = gmac_tag(&ctx.encryption_key, &server_iv, &aad_ctos)?;
337 Ok(CosemDataType::OctetString(assemble_sc_ic_mac(ctx.security_control_byte, &server_ic, &tag)))
338 }
339 AuthMechanism::HlsGostCmac => {
341 let ctx = self.hls_context.as_ref().ok_or("HLS context not configured for GOST CMAC")?;
342 if f_stoc.len() != 21 {
343 return Err("f(StoC) must be 21 octets (SC ‖ IC ‖ 16-octet MAC)".to_string());
344 }
345 let sc = f_stoc[0];
346 if sc != ctx.security_control_byte {
347 return Err("f(StoC) security control byte mismatch".to_string());
348 }
349 let client_iv = build_iv(&ctx.client_system_title, &f_stoc[1..5])?;
350 let expected = hls::gost_cmac(&ctx.gost_key, &client_iv, sc, stoc, ctos).map_err(str::to_string)?;
351 if expected != f_stoc[5..21] {
352 return Err("HLS authentication failed: GOST CMAC f(StoC) mismatch".to_string());
353 }
354 let server_ic = ctx.server_invocation_counter.to_be_bytes();
355 let server_iv = build_iv(&ctx.server_system_title, &server_ic)?;
356 let mac = hls::gost_cmac(&ctx.gost_key, &server_iv, ctx.security_control_byte, ctos, stoc)
357 .map_err(str::to_string)?;
358 Ok(CosemDataType::OctetString(assemble_sc_ic_mac(ctx.security_control_byte, &server_ic, &mac)))
359 }
360 AuthMechanism::HlsEcdsa => {
363 let ctx = self.hls_context.as_ref().ok_or("HLS context not configured for ECDSA")?;
364 let suite = SecuritySuite::from_id(ctx.security_control_byte & 0x0F)
365 .filter(|s| s.has_public_key())
366 .ok_or("ECDSA (mechanism 7) requires security suite 1 or 2")?;
367 let msg_c = [&ctx.client_system_title[..], &ctx.server_system_title, stoc, ctos].concat();
368 signature::ecdsa_verify(suite, &ctx.peer_public_key, &msg_c, &f_stoc)
369 .map_err(|e| format!("HLS authentication failed: ECDSA f(StoC) invalid: {e}"))?;
370 let msg_s = [&ctx.server_system_title[..], &ctx.client_system_title, ctos, stoc].concat();
371 let sig = signature::ecdsa_sign(suite, &ctx.signing_key, &msg_s).map_err(|e| e.to_string())?;
372 Ok(CosemDataType::OctetString(sig))
373 }
374 AuthMechanism::HlsGostSignature => {
377 let ctx = self.hls_context.as_ref().ok_or("HLS context not configured for GOST signature")?;
378 let msg_c = [&ctx.client_system_title[..], &ctx.server_system_title, stoc, ctos].concat();
379 gost3410::gost_verify(&ctx.peer_public_key, &msg_c, &f_stoc)
380 .map_err(|e| format!("HLS authentication failed: GOST 34.10 f(StoC) invalid: {e:?}"))?;
381 let msg_s = [&ctx.server_system_title[..], &ctx.client_system_title, ctos, stoc].concat();
382 let sig = gost3410::gost_sign(&ctx.signing_key, &msg_s)
383 .map_err(|e| format!("GOST 34.10 signing failed: {e:?}"))?;
384 Ok(CosemDataType::OctetString(sig.to_vec()))
385 }
386 AuthMechanism::HlsManufacturer => {
389 let secret = self.secret_bytes();
390 let expected = hls::manufacturer_aes(secret, stoc);
391 if expected != f_stoc {
392 return Err("HLS authentication failed: f(StoC) mismatch".to_string());
393 }
394 Ok(CosemDataType::OctetString(hls::manufacturer_aes(secret, ctos)))
395 }
396 AuthMechanism::None => Err("mechanism 0 does not use HLS authentication".to_string()),
397 AuthMechanism::Lls => unreachable!("LLS handled above"),
398 }
399 }
400
401 fn reply_to_hls_authentication_checked(&mut self, data: CosemDataType) -> Result<CosemDataType, String> {
407 if self.hls_failures >= MAX_HLS_FAILURES {
408 return Err("HLS authentication locked out after too many failed attempts".to_string());
409 }
410 match self.reply_to_hls_authentication(data) {
411 Ok(reply) => {
412 self.hls_failures = 0;
413 self.association_status = 2;
415 Ok(reply)
416 }
417 Err(e) => {
418 self.hls_failures = self.hls_failures.saturating_add(1);
419 Err(e)
420 }
421 }
422 }
423
424 fn secret_bytes(&self) -> &[u8] {
426 &self.secret
427 }
428
429 fn add_object(&mut self, data: &CosemDataType) -> Result<CosemDataType, String> {
432 let elem = ObjectListElement::try_from(data)?;
433 let key = (elem.class_id, elem.logical_name.to_bytes());
434 if let Some(existing) = self.object_list.iter_mut().find(|e| (e.class_id, e.logical_name.to_bytes()) == key) {
435 *existing = elem;
436 } else {
437 self.object_list.push(elem);
438 }
439 Ok(CosemDataType::Null)
440 }
441
442 fn remove_object(&mut self, data: &CosemDataType) -> Result<CosemDataType, String> {
444 let elem = ObjectListElement::try_from(data)?;
445 let key = (elem.class_id, elem.logical_name.to_bytes());
446 let before = self.object_list.len();
447 self.object_list.retain(|e| (e.class_id, e.logical_name.to_bytes()) != key);
448 if self.object_list.len() == before {
449 return Err("Object not found in object_list".to_string());
450 }
451 Ok(CosemDataType::Null)
452 }
453
454 fn add_user(&mut self, data: &CosemDataType) -> Result<CosemDataType, String> {
458 let user = User::try_from(data)?;
459 let id = user.user_id;
460 if let Some(existing) = self.user_list.iter_mut().find(|e| e.user_id == id) {
461 *existing = user;
462 } else {
463 self.user_list.push(user);
464 }
465 Ok(CosemDataType::Null)
466 }
467
468 fn remove_user(&mut self, data: &CosemDataType) -> Result<CosemDataType, String> {
471 let user = User::try_from(data)?;
472 let id = user.user_id;
473 let before = self.user_list.len();
474 self.user_list.retain(|e| e.user_id != id);
475 if self.user_list.len() == before {
476 return Err("User not found in user_list".to_string());
477 }
478 Ok(CosemDataType::Null)
479 }
480
481 pub fn find_object(&self, class_id: u16, logical_name: &ObisCode) -> Option<&ObjectListEntry> {
485 self.parsed_object_list.iter().find(|e| e.class_id == class_id && e.logical_name == logical_name.to_bytes())
486 }
487
488 pub fn can_read(&self, class_id: u16, logical_name: &ObisCode, attribute_id: i8) -> bool {
490 self.find_object(class_id, logical_name).map(|e| e.can_read(attribute_id)).unwrap_or(false)
491 }
492
493 pub fn can_write(&self, class_id: u16, logical_name: &ObisCode, attribute_id: i8) -> bool {
495 self.find_object(class_id, logical_name).map(|e| e.can_write(attribute_id)).unwrap_or(false)
496 }
497
498 pub fn can_invoke(&self, class_id: u16, logical_name: &ObisCode, method_id: i8) -> bool {
500 self.find_object(class_id, logical_name).map(|e| e.can_invoke(method_id)).unwrap_or(false)
501 }
502
503 pub fn object_list_entries(&self) -> &[ObjectListEntry] {
505 &self.parsed_object_list
506 }
507
508 pub fn add_object_with_access(&mut self, entry: ObjectListEntry) {
510 self.parsed_object_list.retain(|e| !(e.class_id == entry.class_id && e.logical_name == entry.logical_name));
512 self.parsed_object_list.push(entry);
513 }
514}
515
516fn assemble_sc_ic_mac(security_control: u8, invocation_counter: &[u8], mac: &[u8]) -> Vec<u8> {
519 let mut out = Vec::with_capacity(1 + invocation_counter.len() + mac.len());
520 out.push(security_control);
521 out.extend_from_slice(invocation_counter);
522 out.extend_from_slice(mac);
523 out
524}
525
526fn build_iv(system_title: &[u8], invocation_counter: &[u8]) -> Result<[u8; 12], String> {
528 if system_title.len() != 8 {
529 return Err("System-Title must be 8 octets".to_string());
530 }
531 if invocation_counter.len() != 4 {
532 return Err("Invocation counter must be 4 octets".to_string());
533 }
534 let mut iv = [0u8; 12];
535 iv[..8].copy_from_slice(system_title);
536 iv[8..].copy_from_slice(invocation_counter);
537 Ok(iv)
538}
539
540fn gmac_tag(ek: &[u8], iv: &[u8; 12], aad: &[u8]) -> Result<Vec<u8>, String> {
545 let nonce = Nonce::from(*iv);
546 let out = match ek.len() {
547 16 => {
548 let cipher = Aes128Gcm::new_from_slice(ek).map_err(|_| "invalid EK".to_string())?;
549 cipher
550 .encrypt(&nonce, aead::Payload { msg: &[], aad })
551 .map_err(|_| "GMAC computation failed".to_string())?
552 }
553 32 => {
554 let cipher = Aes256Gcm::new_from_slice(ek).map_err(|_| "invalid EK".to_string())?;
555 cipher
556 .encrypt(&nonce, aead::Payload { msg: &[], aad })
557 .map_err(|_| "GMAC computation failed".to_string())?
558 }
559 _ => return Err("EK must be 16 or 32 octets".to_string()),
560 };
561 Ok(out[..12].to_vec())
563}
564
565impl InterfaceClass for AssociationLn {
566 fn class_id(&self) -> u16 {
567 15
568 }
569
570 fn version(&self) -> u8 {
571 match self.version {
572 AssociationLnVersion::Version0 => 0,
573 AssociationLnVersion::Version1 => 1,
574 AssociationLnVersion::Version2 => 2,
575 }
576 }
577
578 fn logical_name(&self) -> &ObisCode {
579 &self.logical_name
580 }
581
582 fn attributes(&self) -> Vec<(u8, CosemDataType)> {
583 let mut attrs = vec![
584 (1, CosemDataType::OctetString(self.logical_name.to_bytes())),
585 (2, CosemDataType::Array(self.object_list.iter().cloned().map(CosemDataType::from).collect())),
586 (3, CosemDataType::from(self.associated_partners_id.clone())),
587 (4, CosemDataType::from(self.application_context_name.clone())),
588 (5, CosemDataType::from(self.xdlms_context_info.clone())),
589 (6, self.authentication_mechanism_name()),
590 (7, CosemDataType::OctetString(self.secret.clone())),
591 (8, CosemDataType::Enum(self.association_status)),
592 ];
593 if matches!(self.version, AssociationLnVersion::Version1 | AssociationLnVersion::Version2) {
595 attrs.push((9, CosemDataType::OctetString(self.security_setup_reference.to_bytes())));
596 }
597 if matches!(self.version, AssociationLnVersion::Version2) {
599 attrs.push((10, CosemDataType::Array(self.user_list.iter().cloned().map(CosemDataType::from).collect())));
600 match &self.current_user {
601 Some(user) => attrs.push((11, CosemDataType::from(user.clone()))),
602 None => attrs.push((11, CosemDataType::Null)),
603 }
604 }
605 attrs
606 }
607
608 fn methods(&self) -> Vec<(u8, String)> {
609 let mut methods = vec![
611 (1, "reply_to_HLS_authentication".to_string()),
612 (2, "change_HLS_secret".to_string()),
613 (3, "add_object".to_string()),
614 (4, "remove_object".to_string()),
615 ];
616 if matches!(self.version, AssociationLnVersion::Version2) {
618 methods.push((5, "add_user".to_string()));
619 methods.push((6, "remove_user".to_string()));
620 }
621 methods
622 }
623
624 fn serialize_ber(&self, buf: &mut Vec<u8>) -> Result<(), BerError> {
625 let mut seq_buf = Vec::new();
626 CosemDataType::LongUnsigned(self.class_id()).serialize_ber(&mut seq_buf)?;
627 for (_, attr) in self.attributes() {
628 attr.serialize_ber(&mut seq_buf)?;
629 }
630 buf.push(0x02); write_length(1 + self.attributes().len(), buf); buf.extend_from_slice(&seq_buf);
633 Ok(())
634 }
635
636 fn deserialize_ber(&mut self, data: &[u8]) -> Result<(), BerError> {
637 let (tlv, rest) = CosemDataType::deserialize_ber(data)?;
638 if !rest.is_empty() {
639 return Err(BerError::InvalidTag);
640 }
641 let CosemDataType::Structure(seq) = tlv else {
642 return Err(BerError::InvalidTag);
643 };
644 if !matches!(seq.len(), 9 | 10 | 12) {
648 return Err(BerError::InvalidLength);
649 }
650 if let CosemDataType::LongUnsigned(class_id) = seq[0] {
651 if class_id != self.class_id() {
652 return Err(BerError::InvalidValue);
653 }
654 } else {
655 return Err(BerError::InvalidTag);
656 }
657 if let CosemDataType::OctetString(obis) = &seq[1] {
658 if obis.len() == 6 {
659 self.logical_name = ObisCode::new(obis[0], obis[1], obis[2], obis[3], obis[4], obis[5]);
660 } else {
661 return Err(BerError::InvalidLength);
662 }
663 } else {
664 return Err(BerError::InvalidTag);
665 }
666 self.object_list = match &seq[2] {
667 CosemDataType::Array(list) => list
668 .iter()
669 .map(|e| ObjectListElement::try_from(e).map_err(|_| BerError::InvalidValue))
670 .collect::<Result<Vec<_>, _>>()?,
671 _ => return Err(BerError::InvalidTag),
672 };
673 self.associated_partners_id = AssociatedPartnersId::try_from(&seq[3]).map_err(|_| BerError::InvalidValue)?;
674 self.application_context_name = ContextName::try_from(&seq[4]).map_err(|_| BerError::InvalidValue)?;
675 self.xdlms_context_info = XDLMSContextInfo::try_from(&seq[5]).map_err(|_| BerError::InvalidValue)?;
676 self.authentication_mechanism = match &seq[6] {
677 CosemDataType::OctetString(mech) => {
678 let id = *mech.last().ok_or(BerError::InvalidLength)?;
679 AuthMechanism::from_id(id).ok_or(BerError::InvalidValue)?
680 }
681 _ => return Err(BerError::InvalidTag),
682 };
683 self.secret = match &seq[7] {
684 CosemDataType::OctetString(s) => s.clone(),
685 _ => return Err(BerError::InvalidTag),
686 };
687 self.association_status = match &seq[8] {
688 CosemDataType::Enum(v) | CosemDataType::Unsigned(v) => *v,
689 _ => return Err(BerError::InvalidTag),
690 };
691 if seq.len() >= 10 {
693 self.security_setup_reference = match &seq[9] {
694 CosemDataType::OctetString(bytes) if bytes.len() == 6 => {
695 ObisCode::new(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5])
696 }
697 _ => return Err(BerError::InvalidTag),
698 };
699 }
700 self.version = if seq.len() == 12 {
702 self.user_list = match &seq[10] {
703 CosemDataType::Array(list) => list
704 .iter()
705 .map(|e| User::try_from(e).map_err(|_| BerError::InvalidValue))
706 .collect::<Result<Vec<_>, _>>()?,
707 _ => return Err(BerError::InvalidTag),
708 };
709 self.current_user = match &seq[11] {
710 CosemDataType::Null => None,
711 other => Some(User::try_from(other).map_err(|_| BerError::InvalidValue)?),
712 };
713 AssociationLnVersion::Version2
714 } else if seq.len() == 10 {
715 AssociationLnVersion::Version1
716 } else {
717 AssociationLnVersion::Version0
718 };
719 Ok(())
720 }
721
722 fn set_attribute(&mut self, attribute_id: u8, value: CosemDataType) -> Result<(), String> {
723 match attribute_id {
724 7 => match value {
725 CosemDataType::OctetString(secret) => {
726 zeroize::Zeroize::zeroize(&mut self.secret);
727 self.secret = secret;
728 Ok(())
729 }
730 _ => Err("secret must be octet-string".into()),
731 },
732 10 if matches!(self.version, AssociationLnVersion::Version2) => {
733 let CosemDataType::Array(list) = value else {
734 return Err("user_list must be array".into());
735 };
736 self.user_list = list.iter().map(User::try_from).collect::<Result<Vec<_>, _>>()?;
737 Ok(())
738 }
739 11 if matches!(self.version, AssociationLnVersion::Version2) => {
740 self.current_user = match value {
741 CosemDataType::Null => None,
742 other => Some(User::try_from(&other)?),
743 };
744 Ok(())
745 }
746 _ => Err(format!("AssociationLn attribute {attribute_id} is not writable")),
747 }
748 }
749
750 fn invoke_method(&mut self, method_id: u8, params: Option<CosemDataType>) -> Result<CosemDataType, String> {
751 let params = params.ok_or("Missing method parameter")?;
752 let is_v2 = matches!(self.version, AssociationLnVersion::Version2);
753 match method_id {
754 1 => self.reply_to_hls_authentication_checked(params),
755 2 => self.change_hls_secret(params),
756 3 => self.add_object(¶ms),
757 4 => self.remove_object(¶ms),
758 5 if is_v2 => self.add_user(¶ms),
760 6 if is_v2 => self.remove_user(¶ms),
761 _ => Err(format!("Method {} not supported for Association LN version {}", method_id, self.version())),
762 }
763 }
764
765 fn as_any(&self) -> &dyn Any {
766 self
767 }
768}
769
770impl AssociationLn {
771 fn authentication_mechanism_name(&self) -> CosemDataType {
776 let oid = self.authentication_mechanism.oid();
777 let mut value = vec![0x09, 0x07];
778 value.extend_from_slice(&oid);
779 CosemDataType::OctetString(value)
780 }
781}
782
783#[allow(clippy::cast_possible_truncation)] fn write_length(length: usize, buf: &mut Vec<u8>) {
786 if length < 128 {
787 buf.push(length as u8);
788 } else {
789 let bytes = (length as u64).to_be_bytes();
790 let first_non_zero = bytes.iter().position(|&b| b != 0).unwrap_or(7);
791 let num_octets = 8 - first_non_zero;
792 buf.push(0x80 | num_octets as u8);
793 buf.extend_from_slice(&bytes[first_non_zero..]);
794 }
795}
796
797#[cfg(test)]
798mod tests {
799 use super::*;
800 use sha1::{Digest, Sha1};
801
802 fn sample(version: AssociationLnVersion) -> AssociationLn {
803 AssociationLn::new(AssociationLnConfig {
804 logical_name: ObisCode::new(0, 0, 40, 0, 0, 255),
805 version,
806 object_list: vec![],
807 associated_partners_id: AssociatedPartnersId { client_sap: 1, server_sap: 1 },
808 application_context_name: ContextName::OctetString(vec![
809 0x09, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x01, 0x01,
810 ]),
811 xdlms_context_info: XDLMSContextInfo {
812 conformance: vec![],
813 max_receive_pdu_size: 0xFFFF,
814 max_send_pdu_size: 0xFFFF,
815 dlms_version_number: 6,
816 quality_of_service: 0,
817 cyphering_info: vec![],
818 },
819 authentication_mechanism: AuthenticationMechanism::HlsSha1,
820 secret: b"12345678".to_vec(),
821 association_status: 0,
822 security_setup_reference: ObisCode::new(0, 0, 43, 0, 0, 255),
823 user_list: vec![],
824 current_user: None,
825 })
826 }
827
828 #[test]
829 fn method_ids_match_standard() {
830 let m = sample(AssociationLnVersion::Version1).methods();
831 assert_eq!(m[0], (1, "reply_to_HLS_authentication".to_string()));
832 assert_eq!(m[1], (2, "change_HLS_secret".to_string()));
833 assert_eq!(m[2], (3, "add_object".to_string()));
834 assert_eq!(m[3], (4, "remove_object".to_string()));
835 }
836
837 #[test]
838 fn mechanism_name_oid_is_well_formed() {
839 let obj = sample(AssociationLnVersion::Version0);
840 if let CosemDataType::OctetString(oid) = obj.authentication_mechanism_name() {
842 assert_eq!(oid, vec![0x09, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x02, 0x04]);
843 assert_eq!(oid[1] as usize, oid.len() - 2, "OID length must match");
844 } else {
845 panic!("mechanism name must be octet-string");
846 }
847 }
848
849 #[test]
850 fn attribute_and_method_counts_per_version() {
851 let expected = [
852 (AssociationLnVersion::Version0, 8usize, 4usize),
853 (AssociationLnVersion::Version1, 9, 4),
854 (AssociationLnVersion::Version2, 11, 6),
855 ];
856 for (v, attr_count, method_count) in expected {
857 let obj = sample(v.clone());
858 assert_eq!(obj.attributes().len(), attr_count);
859 assert_eq!(obj.methods().len(), method_count);
860 }
861 }
862
863 #[test]
864 fn round_trip_all_versions() {
865 for v in [AssociationLnVersion::Version0, AssociationLnVersion::Version1, AssociationLnVersion::Version2] {
866 let obj = sample(v.clone());
867 let mut buf = Vec::new();
868 obj.serialize_ber(&mut buf).unwrap();
869 let mut decoded = sample(AssociationLnVersion::Version0);
870 decoded.deserialize_ber(&buf).unwrap();
871 assert_eq!(decoded.version(), obj.version());
872 assert_eq!(decoded.attributes().len(), obj.attributes().len());
873 }
874 }
875
876 #[test]
877 fn add_and_remove_user_v2_only() {
878 let user = CosemDataType::Structure(vec![
879 CosemDataType::Unsigned(7),
880 CosemDataType::OctetString(b"operator".to_vec()),
881 ]);
882 let mut obj = sample(AssociationLnVersion::Version2);
884 obj.invoke_method(5, Some(user.clone())).unwrap();
885 assert_eq!(obj.user_list.len(), 1);
886 obj.invoke_method(6, Some(user.clone())).unwrap();
887 assert_eq!(obj.user_list.len(), 0);
888 let mut v1 = sample(AssociationLnVersion::Version1);
890 assert!(v1.invoke_method(5, Some(user)).is_err());
891 }
892
893 #[test]
894 fn add_and_remove_object() {
895 use crate::types::attrs::ObjectListElement;
896 let mut obj = sample(AssociationLnVersion::Version1);
897 let element = CosemDataType::from(ObjectListElement {
898 class_id: 1,
899 version: 0,
900 logical_name: ObisCode::new(0, 0, 96, 1, 0, 255),
901 access_rights: crate::types::attrs::AccessRight { attribute_access: vec![], method_access: vec![] },
902 });
903 obj.invoke_method(3, Some(element.clone())).unwrap();
904 assert_eq!(obj.object_list.len(), 1);
905 obj.invoke_method(4, Some(element)).unwrap();
906 assert_eq!(obj.object_list.len(), 0);
907 }
908
909 #[test]
912 fn hls4_sha1_verifies_fstoc_and_returns_fctos() {
913 let secret = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
914 let stoc = vec![0xAA, 0xBB, 0xCC, 0xDD];
915 let ctos = vec![0x11, 0x22, 0x33, 0x44];
916 let mut obj = sample(AssociationLnVersion::Version1);
917 obj.secret = secret.clone();
918 obj.set_stoc(stoc.clone());
919 obj.set_ctos(ctos.clone());
920
921 let f_stoc = {
922 let mut h = Sha1::new();
923 h.update(&stoc);
924 h.update(&secret);
925 h.finalize().to_vec()
926 };
927 let expected_f_ctos = {
928 let mut h = Sha1::new();
929 h.update(&ctos);
930 h.update(&secret);
931 h.finalize().to_vec()
932 };
933
934 let reply = obj
935 .invoke_method(1, Some(CosemDataType::OctetString(f_stoc.clone())))
936 .expect("HLS4 authentication should succeed");
937 assert_eq!(reply, CosemDataType::OctetString(expected_f_ctos));
938
939 let mut wrong = f_stoc;
941 wrong[0] ^= 0xFF;
942 assert!(obj.invoke_method(1, Some(CosemDataType::OctetString(wrong))).is_err());
943 }
944
945 #[test]
949 fn hls_authentication_locks_out_after_repeated_failures() {
950 let secret = vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08];
951 let stoc = vec![0xAA, 0xBB, 0xCC, 0xDD];
952 let ctos = vec![0x11, 0x22, 0x33, 0x44];
953 let mut obj = sample(AssociationLnVersion::Version1);
954 obj.secret = secret.clone();
955 obj.set_stoc(stoc.clone());
956 obj.set_ctos(ctos);
957
958 let f_stoc = {
959 let mut h = Sha1::new();
960 h.update(&stoc);
961 h.update(&secret);
962 h.finalize().to_vec()
963 };
964 let mut wrong = f_stoc.clone();
965 wrong[0] ^= 0xFF;
966
967 for _ in 0..MAX_HLS_FAILURES {
968 assert!(obj.invoke_method(1, Some(CosemDataType::OctetString(wrong.clone()))).is_err());
969 }
970 let err = obj.invoke_method(1, Some(CosemDataType::OctetString(f_stoc))).unwrap_err();
972 assert!(err.contains("locked out"), "unexpected error: {err}");
973 }
974
975 #[test]
977 fn hls5_gmac_matches_blue_book_test_vector() {
978 let ek = hex(b"000102030405060708090A0B0C0D0E0F");
979 let ak = hex(b"D0D1D2D3D4D5D6D7D8D9DADBDCDDDEDF");
980 let client_st = hex(b"4D4D4D0000000001");
981 let server_st = hex(b"4D4D4D0000BC614E");
982 let ctos = hex(b"4B35366956616759"); let stoc = hex(b"503677524A323146"); let f_stoc = hex(b"10000000011A52FE7DD3E72748973C1E28");
985 let expected_f_ctos = hex(b"1001234567FE1466AFB3DBCD4F9389E2B7");
986
987 let mut obj = sample(AssociationLnVersion::Version1);
988 obj.authentication_mechanism = AuthenticationMechanism::HlsGmac;
989 obj.set_stoc(stoc);
990 obj.set_ctos(ctos);
991 let mut ctx = HlsContext::default();
992 ctx.security_control_byte = 0x10;
993 ctx.encryption_key = ek;
994 ctx.authentication_key = ak;
995 ctx.server_system_title = server_st;
996 ctx.server_invocation_counter = 0x01234567;
997 ctx.client_system_title = client_st;
998 obj.set_hls_context(ctx);
999
1000 let reply = obj
1001 .invoke_method(1, Some(CosemDataType::OctetString(f_stoc.clone())))
1002 .expect("GMAC authentication should succeed");
1003 assert_eq!(reply, CosemDataType::OctetString(expected_f_ctos));
1004
1005 let mut bad = f_stoc;
1007 bad[16] ^= 0x01;
1008 assert!(obj.invoke_method(1, Some(CosemDataType::OctetString(bad))).is_err());
1009 }
1010
1011 #[test]
1014 fn hls_sha256_and_streebog_four_pass_via_association() {
1015 for mech in [AuthMechanism::HlsSha256, AuthMechanism::HlsGostStreebog] {
1016 let secret = b"0123456789abcdef".to_vec(); let st_c = b"CLIENT01".to_vec();
1018 let st_s = b"SERVER01".to_vec();
1019 let stoc = vec![0xAA, 0xBB, 0xCC, 0xDD];
1020 let ctos = vec![0x11, 0x22, 0x33, 0x44];
1021 let mut obj = sample(AssociationLnVersion::Version1);
1022 obj.authentication_mechanism = mech;
1023 obj.secret = secret.clone();
1024 obj.set_stoc(stoc.clone());
1025 obj.set_ctos(ctos.clone());
1026 let mut ctx = HlsContext::default();
1027 ctx.client_system_title = st_c.clone();
1028 ctx.server_system_title = st_s.clone();
1029 obj.set_hls_context(ctx);
1030 let f_stoc = hls::hash_with_titles(mech, &secret, &st_c, &st_s, &stoc, &ctos).unwrap();
1031 let expected = hls::hash_with_titles(mech, &secret, &st_s, &st_c, &ctos, &stoc).unwrap();
1032 let reply = obj
1033 .invoke_method(1, Some(CosemDataType::OctetString(f_stoc.clone())))
1034 .expect("HLS hash authentication should succeed");
1035 assert_eq!(reply, CosemDataType::OctetString(expected));
1036 let mut bad = f_stoc;
1037 bad[0] ^= 0xFF;
1038 assert!(obj.invoke_method(1, Some(CosemDataType::OctetString(bad))).is_err());
1039 }
1040 }
1041
1042 #[test]
1045 fn hls_gost_cmac_four_pass_via_association() {
1046 let k_em = hex(b"000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132333435363738393a3b3c3d3e3f");
1047 let st_c = hex(b"4d4d4d0000000001");
1048 let st_s = hex(b"4d4d4d0000bc614e");
1049 let stoc = hex(b"8899aabbccddeeff");
1050 let ctos = hex(b"0011223344556677");
1051 let sc = 0x30u8;
1052 let client_ic = 0x0000_0001u32;
1053 let server_ic = 0x0123_4567u32;
1054
1055 let mut obj = sample(AssociationLnVersion::Version1);
1056 obj.authentication_mechanism = AuthMechanism::HlsGostCmac;
1057 obj.set_stoc(stoc.clone());
1058 obj.set_ctos(ctos.clone());
1059 let mut ctx = HlsContext::default();
1060 ctx.client_system_title = st_c.clone();
1061 ctx.server_system_title = st_s.clone();
1062 ctx.security_control_byte = sc;
1063 ctx.server_invocation_counter = server_ic;
1064 ctx.gost_key = k_em.clone();
1065 obj.set_hls_context(ctx);
1066
1067 let iv_c = [&st_c[..], &client_ic.to_be_bytes()].concat();
1069 let mac_c = hls::gost_cmac(&k_em, &iv_c, sc, &stoc, &ctos).unwrap();
1070 let f_stoc = assemble_sc_ic_mac(sc, &client_ic.to_be_bytes(), &mac_c);
1071
1072 let iv_s = [&st_s[..], &server_ic.to_be_bytes()].concat();
1073 let mac_s = hls::gost_cmac(&k_em, &iv_s, sc, &ctos, &stoc).unwrap();
1074 let expected = assemble_sc_ic_mac(sc, &server_ic.to_be_bytes(), &mac_s);
1075
1076 let reply = obj
1077 .invoke_method(1, Some(CosemDataType::OctetString(f_stoc.clone())))
1078 .expect("GOST CMAC authentication should succeed");
1079 assert_eq!(reply, CosemDataType::OctetString(expected));
1080
1081 let mut bad = f_stoc;
1082 let n = bad.len();
1083 bad[n - 1] ^= 0x01;
1084 assert!(obj.invoke_method(1, Some(CosemDataType::OctetString(bad))).is_err());
1085 }
1086
1087 #[test]
1090 fn hls_manufacturer_four_pass_via_association() {
1091 let secret = b"12345678".to_vec();
1092 let stoc = vec![0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11];
1093 let ctos = vec![0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88, 0x99];
1094 let mut obj = sample(AssociationLnVersion::Version1);
1095 obj.authentication_mechanism = AuthMechanism::HlsManufacturer;
1096 obj.secret = secret.clone();
1097 obj.set_stoc(stoc.clone());
1098 obj.set_ctos(ctos.clone());
1099 let f_stoc = hls::manufacturer_aes(&secret, &stoc);
1100 let expected = hls::manufacturer_aes(&secret, &ctos);
1101 let reply = obj
1102 .invoke_method(1, Some(CosemDataType::OctetString(f_stoc.clone())))
1103 .expect("manufacturer HLS should succeed");
1104 assert_eq!(reply, CosemDataType::OctetString(expected));
1105 let mut bad = f_stoc;
1106 bad[0] ^= 0xFF;
1107 assert!(obj.invoke_method(1, Some(CosemDataType::OctetString(bad))).is_err());
1108 }
1109
1110 #[test]
1113 fn hls_ecdsa_four_pass_via_association() {
1114 use p256::ecdsa::SigningKey;
1115 let st_c = b"CLIENT01".to_vec();
1116 let st_s = b"SERVER01".to_vec();
1117 let stoc = vec![0xAA, 0xBB, 0xCC, 0xDD];
1118 let ctos = vec![0x11, 0x22, 0x33, 0x44];
1119 let d_client = hex(b"418073C239FA6125011DE4D6CD2E645780289F761BB21BFB0835CB5585E8B373");
1120 let d_server = hex(b"1122334455667788112233445566778811223344556677881122334455667788");
1121 let pk_client =
1122 SigningKey::from_slice(&d_client).unwrap().verifying_key().to_sec1_point(false).as_bytes().to_vec();
1123 let pk_server =
1124 SigningKey::from_slice(&d_server).unwrap().verifying_key().to_sec1_point(false).as_bytes().to_vec();
1125
1126 let mut obj = sample(AssociationLnVersion::Version1);
1127 obj.authentication_mechanism = AuthMechanism::HlsEcdsa;
1128 obj.set_stoc(stoc.clone());
1129 obj.set_ctos(ctos.clone());
1130 let mut ctx = HlsContext::default();
1131 ctx.client_system_title = st_c.clone();
1132 ctx.server_system_title = st_s.clone();
1133 ctx.security_control_byte = 0x31; ctx.signing_key = d_server;
1135 ctx.peer_public_key = pk_client;
1136 obj.set_hls_context(ctx);
1137
1138 let msg_c = [&st_c[..], &st_s, &stoc, &ctos].concat();
1140 let f_stoc = signature::ecdsa_sign(SecuritySuite::Suite1, &d_client, &msg_c).unwrap();
1141 let reply = obj
1142 .invoke_method(1, Some(CosemDataType::OctetString(f_stoc.clone())))
1143 .expect("ECDSA authentication should succeed");
1144 let msg_s = [&st_s[..], &st_c, &ctos, &stoc].concat();
1146 let CosemDataType::OctetString(sig) = reply else {
1147 panic!("expected octet-string reply");
1148 };
1149 signature::ecdsa_verify(SecuritySuite::Suite1, &pk_server, &msg_s, &sig).unwrap();
1150
1151 let mut bad = f_stoc;
1152 bad[10] ^= 0x01;
1153 assert!(obj.invoke_method(1, Some(CosemDataType::OctetString(bad))).is_err());
1154 }
1155
1156 #[test]
1159 fn hls_gost_signature_four_pass_via_association() {
1160 let st_c = hex(b"ff00ee11dd22cc33");
1161 let st_s = hex(b"bb44aa5599668877");
1162 let stoc = hex(b"8899aabbccddeeff");
1163 let ctos = hex(b"0011223344556677");
1164 let d_client = hex(b"48494a4b4c4d4e4f4041424344454647bbbbaaaa999988884444555566667777");
1165 let d_server = hex(b"58595a5b5c5d5e5f5051525354555657ffffffffeeeeeeee8888888899999999");
1166 let pk_client = gost3410::public_key(&d_client).unwrap();
1167 let pk_server = gost3410::public_key(&d_server).unwrap();
1168
1169 let mut obj = sample(AssociationLnVersion::Version1);
1170 obj.authentication_mechanism = AuthMechanism::HlsGostSignature;
1171 obj.set_stoc(stoc.clone());
1172 obj.set_ctos(ctos.clone());
1173 let mut ctx = HlsContext::default();
1174 ctx.client_system_title = st_c.clone();
1175 ctx.server_system_title = st_s.clone();
1176 ctx.signing_key = d_server.to_vec();
1177 ctx.peer_public_key = pk_client.to_vec();
1178 obj.set_hls_context(ctx);
1179
1180 let msg_c = [&st_c[..], &st_s, &stoc, &ctos].concat();
1182 let f_stoc = gost3410::gost_sign(&d_client, &msg_c).unwrap().to_vec();
1183 let reply = obj
1184 .invoke_method(1, Some(CosemDataType::OctetString(f_stoc.clone())))
1185 .expect("GOST 34.10 authentication should succeed");
1186 let msg_s = [&st_s[..], &st_c, &ctos, &stoc].concat();
1187 let CosemDataType::OctetString(sig) = reply else {
1188 panic!("expected octet-string reply");
1189 };
1190 gost3410::gost_verify(&pk_server, &msg_s, &sig).unwrap();
1191
1192 let mut bad = f_stoc;
1193 bad[10] ^= 0x01;
1194 assert!(obj.invoke_method(1, Some(CosemDataType::OctetString(bad))).is_err());
1195 }
1196
1197 #[test]
1199 fn mechanism_name_oid_covers_all_ids() {
1200 for id in 0..=10u8 {
1201 let mut obj = sample(AssociationLnVersion::Version0);
1202 obj.authentication_mechanism = AuthMechanism::from_id(id).unwrap();
1203 if let CosemDataType::OctetString(oid) = obj.authentication_mechanism_name() {
1204 assert_eq!(oid, vec![0x09, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x02, id]);
1205 } else {
1206 panic!("mechanism name must be an octet-string");
1207 }
1208 }
1209 }
1210
1211 fn hex(s: &[u8]) -> Vec<u8> {
1213 fn nib(c: u8) -> u8 {
1214 match c {
1215 b'0'..=b'9' => c - b'0',
1216 b'A'..=b'F' => c - b'A' + 10,
1217 b'a'..=b'f' => c - b'a' + 10,
1218 _ => panic!("invalid hex digit"),
1219 }
1220 }
1221 s.chunks(2).map(|p| (nib(p[0]) << 4) | nib(p[1])).collect()
1222 }
1223}