1use crate::errors::{AuthError, Result};
7use ring::digest::{Context, SHA256};
8use serde::{Deserialize, Serialize};
9
10const TACACS_MAJOR_VERSION: u8 = 0xC0; const TACACS_MINOR_VERSION_DEFAULT: u8 = 0x00;
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
16#[repr(u8)]
17pub enum TacacsPacketType {
18 Authentication = 0x01,
19 Authorization = 0x02,
20 Accounting = 0x03,
21}
22
23#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
25#[repr(u8)]
26pub enum AuthenAction {
27 Login = 0x01,
28 ChangePassword = 0x02,
29 SendAuth = 0x04,
30}
31
32#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
34#[repr(u8)]
35pub enum AuthenType {
36 Ascii = 0x01,
37 Pap = 0x02,
38 Chap = 0x03,
39 MSChap = 0x05,
40 MSChapV2 = 0x06,
41}
42
43#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
45#[repr(u8)]
46pub enum AuthenService {
47 None = 0x00,
48 Login = 0x01,
49 Enable = 0x02,
50 Ppp = 0x03,
51}
52
53#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
55#[repr(u8)]
56pub enum AuthenStatus {
57 Pass = 0x01,
58 Fail = 0x02,
59 GetData = 0x03,
60 GetUser = 0x04,
61 GetPass = 0x05,
62 Restart = 0x06,
63 Error = 0x07,
64 Follow = 0x21,
65}
66
67#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
69#[repr(u8)]
70pub enum AuthorStatus {
71 PassAdd = 0x01,
72 PassReplace = 0x02,
73 Fail = 0x10,
74 Error = 0x11,
75 Follow = 0x21,
76}
77
78#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
80pub struct AcctFlags(pub u8);
81
82impl AcctFlags {
83 pub const START: Self = Self(0x02);
84 pub const STOP: Self = Self(0x04);
85 pub const WATCHDOG: Self = Self(0x08);
86
87 pub fn is_start(self) -> bool {
88 self.0 & 0x02 != 0
89 }
90 pub fn is_stop(self) -> bool {
91 self.0 & 0x04 != 0
92 }
93 pub fn is_watchdog(self) -> bool {
94 self.0 & 0x08 != 0
95 }
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize)]
100pub struct TacacsHeader {
101 pub version: u8,
102 pub packet_type: TacacsPacketType,
103 pub seq_no: u8,
104 pub flags: u8,
105 pub session_id: u32,
106 pub length: u32,
107}
108
109impl TacacsHeader {
110 pub fn new(packet_type: TacacsPacketType, seq_no: u8, session_id: u32, body_len: u32) -> Self {
112 Self {
113 version: TACACS_MAJOR_VERSION | TACACS_MINOR_VERSION_DEFAULT,
114 packet_type,
115 seq_no,
116 flags: 0x00, session_id,
118 length: body_len,
119 }
120 }
121
122 pub fn to_bytes(&self) -> [u8; 12] {
124 let mut buf = [0u8; 12];
125 buf[0] = self.version;
126 buf[1] = self.packet_type as u8;
127 buf[2] = self.seq_no;
128 buf[3] = self.flags;
129 buf[4..8].copy_from_slice(&self.session_id.to_be_bytes());
130 buf[8..12].copy_from_slice(&self.length.to_be_bytes());
131 buf
132 }
133
134 pub fn from_bytes(data: &[u8]) -> Result<Self> {
136 if data.len() < 12 {
137 return Err(AuthError::validation("TACACS+ header too short"));
138 }
139 let packet_type = match data[1] {
140 0x01 => TacacsPacketType::Authentication,
141 0x02 => TacacsPacketType::Authorization,
142 0x03 => TacacsPacketType::Accounting,
143 other => {
144 return Err(AuthError::validation(format!(
145 "Unknown TACACS+ packet type: {other:#x}"
146 )));
147 }
148 };
149 Ok(Self {
150 version: data[0],
151 packet_type,
152 seq_no: data[2],
153 flags: data[3],
154 session_id: u32::from_be_bytes([data[4], data[5], data[6], data[7]]),
155 length: u32::from_be_bytes([data[8], data[9], data[10], data[11]]),
156 })
157 }
158}
159
160#[derive(Debug, Clone, Serialize, Deserialize)]
162pub struct AuthenStartBody {
163 pub action: AuthenAction,
164 pub authen_type: AuthenType,
165 pub authen_service: AuthenService,
166 pub user: String,
167 pub port: String,
168 pub remote_address: String,
169 pub data: Vec<u8>,
170}
171
172impl AuthenStartBody {
173 pub fn to_bytes(&self) -> Vec<u8> {
175 let user_bytes = self.user.as_bytes();
176 let port_bytes = self.port.as_bytes();
177 let rem_bytes = self.remote_address.as_bytes();
178 let mut buf = Vec::with_capacity(
179 8 + user_bytes.len() + port_bytes.len() + rem_bytes.len() + self.data.len(),
180 );
181
182 buf.push(self.action as u8);
183 buf.push(0x01); buf.push(self.authen_type as u8);
185 buf.push(self.authen_service as u8);
186 buf.push(user_bytes.len() as u8);
187 buf.push(port_bytes.len() as u8);
188 buf.push(rem_bytes.len() as u8);
189 buf.push(self.data.len() as u8);
190 buf.extend_from_slice(user_bytes);
191 buf.extend_from_slice(port_bytes);
192 buf.extend_from_slice(rem_bytes);
193 buf.extend_from_slice(&self.data);
194
195 buf
196 }
197}
198
199#[derive(Debug, Clone, Serialize, Deserialize)]
201pub struct AuthenReplyBody {
202 pub status: AuthenStatus,
203 pub flags: u8,
204 pub server_msg: String,
205 pub data: Vec<u8>,
206}
207
208impl AuthenReplyBody {
209 pub fn from_bytes(data: &[u8]) -> Result<Self> {
211 if data.len() < 6 {
212 return Err(AuthError::validation("TACACS+ authen reply too short"));
213 }
214 let status = match data[0] {
215 0x01 => AuthenStatus::Pass,
216 0x02 => AuthenStatus::Fail,
217 0x03 => AuthenStatus::GetData,
218 0x04 => AuthenStatus::GetUser,
219 0x05 => AuthenStatus::GetPass,
220 0x06 => AuthenStatus::Restart,
221 0x07 => AuthenStatus::Error,
222 0x21 => AuthenStatus::Follow,
223 other => {
224 return Err(AuthError::validation(format!(
225 "Unknown authen status: {other:#x}"
226 )));
227 }
228 };
229 let flags = data[1];
230 let server_msg_len = u16::from_be_bytes([data[2], data[3]]) as usize;
231 let data_len = u16::from_be_bytes([data[4], data[5]]) as usize;
232
233 if data.len() < 6 + server_msg_len + data_len {
234 return Err(AuthError::validation("TACACS+ authen reply truncated"));
235 }
236
237 let server_msg = String::from_utf8_lossy(&data[6..6 + server_msg_len]).to_string();
238 let reply_data = data[6 + server_msg_len..6 + server_msg_len + data_len].to_vec();
239
240 Ok(Self {
241 status,
242 flags,
243 server_msg,
244 data: reply_data,
245 })
246 }
247}
248
249#[derive(Debug, Clone, Serialize, Deserialize)]
253pub struct AuthorRequestBody {
254 pub authen_method: u8,
255 pub authen_type: AuthenType,
256 pub authen_service: AuthenService,
257 pub user: String,
258 pub port: String,
259 pub remote_address: String,
260 pub args: Vec<String>,
262}
263
264impl AuthorRequestBody {
265 #[allow(clippy::vec_init_then_push)] pub fn to_bytes(&self) -> Vec<u8> {
268 let user_bytes = self.user.as_bytes();
269 let port_bytes = self.port.as_bytes();
270 let rem_bytes = self.remote_address.as_bytes();
271 let arg_count = self.args.len() as u8;
272
273 let mut buf = Vec::new();
276 buf.push(self.authen_method);
277 buf.push(0x01); buf.push(self.authen_type as u8);
279 buf.push(self.authen_service as u8);
280 buf.push(user_bytes.len() as u8);
281 buf.push(port_bytes.len() as u8);
282 buf.push(rem_bytes.len() as u8);
283 buf.push(arg_count);
284
285 for arg in &self.args {
287 buf.push(arg.len() as u8);
288 }
289
290 buf.extend_from_slice(user_bytes);
292 buf.extend_from_slice(port_bytes);
293 buf.extend_from_slice(rem_bytes);
294 for arg in &self.args {
295 buf.extend_from_slice(arg.as_bytes());
296 }
297
298 buf
299 }
300}
301
302#[derive(Debug, Clone, Serialize, Deserialize)]
304pub struct AuthorReplyBody {
305 pub status: AuthorStatus,
306 pub server_msg: String,
307 pub data: Vec<u8>,
308 pub args: Vec<String>,
309}
310
311impl AuthorReplyBody {
312 pub fn from_bytes(data: &[u8]) -> Result<Self> {
314 if data.len() < 6 {
315 return Err(AuthError::validation("TACACS+ author reply too short"));
316 }
317 let status = match data[0] {
318 0x01 => AuthorStatus::PassAdd,
319 0x02 => AuthorStatus::PassReplace,
320 0x10 => AuthorStatus::Fail,
321 0x11 => AuthorStatus::Error,
322 0x21 => AuthorStatus::Follow,
323 other => {
324 return Err(AuthError::validation(format!(
325 "Unknown author status: {other:#x}"
326 )));
327 }
328 };
329
330 let arg_count = data[1] as usize;
331 let server_msg_len = u16::from_be_bytes([data[2], data[3]]) as usize;
332 let data_len = u16::from_be_bytes([data[4], data[5]]) as usize;
333
334 let mut offset = 6;
335 if data.len() < offset + arg_count {
337 return Err(AuthError::validation(
338 "TACACS+ author reply truncated (arg lengths)",
339 ));
340 }
341 let arg_lens: Vec<usize> = data[offset..offset + arg_count]
342 .iter()
343 .map(|&b| b as usize)
344 .collect();
345 offset += arg_count;
346
347 if data.len() < offset + server_msg_len {
349 return Err(AuthError::validation(
350 "TACACS+ author reply truncated (msg)",
351 ));
352 }
353 let server_msg =
354 String::from_utf8_lossy(&data[offset..offset + server_msg_len]).to_string();
355 offset += server_msg_len;
356
357 if data.len() < offset + data_len {
359 return Err(AuthError::validation(
360 "TACACS+ author reply truncated (data)",
361 ));
362 }
363 let reply_data = data[offset..offset + data_len].to_vec();
364 offset += data_len;
365
366 let mut args = Vec::with_capacity(arg_count);
368 for &len in &arg_lens {
369 if data.len() < offset + len {
370 return Err(AuthError::validation(
371 "TACACS+ author reply truncated (args)",
372 ));
373 }
374 args.push(String::from_utf8_lossy(&data[offset..offset + len]).to_string());
375 offset += len;
376 }
377
378 Ok(Self {
379 status,
380 server_msg,
381 data: reply_data,
382 args,
383 })
384 }
385}
386
387#[derive(Debug, Clone, Serialize, Deserialize)]
391pub struct AcctRequestBody {
392 pub flags: AcctFlags,
393 pub authen_method: u8,
394 pub authen_type: AuthenType,
395 pub authen_service: AuthenService,
396 pub user: String,
397 pub port: String,
398 pub remote_address: String,
399 pub args: Vec<String>,
401}
402
403impl AcctRequestBody {
404 #[allow(clippy::vec_init_then_push)] pub fn to_bytes(&self) -> Vec<u8> {
407 let user_bytes = self.user.as_bytes();
408 let port_bytes = self.port.as_bytes();
409 let rem_bytes = self.remote_address.as_bytes();
410 let arg_count = self.args.len() as u8;
411
412 let mut buf = Vec::new();
414 buf.push(self.flags.0);
415 buf.push(self.authen_method);
416 buf.push(0x01); buf.push(self.authen_type as u8);
418 buf.push(self.authen_service as u8);
419 buf.push(user_bytes.len() as u8);
420 buf.push(port_bytes.len() as u8);
421 buf.push(rem_bytes.len() as u8);
422 buf.push(arg_count);
423
424 for arg in &self.args {
426 buf.push(arg.len() as u8);
427 }
428
429 buf.extend_from_slice(user_bytes);
431 buf.extend_from_slice(port_bytes);
432 buf.extend_from_slice(rem_bytes);
433 for arg in &self.args {
434 buf.extend_from_slice(arg.as_bytes());
435 }
436
437 buf
438 }
439}
440
441#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
443#[repr(u8)]
444pub enum AcctStatus {
445 Success = 0x01,
446 Error = 0x02,
447 Follow = 0x21,
448}
449
450#[derive(Debug, Clone, Serialize, Deserialize)]
452pub struct AcctReplyBody {
453 pub status: AcctStatus,
454 pub server_msg: String,
455 pub data: Vec<u8>,
456}
457
458impl AcctReplyBody {
459 pub fn from_bytes(data: &[u8]) -> Result<Self> {
461 if data.len() < 5 {
462 return Err(AuthError::validation("TACACS+ acct reply too short"));
463 }
464 let server_msg_len = u16::from_be_bytes([data[0], data[1]]) as usize;
465 let data_len = u16::from_be_bytes([data[2], data[3]]) as usize;
466 let status = match data[4] {
467 0x01 => AcctStatus::Success,
468 0x02 => AcctStatus::Error,
469 0x21 => AcctStatus::Follow,
470 other => {
471 return Err(AuthError::validation(format!(
472 "Unknown acct status: {other:#x}"
473 )));
474 }
475 };
476
477 let offset = 5;
478 if data.len() < offset + server_msg_len + data_len {
479 return Err(AuthError::validation("TACACS+ acct reply truncated"));
480 }
481 let server_msg =
482 String::from_utf8_lossy(&data[offset..offset + server_msg_len]).to_string();
483 let reply_data = data[offset + server_msg_len..offset + server_msg_len + data_len].to_vec();
484
485 Ok(Self {
486 status,
487 server_msg,
488 data: reply_data,
489 })
490 }
491}
492
493pub fn obfuscate(header: &TacacsHeader, secret: &[u8], body: &mut [u8]) {
499 if secret.is_empty() || body.is_empty() {
500 return;
501 }
502
503 let mut pad = Vec::new();
504 let session_id_bytes = header.session_id.to_be_bytes();
505
506 let mut ctx = Context::new(&SHA256);
508 ctx.update(&session_id_bytes);
509 ctx.update(secret);
510 ctx.update(&[header.version]);
511 ctx.update(&[header.seq_no]);
512 let digest = ctx.finish();
513 pad.extend_from_slice(digest.as_ref());
514
515 while pad.len() < body.len() {
517 let mut ctx = Context::new(&SHA256);
518 ctx.update(&session_id_bytes);
519 ctx.update(secret);
520 ctx.update(&[header.version]);
521 ctx.update(&[header.seq_no]);
522 let prev_start = pad.len().saturating_sub(32);
523 ctx.update(&pad[prev_start..]);
524 let digest = ctx.finish();
525 pad.extend_from_slice(digest.as_ref());
526 }
527
528 for (i, b) in body.iter_mut().enumerate() {
530 *b ^= pad[i];
531 }
532}
533
534pub fn generate_session_id() -> Result<u32> {
536 use ring::rand::{SecureRandom, SystemRandom};
537 let rng = SystemRandom::new();
538 let mut buf = [0u8; 4];
539 rng.fill(&mut buf)
540 .map_err(|_| AuthError::crypto("Failed to generate session ID".to_string()))?;
541 Ok(u32::from_be_bytes(buf))
542}
543
544#[cfg(test)]
545mod tests {
546 use super::*;
547
548 #[test]
549 fn test_header_roundtrip() {
550 let h = TacacsHeader::new(TacacsPacketType::Authentication, 1, 0xDEADBEEF, 42);
551 let bytes = h.to_bytes();
552 assert_eq!(bytes.len(), 12);
553 let h2 = TacacsHeader::from_bytes(&bytes).unwrap();
554 assert_eq!(h2.packet_type, TacacsPacketType::Authentication);
555 assert_eq!(h2.session_id, 0xDEADBEEF);
556 assert_eq!(h2.length, 42);
557 assert_eq!(h2.seq_no, 1);
558 }
559
560 #[test]
561 fn test_header_too_short() {
562 assert!(TacacsHeader::from_bytes(&[0; 5]).is_err());
563 }
564
565 #[test]
566 fn test_header_unknown_type() {
567 let mut bytes = TacacsHeader::new(TacacsPacketType::Authentication, 1, 1, 0).to_bytes();
568 bytes[1] = 0xFF;
569 assert!(TacacsHeader::from_bytes(&bytes).is_err());
570 }
571
572 #[test]
573 fn test_authen_start_body_serialization() {
574 let body = AuthenStartBody {
575 action: AuthenAction::Login,
576 authen_type: AuthenType::Pap,
577 authen_service: AuthenService::Login,
578 user: "admin".to_string(),
579 port: "tty0".to_string(),
580 remote_address: "10.0.0.1".to_string(),
581 data: b"password".to_vec(),
582 };
583 let bytes = body.to_bytes();
584 assert_eq!(bytes[0], AuthenAction::Login as u8);
585 assert_eq!(bytes[2], AuthenType::Pap as u8);
586 assert_eq!(bytes[4], 5); }
588
589 #[test]
590 fn test_authen_reply_parsing() {
591 let mut data = vec![0x01, 0x00]; data.extend_from_slice(&3u16.to_be_bytes()); data.extend_from_slice(&0u16.to_be_bytes()); data.extend_from_slice(b"OK!");
595
596 let reply = AuthenReplyBody::from_bytes(&data).unwrap();
597 assert_eq!(reply.status, AuthenStatus::Pass);
598 assert_eq!(reply.server_msg, "OK!");
599 assert!(reply.data.is_empty());
600 }
601
602 #[test]
603 fn test_authen_reply_too_short() {
604 assert!(AuthenReplyBody::from_bytes(&[0x01, 0x00]).is_err());
605 }
606
607 #[test]
608 fn test_obfuscate_deobfuscate_roundtrip() {
609 let header = TacacsHeader::new(TacacsPacketType::Authentication, 1, 12345, 11);
610 let secret = b"shared-secret";
611 let original = b"hello world".to_vec();
612 let mut encrypted = original.clone();
613
614 obfuscate(&header, secret, &mut encrypted);
615 assert_ne!(encrypted, original, "obfuscation should change data");
616
617 obfuscate(&header, secret, &mut encrypted);
618 assert_eq!(
619 encrypted, original,
620 "double obfuscation should restore data"
621 );
622 }
623
624 #[test]
625 fn test_obfuscate_empty_secret_noop() {
626 let header = TacacsHeader::new(TacacsPacketType::Authentication, 1, 1, 5);
627 let mut data = b"hello".to_vec();
628 let orig = data.clone();
629 obfuscate(&header, b"", &mut data);
630 assert_eq!(data, orig);
631 }
632
633 #[test]
634 fn test_generate_session_id() {
635 let id1 = generate_session_id().unwrap();
636 let id2 = generate_session_id().unwrap();
637 assert!(id1 != 0 || id2 != 0);
640 }
641
642 #[test]
643 fn test_acct_flags() {
644 let start = AcctFlags::START;
645 assert!(start.is_start());
646 assert!(!start.is_stop());
647 assert!(!start.is_watchdog());
648
649 let stop = AcctFlags::STOP;
650 assert!(stop.is_stop());
651 }
652
653 #[test]
654 fn test_packet_type_values() {
655 assert_eq!(TacacsPacketType::Authentication as u8, 0x01);
656 assert_eq!(TacacsPacketType::Authorization as u8, 0x02);
657 assert_eq!(TacacsPacketType::Accounting as u8, 0x03);
658 }
659
660 #[test]
663 fn test_author_request_serialization() {
664 let body = AuthorRequestBody {
665 authen_method: 0x06, authen_type: AuthenType::Pap,
667 authen_service: AuthenService::Login,
668 user: "admin".to_string(),
669 port: "tty0".to_string(),
670 remote_address: "10.0.0.1".to_string(),
671 args: vec!["service=shell".to_string(), "cmd=show".to_string()],
672 };
673 let bytes = body.to_bytes();
674 assert_eq!(bytes[0], 0x06); assert_eq!(bytes[7], 2); assert_eq!(bytes[8], 13); assert_eq!(bytes[9], 8); }
680
681 #[test]
682 fn test_author_reply_parsing() {
683 let mut data = vec![0x01]; data.push(2); data.extend_from_slice(&2u16.to_be_bytes()); data.extend_from_slice(&0u16.to_be_bytes()); data.push(6); data.push(6); data.extend_from_slice(b"OK"); data.extend_from_slice(b"priv=1role=a"); let reply = AuthorReplyBody::from_bytes(&data).unwrap();
695 assert_eq!(reply.status, AuthorStatus::PassAdd);
696 assert_eq!(reply.server_msg, "OK");
697 assert_eq!(reply.args.len(), 2);
698 assert_eq!(reply.args[0], "priv=1");
699 assert_eq!(reply.args[1], "role=a");
700 }
701
702 #[test]
703 fn test_author_reply_too_short() {
704 assert!(AuthorReplyBody::from_bytes(&[0x01]).is_err());
705 }
706
707 #[test]
710 fn test_acct_request_serialization() {
711 let body = AcctRequestBody {
712 flags: AcctFlags::START,
713 authen_method: 0x06,
714 authen_type: AuthenType::Pap,
715 authen_service: AuthenService::Login,
716 user: "admin".to_string(),
717 port: "tty0".to_string(),
718 remote_address: "10.0.0.1".to_string(),
719 args: vec!["task_id=1".to_string()],
720 };
721 let bytes = body.to_bytes();
722 assert_eq!(bytes[0], AcctFlags::START.0); assert_eq!(bytes[8], 1); }
725
726 #[test]
727 fn test_acct_reply_parsing() {
728 let mut data = Vec::new();
729 data.extend_from_slice(&4u16.to_be_bytes()); data.extend_from_slice(&0u16.to_be_bytes()); data.push(0x01); data.extend_from_slice(b"Done"); let reply = AcctReplyBody::from_bytes(&data).unwrap();
735 assert_eq!(reply.status, AcctStatus::Success);
736 assert_eq!(reply.server_msg, "Done");
737 }
738
739 #[test]
740 fn test_acct_reply_too_short() {
741 assert!(AcctReplyBody::from_bytes(&[0x00, 0x01]).is_err());
742 }
743}