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(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
245impl std::fmt::Debug for RadiusAuthResult {
246 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
247 let mut d = f.debug_struct("RadiusAuthResult");
248 d.field("accepted", &self.accepted);
249 d.field("reply_message", &self.reply_message);
250 d.field("session_timeout", &self.session_timeout);
251 d.field("filter_id", &self.filter_id);
252 d.field("challenge", &self.challenge);
253 d.field("state", &crate::utils::redact::redacted(&self.state));
254 d.field(
255 "reply_attributes",
256 &crate::utils::redact::redacted(&self.reply_attributes),
257 );
258 d.finish()
259 }
260}
261
262#[derive(Debug)]
266pub struct RadiusClient {
267 config: RadiusConfig,
268}
269
270impl RadiusClient {
271 pub fn new(config: RadiusConfig) -> Result<Self> {
273 if config.shared_secret.is_empty() {
274 return Err(AuthError::config("RADIUS shared secret must not be empty"));
275 }
276 if config.shared_secret.len() < 6 {
277 return Err(AuthError::config(
278 "RADIUS shared secret should be at least 6 bytes",
279 ));
280 }
281 Ok(Self { config })
282 }
283
284 pub async fn authenticate(&self, username: &str, password: &str) -> Result<RadiusAuthResult> {
286 self.authenticate_with_state(username, password, None).await
287 }
288
289 pub async fn authenticate_with_state(
291 &self,
292 username: &str,
293 password: &str,
294 state: Option<&[u8]>,
295 ) -> Result<RadiusAuthResult> {
296 let rng = ring::rand::SystemRandom::new();
297 let mut authenticator = [0u8; AUTHENTICATOR_LEN];
298 rng.fill(&mut authenticator)
299 .map_err(|_| AuthError::crypto("Failed to generate RADIUS authenticator"))?;
300
301 let mut id_buf = [0u8; 1];
302 rng.fill(&mut id_buf)
303 .map_err(|_| AuthError::crypto("Failed to generate RADIUS identifier"))?;
304
305 let mut packet = RadiusPacket {
306 code: code::ACCESS_REQUEST,
307 identifier: id_buf[0],
308 authenticator,
309 attributes: Vec::new(),
310 };
311
312 packet.attributes.push(RadiusAttribute {
314 attr_type: attr::USER_NAME,
315 value: username.as_bytes().to_vec(),
316 });
317
318 let encrypted_password =
320 encrypt_pap_password(password, &self.config.shared_secret, &authenticator);
321 packet.attributes.push(RadiusAttribute {
322 attr_type: attr::USER_PASSWORD,
323 value: encrypted_password,
324 });
325
326 packet.attributes.push(RadiusAttribute {
328 attr_type: attr::NAS_IDENTIFIER,
329 value: self.config.nas_identifier.as_bytes().to_vec(),
330 });
331
332 if let Some(state_val) = state {
334 packet.attributes.push(RadiusAttribute {
335 attr_type: attr::STATE,
336 value: state_val.to_vec(),
337 });
338 }
339
340 let msg_auth =
342 compute_message_authenticator(&packet, self.config.shared_secret.as_bytes())?;
343 packet.attributes.push(RadiusAttribute {
344 attr_type: attr::MESSAGE_AUTHENTICATOR,
345 value: msg_auth.to_vec(),
346 });
347
348 let response = self.send_request(&packet).await?;
349 self.parse_response(&response, &authenticator)
350 }
351
352 pub async fn send_accounting(
354 &self,
355 username: &str,
356 session_id: &str,
357 status_type: u32,
358 ) -> Result<bool> {
359 let addr = self
360 .config
361 .accounting_addr
362 .as_deref()
363 .unwrap_or("127.0.0.1:1813");
364
365 let rng = ring::rand::SystemRandom::new();
366 let mut authenticator = [0u8; AUTHENTICATOR_LEN];
367 rng.fill(&mut authenticator)
368 .map_err(|_| AuthError::crypto("Failed to generate RADIUS authenticator"))?;
369
370 let mut id_buf = [0u8; 1];
371 rng.fill(&mut id_buf)
372 .map_err(|_| AuthError::crypto("Failed to generate RADIUS identifier"))?;
373
374 let mut packet = RadiusPacket {
375 code: code::ACCOUNTING_REQUEST,
376 identifier: id_buf[0],
377 authenticator,
378 attributes: Vec::new(),
379 };
380
381 packet.attributes.push(RadiusAttribute {
382 attr_type: attr::USER_NAME,
383 value: username.as_bytes().to_vec(),
384 });
385
386 packet.attributes.push(RadiusAttribute {
387 attr_type: attr::ACCT_SESSION_ID,
388 value: session_id.as_bytes().to_vec(),
389 });
390
391 packet.attributes.push(RadiusAttribute {
392 attr_type: attr::ACCT_STATUS_TYPE,
393 value: status_type.to_be_bytes().to_vec(),
394 });
395
396 packet.attributes.push(RadiusAttribute {
397 attr_type: attr::NAS_IDENTIFIER,
398 value: self.config.nas_identifier.as_bytes().to_vec(),
399 });
400
401 let encoded = encode_packet(&packet);
403 let acct_auth =
404 compute_accounting_authenticator(&encoded, self.config.shared_secret.as_bytes());
405 let mut final_packet = packet;
406 final_packet.authenticator = acct_auth;
407
408 let response = self
409 .send_packet(&encode_packet(&final_packet), addr)
410 .await?;
411 Ok(response[0] == code::ACCOUNTING_RESPONSE)
412 }
413
414 async fn send_request(&self, packet: &RadiusPacket) -> Result<Vec<u8>> {
416 let encoded = encode_packet(packet);
417 self.send_packet(&encoded, &self.config.server_addr).await
418 }
419
420 async fn send_packet(&self, data: &[u8], addr: &str) -> Result<Vec<u8>> {
422 let server_addr: SocketAddr = addr
423 .parse()
424 .map_err(|e| AuthError::config(format!("Invalid RADIUS server address: {e}")))?;
425
426 let socket = UdpSocket::bind("0.0.0.0:0")
427 .await
428 .map_err(|e| AuthError::internal(format!("Failed to bind UDP socket: {e}")))?;
429
430 for attempt in 0..=self.config.retries {
431 socket
432 .send_to(data, server_addr)
433 .await
434 .map_err(|e| AuthError::internal(format!("RADIUS send failed: {e}")))?;
435
436 let mut buf = vec![0u8; MAX_PACKET_SIZE];
437 match tokio::time::timeout(self.config.timeout, socket.recv_from(&mut buf)).await {
438 Ok(Ok((len, _))) => return Ok(buf[..len].to_vec()),
439 Ok(Err(e)) => {
440 return Err(AuthError::internal(format!("RADIUS recv failed: {e}")));
441 }
442 Err(_) if attempt < self.config.retries => continue,
443 Err(_) => {
444 return Err(AuthError::internal("RADIUS request timed out"));
445 }
446 }
447 }
448
449 Err(AuthError::internal("RADIUS request failed after retries"))
450 }
451
452 fn parse_response(
454 &self,
455 data: &[u8],
456 request_authenticator: &[u8; AUTHENTICATOR_LEN],
457 ) -> Result<RadiusAuthResult> {
458 if data.len() < HEADER_LEN {
459 return Err(AuthError::validation("RADIUS response too short"));
460 }
461
462 let response_code = data[0];
463 let _identifier = data[1];
464 let length = u16::from_be_bytes([data[2], data[3]]) as usize;
465
466 if length > data.len() {
467 return Err(AuthError::validation("RADIUS response length mismatch"));
468 }
469
470 let expected_auth = compute_response_authenticator(
472 data,
473 request_authenticator,
474 self.config.shared_secret.as_bytes(),
475 );
476 let actual_auth = &data[4..20];
477 if !constant_time_eq(actual_auth, &expected_auth) {
478 return Err(AuthError::validation(
479 "RADIUS response authenticator verification failed",
480 ));
481 }
482
483 let mut reply_attributes: HashMap<u8, Vec<Vec<u8>>> = HashMap::new();
485 let mut pos = HEADER_LEN;
486 while pos + 2 <= length {
487 let attr_type = data[pos];
488 let attr_len = data[pos + 1] as usize;
489 if attr_len < 2 || pos + attr_len > length {
490 break;
491 }
492 let value = data[pos + 2..pos + attr_len].to_vec();
493 reply_attributes.entry(attr_type).or_default().push(value);
494 pos += attr_len;
495 }
496
497 let reply_message = reply_attributes
498 .get(&attr::REPLY_MESSAGE)
499 .and_then(|v| v.first())
500 .and_then(|b| String::from_utf8(b.clone()).ok());
501
502 let session_timeout = reply_attributes
503 .get(&attr::SESSION_TIMEOUT)
504 .and_then(|v| v.first())
505 .and_then(|b| {
506 if b.len() == 4 {
507 Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
508 } else {
509 None
510 }
511 });
512
513 let filter_id = reply_attributes
514 .get(&attr::FILTER_ID)
515 .and_then(|v| v.first())
516 .and_then(|b| String::from_utf8(b.clone()).ok());
517
518 let state = reply_attributes
519 .get(&attr::STATE)
520 .and_then(|v| v.first())
521 .cloned();
522
523 Ok(RadiusAuthResult {
524 accepted: response_code == code::ACCESS_ACCEPT,
525 reply_message,
526 session_timeout,
527 filter_id,
528 challenge: response_code == code::ACCESS_CHALLENGE,
529 state,
530 reply_attributes,
531 })
532 }
533}
534
535fn encode_packet(packet: &RadiusPacket) -> Vec<u8> {
539 let mut buf = Vec::with_capacity(MAX_PACKET_SIZE);
540
541 buf.push(packet.code);
543 buf.push(packet.identifier);
544 buf.extend_from_slice(&[0, 0]); buf.extend_from_slice(&packet.authenticator);
546
547 for attr in &packet.attributes {
549 let attr_len = (2 + attr.value.len()) as u8;
550 buf.push(attr.attr_type);
551 buf.push(attr_len);
552 buf.extend_from_slice(&attr.value);
553 }
554
555 let len = buf.len() as u16;
557 buf[2..4].copy_from_slice(&len.to_be_bytes());
558
559 buf
560}
561
562fn encrypt_pap_password(
567 password: &str,
568 shared_secret: &str,
569 authenticator: &[u8; AUTHENTICATOR_LEN],
570) -> Vec<u8> {
571 let pwd_bytes = password.as_bytes();
572 let padded_len = pwd_bytes.len().div_ceil(16) * 16;
574 let padded_len = padded_len.max(16);
575 let mut padded = vec![0u8; padded_len];
576 padded[..pwd_bytes.len()].copy_from_slice(pwd_bytes);
577
578 let mut result = vec![0u8; padded_len];
579 let mut prev_block = authenticator.to_vec();
580
581 for i in 0..(padded_len / 16) {
582 let hasher = md5_hash(shared_secret.as_bytes(), &prev_block);
583 let chunk_start = i * 16;
584 for j in 0..16 {
585 result[chunk_start + j] = padded[chunk_start + j] ^ hasher[j];
586 }
587 prev_block = result[chunk_start..chunk_start + 16].to_vec();
588 }
589
590 result
591}
592
593fn md5_hash(a: &[u8], b: &[u8]) -> [u8; 16] {
595 let mut hasher = md5::Md5::new();
596 hasher.update(a);
597 hasher.update(b);
598 hasher.finalize().into()
599}
600
601fn compute_message_authenticator(packet: &RadiusPacket, secret: &[u8]) -> Result<[u8; 16]> {
603 let mut temp_packet = packet.clone();
606 temp_packet
608 .attributes
609 .retain(|a| a.attr_type != attr::MESSAGE_AUTHENTICATOR);
610 temp_packet.attributes.push(RadiusAttribute {
612 attr_type: attr::MESSAGE_AUTHENTICATOR,
613 value: vec![0u8; 16],
614 });
615
616 let encoded = encode_packet(&temp_packet);
617 let hmac_result = hmac_md5_truncated(secret, &encoded);
618 Ok(hmac_result)
619}
620
621fn hmac_md5_truncated(key: &[u8], data: &[u8]) -> [u8; 16] {
623 use hmac::{KeyInit, Mac};
624 type HmacMd5 = hmac::Hmac<md5::Md5>;
625 let mut mac = HmacMd5::new_from_slice(key).expect("HMAC key length");
626 mac.update(data);
627 let result = mac.finalize().into_bytes();
628 let mut out = [0u8; 16];
629 out.copy_from_slice(&result[..16]);
630 out
631}
632
633fn compute_response_authenticator(
637 response: &[u8],
638 request_auth: &[u8; AUTHENTICATOR_LEN],
639 secret: &[u8],
640) -> [u8; 16] {
641 let mut hasher = md5::Md5::new();
642 hasher.update(&response[..4]); hasher.update(request_auth); if response.len() > HEADER_LEN {
645 hasher.update(&response[HEADER_LEN..]); }
647 hasher.update(secret);
648 hasher.finalize().into()
649}
650
651fn compute_accounting_authenticator(packet_bytes: &[u8], secret: &[u8]) -> [u8; AUTHENTICATOR_LEN] {
653 let mut hasher = md5::Md5::new();
654 hasher.update(&packet_bytes[..4]); hasher.update([0u8; AUTHENTICATOR_LEN]); if packet_bytes.len() > HEADER_LEN {
657 hasher.update(&packet_bytes[HEADER_LEN..]); }
659 hasher.update(secret);
660 hasher.finalize().into()
661}
662
663fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
665 use subtle::ConstantTimeEq;
666 if a.len() != b.len() {
667 return false;
668 }
669 a.ct_eq(b).into()
670}
671
672#[cfg(test)]
673mod tests {
674 use super::*;
675
676 #[test]
679 fn digest_known_answers() {
680 let hex = |b: &[u8]| b.iter().map(|x| format!("{x:02x}")).collect::<String>();
681 assert_eq!(
683 hex(&md5_hash(b"a", b"bc")),
684 "900150983cd24fb0d6963f7d28e17f72"
685 );
686 assert_eq!(
688 hex(&hmac_md5_truncated(&[0x0b; 16], b"Hi There")),
689 "9294727a3638bb1c13f48ef8158bfc9d"
690 );
691 let secret = b"testing123";
692 let mut response = vec![2u8, 1, 0, 24];
693 response.extend_from_slice(&[0u8; 16]);
694 response.extend_from_slice(&[0x12, 0x04, 0xAA, 0xBB]);
695 let request_auth: [u8; AUTHENTICATOR_LEN] = core::array::from_fn(|i| i as u8);
696 assert_eq!(
697 hex(&compute_response_authenticator(
698 &response,
699 &request_auth,
700 secret
701 )),
702 "a66b6244b8360d8b2763b82d84b435d1"
703 );
704 let mut accounting = vec![4u8, 1, 0, 24];
705 accounting.extend((16u8..32).collect::<Vec<_>>());
706 accounting.extend_from_slice(&[0x12, 0x04, 0xAA, 0xBB]);
707 assert_eq!(
708 hex(&compute_accounting_authenticator(&accounting, secret)),
709 "e4864f7f59f85599ece0fa0ab2d3ec9c"
710 );
711 }
712
713 #[test]
714 fn test_config_defaults() {
715 let config = RadiusConfig::default();
716 assert_eq!(config.server_addr, "127.0.0.1:1812");
717 assert_eq!(config.retries, 3);
718 }
719
720 #[test]
721 fn test_client_requires_secret() {
722 let config = RadiusConfig::default();
723 let err = RadiusClient::new(config).unwrap_err();
724 assert!(err.to_string().contains("secret"));
725 }
726
727 #[test]
728 fn test_client_rejects_short_secret() {
729 let config = RadiusConfig {
730 shared_secret: "abc".to_string().into(),
731 ..Default::default()
732 };
733 let err = RadiusClient::new(config).unwrap_err();
734 assert!(err.to_string().contains("6 bytes"));
735 }
736
737 #[test]
738 fn test_client_creation() {
739 let config = RadiusConfig {
740 shared_secret: "testing123".to_string().into(),
741 ..Default::default()
742 };
743 assert!(RadiusClient::new(config).is_ok());
744 }
745
746 #[test]
747 fn test_packet_encoding() {
748 let packet = RadiusPacket {
749 code: code::ACCESS_REQUEST,
750 identifier: 42,
751 authenticator: [0u8; AUTHENTICATOR_LEN],
752 attributes: vec![RadiusAttribute {
753 attr_type: attr::USER_NAME,
754 value: b"test".to_vec(),
755 }],
756 };
757
758 let encoded = encode_packet(&packet);
759 assert_eq!(encoded[0], code::ACCESS_REQUEST);
760 assert_eq!(encoded[1], 42);
761 let length = u16::from_be_bytes([encoded[2], encoded[3]]);
762 assert_eq!(length as usize, encoded.len());
763 }
764
765 #[test]
766 fn test_pap_password_encryption() {
767 let auth = [1u8; AUTHENTICATOR_LEN];
768 let encrypted = encrypt_pap_password("password", "secret", &auth);
769 assert_eq!(encrypted.len(), 16); assert_ne!(&encrypted[..8], b"password");
772 }
773
774 #[test]
775 fn test_radius_attribute_codes() {
776 assert_eq!(attr::USER_NAME, 1);
777 assert_eq!(attr::USER_PASSWORD, 2);
778 assert_eq!(attr::MESSAGE_AUTHENTICATOR, 80);
779 }
780
781 #[test]
782 fn test_radius_config_with_server() {
783 let config = RadiusConfig::with_server("10.0.0.1:1812", "testing123").unwrap();
784 assert_eq!(config.server_addr, "10.0.0.1:1812");
785 assert_eq!(config.shared_secret.as_str(), "testing123");
786 assert_eq!(config.retries, 3); }
788
789 #[test]
790 fn test_radius_config_with_server_rejects_short_secret() {
791 let err = RadiusConfig::with_server("10.0.0.1:1812", "abc").unwrap_err();
792 assert!(err.to_string().contains("6 bytes"));
793 }
794
795 #[test]
796 fn test_radius_config_with_options() {
797 let config =
798 RadiusConfig::with_options("10.0.0.1:1812", "testing123", Duration::from_secs(10), 5)
799 .unwrap();
800 assert_eq!(config.timeout, Duration::from_secs(10));
801 assert_eq!(config.retries, 5);
802 }
803
804 #[test]
805 fn test_radius_packet_add_attribute() {
806 let mut packet = RadiusPacket {
807 code: code::ACCESS_REQUEST,
808 identifier: 1,
809 authenticator: [0u8; AUTHENTICATOR_LEN],
810 attributes: Vec::new(),
811 };
812 packet.add_attribute(attr::USER_NAME, b"alice");
813 packet.add_attribute(attr::NAS_IDENTIFIER, b"my-nas");
814
815 assert_eq!(packet.attributes.len(), 2);
816 assert_eq!(packet.attributes[0].attr_type, attr::USER_NAME);
817 assert_eq!(packet.attributes[0].value, b"alice");
818 assert_eq!(packet.attributes[1].attr_type, attr::NAS_IDENTIFIER);
819 }
820}