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(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 std::fmt::Debug for AuthenStartBody {
173 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174 let mut d = f.debug_struct("AuthenStartBody");
175 d.field("action", &self.action);
176 d.field("authen_type", &self.authen_type);
177 d.field("authen_service", &self.authen_service);
178 d.field("user", &self.user);
179 d.field("port", &self.port);
180 d.field("remote_address", &self.remote_address);
181 d.field("data", &crate::utils::redact::redacted(&self.data));
182 d.finish()
183 }
184}
185
186impl AuthenStartBody {
187 pub fn to_bytes(&self) -> Vec<u8> {
189 let user_bytes = self.user.as_bytes();
190 let port_bytes = self.port.as_bytes();
191 let rem_bytes = self.remote_address.as_bytes();
192 let mut buf = Vec::with_capacity(
193 8 + user_bytes.len() + port_bytes.len() + rem_bytes.len() + self.data.len(),
194 );
195
196 buf.push(self.action as u8);
197 buf.push(0x01); buf.push(self.authen_type as u8);
199 buf.push(self.authen_service as u8);
200 buf.push(user_bytes.len() as u8);
201 buf.push(port_bytes.len() as u8);
202 buf.push(rem_bytes.len() as u8);
203 buf.push(self.data.len() as u8);
204 buf.extend_from_slice(user_bytes);
205 buf.extend_from_slice(port_bytes);
206 buf.extend_from_slice(rem_bytes);
207 buf.extend_from_slice(&self.data);
208
209 buf
210 }
211}
212
213#[derive(Debug, Clone, Serialize, Deserialize)]
215pub struct AuthenReplyBody {
216 pub status: AuthenStatus,
217 pub flags: u8,
218 pub server_msg: String,
219 pub data: Vec<u8>,
220}
221
222impl AuthenReplyBody {
223 pub fn from_bytes(data: &[u8]) -> Result<Self> {
225 if data.len() < 6 {
226 return Err(AuthError::validation("TACACS+ authen reply too short"));
227 }
228 let status = match data[0] {
229 0x01 => AuthenStatus::Pass,
230 0x02 => AuthenStatus::Fail,
231 0x03 => AuthenStatus::GetData,
232 0x04 => AuthenStatus::GetUser,
233 0x05 => AuthenStatus::GetPass,
234 0x06 => AuthenStatus::Restart,
235 0x07 => AuthenStatus::Error,
236 0x21 => AuthenStatus::Follow,
237 other => {
238 return Err(AuthError::validation(format!(
239 "Unknown authen status: {other:#x}"
240 )));
241 }
242 };
243 let flags = data[1];
244 let server_msg_len = u16::from_be_bytes([data[2], data[3]]) as usize;
245 let data_len = u16::from_be_bytes([data[4], data[5]]) as usize;
246
247 if data.len() < 6 + server_msg_len + data_len {
248 return Err(AuthError::validation("TACACS+ authen reply truncated"));
249 }
250
251 let server_msg = String::from_utf8_lossy(&data[6..6 + server_msg_len]).to_string();
252 let reply_data = data[6 + server_msg_len..6 + server_msg_len + data_len].to_vec();
253
254 Ok(Self {
255 status,
256 flags,
257 server_msg,
258 data: reply_data,
259 })
260 }
261}
262
263#[derive(Debug, Clone, Serialize, Deserialize)]
267pub struct AuthorRequestBody {
268 pub authen_method: u8,
269 pub authen_type: AuthenType,
270 pub authen_service: AuthenService,
271 pub user: String,
272 pub port: String,
273 pub remote_address: String,
274 pub args: Vec<String>,
276}
277
278impl AuthorRequestBody {
279 pub fn to_bytes(&self) -> Vec<u8> {
281 let user_bytes = self.user.as_bytes();
282 let port_bytes = self.port.as_bytes();
283 let rem_bytes = self.remote_address.as_bytes();
284 let arg_count = self.args.len() as u8;
285
286 let mut buf = vec![
288 self.authen_method,
289 0x01, self.authen_type as u8,
291 self.authen_service as u8,
292 user_bytes.len() as u8,
293 port_bytes.len() as u8,
294 rem_bytes.len() as u8,
295 arg_count,
296 ];
297
298 for arg in &self.args {
300 buf.push(arg.len() as u8);
301 }
302
303 buf.extend_from_slice(user_bytes);
305 buf.extend_from_slice(port_bytes);
306 buf.extend_from_slice(rem_bytes);
307 for arg in &self.args {
308 buf.extend_from_slice(arg.as_bytes());
309 }
310
311 buf
312 }
313}
314
315#[derive(Debug, Clone, Serialize, Deserialize)]
317pub struct AuthorReplyBody {
318 pub status: AuthorStatus,
319 pub server_msg: String,
320 pub data: Vec<u8>,
321 pub args: Vec<String>,
322}
323
324impl AuthorReplyBody {
325 pub fn from_bytes(data: &[u8]) -> Result<Self> {
327 if data.len() < 6 {
328 return Err(AuthError::validation("TACACS+ author reply too short"));
329 }
330 let status = match data[0] {
331 0x01 => AuthorStatus::PassAdd,
332 0x02 => AuthorStatus::PassReplace,
333 0x10 => AuthorStatus::Fail,
334 0x11 => AuthorStatus::Error,
335 0x21 => AuthorStatus::Follow,
336 other => {
337 return Err(AuthError::validation(format!(
338 "Unknown author status: {other:#x}"
339 )));
340 }
341 };
342
343 let arg_count = data[1] as usize;
344 let server_msg_len = u16::from_be_bytes([data[2], data[3]]) as usize;
345 let data_len = u16::from_be_bytes([data[4], data[5]]) as usize;
346
347 let mut offset = 6;
348 if data.len() < offset + arg_count {
350 return Err(AuthError::validation(
351 "TACACS+ author reply truncated (arg lengths)",
352 ));
353 }
354 let arg_lens: Vec<usize> = data[offset..offset + arg_count]
355 .iter()
356 .map(|&b| b as usize)
357 .collect();
358 offset += arg_count;
359
360 if data.len() < offset + server_msg_len {
362 return Err(AuthError::validation(
363 "TACACS+ author reply truncated (msg)",
364 ));
365 }
366 let server_msg =
367 String::from_utf8_lossy(&data[offset..offset + server_msg_len]).to_string();
368 offset += server_msg_len;
369
370 if data.len() < offset + data_len {
372 return Err(AuthError::validation(
373 "TACACS+ author reply truncated (data)",
374 ));
375 }
376 let reply_data = data[offset..offset + data_len].to_vec();
377 offset += data_len;
378
379 let mut args = Vec::with_capacity(arg_count);
381 for &len in &arg_lens {
382 if data.len() < offset + len {
383 return Err(AuthError::validation(
384 "TACACS+ author reply truncated (args)",
385 ));
386 }
387 args.push(String::from_utf8_lossy(&data[offset..offset + len]).to_string());
388 offset += len;
389 }
390
391 Ok(Self {
392 status,
393 server_msg,
394 data: reply_data,
395 args,
396 })
397 }
398}
399
400#[derive(Debug, Clone, Serialize, Deserialize)]
404pub struct AcctRequestBody {
405 pub flags: AcctFlags,
406 pub authen_method: u8,
407 pub authen_type: AuthenType,
408 pub authen_service: AuthenService,
409 pub user: String,
410 pub port: String,
411 pub remote_address: String,
412 pub args: Vec<String>,
414}
415
416impl AcctRequestBody {
417 pub fn to_bytes(&self) -> Vec<u8> {
419 let user_bytes = self.user.as_bytes();
420 let port_bytes = self.port.as_bytes();
421 let rem_bytes = self.remote_address.as_bytes();
422 let arg_count = self.args.len() as u8;
423
424 let mut buf = vec![
425 self.flags.0,
426 self.authen_method,
427 0x01, self.authen_type as u8,
429 self.authen_service as u8,
430 user_bytes.len() as u8,
431 port_bytes.len() as u8,
432 rem_bytes.len() as u8,
433 arg_count,
434 ];
435
436 for arg in &self.args {
438 buf.push(arg.len() as u8);
439 }
440
441 buf.extend_from_slice(user_bytes);
443 buf.extend_from_slice(port_bytes);
444 buf.extend_from_slice(rem_bytes);
445 for arg in &self.args {
446 buf.extend_from_slice(arg.as_bytes());
447 }
448
449 buf
450 }
451}
452
453#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
455#[repr(u8)]
456pub enum AcctStatus {
457 Success = 0x01,
458 Error = 0x02,
459 Follow = 0x21,
460}
461
462#[derive(Debug, Clone, Serialize, Deserialize)]
464pub struct AcctReplyBody {
465 pub status: AcctStatus,
466 pub server_msg: String,
467 pub data: Vec<u8>,
468}
469
470impl AcctReplyBody {
471 pub fn from_bytes(data: &[u8]) -> Result<Self> {
473 if data.len() < 5 {
474 return Err(AuthError::validation("TACACS+ acct reply too short"));
475 }
476 let server_msg_len = u16::from_be_bytes([data[0], data[1]]) as usize;
477 let data_len = u16::from_be_bytes([data[2], data[3]]) as usize;
478 let status = match data[4] {
479 0x01 => AcctStatus::Success,
480 0x02 => AcctStatus::Error,
481 0x21 => AcctStatus::Follow,
482 other => {
483 return Err(AuthError::validation(format!(
484 "Unknown acct status: {other:#x}"
485 )));
486 }
487 };
488
489 let offset = 5;
490 if data.len() < offset + server_msg_len + data_len {
491 return Err(AuthError::validation("TACACS+ acct reply truncated"));
492 }
493 let server_msg =
494 String::from_utf8_lossy(&data[offset..offset + server_msg_len]).to_string();
495 let reply_data = data[offset + server_msg_len..offset + server_msg_len + data_len].to_vec();
496
497 Ok(Self {
498 status,
499 server_msg,
500 data: reply_data,
501 })
502 }
503}
504
505pub fn obfuscate(header: &TacacsHeader, secret: &[u8], body: &mut [u8]) {
511 if secret.is_empty() || body.is_empty() {
512 return;
513 }
514
515 let mut pad = Vec::new();
516 let session_id_bytes = header.session_id.to_be_bytes();
517
518 let mut ctx = Context::new(&SHA256);
520 ctx.update(&session_id_bytes);
521 ctx.update(secret);
522 ctx.update(&[header.version]);
523 ctx.update(&[header.seq_no]);
524 let digest = ctx.finish();
525 pad.extend_from_slice(digest.as_ref());
526
527 while pad.len() < body.len() {
529 let mut ctx = Context::new(&SHA256);
530 ctx.update(&session_id_bytes);
531 ctx.update(secret);
532 ctx.update(&[header.version]);
533 ctx.update(&[header.seq_no]);
534 let prev_start = pad.len().saturating_sub(32);
535 ctx.update(&pad[prev_start..]);
536 let digest = ctx.finish();
537 pad.extend_from_slice(digest.as_ref());
538 }
539
540 for (i, b) in body.iter_mut().enumerate() {
542 *b ^= pad[i];
543 }
544}
545
546pub fn generate_session_id() -> Result<u32> {
548 use ring::rand::{SecureRandom, SystemRandom};
549 let rng = SystemRandom::new();
550 let mut buf = [0u8; 4];
551 rng.fill(&mut buf)
552 .map_err(|_| AuthError::crypto("Failed to generate session ID".to_string()))?;
553 Ok(u32::from_be_bytes(buf))
554}
555
556#[cfg(test)]
557mod tests {
558 use super::*;
559
560 #[test]
561 fn test_header_roundtrip() {
562 let h = TacacsHeader::new(TacacsPacketType::Authentication, 1, 0xDEADBEEF, 42);
563 let bytes = h.to_bytes();
564 assert_eq!(bytes.len(), 12);
565 let h2 = TacacsHeader::from_bytes(&bytes).unwrap();
566 assert_eq!(h2.packet_type, TacacsPacketType::Authentication);
567 assert_eq!(h2.session_id, 0xDEADBEEF);
568 assert_eq!(h2.length, 42);
569 assert_eq!(h2.seq_no, 1);
570 }
571
572 #[test]
573 fn test_header_too_short() {
574 assert!(TacacsHeader::from_bytes(&[0; 5]).is_err());
575 }
576
577 #[test]
578 fn test_header_unknown_type() {
579 let mut bytes = TacacsHeader::new(TacacsPacketType::Authentication, 1, 1, 0).to_bytes();
580 bytes[1] = 0xFF;
581 assert!(TacacsHeader::from_bytes(&bytes).is_err());
582 }
583
584 #[test]
585 fn test_authen_start_body_serialization() {
586 let body = AuthenStartBody {
587 action: AuthenAction::Login,
588 authen_type: AuthenType::Pap,
589 authen_service: AuthenService::Login,
590 user: "admin".to_string(),
591 port: "tty0".to_string(),
592 remote_address: "10.0.0.1".to_string(),
593 data: b"password".to_vec(),
594 };
595 let bytes = body.to_bytes();
596 assert_eq!(bytes[0], AuthenAction::Login as u8);
597 assert_eq!(bytes[2], AuthenType::Pap as u8);
598 assert_eq!(bytes[4], 5); }
600
601 #[test]
602 fn test_authen_reply_parsing() {
603 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!");
607
608 let reply = AuthenReplyBody::from_bytes(&data).unwrap();
609 assert_eq!(reply.status, AuthenStatus::Pass);
610 assert_eq!(reply.server_msg, "OK!");
611 assert!(reply.data.is_empty());
612 }
613
614 #[test]
615 fn test_authen_reply_too_short() {
616 assert!(AuthenReplyBody::from_bytes(&[0x01, 0x00]).is_err());
617 }
618
619 #[test]
620 fn test_obfuscate_deobfuscate_roundtrip() {
621 let header = TacacsHeader::new(TacacsPacketType::Authentication, 1, 12345, 11);
622 let secret = b"shared-secret";
623 let original = b"hello world".to_vec();
624 let mut encrypted = original.clone();
625
626 obfuscate(&header, secret, &mut encrypted);
627 assert_ne!(encrypted, original, "obfuscation should change data");
628
629 obfuscate(&header, secret, &mut encrypted);
630 assert_eq!(
631 encrypted, original,
632 "double obfuscation should restore data"
633 );
634 }
635
636 #[test]
637 fn test_obfuscate_empty_secret_noop() {
638 let header = TacacsHeader::new(TacacsPacketType::Authentication, 1, 1, 5);
639 let mut data = b"hello".to_vec();
640 let orig = data.clone();
641 obfuscate(&header, b"", &mut data);
642 assert_eq!(data, orig);
643 }
644
645 #[test]
646 fn test_generate_session_id() {
647 let id1 = generate_session_id().unwrap();
648 let id2 = generate_session_id().unwrap();
649 assert!(id1 != 0 || id2 != 0);
652 }
653
654 #[test]
655 fn test_acct_flags() {
656 let start = AcctFlags::START;
657 assert!(start.is_start());
658 assert!(!start.is_stop());
659 assert!(!start.is_watchdog());
660
661 let stop = AcctFlags::STOP;
662 assert!(stop.is_stop());
663 }
664
665 #[test]
666 fn test_packet_type_values() {
667 assert_eq!(TacacsPacketType::Authentication as u8, 0x01);
668 assert_eq!(TacacsPacketType::Authorization as u8, 0x02);
669 assert_eq!(TacacsPacketType::Accounting as u8, 0x03);
670 }
671
672 #[test]
675 fn test_author_request_serialization() {
676 let body = AuthorRequestBody {
677 authen_method: 0x06, authen_type: AuthenType::Pap,
679 authen_service: AuthenService::Login,
680 user: "admin".to_string(),
681 port: "tty0".to_string(),
682 remote_address: "10.0.0.1".to_string(),
683 args: vec!["service=shell".to_string(), "cmd=show".to_string()],
684 };
685 let bytes = body.to_bytes();
686 assert_eq!(bytes[0], 0x06); assert_eq!(bytes[7], 2); assert_eq!(bytes[8], 13); assert_eq!(bytes[9], 8); }
692
693 #[test]
694 fn test_author_reply_parsing() {
695 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();
707 assert_eq!(reply.status, AuthorStatus::PassAdd);
708 assert_eq!(reply.server_msg, "OK");
709 assert_eq!(reply.args.len(), 2);
710 assert_eq!(reply.args[0], "priv=1");
711 assert_eq!(reply.args[1], "role=a");
712 }
713
714 #[test]
715 fn test_author_reply_too_short() {
716 assert!(AuthorReplyBody::from_bytes(&[0x01]).is_err());
717 }
718
719 #[test]
722 fn test_acct_request_serialization() {
723 let body = AcctRequestBody {
724 flags: AcctFlags::START,
725 authen_method: 0x06,
726 authen_type: AuthenType::Pap,
727 authen_service: AuthenService::Login,
728 user: "admin".to_string(),
729 port: "tty0".to_string(),
730 remote_address: "10.0.0.1".to_string(),
731 args: vec!["task_id=1".to_string()],
732 };
733 let bytes = body.to_bytes();
734 assert_eq!(bytes[0], AcctFlags::START.0); assert_eq!(bytes[8], 1); }
737
738 #[test]
739 fn test_acct_reply_parsing() {
740 let mut data = Vec::new();
741 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();
747 assert_eq!(reply.status, AcctStatus::Success);
748 assert_eq!(reply.server_msg, "Done");
749 }
750
751 #[test]
752 fn test_acct_reply_too_short() {
753 assert!(AcctReplyBody::from_bytes(&[0x00, 0x01]).is_err());
754 }
755}