1use crate::errors::{AuthError, Result};
22use md5::Digest;
23use ring::rand::SecureRandom;
24use serde::{Deserialize, Serialize};
25use std::collections::HashMap;
26use std::net::SocketAddr;
27use std::time::Duration;
28use tokio::net::UdpSocket;
29use zeroize::Zeroizing;
30
31pub mod code {
35 pub const ACCESS_REQUEST: u8 = 1;
36 pub const ACCESS_ACCEPT: u8 = 2;
37 pub const ACCESS_REJECT: u8 = 3;
38 pub const ACCOUNTING_REQUEST: u8 = 4;
39 pub const ACCOUNTING_RESPONSE: u8 = 5;
40 pub const ACCESS_CHALLENGE: u8 = 11;
41}
42
43pub mod attr {
45 pub const USER_NAME: u8 = 1;
46 pub const USER_PASSWORD: u8 = 2;
47 pub const NAS_IP_ADDRESS: u8 = 4;
48 pub const NAS_PORT: u8 = 5;
49 pub const SERVICE_TYPE: u8 = 6;
50 pub const FRAMED_PROTOCOL: u8 = 7;
51 pub const FILTER_ID: u8 = 11;
52 pub const REPLY_MESSAGE: u8 = 18;
53 pub const STATE: u8 = 24;
54 pub const SESSION_TIMEOUT: u8 = 27;
55 pub const CALLING_STATION_ID: u8 = 31;
56 pub const NAS_IDENTIFIER: u8 = 32;
57 pub const ACCT_STATUS_TYPE: u8 = 40;
58 pub const ACCT_SESSION_ID: u8 = 44;
59 pub const NAS_PORT_TYPE: u8 = 61;
60 pub const EAP_MESSAGE: u8 = 79;
61 pub const MESSAGE_AUTHENTICATOR: u8 = 80;
62}
63
64const MAX_PACKET_SIZE: usize = 4096;
66
67const HEADER_LEN: usize = 20;
69
70const AUTHENTICATOR_LEN: usize = 16;
72
73#[derive(Debug, Clone)]
77pub struct RadiusConfig {
78 pub server_addr: String,
80
81 pub shared_secret: Zeroizing<String>,
83
84 pub timeout: Duration,
86
87 pub retries: u32,
89
90 pub nas_identifier: String,
92
93 pub accounting_addr: Option<String>,
95}
96
97impl Default for RadiusConfig {
98 fn default() -> Self {
99 Self {
100 server_addr: "127.0.0.1:1812".into(),
101 shared_secret: String::new().into(),
102 timeout: Duration::from_secs(5),
103 retries: 3,
104 nas_identifier: "auth-framework".into(),
105 accounting_addr: None,
106 }
107 }
108}
109
110impl RadiusConfig {
111 pub fn with_server(
124 server_addr: impl Into<String>,
125 shared_secret: impl Into<String>,
126 ) -> Result<Self> {
127 let secret = shared_secret.into();
128 if secret.len() < 6 {
129 return Err(AuthError::config(
130 "RADIUS shared_secret must be at least 6 bytes",
131 ));
132 }
133 Ok(Self {
134 server_addr: server_addr.into(),
135 shared_secret: secret.into(),
136 ..Default::default()
137 })
138 }
139
140 pub fn with_options(
155 server_addr: impl Into<String>,
156 shared_secret: impl Into<String>,
157 timeout: Duration,
158 retries: u32,
159 ) -> Result<Self> {
160 let mut cfg = Self::with_server(server_addr, shared_secret)?;
161 cfg.timeout = timeout;
162 cfg.retries = retries;
163 Ok(cfg)
164 }
165}
166
167#[derive(Clone)]
171pub struct RadiusAttribute {
172 pub attr_type: u8,
173 pub value: Vec<u8>,
174}
175
176impl std::fmt::Debug for RadiusAttribute {
177 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
178 let mut d = f.debug_struct("RadiusAttribute");
179 d.field("attr_type", &self.attr_type);
180 d.field("value", &crate::utils::redact::redacted(&self.value));
181 d.finish()
182 }
183}
184
185#[derive(Debug, Clone)]
187pub struct RadiusPacket {
188 pub code: u8,
189 pub identifier: u8,
190 pub authenticator: [u8; AUTHENTICATOR_LEN],
191 pub attributes: Vec<RadiusAttribute>,
192}
193
194impl RadiusPacket {
195 pub fn add_attribute(&mut self, attr_type: u8, value: impl AsRef<[u8]>) {
213 self.attributes.push(RadiusAttribute {
214 attr_type,
215 value: value.as_ref().to_vec(),
216 });
217 }
218}
219
220#[derive(Debug, Clone, Serialize, Deserialize)]
222pub struct RadiusAuthResult {
223 pub accepted: bool,
225
226 pub reply_message: Option<String>,
228
229 pub session_timeout: Option<u32>,
231
232 pub filter_id: Option<String>,
234
235 pub challenge: bool,
237
238 pub state: Option<Vec<u8>>,
240
241 pub reply_attributes: HashMap<u8, Vec<Vec<u8>>>,
243}
244
245#[derive(Debug)]
249pub struct RadiusClient {
250 config: RadiusConfig,
251}
252
253impl RadiusClient {
254 pub fn new(config: RadiusConfig) -> Result<Self> {
256 if config.shared_secret.is_empty() {
257 return Err(AuthError::config("RADIUS shared secret must not be empty"));
258 }
259 if config.shared_secret.len() < 6 {
260 return Err(AuthError::config(
261 "RADIUS shared secret should be at least 6 bytes",
262 ));
263 }
264 Ok(Self { config })
265 }
266
267 pub async fn authenticate(&self, username: &str, password: &str) -> Result<RadiusAuthResult> {
269 self.authenticate_with_state(username, password, None).await
270 }
271
272 pub async fn authenticate_with_state(
274 &self,
275 username: &str,
276 password: &str,
277 state: Option<&[u8]>,
278 ) -> Result<RadiusAuthResult> {
279 let rng = ring::rand::SystemRandom::new();
280 let mut authenticator = [0u8; AUTHENTICATOR_LEN];
281 rng.fill(&mut authenticator)
282 .map_err(|_| AuthError::crypto("Failed to generate RADIUS authenticator"))?;
283
284 let mut id_buf = [0u8; 1];
285 rng.fill(&mut id_buf)
286 .map_err(|_| AuthError::crypto("Failed to generate RADIUS identifier"))?;
287
288 let mut packet = RadiusPacket {
289 code: code::ACCESS_REQUEST,
290 identifier: id_buf[0],
291 authenticator,
292 attributes: Vec::new(),
293 };
294
295 packet.attributes.push(RadiusAttribute {
297 attr_type: attr::USER_NAME,
298 value: username.as_bytes().to_vec(),
299 });
300
301 let encrypted_password =
303 encrypt_pap_password(password, &self.config.shared_secret, &authenticator);
304 packet.attributes.push(RadiusAttribute {
305 attr_type: attr::USER_PASSWORD,
306 value: encrypted_password,
307 });
308
309 packet.attributes.push(RadiusAttribute {
311 attr_type: attr::NAS_IDENTIFIER,
312 value: self.config.nas_identifier.as_bytes().to_vec(),
313 });
314
315 if let Some(state_val) = state {
317 packet.attributes.push(RadiusAttribute {
318 attr_type: attr::STATE,
319 value: state_val.to_vec(),
320 });
321 }
322
323 let msg_auth =
325 compute_message_authenticator(&packet, self.config.shared_secret.as_bytes())?;
326 packet.attributes.push(RadiusAttribute {
327 attr_type: attr::MESSAGE_AUTHENTICATOR,
328 value: msg_auth.to_vec(),
329 });
330
331 let response = self.send_request(&packet).await?;
332 self.parse_response(&response, &authenticator)
333 }
334
335 pub async fn send_accounting(
337 &self,
338 username: &str,
339 session_id: &str,
340 status_type: u32,
341 ) -> Result<bool> {
342 let addr = self
343 .config
344 .accounting_addr
345 .as_deref()
346 .unwrap_or("127.0.0.1:1813");
347
348 let rng = ring::rand::SystemRandom::new();
349 let mut authenticator = [0u8; AUTHENTICATOR_LEN];
350 rng.fill(&mut authenticator)
351 .map_err(|_| AuthError::crypto("Failed to generate RADIUS authenticator"))?;
352
353 let mut id_buf = [0u8; 1];
354 rng.fill(&mut id_buf)
355 .map_err(|_| AuthError::crypto("Failed to generate RADIUS identifier"))?;
356
357 let mut packet = RadiusPacket {
358 code: code::ACCOUNTING_REQUEST,
359 identifier: id_buf[0],
360 authenticator,
361 attributes: Vec::new(),
362 };
363
364 packet.attributes.push(RadiusAttribute {
365 attr_type: attr::USER_NAME,
366 value: username.as_bytes().to_vec(),
367 });
368
369 packet.attributes.push(RadiusAttribute {
370 attr_type: attr::ACCT_SESSION_ID,
371 value: session_id.as_bytes().to_vec(),
372 });
373
374 packet.attributes.push(RadiusAttribute {
375 attr_type: attr::ACCT_STATUS_TYPE,
376 value: status_type.to_be_bytes().to_vec(),
377 });
378
379 packet.attributes.push(RadiusAttribute {
380 attr_type: attr::NAS_IDENTIFIER,
381 value: self.config.nas_identifier.as_bytes().to_vec(),
382 });
383
384 let encoded = encode_packet(&packet);
386 let acct_auth =
387 compute_accounting_authenticator(&encoded, self.config.shared_secret.as_bytes());
388 let mut final_packet = packet;
389 final_packet.authenticator = acct_auth;
390
391 let response = self
392 .send_packet(&encode_packet(&final_packet), addr)
393 .await?;
394 Ok(response[0] == code::ACCOUNTING_RESPONSE)
395 }
396
397 async fn send_request(&self, packet: &RadiusPacket) -> Result<Vec<u8>> {
399 let encoded = encode_packet(packet);
400 self.send_packet(&encoded, &self.config.server_addr).await
401 }
402
403 async fn send_packet(&self, data: &[u8], addr: &str) -> Result<Vec<u8>> {
405 let server_addr: SocketAddr = addr
406 .parse()
407 .map_err(|e| AuthError::config(format!("Invalid RADIUS server address: {e}")))?;
408
409 let socket = UdpSocket::bind("0.0.0.0:0")
410 .await
411 .map_err(|e| AuthError::internal(format!("Failed to bind UDP socket: {e}")))?;
412
413 for attempt in 0..=self.config.retries {
414 socket
415 .send_to(data, server_addr)
416 .await
417 .map_err(|e| AuthError::internal(format!("RADIUS send failed: {e}")))?;
418
419 let mut buf = vec![0u8; MAX_PACKET_SIZE];
420 match tokio::time::timeout(self.config.timeout, socket.recv_from(&mut buf)).await {
421 Ok(Ok((len, _))) => return Ok(buf[..len].to_vec()),
422 Ok(Err(e)) => {
423 return Err(AuthError::internal(format!("RADIUS recv failed: {e}")));
424 }
425 Err(_) if attempt < self.config.retries => continue,
426 Err(_) => {
427 return Err(AuthError::internal("RADIUS request timed out"));
428 }
429 }
430 }
431
432 Err(AuthError::internal("RADIUS request failed after retries"))
433 }
434
435 fn parse_response(
437 &self,
438 data: &[u8],
439 request_authenticator: &[u8; AUTHENTICATOR_LEN],
440 ) -> Result<RadiusAuthResult> {
441 if data.len() < HEADER_LEN {
442 return Err(AuthError::validation("RADIUS response too short"));
443 }
444
445 let response_code = data[0];
446 let _identifier = data[1];
447 let length = u16::from_be_bytes([data[2], data[3]]) as usize;
448
449 if length > data.len() {
450 return Err(AuthError::validation("RADIUS response length mismatch"));
451 }
452
453 let expected_auth = compute_response_authenticator(
455 data,
456 request_authenticator,
457 self.config.shared_secret.as_bytes(),
458 );
459 let actual_auth = &data[4..20];
460 if !constant_time_eq(actual_auth, &expected_auth) {
461 return Err(AuthError::validation(
462 "RADIUS response authenticator verification failed",
463 ));
464 }
465
466 let mut reply_attributes: HashMap<u8, Vec<Vec<u8>>> = HashMap::new();
468 let mut pos = HEADER_LEN;
469 while pos + 2 <= length {
470 let attr_type = data[pos];
471 let attr_len = data[pos + 1] as usize;
472 if attr_len < 2 || pos + attr_len > length {
473 break;
474 }
475 let value = data[pos + 2..pos + attr_len].to_vec();
476 reply_attributes.entry(attr_type).or_default().push(value);
477 pos += attr_len;
478 }
479
480 let reply_message = reply_attributes
481 .get(&attr::REPLY_MESSAGE)
482 .and_then(|v| v.first())
483 .and_then(|b| String::from_utf8(b.clone()).ok());
484
485 let session_timeout = reply_attributes
486 .get(&attr::SESSION_TIMEOUT)
487 .and_then(|v| v.first())
488 .and_then(|b| {
489 if b.len() == 4 {
490 Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
491 } else {
492 None
493 }
494 });
495
496 let filter_id = reply_attributes
497 .get(&attr::FILTER_ID)
498 .and_then(|v| v.first())
499 .and_then(|b| String::from_utf8(b.clone()).ok());
500
501 let state = reply_attributes
502 .get(&attr::STATE)
503 .and_then(|v| v.first())
504 .cloned();
505
506 Ok(RadiusAuthResult {
507 accepted: response_code == code::ACCESS_ACCEPT,
508 reply_message,
509 session_timeout,
510 filter_id,
511 challenge: response_code == code::ACCESS_CHALLENGE,
512 state,
513 reply_attributes,
514 })
515 }
516}
517
518fn encode_packet(packet: &RadiusPacket) -> Vec<u8> {
522 let mut buf = Vec::with_capacity(MAX_PACKET_SIZE);
523
524 buf.push(packet.code);
526 buf.push(packet.identifier);
527 buf.extend_from_slice(&[0, 0]); buf.extend_from_slice(&packet.authenticator);
529
530 for attr in &packet.attributes {
532 let attr_len = (2 + attr.value.len()) as u8;
533 buf.push(attr.attr_type);
534 buf.push(attr_len);
535 buf.extend_from_slice(&attr.value);
536 }
537
538 let len = buf.len() as u16;
540 buf[2..4].copy_from_slice(&len.to_be_bytes());
541
542 buf
543}
544
545fn encrypt_pap_password(
550 password: &str,
551 shared_secret: &str,
552 authenticator: &[u8; AUTHENTICATOR_LEN],
553) -> Vec<u8> {
554 let pwd_bytes = password.as_bytes();
555 let padded_len = pwd_bytes.len().div_ceil(16) * 16;
557 let padded_len = padded_len.max(16);
558 let mut padded = vec![0u8; padded_len];
559 padded[..pwd_bytes.len()].copy_from_slice(pwd_bytes);
560
561 let mut result = vec![0u8; padded_len];
562 let mut prev_block = authenticator.to_vec();
563
564 for i in 0..(padded_len / 16) {
565 let hasher = md5_hash(shared_secret.as_bytes(), &prev_block);
566 let chunk_start = i * 16;
567 for j in 0..16 {
568 result[chunk_start + j] = padded[chunk_start + j] ^ hasher[j];
569 }
570 prev_block = result[chunk_start..chunk_start + 16].to_vec();
571 }
572
573 result
574}
575
576fn md5_hash(a: &[u8], b: &[u8]) -> [u8; 16] {
578 let mut hasher = md5::Md5::new();
579 hasher.update(a);
580 hasher.update(b);
581 hasher.finalize().into()
582}
583
584fn compute_message_authenticator(packet: &RadiusPacket, secret: &[u8]) -> Result<[u8; 16]> {
586 let mut temp_packet = packet.clone();
589 temp_packet
591 .attributes
592 .retain(|a| a.attr_type != attr::MESSAGE_AUTHENTICATOR);
593 temp_packet.attributes.push(RadiusAttribute {
595 attr_type: attr::MESSAGE_AUTHENTICATOR,
596 value: vec![0u8; 16],
597 });
598
599 let encoded = encode_packet(&temp_packet);
600 let hmac_result = hmac_md5_truncated(secret, &encoded);
601 Ok(hmac_result)
602}
603
604fn hmac_md5_truncated(key: &[u8], data: &[u8]) -> [u8; 16] {
606 use hmac::{KeyInit, Mac};
607 type HmacMd5 = hmac::Hmac<md5::Md5>;
608 let mut mac = HmacMd5::new_from_slice(key).expect("HMAC key length");
609 mac.update(data);
610 let result = mac.finalize().into_bytes();
611 let mut out = [0u8; 16];
612 out.copy_from_slice(&result[..16]);
613 out
614}
615
616fn compute_response_authenticator(
620 response: &[u8],
621 request_auth: &[u8; AUTHENTICATOR_LEN],
622 secret: &[u8],
623) -> [u8; 16] {
624 let mut hasher = md5::Md5::new();
625 hasher.update(&response[..4]); hasher.update(request_auth); if response.len() > HEADER_LEN {
628 hasher.update(&response[HEADER_LEN..]); }
630 hasher.update(secret);
631 hasher.finalize().into()
632}
633
634fn compute_accounting_authenticator(packet_bytes: &[u8], secret: &[u8]) -> [u8; AUTHENTICATOR_LEN] {
636 let mut hasher = md5::Md5::new();
637 hasher.update(&packet_bytes[..4]); hasher.update([0u8; AUTHENTICATOR_LEN]); if packet_bytes.len() > HEADER_LEN {
640 hasher.update(&packet_bytes[HEADER_LEN..]); }
642 hasher.update(secret);
643 hasher.finalize().into()
644}
645
646fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
648 use subtle::ConstantTimeEq;
649 if a.len() != b.len() {
650 return false;
651 }
652 a.ct_eq(b).into()
653}
654
655#[cfg(test)]
656mod tests {
657 use super::*;
658
659 #[test]
662 fn digest_known_answers() {
663 let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::<String>();
664 assert_eq!(
666 hex(&md5_hash(b"a", b"bc")),
667 "900150983cd24fb0d6963f7d28e17f72"
668 );
669 assert_eq!(
671 hex(&hmac_md5_truncated(&[0x0b; 16], b"Hi There")),
672 "9294727a3638bb1c13f48ef8158bfc9d"
673 );
674 let secret = b"testing123";
675 let mut response = vec![2u8, 1, 0, 24];
676 response.extend_from_slice(&[0u8; 16]);
677 response.extend_from_slice(&[0x12, 0x04, 0xAA, 0xBB]);
678 let request_auth: [u8; AUTHENTICATOR_LEN] = core::array::from_fn(|i| i as u8);
679 assert_eq!(
680 hex(&compute_response_authenticator(
681 &response,
682 &request_auth,
683 secret
684 )),
685 "a66b6244b8360d8b2763b82d84b435d1"
686 );
687 let mut accounting = vec![4u8, 1, 0, 24];
688 accounting.extend((16u8..32).collect::<Vec<_>>());
689 accounting.extend_from_slice(&[0x12, 0x04, 0xAA, 0xBB]);
690 assert_eq!(
691 hex(&compute_accounting_authenticator(&accounting, secret)),
692 "e4864f7f59f85599ece0fa0ab2d3ec9c"
693 );
694 }
695
696 #[test]
697 fn test_config_defaults() {
698 let config = RadiusConfig::default();
699 assert_eq!(config.server_addr, "127.0.0.1:1812");
700 assert_eq!(config.retries, 3);
701 }
702
703 #[test]
704 fn test_client_requires_secret() {
705 let config = RadiusConfig::default();
706 let err = RadiusClient::new(config).unwrap_err();
707 assert!(err.to_string().contains("secret"));
708 }
709
710 #[test]
711 fn test_client_rejects_short_secret() {
712 let config = RadiusConfig {
713 shared_secret: "abc".to_string().into(),
714 ..Default::default()
715 };
716 let err = RadiusClient::new(config).unwrap_err();
717 assert!(err.to_string().contains("6 bytes"));
718 }
719
720 #[test]
721 fn test_client_creation() {
722 let config = RadiusConfig {
723 shared_secret: "testing123".to_string().into(),
724 ..Default::default()
725 };
726 assert!(RadiusClient::new(config).is_ok());
727 }
728
729 #[test]
730 fn test_packet_encoding() {
731 let packet = RadiusPacket {
732 code: code::ACCESS_REQUEST,
733 identifier: 42,
734 authenticator: [0u8; AUTHENTICATOR_LEN],
735 attributes: vec![RadiusAttribute {
736 attr_type: attr::USER_NAME,
737 value: b"test".to_vec(),
738 }],
739 };
740
741 let encoded = encode_packet(&packet);
742 assert_eq!(encoded[0], code::ACCESS_REQUEST);
743 assert_eq!(encoded[1], 42);
744 let length = u16::from_be_bytes([encoded[2], encoded[3]]);
745 assert_eq!(length as usize, encoded.len());
746 }
747
748 #[test]
749 fn test_pap_password_encryption() {
750 let auth = [1u8; AUTHENTICATOR_LEN];
751 let encrypted = encrypt_pap_password("password", "secret", &auth);
752 assert_eq!(encrypted.len(), 16); assert_ne!(&encrypted[..8], b"password");
755 }
756
757 #[test]
758 fn test_radius_attribute_codes() {
759 assert_eq!(attr::USER_NAME, 1);
760 assert_eq!(attr::USER_PASSWORD, 2);
761 assert_eq!(attr::MESSAGE_AUTHENTICATOR, 80);
762 }
763
764 #[test]
765 fn test_radius_config_with_server() {
766 let config = RadiusConfig::with_server("10.0.0.1:1812", "testing123").unwrap();
767 assert_eq!(config.server_addr, "10.0.0.1:1812");
768 assert_eq!(config.shared_secret.as_str(), "testing123");
769 assert_eq!(config.retries, 3); }
771
772 #[test]
773 fn test_radius_config_with_server_rejects_short_secret() {
774 let err = RadiusConfig::with_server("10.0.0.1:1812", "abc").unwrap_err();
775 assert!(err.to_string().contains("6 bytes"));
776 }
777
778 #[test]
779 fn test_radius_config_with_options() {
780 let config =
781 RadiusConfig::with_options("10.0.0.1:1812", "testing123", Duration::from_secs(10), 5)
782 .unwrap();
783 assert_eq!(config.timeout, Duration::from_secs(10));
784 assert_eq!(config.retries, 5);
785 }
786
787 #[test]
788 fn test_radius_packet_add_attribute() {
789 let mut packet = RadiusPacket {
790 code: code::ACCESS_REQUEST,
791 identifier: 1,
792 authenticator: [0u8; AUTHENTICATOR_LEN],
793 attributes: Vec::new(),
794 };
795 packet.add_attribute(attr::USER_NAME, b"alice");
796 packet.add_attribute(attr::NAS_IDENTIFIER, b"my-nas");
797
798 assert_eq!(packet.attributes.len(), 2);
799 assert_eq!(packet.attributes[0].attr_type, attr::USER_NAME);
800 assert_eq!(packet.attributes[0].value, b"alice");
801 assert_eq!(packet.attributes[1].attr_type, attr::NAS_IDENTIFIER);
802 }
803}