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(Debug, Clone)]
171pub struct RadiusAttribute {
172 pub attr_type: u8,
173 pub value: Vec<u8>,
174}
175
176#[derive(Debug, Clone)]
178pub struct RadiusPacket {
179 pub code: u8,
180 pub identifier: u8,
181 pub authenticator: [u8; AUTHENTICATOR_LEN],
182 pub attributes: Vec<RadiusAttribute>,
183}
184
185impl RadiusPacket {
186 pub fn add_attribute(&mut self, attr_type: u8, value: impl AsRef<[u8]>) {
204 self.attributes.push(RadiusAttribute {
205 attr_type,
206 value: value.as_ref().to_vec(),
207 });
208 }
209}
210
211#[derive(Debug, Clone, Serialize, Deserialize)]
213pub struct RadiusAuthResult {
214 pub accepted: bool,
216
217 pub reply_message: Option<String>,
219
220 pub session_timeout: Option<u32>,
222
223 pub filter_id: Option<String>,
225
226 pub challenge: bool,
228
229 pub state: Option<Vec<u8>>,
231
232 pub reply_attributes: HashMap<u8, Vec<Vec<u8>>>,
234}
235
236#[derive(Debug)]
240pub struct RadiusClient {
241 config: RadiusConfig,
242}
243
244impl RadiusClient {
245 pub fn new(config: RadiusConfig) -> Result<Self> {
247 if config.shared_secret.is_empty() {
248 return Err(AuthError::config("RADIUS shared secret must not be empty"));
249 }
250 if config.shared_secret.len() < 6 {
251 return Err(AuthError::config(
252 "RADIUS shared secret should be at least 6 bytes",
253 ));
254 }
255 Ok(Self { config })
256 }
257
258 pub async fn authenticate(&self, username: &str, password: &str) -> Result<RadiusAuthResult> {
260 self.authenticate_with_state(username, password, None).await
261 }
262
263 pub async fn authenticate_with_state(
265 &self,
266 username: &str,
267 password: &str,
268 state: Option<&[u8]>,
269 ) -> Result<RadiusAuthResult> {
270 let rng = ring::rand::SystemRandom::new();
271 let mut authenticator = [0u8; AUTHENTICATOR_LEN];
272 rng.fill(&mut authenticator)
273 .map_err(|_| AuthError::crypto("Failed to generate RADIUS authenticator"))?;
274
275 let mut id_buf = [0u8; 1];
276 rng.fill(&mut id_buf)
277 .map_err(|_| AuthError::crypto("Failed to generate RADIUS identifier"))?;
278
279 let mut packet = RadiusPacket {
280 code: code::ACCESS_REQUEST,
281 identifier: id_buf[0],
282 authenticator,
283 attributes: Vec::new(),
284 };
285
286 packet.attributes.push(RadiusAttribute {
288 attr_type: attr::USER_NAME,
289 value: username.as_bytes().to_vec(),
290 });
291
292 let encrypted_password =
294 encrypt_pap_password(password, &self.config.shared_secret, &authenticator);
295 packet.attributes.push(RadiusAttribute {
296 attr_type: attr::USER_PASSWORD,
297 value: encrypted_password,
298 });
299
300 packet.attributes.push(RadiusAttribute {
302 attr_type: attr::NAS_IDENTIFIER,
303 value: self.config.nas_identifier.as_bytes().to_vec(),
304 });
305
306 if let Some(state_val) = state {
308 packet.attributes.push(RadiusAttribute {
309 attr_type: attr::STATE,
310 value: state_val.to_vec(),
311 });
312 }
313
314 let msg_auth =
316 compute_message_authenticator(&packet, self.config.shared_secret.as_bytes())?;
317 packet.attributes.push(RadiusAttribute {
318 attr_type: attr::MESSAGE_AUTHENTICATOR,
319 value: msg_auth.to_vec(),
320 });
321
322 let response = self.send_request(&packet).await?;
323 self.parse_response(&response, &authenticator)
324 }
325
326 pub async fn send_accounting(
328 &self,
329 username: &str,
330 session_id: &str,
331 status_type: u32,
332 ) -> Result<bool> {
333 let addr = self
334 .config
335 .accounting_addr
336 .as_deref()
337 .unwrap_or("127.0.0.1:1813");
338
339 let rng = ring::rand::SystemRandom::new();
340 let mut authenticator = [0u8; AUTHENTICATOR_LEN];
341 rng.fill(&mut authenticator)
342 .map_err(|_| AuthError::crypto("Failed to generate RADIUS authenticator"))?;
343
344 let mut id_buf = [0u8; 1];
345 rng.fill(&mut id_buf)
346 .map_err(|_| AuthError::crypto("Failed to generate RADIUS identifier"))?;
347
348 let mut packet = RadiusPacket {
349 code: code::ACCOUNTING_REQUEST,
350 identifier: id_buf[0],
351 authenticator,
352 attributes: Vec::new(),
353 };
354
355 packet.attributes.push(RadiusAttribute {
356 attr_type: attr::USER_NAME,
357 value: username.as_bytes().to_vec(),
358 });
359
360 packet.attributes.push(RadiusAttribute {
361 attr_type: attr::ACCT_SESSION_ID,
362 value: session_id.as_bytes().to_vec(),
363 });
364
365 packet.attributes.push(RadiusAttribute {
366 attr_type: attr::ACCT_STATUS_TYPE,
367 value: status_type.to_be_bytes().to_vec(),
368 });
369
370 packet.attributes.push(RadiusAttribute {
371 attr_type: attr::NAS_IDENTIFIER,
372 value: self.config.nas_identifier.as_bytes().to_vec(),
373 });
374
375 let encoded = encode_packet(&packet);
377 let acct_auth =
378 compute_accounting_authenticator(&encoded, self.config.shared_secret.as_bytes());
379 let mut final_packet = packet;
380 final_packet.authenticator = acct_auth;
381
382 let response = self
383 .send_packet(&encode_packet(&final_packet), addr)
384 .await?;
385 Ok(response[0] == code::ACCOUNTING_RESPONSE)
386 }
387
388 async fn send_request(&self, packet: &RadiusPacket) -> Result<Vec<u8>> {
390 let encoded = encode_packet(packet);
391 self.send_packet(&encoded, &self.config.server_addr).await
392 }
393
394 async fn send_packet(&self, data: &[u8], addr: &str) -> Result<Vec<u8>> {
396 let server_addr: SocketAddr = addr
397 .parse()
398 .map_err(|e| AuthError::config(format!("Invalid RADIUS server address: {e}")))?;
399
400 let socket = UdpSocket::bind("0.0.0.0:0")
401 .await
402 .map_err(|e| AuthError::internal(format!("Failed to bind UDP socket: {e}")))?;
403
404 for attempt in 0..=self.config.retries {
405 socket
406 .send_to(data, server_addr)
407 .await
408 .map_err(|e| AuthError::internal(format!("RADIUS send failed: {e}")))?;
409
410 let mut buf = vec![0u8; MAX_PACKET_SIZE];
411 match tokio::time::timeout(self.config.timeout, socket.recv_from(&mut buf)).await {
412 Ok(Ok((len, _))) => return Ok(buf[..len].to_vec()),
413 Ok(Err(e)) => {
414 return Err(AuthError::internal(format!("RADIUS recv failed: {e}")));
415 }
416 Err(_) if attempt < self.config.retries => continue,
417 Err(_) => {
418 return Err(AuthError::internal("RADIUS request timed out"));
419 }
420 }
421 }
422
423 Err(AuthError::internal("RADIUS request failed after retries"))
424 }
425
426 fn parse_response(
428 &self,
429 data: &[u8],
430 request_authenticator: &[u8; AUTHENTICATOR_LEN],
431 ) -> Result<RadiusAuthResult> {
432 if data.len() < HEADER_LEN {
433 return Err(AuthError::validation("RADIUS response too short"));
434 }
435
436 let response_code = data[0];
437 let _identifier = data[1];
438 let length = u16::from_be_bytes([data[2], data[3]]) as usize;
439
440 if length > data.len() {
441 return Err(AuthError::validation("RADIUS response length mismatch"));
442 }
443
444 let expected_auth = compute_response_authenticator(
446 data,
447 request_authenticator,
448 self.config.shared_secret.as_bytes(),
449 );
450 let actual_auth = &data[4..20];
451 if !constant_time_eq(actual_auth, &expected_auth) {
452 return Err(AuthError::validation(
453 "RADIUS response authenticator verification failed",
454 ));
455 }
456
457 let mut reply_attributes: HashMap<u8, Vec<Vec<u8>>> = HashMap::new();
459 let mut pos = HEADER_LEN;
460 while pos + 2 <= length {
461 let attr_type = data[pos];
462 let attr_len = data[pos + 1] as usize;
463 if attr_len < 2 || pos + attr_len > length {
464 break;
465 }
466 let value = data[pos + 2..pos + attr_len].to_vec();
467 reply_attributes.entry(attr_type).or_default().push(value);
468 pos += attr_len;
469 }
470
471 let reply_message = reply_attributes
472 .get(&attr::REPLY_MESSAGE)
473 .and_then(|v| v.first())
474 .and_then(|b| String::from_utf8(b.clone()).ok());
475
476 let session_timeout = reply_attributes
477 .get(&attr::SESSION_TIMEOUT)
478 .and_then(|v| v.first())
479 .and_then(|b| {
480 if b.len() == 4 {
481 Some(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
482 } else {
483 None
484 }
485 });
486
487 let filter_id = reply_attributes
488 .get(&attr::FILTER_ID)
489 .and_then(|v| v.first())
490 .and_then(|b| String::from_utf8(b.clone()).ok());
491
492 let state = reply_attributes
493 .get(&attr::STATE)
494 .and_then(|v| v.first())
495 .cloned();
496
497 Ok(RadiusAuthResult {
498 accepted: response_code == code::ACCESS_ACCEPT,
499 reply_message,
500 session_timeout,
501 filter_id,
502 challenge: response_code == code::ACCESS_CHALLENGE,
503 state,
504 reply_attributes,
505 })
506 }
507}
508
509fn encode_packet(packet: &RadiusPacket) -> Vec<u8> {
513 let mut buf = Vec::with_capacity(MAX_PACKET_SIZE);
514
515 buf.push(packet.code);
517 buf.push(packet.identifier);
518 buf.extend_from_slice(&[0, 0]); buf.extend_from_slice(&packet.authenticator);
520
521 for attr in &packet.attributes {
523 let attr_len = (2 + attr.value.len()) as u8;
524 buf.push(attr.attr_type);
525 buf.push(attr_len);
526 buf.extend_from_slice(&attr.value);
527 }
528
529 let len = buf.len() as u16;
531 buf[2..4].copy_from_slice(&len.to_be_bytes());
532
533 buf
534}
535
536fn encrypt_pap_password(
541 password: &str,
542 shared_secret: &str,
543 authenticator: &[u8; AUTHENTICATOR_LEN],
544) -> Vec<u8> {
545 let pwd_bytes = password.as_bytes();
546 let padded_len = pwd_bytes.len().div_ceil(16) * 16;
548 let padded_len = padded_len.max(16);
549 let mut padded = vec![0u8; padded_len];
550 padded[..pwd_bytes.len()].copy_from_slice(pwd_bytes);
551
552 let mut result = vec![0u8; padded_len];
553 let mut prev_block = authenticator.to_vec();
554
555 for i in 0..(padded_len / 16) {
556 let hasher = md5_hash(shared_secret.as_bytes(), &prev_block);
557 let chunk_start = i * 16;
558 for j in 0..16 {
559 result[chunk_start + j] = padded[chunk_start + j] ^ hasher[j];
560 }
561 prev_block = result[chunk_start..chunk_start + 16].to_vec();
562 }
563
564 result
565}
566
567fn md5_hash(a: &[u8], b: &[u8]) -> [u8; 16] {
569 let mut hasher = md5::Md5::new();
570 hasher.update(a);
571 hasher.update(b);
572 hasher.finalize().into()
573}
574
575fn compute_message_authenticator(packet: &RadiusPacket, secret: &[u8]) -> Result<[u8; 16]> {
577 let mut temp_packet = packet.clone();
580 temp_packet
582 .attributes
583 .retain(|a| a.attr_type != attr::MESSAGE_AUTHENTICATOR);
584 temp_packet.attributes.push(RadiusAttribute {
586 attr_type: attr::MESSAGE_AUTHENTICATOR,
587 value: vec![0u8; 16],
588 });
589
590 let encoded = encode_packet(&temp_packet);
591 let hmac_result = hmac_md5_truncated(secret, &encoded);
592 Ok(hmac_result)
593}
594
595fn hmac_md5_truncated(key: &[u8], data: &[u8]) -> [u8; 16] {
597 use hmac::Mac;
598 type HmacMd5 = hmac::Hmac<md5::Md5>;
599 let mut mac = HmacMd5::new_from_slice(key).expect("HMAC key length");
600 mac.update(data);
601 let result = mac.finalize().into_bytes();
602 let mut out = [0u8; 16];
603 out.copy_from_slice(&result[..16]);
604 out
605}
606
607fn compute_response_authenticator(
611 response: &[u8],
612 request_auth: &[u8; AUTHENTICATOR_LEN],
613 secret: &[u8],
614) -> [u8; 16] {
615 let mut hasher = md5::Md5::new();
616 hasher.update(&response[..4]); hasher.update(request_auth); if response.len() > HEADER_LEN {
619 hasher.update(&response[HEADER_LEN..]); }
621 hasher.update(secret);
622 hasher.finalize().into()
623}
624
625fn compute_accounting_authenticator(packet_bytes: &[u8], secret: &[u8]) -> [u8; AUTHENTICATOR_LEN] {
627 let mut hasher = md5::Md5::new();
628 hasher.update(&packet_bytes[..4]); hasher.update([0u8; AUTHENTICATOR_LEN]); if packet_bytes.len() > HEADER_LEN {
631 hasher.update(&packet_bytes[HEADER_LEN..]); }
633 hasher.update(secret);
634 hasher.finalize().into()
635}
636
637fn constant_time_eq(a: &[u8], b: &[u8]) -> bool {
639 use subtle::ConstantTimeEq;
640 if a.len() != b.len() {
641 return false;
642 }
643 a.ct_eq(b).into()
644}
645
646#[cfg(test)]
647mod tests {
648 use super::*;
649
650 #[test]
651 fn test_config_defaults() {
652 let config = RadiusConfig::default();
653 assert_eq!(config.server_addr, "127.0.0.1:1812");
654 assert_eq!(config.retries, 3);
655 }
656
657 #[test]
658 fn test_client_requires_secret() {
659 let config = RadiusConfig::default();
660 let err = RadiusClient::new(config).unwrap_err();
661 assert!(err.to_string().contains("secret"));
662 }
663
664 #[test]
665 fn test_client_rejects_short_secret() {
666 let config = RadiusConfig {
667 shared_secret: "abc".to_string().into(),
668 ..Default::default()
669 };
670 let err = RadiusClient::new(config).unwrap_err();
671 assert!(err.to_string().contains("6 bytes"));
672 }
673
674 #[test]
675 fn test_client_creation() {
676 let config = RadiusConfig {
677 shared_secret: "testing123".to_string().into(),
678 ..Default::default()
679 };
680 assert!(RadiusClient::new(config).is_ok());
681 }
682
683 #[test]
684 fn test_packet_encoding() {
685 let packet = RadiusPacket {
686 code: code::ACCESS_REQUEST,
687 identifier: 42,
688 authenticator: [0u8; AUTHENTICATOR_LEN],
689 attributes: vec![RadiusAttribute {
690 attr_type: attr::USER_NAME,
691 value: b"test".to_vec(),
692 }],
693 };
694
695 let encoded = encode_packet(&packet);
696 assert_eq!(encoded[0], code::ACCESS_REQUEST);
697 assert_eq!(encoded[1], 42);
698 let length = u16::from_be_bytes([encoded[2], encoded[3]]);
699 assert_eq!(length as usize, encoded.len());
700 }
701
702 #[test]
703 fn test_pap_password_encryption() {
704 let auth = [1u8; AUTHENTICATOR_LEN];
705 let encrypted = encrypt_pap_password("password", "secret", &auth);
706 assert_eq!(encrypted.len(), 16); assert_ne!(&encrypted[..8], b"password");
709 }
710
711 #[test]
712 fn test_radius_attribute_codes() {
713 assert_eq!(attr::USER_NAME, 1);
714 assert_eq!(attr::USER_PASSWORD, 2);
715 assert_eq!(attr::MESSAGE_AUTHENTICATOR, 80);
716 }
717
718 #[test]
719 fn test_radius_config_with_server() {
720 let config = RadiusConfig::with_server("10.0.0.1:1812", "testing123").unwrap();
721 assert_eq!(config.server_addr, "10.0.0.1:1812");
722 assert_eq!(config.shared_secret.as_str(), "testing123");
723 assert_eq!(config.retries, 3); }
725
726 #[test]
727 fn test_radius_config_with_server_rejects_short_secret() {
728 let err = RadiusConfig::with_server("10.0.0.1:1812", "abc").unwrap_err();
729 assert!(err.to_string().contains("6 bytes"));
730 }
731
732 #[test]
733 fn test_radius_config_with_options() {
734 let config =
735 RadiusConfig::with_options("10.0.0.1:1812", "testing123", Duration::from_secs(10), 5)
736 .unwrap();
737 assert_eq!(config.timeout, Duration::from_secs(10));
738 assert_eq!(config.retries, 5);
739 }
740
741 #[test]
742 fn test_radius_packet_add_attribute() {
743 let mut packet = RadiusPacket {
744 code: code::ACCESS_REQUEST,
745 identifier: 1,
746 authenticator: [0u8; AUTHENTICATOR_LEN],
747 attributes: Vec::new(),
748 };
749 packet.add_attribute(attr::USER_NAME, b"alice");
750 packet.add_attribute(attr::NAS_IDENTIFIER, b"my-nas");
751
752 assert_eq!(packet.attributes.len(), 2);
753 assert_eq!(packet.attributes[0].attr_type, attr::USER_NAME);
754 assert_eq!(packet.attributes[0].value, b"alice");
755 assert_eq!(packet.attributes[1].attr_type, attr::NAS_IDENTIFIER);
756 }
757}