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;
29
30pub mod code {
34 pub const ACCESS_REQUEST: u8 = 1;
35 pub const ACCESS_ACCEPT: u8 = 2;
36 pub const ACCESS_REJECT: u8 = 3;
37 pub const ACCOUNTING_REQUEST: u8 = 4;
38 pub const ACCOUNTING_RESPONSE: u8 = 5;
39 pub const ACCESS_CHALLENGE: u8 = 11;
40}
41
42pub mod attr {
44 pub const USER_NAME: u8 = 1;
45 pub const USER_PASSWORD: u8 = 2;
46 pub const NAS_IP_ADDRESS: u8 = 4;
47 pub const NAS_PORT: u8 = 5;
48 pub const SERVICE_TYPE: u8 = 6;
49 pub const FRAMED_PROTOCOL: u8 = 7;
50 pub const FILTER_ID: u8 = 11;
51 pub const REPLY_MESSAGE: u8 = 18;
52 pub const STATE: u8 = 24;
53 pub const SESSION_TIMEOUT: u8 = 27;
54 pub const CALLING_STATION_ID: u8 = 31;
55 pub const NAS_IDENTIFIER: u8 = 32;
56 pub const ACCT_STATUS_TYPE: u8 = 40;
57 pub const ACCT_SESSION_ID: u8 = 44;
58 pub const NAS_PORT_TYPE: u8 = 61;
59 pub const EAP_MESSAGE: u8 = 79;
60 pub const MESSAGE_AUTHENTICATOR: u8 = 80;
61}
62
63const MAX_PACKET_SIZE: usize = 4096;
65
66const HEADER_LEN: usize = 20;
68
69const AUTHENTICATOR_LEN: usize = 16;
71
72#[derive(Clone)]
76pub struct RadiusConfig {
77 pub server_addr: String,
79
80 pub shared_secret: String,
82
83 pub timeout: Duration,
85
86 pub retries: u32,
88
89 pub nas_identifier: String,
91
92 pub accounting_addr: Option<String>,
94}
95
96impl std::fmt::Debug for RadiusConfig {
97 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
98 let mut d = f.debug_struct("RadiusConfig");
99 d.field("server_addr", &self.server_addr);
100 d.field(
101 "shared_secret",
102 &crate::utils::redact::redacted(&self.shared_secret),
103 );
104 d.field("timeout", &self.timeout);
105 d.field("retries", &self.retries);
106 d.field("nas_identifier", &self.nas_identifier);
107 d.field("accounting_addr", &self.accounting_addr);
108 d.finish()
109 }
110}
111
112impl Default for RadiusConfig {
113 fn default() -> Self {
114 Self {
115 server_addr: "127.0.0.1:1812".into(),
116 shared_secret: String::new(),
117 timeout: Duration::from_secs(5),
118 retries: 3,
119 nas_identifier: "auth-framework".into(),
120 accounting_addr: None,
121 }
122 }
123}
124
125impl RadiusConfig {
126 pub fn with_server(
139 server_addr: impl Into<String>,
140 shared_secret: impl Into<String>,
141 ) -> Result<Self> {
142 let secret = shared_secret.into();
143 if secret.len() < 6 {
144 return Err(AuthError::config(
145 "RADIUS shared_secret must be at least 6 bytes",
146 ));
147 }
148 Ok(Self {
149 server_addr: server_addr.into(),
150 shared_secret: secret,
151 ..Default::default()
152 })
153 }
154
155 pub fn with_options(
170 server_addr: impl Into<String>,
171 shared_secret: impl Into<String>,
172 timeout: Duration,
173 retries: u32,
174 ) -> Result<Self> {
175 let mut cfg = Self::with_server(server_addr, shared_secret)?;
176 cfg.timeout = timeout;
177 cfg.retries = retries;
178 Ok(cfg)
179 }
180}
181
182#[derive(Clone)]
186pub struct RadiusAttribute {
187 pub attr_type: u8,
188 pub value: Vec<u8>,
189}
190
191impl std::fmt::Debug for RadiusAttribute {
192 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
193 let mut d = f.debug_struct("RadiusAttribute");
194 d.field("attr_type", &self.attr_type);
195 d.field("value", &crate::utils::redact::redacted(&self.value));
196 d.finish()
197 }
198}
199
200#[derive(Debug, Clone)]
202pub struct RadiusPacket {
203 pub code: u8,
204 pub identifier: u8,
205 pub authenticator: [u8; AUTHENTICATOR_LEN],
206 pub attributes: Vec<RadiusAttribute>,
207}
208
209impl RadiusPacket {
210 pub fn add_attribute(&mut self, attr_type: u8, value: impl AsRef<[u8]>) {
228 self.attributes.push(RadiusAttribute {
229 attr_type,
230 value: value.as_ref().to_vec(),
231 });
232 }
233}
234
235#[derive(Clone, Serialize, Deserialize)]
237pub struct RadiusAuthResult {
238 pub accepted: bool,
240
241 pub reply_message: Option<String>,
243
244 pub session_timeout: Option<u32>,
246
247 pub filter_id: Option<String>,
249
250 pub challenge: bool,
252
253 pub state: Option<Vec<u8>>,
255
256 pub reply_attributes: HashMap<u8, Vec<Vec<u8>>>,
258}
259
260impl std::fmt::Debug for RadiusAuthResult {
261 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
262 let mut d = f.debug_struct("RadiusAuthResult");
263 d.field("accepted", &self.accepted);
264 d.field("reply_message", &self.reply_message);
265 d.field("session_timeout", &self.session_timeout);
266 d.field("filter_id", &self.filter_id);
267 d.field("challenge", &self.challenge);
268 d.field("state", &crate::utils::redact::redacted(&self.state));
269 d.field(
270 "reply_attributes",
271 &crate::utils::redact::redacted(&self.reply_attributes),
272 );
273 d.finish()
274 }
275}
276
277#[derive(Debug)]
281pub struct RadiusClient {
282 config: RadiusConfig,
283}
284
285impl RadiusClient {
286 pub fn new(config: RadiusConfig) -> Result<Self> {
288 if config.shared_secret.is_empty() {
289 return Err(AuthError::config("RADIUS shared secret must not be empty"));
290 }
291 if config.shared_secret.len() < 6 {
292 return Err(AuthError::config(
293 "RADIUS shared secret should be at least 6 bytes",
294 ));
295 }
296 Ok(Self { config })
297 }
298
299 pub async fn authenticate(&self, username: &str, password: &str) -> Result<RadiusAuthResult> {
301 self.authenticate_with_state(username, password, None).await
302 }
303
304 pub async fn authenticate_with_state(
306 &self,
307 username: &str,
308 password: &str,
309 state: Option<&[u8]>,
310 ) -> Result<RadiusAuthResult> {
311 let rng = ring::rand::SystemRandom::new();
312 let mut authenticator = [0u8; AUTHENTICATOR_LEN];
313 rng.fill(&mut authenticator)
314 .map_err(|_| AuthError::crypto("Failed to generate RADIUS authenticator"))?;
315
316 let mut id_buf = [0u8; 1];
317 rng.fill(&mut id_buf)
318 .map_err(|_| AuthError::crypto("Failed to generate RADIUS identifier"))?;
319
320 let mut packet = RadiusPacket {
321 code: code::ACCESS_REQUEST,
322 identifier: id_buf[0],
323 authenticator,
324 attributes: Vec::new(),
325 };
326
327 packet.attributes.push(RadiusAttribute {
329 attr_type: attr::USER_NAME,
330 value: username.as_bytes().to_vec(),
331 });
332
333 let encrypted_password =
335 encrypt_pap_password(password, &self.config.shared_secret, &authenticator);
336 packet.attributes.push(RadiusAttribute {
337 attr_type: attr::USER_PASSWORD,
338 value: encrypted_password,
339 });
340
341 packet.attributes.push(RadiusAttribute {
343 attr_type: attr::NAS_IDENTIFIER,
344 value: self.config.nas_identifier.as_bytes().to_vec(),
345 });
346
347 if let Some(state_val) = state {
349 packet.attributes.push(RadiusAttribute {
350 attr_type: attr::STATE,
351 value: state_val.to_vec(),
352 });
353 }
354
355 let msg_auth =
357 compute_message_authenticator(&packet, self.config.shared_secret.as_bytes())?;
358 packet.attributes.push(RadiusAttribute {
359 attr_type: attr::MESSAGE_AUTHENTICATOR,
360 value: msg_auth.to_vec(),
361 });
362
363 let response = self.send_request(&packet).await?;
364 self.parse_response(&response, &authenticator)
365 }
366
367 pub async fn send_accounting(
369 &self,
370 username: &str,
371 session_id: &str,
372 status_type: u32,
373 ) -> Result<bool> {
374 let addr = self
375 .config
376 .accounting_addr
377 .as_deref()
378 .unwrap_or("127.0.0.1:1813");
379
380 let rng = ring::rand::SystemRandom::new();
381 let mut authenticator = [0u8; AUTHENTICATOR_LEN];
382 rng.fill(&mut authenticator)
383 .map_err(|_| AuthError::crypto("Failed to generate RADIUS authenticator"))?;
384
385 let mut id_buf = [0u8; 1];
386 rng.fill(&mut id_buf)
387 .map_err(|_| AuthError::crypto("Failed to generate RADIUS identifier"))?;
388
389 let mut packet = RadiusPacket {
390 code: code::ACCOUNTING_REQUEST,
391 identifier: id_buf[0],
392 authenticator,
393 attributes: Vec::new(),
394 };
395
396 packet.attributes.push(RadiusAttribute {
397 attr_type: attr::USER_NAME,
398 value: username.as_bytes().to_vec(),
399 });
400
401 packet.attributes.push(RadiusAttribute {
402 attr_type: attr::ACCT_SESSION_ID,
403 value: session_id.as_bytes().to_vec(),
404 });
405
406 packet.attributes.push(RadiusAttribute {
407 attr_type: attr::ACCT_STATUS_TYPE,
408 value: status_type.to_be_bytes().to_vec(),
409 });
410
411 packet.attributes.push(RadiusAttribute {
412 attr_type: attr::NAS_IDENTIFIER,
413 value: self.config.nas_identifier.as_bytes().to_vec(),
414 });
415
416 let encoded = encode_packet(&packet);
418 let acct_auth =
419 compute_accounting_authenticator(&encoded, self.config.shared_secret.as_bytes());
420 let mut final_packet = packet;
421 final_packet.authenticator = acct_auth;
422
423 let response = self
424 .send_packet(&encode_packet(&final_packet), addr)
425 .await?;
426 Ok(response[0] == code::ACCOUNTING_RESPONSE)
427 }
428
429 async fn send_request(&self, packet: &RadiusPacket) -> Result<Vec<u8>> {
431 let encoded = encode_packet(packet);
432 self.send_packet(&encoded, &self.config.server_addr).await
433 }
434
435 async fn send_packet(&self, data: &[u8], addr: &str) -> Result<Vec<u8>> {
437 let server_addr: SocketAddr = addr
438 .parse()
439 .map_err(|e| AuthError::config(format!("Invalid RADIUS server address: {e}")))?;
440
441 let socket = UdpSocket::bind("0.0.0.0:0")
442 .await
443 .map_err(|e| AuthError::internal(format!("Failed to bind UDP socket: {e}")))?;
444
445 for attempt in 0..=self.config.retries {
446 socket
447 .send_to(data, server_addr)
448 .await
449 .map_err(|e| AuthError::internal(format!("RADIUS send failed: {e}")))?;
450
451 let mut buf = vec![0u8; MAX_PACKET_SIZE];
452 match tokio::time::timeout(self.config.timeout, socket.recv_from(&mut buf)).await {
453 Ok(Ok((len, _))) => return Ok(buf[..len].to_vec()),
454 Ok(Err(e)) => {
455 return Err(AuthError::internal(format!("RADIUS recv failed: {e}")));
456 }
457 Err(_) if attempt < self.config.retries => continue,
458 Err(_) => {
459 return Err(AuthError::internal("RADIUS request timed out"));
460 }
461 }
462 }
463
464 Err(AuthError::internal("RADIUS request failed after retries"))
465 }
466
467 fn parse_response(
469 &self,
470 data: &[u8],
471 request_authenticator: &[u8; AUTHENTICATOR_LEN],
472 ) -> Result<RadiusAuthResult> {
473 if data.len() < HEADER_LEN {
474 return Err(AuthError::validation("RADIUS response too short"));
475 }
476
477 let response_code = data[0];
478 let _identifier = data[1];
479 let length = u16::from_be_bytes([data[2], data[3]]) as usize;
480
481 if length > data.len() {
482 return Err(AuthError::validation("RADIUS response length mismatch"));
483 }
484
485 let expected_auth = compute_response_authenticator(
487 data,
488 request_authenticator,
489 self.config.shared_secret.as_bytes(),
490 );
491 let actual_auth = &data[4..20];
492 if !constant_time_eq(actual_auth, &expected_auth) {
493 return Err(AuthError::validation(
494 "RADIUS response authenticator verification failed",
495 ));
496 }
497
498 let mut reply_attributes: HashMap<u8, Vec<Vec<u8>>> = HashMap::new();
500 let mut pos = HEADER_LEN;
501 while pos + 2 <= length {
502 let attr_type = data[pos];
503 let attr_len = data[pos + 1] as usize;
504 if attr_len < 2 || pos + attr_len > length {
505 break;
506 }
507 let value = data[pos + 2..pos + attr_len].to_vec();
508 reply_attributes.entry(attr_type).or_default().push(value);
509 pos += attr_len;
510 }
511
512 let reply_message = reply_attributes
513 .get(&attr::REPLY_MESSAGE)
514 .and_then(|v| v.first())
515 .and_then(|b| String::from_utf8(b.clone()).ok());
516
517 let session_timeout = reply_attributes
518 .get(&attr::SESSION_TIMEOUT)
519 .and_then(|v| v.first())
520 .and_then(|b| {
521 if b.len() == 4 {
522 Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
523 } else {
524 None
525 }
526 });
527
528 let filter_id = reply_attributes
529 .get(&attr::FILTER_ID)
530 .and_then(|v| v.first())
531 .and_then(|b| String::from_utf8(b.clone()).ok());
532
533 let state = reply_attributes
534 .get(&attr::STATE)
535 .and_then(|v| v.first())
536 .cloned();
537
538 Ok(RadiusAuthResult {
539 accepted: response_code == code::ACCESS_ACCEPT,
540 reply_message,
541 session_timeout,
542 filter_id,
543 challenge: response_code == code::ACCESS_CHALLENGE,
544 state,
545 reply_attributes,
546 })
547 }
548}
549
550fn encode_packet(packet: &RadiusPacket) -> Vec<u8> {
554 let mut buf = Vec::with_capacity(MAX_PACKET_SIZE);
555
556 buf.push(packet.code);
558 buf.push(packet.identifier);
559 buf.extend_from_slice(&[0, 0]); buf.extend_from_slice(&packet.authenticator);
561
562 for attr in &packet.attributes {
564 let attr_len = (2 + attr.value.len()) as u8;
565 buf.push(attr.attr_type);
566 buf.push(attr_len);
567 buf.extend_from_slice(&attr.value);
568 }
569
570 let len = buf.len() as u16;
572 buf[2..4].copy_from_slice(&len.to_be_bytes());
573
574 buf
575}
576
577fn encrypt_pap_password(
582 password: &str,
583 shared_secret: &str,
584 authenticator: &[u8; AUTHENTICATOR_LEN],
585) -> Vec<u8> {
586 let pwd_bytes = password.as_bytes();
587 let padded_len = pwd_bytes.len().div_ceil(16) * 16;
589 let padded_len = padded_len.max(16);
590 let mut padded = vec![0u8; padded_len];
591 padded[..pwd_bytes.len()].copy_from_slice(pwd_bytes);
592
593 let mut result = vec![0u8; padded_len];
594 let mut prev_block = authenticator.to_vec();
595
596 for i in 0..(padded_len / 16) {
597 let hasher = md5_hash(shared_secret.as_bytes(), &prev_block);
598 let chunk_start = i * 16;
599 for j in 0..16 {
600 result[chunk_start + j] = padded[chunk_start + j] ^ hasher[j];
601 }
602 prev_block = result[chunk_start..chunk_start + 16].to_vec();
603 }
604
605 result
606}
607
608fn md5_hash(a: &[u8], b: &[u8]) -> [u8; 16] {
610 let mut hasher = md5::Md5::new();
611 hasher.update(a);
612 hasher.update(b);
613 hasher.finalize().into()
614}
615
616fn compute_message_authenticator(packet: &RadiusPacket, secret: &[u8]) -> Result<[u8; 16]> {
618 let mut temp_packet = packet.clone();
621 temp_packet
623 .attributes
624 .retain(|a| a.attr_type != attr::MESSAGE_AUTHENTICATOR);
625 temp_packet.attributes.push(RadiusAttribute {
627 attr_type: attr::MESSAGE_AUTHENTICATOR,
628 value: vec![0u8; 16],
629 });
630
631 let encoded = encode_packet(&temp_packet);
632 let hmac_result = hmac_md5_truncated(secret, &encoded);
633 Ok(hmac_result)
634}
635
636fn hmac_md5_truncated(key: &[u8], data: &[u8]) -> [u8; 16] {
638 use hmac::Mac;
639 type HmacMd5 = hmac::Hmac<md5::Md5>;
640 let mut mac = HmacMd5::new_from_slice(key).expect("HMAC key length");
641 mac.update(data);
642 let result = mac.finalize().into_bytes();
643 let mut out = [0u8; 16];
644 out.copy_from_slice(&result[..16]);
645 out
646}
647
648fn compute_response_authenticator(
652 response: &[u8],
653 request_auth: &[u8; AUTHENTICATOR_LEN],
654 secret: &[u8],
655) -> [u8; 16] {
656 let mut hasher = md5::Md5::new();
657 hasher.update(&response[..4]); hasher.update(request_auth); if response.len() > HEADER_LEN {
660 hasher.update(&response[HEADER_LEN..]); }
662 hasher.update(secret);
663 hasher.finalize().into()
664}
665
666fn compute_accounting_authenticator(packet_bytes: &[u8], secret: &[u8]) -> [u8; AUTHENTICATOR_LEN] {
668 let mut hasher = md5::Md5::new();
669 hasher.update(&packet_bytes[..4]); hasher.update([0u8; AUTHENTICATOR_LEN]); if packet_bytes.len() > HEADER_LEN {
672 hasher.update(&packet_bytes[HEADER_LEN..]); }
674 hasher.update(secret);
675 hasher.finalize().into()
676}
677
678fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
680 use subtle::ConstantTimeEq;
681 if a.len() != b.len() {
682 return false;
683 }
684 a.ct_eq(b).into()
685}
686
687#[cfg(test)]
688mod tests {
689 use super::*;
690
691 #[test]
692 fn test_config_defaults() {
693 let config = RadiusConfig::default();
694 assert_eq!(config.server_addr, "127.0.0.1:1812");
695 assert_eq!(config.retries, 3);
696 }
697
698 #[test]
699 fn test_client_requires_secret() {
700 let config = RadiusConfig::default();
701 let err = RadiusClient::new(config).unwrap_err();
702 assert!(err.to_string().contains("secret"));
703 }
704
705 #[test]
706 fn test_client_rejects_short_secret() {
707 let config = RadiusConfig {
708 shared_secret: "abc".into(),
709 ..Default::default()
710 };
711 let err = RadiusClient::new(config).unwrap_err();
712 assert!(err.to_string().contains("6 bytes"));
713 }
714
715 #[test]
716 fn test_client_creation() {
717 let config = RadiusConfig {
718 shared_secret: "testing123".into(),
719 ..Default::default()
720 };
721 assert!(RadiusClient::new(config).is_ok());
722 }
723
724 #[test]
725 fn test_packet_encoding() {
726 let packet = RadiusPacket {
727 code: code::ACCESS_REQUEST,
728 identifier: 42,
729 authenticator: [0u8; AUTHENTICATOR_LEN],
730 attributes: vec![RadiusAttribute {
731 attr_type: attr::USER_NAME,
732 value: b"test".to_vec(),
733 }],
734 };
735
736 let encoded = encode_packet(&packet);
737 assert_eq!(encoded[0], code::ACCESS_REQUEST);
738 assert_eq!(encoded[1], 42);
739 let length = u16::from_be_bytes([encoded[2], encoded[3]]);
740 assert_eq!(length as usize, encoded.len());
741 }
742
743 #[test]
744 fn test_pap_password_encryption() {
745 let auth = [1u8; AUTHENTICATOR_LEN];
746 let encrypted = encrypt_pap_password("password", "secret", &auth);
747 assert_eq!(encrypted.len(), 16); assert_ne!(&encrypted[..8], b"password");
750 }
751
752 #[test]
753 fn test_radius_attribute_codes() {
754 assert_eq!(attr::USER_NAME, 1);
755 assert_eq!(attr::USER_PASSWORD, 2);
756 assert_eq!(attr::MESSAGE_AUTHENTICATOR, 80);
757 }
758
759 #[test]
760 fn test_radius_config_with_server() {
761 let config = RadiusConfig::with_server("10.0.0.1:1812", "testing123").unwrap();
762 assert_eq!(config.server_addr, "10.0.0.1:1812");
763 assert_eq!(config.shared_secret, "testing123");
764 assert_eq!(config.retries, 3); }
766
767 #[test]
768 fn test_radius_config_with_server_rejects_short_secret() {
769 let err = RadiusConfig::with_server("10.0.0.1:1812", "abc").unwrap_err();
770 assert!(err.to_string().contains("6 bytes"));
771 }
772
773 #[test]
774 fn test_radius_config_with_options() {
775 let config =
776 RadiusConfig::with_options("10.0.0.1:1812", "testing123", Duration::from_secs(10), 5)
777 .unwrap();
778 assert_eq!(config.timeout, Duration::from_secs(10));
779 assert_eq!(config.retries, 5);
780 }
781
782 #[test]
783 fn test_radius_packet_add_attribute() {
784 let mut packet = RadiusPacket {
785 code: code::ACCESS_REQUEST,
786 identifier: 1,
787 authenticator: [0u8; AUTHENTICATOR_LEN],
788 attributes: Vec::new(),
789 };
790 packet.add_attribute(attr::USER_NAME, b"alice");
791 packet.add_attribute(attr::NAS_IDENTIFIER, b"my-nas");
792
793 assert_eq!(packet.attributes.len(), 2);
794 assert_eq!(packet.attributes[0].attr_type, attr::USER_NAME);
795 assert_eq!(packet.attributes[0].value, b"alice");
796 assert_eq!(packet.attributes[1].attr_type, attr::NAS_IDENTIFIER);
797 }
798}