1use super::ServiceError;
13
14pub const AARQ_TAG: u8 = 0x60;
16pub const AARE_TAG: u8 = 0x61;
18pub const RLRQ_TAG: u8 = 0x62;
20pub const RLRE_TAG: u8 = 0x63;
22
23pub mod release_reason {
25 pub const NORMAL: u8 = 0;
27 pub const URGENT: u8 = 1;
29 pub const NOT_FINISHED: u8 = 1;
31 pub const USER_DEFINED: u8 = 30;
33}
34
35pub mod result {
37 pub const ACCEPTED: u8 = 0;
39 pub const REJECTED_PERMANENT: u8 = 1;
41 pub const REJECTED_TRANSIENT: u8 = 2;
43}
44
45pub mod application_context {
48 pub const LN: u8 = 1;
50 pub const SN: u8 = 2;
52 pub const LN_CIPHERING: u8 = 3;
54 pub const SN_CIPHERING: u8 = 4;
56}
57
58pub mod mechanism {
61 pub const LOWEST: u8 = 0;
63 pub const LLS: u8 = 1;
65 pub const HLS_MD5: u8 = 3;
67 pub const HLS_SHA1: u8 = 4;
69 pub const HLS_GMAC: u8 = 5;
71 pub const HLS_SHA256: u8 = 6;
73 pub const HLS_ECDSA: u8 = 7;
75 pub const HLS_GOST_CMAC: u8 = 8;
77 pub const HLS_GOST_STREEBOG: u8 = 9;
79 pub const HLS_GOST_SIGNATURE: u8 = 10;
81}
82
83pub mod acse_diagnostic {
86 pub const NULL: u8 = 0;
88 pub const APPLICATION_CONTEXT_NAME_NOT_SUPPORTED: u8 = 2;
90 pub const CALLING_AP_TITLE_NOT_RECOGNIZED: u8 = 3;
92 pub const AUTHENTICATION_MECHANISM_NAME_NOT_RECOGNISED: u8 = 11;
94 pub const AUTHENTICATION_FAILURE: u8 = 13;
96 pub const AUTHENTICATION_REQUIRED: u8 = 14;
98}
99
100pub mod acse_provider_diagnostic {
102 pub const NO_COMMON_ACSE_VERSION: u8 = 2;
104}
105
106pub const PROTOCOL_VERSION_1: [u8; 2] = [0x02, 0x84];
108
109const OID_PREFIX_APP_CONTEXT: [u8; 6] = [0x60, 0x85, 0x74, 0x05, 0x08, 0x01];
110const OID_PREFIX_MECHANISM: [u8; 6] = [0x60, 0x85, 0x74, 0x05, 0x08, 0x02];
111
112#[derive(Debug, Clone, PartialEq, Default)]
114pub struct AssociationRequest {
115 pub protocol_version: Option<[u8; 2]>,
117 pub application_context: u8,
119 pub calling_ap_title: Option<Vec<u8>>,
121 pub sender_acse_requirements: Option<u8>,
123 pub mechanism_name: Option<u8>,
125 pub calling_authentication_value: Option<Vec<u8>>,
127 pub user_information: Vec<u8>,
129}
130
131impl AssociationRequest {
132 pub fn encode(&self) -> Vec<u8> {
134 let mut content = Vec::new();
135 if let Some(pv) = self.protocol_version {
137 content.extend_from_slice(&[0x80, 0x02, pv[0], pv[1]]);
138 }
139 ber_tlv(0xA1, &object_identifier(OID_PREFIX_APP_CONTEXT, self.application_context), &mut content);
141 if let Some(title) = &self.calling_ap_title {
143 ber_tlv(0xA6, &octet_string(title), &mut content);
144 }
145 if let Some(mech) = self.mechanism_name {
147 let acse_req = self.sender_acse_requirements.unwrap_or(0x80);
149 content.extend_from_slice(&[0x8A, 0x02, 0x07, acse_req]);
150 content.push(0x8B);
152 let oid = raw_oid(OID_PREFIX_MECHANISM, mech);
153 push_length(oid.len(), &mut content);
154 content.extend_from_slice(&oid);
155 if let Some(auth) = &self.calling_authentication_value {
157 let mut inner = vec![0x80];
158 push_length(auth.len(), &mut inner);
159 inner.extend_from_slice(auth);
160 ber_tlv(0xAC, &inner, &mut content);
161 }
162 } else if let Some(acse_req) = self.sender_acse_requirements {
163 content.extend_from_slice(&[0x8A, 0x02, 0x07, acse_req]);
164 if let Some(auth) = &self.calling_authentication_value {
165 let mut inner = vec![0x80];
166 push_length(auth.len(), &mut inner);
167 inner.extend_from_slice(auth);
168 ber_tlv(0xAC, &inner, &mut content);
169 }
170 } else if let Some(auth) = &self.calling_authentication_value {
171 let mut inner = vec![0x80];
172 push_length(auth.len(), &mut inner);
173 inner.extend_from_slice(auth);
174 ber_tlv(0xAC, &inner, &mut content);
175 }
176 ber_tlv(0xBE, &octet_string(&self.user_information), &mut content);
178
179 let mut apdu = vec![AARQ_TAG];
180 push_length(content.len(), &mut apdu);
181 apdu.extend_from_slice(&content);
182 apdu
183 }
184
185 pub fn decode(bytes: &[u8]) -> Result<AssociationRequest, ServiceError> {
187 let content = outer_content(bytes, AARQ_TAG)?;
188 let mut req = AssociationRequest::default();
189 for (tag, value) in TlvIter::new(content) {
190 match tag {
191 0x80 if value.len() >= 2 => req.protocol_version = Some([value[0], value[1]]),
192 0xA1 => req.application_context = parse_oid_last_arc(value)?,
193 0xA6 => req.calling_ap_title = Some(parse_octet_string(value)?),
194 0x8A if value.len() >= 2 => req.sender_acse_requirements = Some(value[1]),
195 0x8B => req.mechanism_name = Some(*value.last().ok_or(ServiceError::Truncated)?),
196 0xAC => req.calling_authentication_value = Some(parse_auth_value(value)?),
197 0xBE => req.user_information = parse_octet_string(value)?,
198 _ => {} }
200 }
201 Ok(req)
202 }
203}
204
205#[derive(Debug, Clone, PartialEq, Default)]
207pub struct AssociationResponse {
208 pub protocol_version: Option<[u8; 2]>,
210 pub application_context: u8,
212 pub result: u8,
214 pub diagnostic: u8,
216 pub diagnostic_is_provider: bool,
218 pub responding_ap_title: Option<Vec<u8>>,
220 pub mechanism_name: Option<u8>,
222 pub responding_authentication_value: Option<Vec<u8>>,
224 pub user_information: Vec<u8>,
226}
227
228impl AssociationResponse {
229 pub fn encode(&self) -> Vec<u8> {
231 let mut content = Vec::new();
232 if let Some(pv) = self.protocol_version {
234 content.extend_from_slice(&[0x80, 0x02, pv[0], pv[1]]);
235 }
236 ber_tlv(0xA1, &object_identifier(OID_PREFIX_APP_CONTEXT, self.application_context), &mut content);
238 ber_tlv(0xA2, &[0x02, 0x01, self.result], &mut content);
240 let diag_choice = if self.diagnostic_is_provider { 0xA2 } else { 0xA1 };
242 ber_tlv(0xA3, &[diag_choice, 0x03, 0x02, 0x01, self.diagnostic], &mut content);
243 if let Some(title) = &self.responding_ap_title {
245 ber_tlv(0xA4, &octet_string(title), &mut content);
246 }
247 if self.responding_authentication_value.is_some() {
249 content.extend_from_slice(&[0x88, 0x02, 0x07, 0x80]);
250 if let Some(mech) = self.mechanism_name {
251 content.push(0x89);
252 let oid = raw_oid(OID_PREFIX_MECHANISM, mech);
253 push_length(oid.len(), &mut content);
254 content.extend_from_slice(&oid);
255 }
256 if let Some(auth) = &self.responding_authentication_value {
257 let mut inner = vec![0x80];
258 push_length(auth.len(), &mut inner);
259 inner.extend_from_slice(auth);
260 ber_tlv(0xAA, &inner, &mut content);
261 }
262 }
263 ber_tlv(0xBE, &octet_string(&self.user_information), &mut content);
265
266 let mut apdu = vec![AARE_TAG];
267 push_length(content.len(), &mut apdu);
268 apdu.extend_from_slice(&content);
269 apdu
270 }
271
272 pub fn decode(bytes: &[u8]) -> Result<AssociationResponse, ServiceError> {
274 let content = outer_content(bytes, AARE_TAG)?;
275 let mut resp = AssociationResponse { result: result::REJECTED_PERMANENT, ..AssociationResponse::default() };
276 for (tag, value) in TlvIter::new(content) {
277 match tag {
278 0x80 if value.len() >= 2 => resp.protocol_version = Some([value[0], value[1]]),
279 0xA1 => resp.application_context = parse_oid_last_arc(value)?,
280 0xA2 => resp.result = *value.last().ok_or(ServiceError::Truncated)?,
281 0xA3 => {
282 resp.diagnostic_is_provider = value.first() == Some(&0xA2);
283 resp.diagnostic = *value.last().ok_or(ServiceError::Truncated)?;
284 }
285 0xA4 => resp.responding_ap_title = Some(parse_octet_string(value)?),
286 0x89 => resp.mechanism_name = Some(*value.last().ok_or(ServiceError::Truncated)?),
287 0xAA => resp.responding_authentication_value = Some(parse_auth_value(value)?),
288 0xBE => resp.user_information = parse_octet_string(value)?,
289 _ => {}
290 }
291 }
292 Ok(resp)
293 }
294}
295
296#[derive(Debug, Clone, PartialEq)]
300pub struct ReleaseRequest {
301 pub reason: Option<u8>,
303 pub user_information: Option<Vec<u8>>,
305}
306
307pub type ReleaseResponse = ReleaseRequest;
309
310impl ReleaseRequest {
311 pub fn encode_rlrq(&self) -> Vec<u8> {
313 self.encode(RLRQ_TAG)
314 }
315
316 pub fn encode_rlre(&self) -> Vec<u8> {
318 self.encode(RLRE_TAG)
319 }
320
321 fn encode(&self, apdu_tag: u8) -> Vec<u8> {
322 let mut content = Vec::new();
323 if let Some(reason) = self.reason {
325 content.extend_from_slice(&[0x80, 0x01, reason]);
326 }
327 if let Some(info) = &self.user_information {
329 ber_tlv(0xBE, &octet_string(info), &mut content);
330 }
331 let mut apdu = vec![apdu_tag];
332 push_length(content.len(), &mut apdu);
333 apdu.extend_from_slice(&content);
334 apdu
335 }
336
337 pub fn decode_rlrq(bytes: &[u8]) -> Result<ReleaseRequest, ServiceError> {
339 Self::decode(bytes, RLRQ_TAG)
340 }
341
342 pub fn decode_rlre(bytes: &[u8]) -> Result<ReleaseResponse, ServiceError> {
344 Self::decode(bytes, RLRE_TAG)
345 }
346
347 fn decode(bytes: &[u8], apdu_tag: u8) -> Result<ReleaseRequest, ServiceError> {
348 let content = outer_content(bytes, apdu_tag)?;
349 let mut req = ReleaseRequest { reason: None, user_information: None };
350 for (tag, value) in TlvIter::new(content) {
351 match tag {
352 0x80 => req.reason = Some(*value.last().ok_or(ServiceError::Truncated)?),
353 0xBE => req.user_information = Some(parse_octet_string(value)?),
354 _ => {}
355 }
356 }
357 Ok(req)
358 }
359}
360
361fn object_identifier(prefix: [u8; 6], last_arc: u8) -> Vec<u8> {
365 let mut v = vec![0x06, 0x07];
366 v.extend_from_slice(&prefix);
367 v.push(last_arc);
368 v
369}
370
371fn raw_oid(prefix: [u8; 6], last_arc: u8) -> Vec<u8> {
373 let mut v = prefix.to_vec();
374 v.push(last_arc);
375 v
376}
377
378fn octet_string(bytes: &[u8]) -> Vec<u8> {
380 let mut v = vec![0x04];
381 push_length(bytes.len(), &mut v);
382 v.extend_from_slice(bytes);
383 v
384}
385
386fn ber_tlv(tag: u8, value: &[u8], out: &mut Vec<u8>) {
387 out.push(tag);
388 push_length(value.len(), out);
389 out.extend_from_slice(value);
390}
391
392#[allow(clippy::cast_possible_truncation)] fn push_length(length: usize, out: &mut Vec<u8>) {
395 if length < 128 {
396 out.push(length as u8);
397 } else {
398 let bytes = (length as u64).to_be_bytes();
399 let first = bytes.iter().position(|&b| b != 0).unwrap_or(7);
400 let n = 8 - first;
401 out.push(0x80 | n as u8);
402 out.extend_from_slice(&bytes[first..]);
403 }
404}
405
406fn read_length(bytes: &[u8]) -> Result<(usize, usize), ServiceError> {
408 let first = *bytes.first().ok_or(ServiceError::Truncated)?;
409 if first < 128 {
410 Ok((first as usize, 1))
411 } else {
412 let n = (first & 0x7F) as usize;
413 let slice = bytes.get(1..1 + n).ok_or(ServiceError::Truncated)?;
414 let mut len = 0usize;
415 for &b in slice {
416 len = (len << 8) | b as usize;
417 }
418 Ok((len, 1 + n))
419 }
420}
421
422fn outer_content(bytes: &[u8], expected_tag: u8) -> Result<&[u8], ServiceError> {
424 let tag = *bytes.first().ok_or(ServiceError::Truncated)?;
425 if tag != expected_tag {
426 return Err(ServiceError::UnexpectedTag(tag));
427 }
428 let (len, header) = read_length(&bytes[1..])?;
429 let start = 1 + header;
430 bytes.get(start..start + len).ok_or(ServiceError::Truncated)
431}
432
433fn parse_oid_last_arc(value: &[u8]) -> Result<u8, ServiceError> {
436 value.last().copied().ok_or(ServiceError::Truncated)
438}
439
440fn parse_octet_string(value: &[u8]) -> Result<Vec<u8>, ServiceError> {
442 if value.first() != Some(&0x04) {
443 return Err(ServiceError::InvalidData);
444 }
445 let (len, header) = read_length(&value[1..])?;
446 let start = 1 + header;
447 value.get(start..start + len).map(|s| s.to_vec()).ok_or(ServiceError::Truncated)
448}
449
450fn parse_auth_value(value: &[u8]) -> Result<Vec<u8>, ServiceError> {
453 if value.first() != Some(&0x80) {
454 return Err(ServiceError::InvalidData);
455 }
456 let (len, header) = read_length(&value[1..])?;
457 let start = 1 + header;
458 value.get(start..start + len).map(|s| s.to_vec()).ok_or(ServiceError::Truncated)
459}
460
461struct TlvIter<'a> {
464 rest: &'a [u8],
465}
466
467impl<'a> TlvIter<'a> {
468 fn new(rest: &'a [u8]) -> Self {
469 TlvIter { rest }
470 }
471}
472
473impl<'a> Iterator for TlvIter<'a> {
474 type Item = (u8, &'a [u8]);
475
476 fn next(&mut self) -> Option<Self::Item> {
477 if self.rest.is_empty() {
478 return None;
479 }
480 let tag = self.rest[0];
481 let (len, header) = read_length(&self.rest[1..]).ok()?;
482 let start = 1 + header;
483 let value = self.rest.get(start..start + len)?;
484 self.rest = &self.rest[start + len..];
485 Some((tag, value))
486 }
487}
488
489#[cfg(test)]
490mod tests {
491 use super::*;
492
493 #[test]
494 fn aarq_lls_matches_reference_bytes() {
495 let initiate_request = vec![0x01, 0x00, 0x00, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0];
497 let aarq = AssociationRequest {
498 protocol_version: None,
499 application_context: application_context::LN,
500 calling_ap_title: None,
501 sender_acse_requirements: Some(0x80),
502 mechanism_name: Some(mechanism::LLS),
503 calling_authentication_value: Some(b"12345678".to_vec()),
504 user_information: initiate_request,
505 };
506 let encoded = aarq.encode();
507 let expected = vec![
508 0x60, 0x36, 0xA1, 0x09, 0x06, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x01, 0x01, 0x8A, 0x02, 0x07, 0x80, 0x8B, 0x07, 0x60, 0x85, 0x74, 0x05, 0x08, 0x02, 0x01, 0xAC, 0x0A, 0x80, 0x08, 0x31, 0x32, 0x33, 0x34, 0x35, 0x36, 0x37, 0x38, 0xBE, 0x10, 0x04, 0x0E, 0x01, 0x00, 0x00, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0,
515 ];
516 assert_eq!(encoded, expected);
517 assert_eq!(AssociationRequest::decode(&encoded).unwrap(), aarq);
518 }
519
520 #[test]
521 fn aarq_no_security_round_trips() {
522 let aarq = AssociationRequest {
523 application_context: application_context::LN,
524 calling_ap_title: None,
525 mechanism_name: None,
526 calling_authentication_value: None,
527 user_information: vec![0x01, 0x00, 0x00, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0],
528 ..Default::default()
529 };
530 assert_eq!(AssociationRequest::decode(&aarq.encode()).unwrap(), aarq);
531 }
532
533 #[test]
534 fn aare_accepted_round_trips() {
535 let aare = AssociationResponse {
536 application_context: application_context::LN,
537 result: result::ACCEPTED,
538 diagnostic: 0,
539 responding_ap_title: None,
540 responding_authentication_value: None,
541 user_information: vec![0x08, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0],
542 ..Default::default()
543 };
544 let encoded = aare.encode();
545 assert_eq!(encoded[0], AARE_TAG);
546 assert_eq!(AssociationResponse::decode(&encoded).unwrap(), aare);
547 }
548
549 #[test]
550 fn rlrq_normal_round_trips() {
551 let rlrq = ReleaseRequest { reason: Some(release_reason::NORMAL), user_information: None };
552 assert_eq!(rlrq.encode_rlrq(), vec![0x62, 0x03, 0x80, 0x01, 0x00]);
554 assert_eq!(ReleaseRequest::decode_rlrq(&rlrq.encode_rlrq()).unwrap(), rlrq);
555 }
556
557 #[test]
558 fn rlre_with_user_information_round_trips() {
559 let rlre = ReleaseResponse {
560 reason: Some(release_reason::NORMAL),
561 user_information: Some(vec![0x08, 0x00, 0x06, 0x5F, 0x1F, 0x04, 0x00, 0x00, 0x7E, 0x1F, 0x04, 0xB0]),
562 };
563 let bytes = rlre.encode_rlre();
564 assert_eq!(bytes[0], RLRE_TAG);
565 assert_eq!(ReleaseResponse::decode_rlre(&bytes).unwrap(), rlre);
566 }
567
568 #[test]
569 fn aare_hls_carries_stoc_and_server_title() {
570 let aare = AssociationResponse {
571 application_context: application_context::LN_CIPHERING,
572 result: result::ACCEPTED,
573 diagnostic: 0,
574 responding_ap_title: Some(vec![0x4D, 0x4D, 0x4D, 0x00, 0x00, 0xBC, 0x61, 0x4E]),
575 responding_authentication_value: Some(b"P6wRJ21F".to_vec()),
576 user_information: vec![0x08, 0x00],
577 ..Default::default()
578 };
579 let decoded = AssociationResponse::decode(&aare.encode()).unwrap();
580 assert_eq!(decoded, aare);
581 assert_eq!(decoded.responding_authentication_value.unwrap(), b"P6wRJ21F");
582 }
583}