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 pub fn to_bytes(&self) -> Vec<u8> {
267 let user_bytes = self.user.as_bytes();
268 let port_bytes = self.port.as_bytes();
269 let rem_bytes = self.remote_address.as_bytes();
270 let arg_count = self.args.len() as u8;
271
272 let mut buf = vec![
274 self.authen_method,
275 0x01, self.authen_type as u8,
277 self.authen_service as u8,
278 user_bytes.len() as u8,
279 port_bytes.len() as u8,
280 rem_bytes.len() as u8,
281 arg_count,
282 ];
283
284 for arg in &self.args {
286 buf.push(arg.len() as u8);
287 }
288
289 buf.extend_from_slice(user_bytes);
291 buf.extend_from_slice(port_bytes);
292 buf.extend_from_slice(rem_bytes);
293 for arg in &self.args {
294 buf.extend_from_slice(arg.as_bytes());
295 }
296
297 buf
298 }
299}
300
301#[derive(Debug, Clone, Serialize, Deserialize)]
303pub struct AuthorReplyBody {
304 pub status: AuthorStatus,
305 pub server_msg: String,
306 pub data: Vec<u8>,
307 pub args: Vec<String>,
308}
309
310impl AuthorReplyBody {
311 pub fn from_bytes(data: &[u8]) -> Result<Self> {
313 if data.len() < 6 {
314 return Err(AuthError::validation("TACACS+ author reply too short"));
315 }
316 let status = match data[0] {
317 0x01 => AuthorStatus::PassAdd,
318 0x02 => AuthorStatus::PassReplace,
319 0x10 => AuthorStatus::Fail,
320 0x11 => AuthorStatus::Error,
321 0x21 => AuthorStatus::Follow,
322 other => {
323 return Err(AuthError::validation(format!(
324 "Unknown author status: {other:#x}"
325 )));
326 }
327 };
328
329 let arg_count = data[1] as usize;
330 let server_msg_len = u16::from_be_bytes([data[2], data[3]]) as usize;
331 let data_len = u16::from_be_bytes([data[4], data[5]]) as usize;
332
333 let mut offset = 6;
334 if data.len() < offset + arg_count {
336 return Err(AuthError::validation(
337 "TACACS+ author reply truncated (arg lengths)",
338 ));
339 }
340 let arg_lens: Vec<usize> = data[offset..offset + arg_count]
341 .iter()
342 .map(|&b| b as usize)
343 .collect();
344 offset += arg_count;
345
346 if data.len() < offset + server_msg_len {
348 return Err(AuthError::validation(
349 "TACACS+ author reply truncated (msg)",
350 ));
351 }
352 let server_msg =
353 String::from_utf8_lossy(&data[offset..offset + server_msg_len]).to_string();
354 offset += server_msg_len;
355
356 if data.len() < offset + data_len {
358 return Err(AuthError::validation(
359 "TACACS+ author reply truncated (data)",
360 ));
361 }
362 let reply_data = data[offset..offset + data_len].to_vec();
363 offset += data_len;
364
365 let mut args = Vec::with_capacity(arg_count);
367 for &len in &arg_lens {
368 if data.len() < offset + len {
369 return Err(AuthError::validation(
370 "TACACS+ author reply truncated (args)",
371 ));
372 }
373 args.push(String::from_utf8_lossy(&data[offset..offset + len]).to_string());
374 offset += len;
375 }
376
377 Ok(Self {
378 status,
379 server_msg,
380 data: reply_data,
381 args,
382 })
383 }
384}
385
386#[derive(Debug, Clone, Serialize, Deserialize)]
390pub struct AcctRequestBody {
391 pub flags: AcctFlags,
392 pub authen_method: u8,
393 pub authen_type: AuthenType,
394 pub authen_service: AuthenService,
395 pub user: String,
396 pub port: String,
397 pub remote_address: String,
398 pub args: Vec<String>,
400}
401
402impl AcctRequestBody {
403 pub fn to_bytes(&self) -> Vec<u8> {
405 let user_bytes = self.user.as_bytes();
406 let port_bytes = self.port.as_bytes();
407 let rem_bytes = self.remote_address.as_bytes();
408 let arg_count = self.args.len() as u8;
409
410 let mut buf = vec![
411 self.flags.0,
412 self.authen_method,
413 0x01, self.authen_type as u8,
415 self.authen_service as u8,
416 user_bytes.len() as u8,
417 port_bytes.len() as u8,
418 rem_bytes.len() as u8,
419 arg_count,
420 ];
421
422 for arg in &self.args {
424 buf.push(arg.len() as u8);
425 }
426
427 buf.extend_from_slice(user_bytes);
429 buf.extend_from_slice(port_bytes);
430 buf.extend_from_slice(rem_bytes);
431 for arg in &self.args {
432 buf.extend_from_slice(arg.as_bytes());
433 }
434
435 buf
436 }
437}
438
439#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
441#[repr(u8)]
442pub enum AcctStatus {
443 Success = 0x01,
444 Error = 0x02,
445 Follow = 0x21,
446}
447
448#[derive(Debug, Clone, Serialize, Deserialize)]
450pub struct AcctReplyBody {
451 pub status: AcctStatus,
452 pub server_msg: String,
453 pub data: Vec<u8>,
454}
455
456impl AcctReplyBody {
457 pub fn from_bytes(data: &[u8]) -> Result<Self> {
459 if data.len() < 5 {
460 return Err(AuthError::validation("TACACS+ acct reply too short"));
461 }
462 let server_msg_len = u16::from_be_bytes([data[0], data[1]]) as usize;
463 let data_len = u16::from_be_bytes([data[2], data[3]]) as usize;
464 let status = match data[4] {
465 0x01 => AcctStatus::Success,
466 0x02 => AcctStatus::Error,
467 0x21 => AcctStatus::Follow,
468 other => {
469 return Err(AuthError::validation(format!(
470 "Unknown acct status: {other:#x}"
471 )));
472 }
473 };
474
475 let offset = 5;
476 if data.len() < offset + server_msg_len + data_len {
477 return Err(AuthError::validation("TACACS+ acct reply truncated"));
478 }
479 let server_msg =
480 String::from_utf8_lossy(&data[offset..offset + server_msg_len]).to_string();
481 let reply_data = data[offset + server_msg_len..offset + server_msg_len + data_len].to_vec();
482
483 Ok(Self {
484 status,
485 server_msg,
486 data: reply_data,
487 })
488 }
489}
490
491pub fn obfuscate(header: &TacacsHeader, secret: &[u8], body: &mut [u8]) {
497 if secret.is_empty() || body.is_empty() {
498 return;
499 }
500
501 let mut pad = Vec::new();
502 let session_id_bytes = header.session_id.to_be_bytes();
503
504 let mut ctx = Context::new(&SHA256);
506 ctx.update(&session_id_bytes);
507 ctx.update(secret);
508 ctx.update(&[header.version]);
509 ctx.update(&[header.seq_no]);
510 let digest = ctx.finish();
511 pad.extend_from_slice(digest.as_ref());
512
513 while pad.len() < body.len() {
515 let mut ctx = Context::new(&SHA256);
516 ctx.update(&session_id_bytes);
517 ctx.update(secret);
518 ctx.update(&[header.version]);
519 ctx.update(&[header.seq_no]);
520 let prev_start = pad.len().saturating_sub(32);
521 ctx.update(&pad[prev_start..]);
522 let digest = ctx.finish();
523 pad.extend_from_slice(digest.as_ref());
524 }
525
526 for (i, b) in body.iter_mut().enumerate() {
528 *b ^= pad[i];
529 }
530}
531
532pub fn generate_session_id() -> Result<u32> {
534 use ring::rand::{SecureRandom, SystemRandom};
535 let rng = SystemRandom::new();
536 let mut buf = [0u8; 4];
537 rng.fill(&mut buf)
538 .map_err(|_| AuthError::crypto("Failed to generate session ID".to_string()))?;
539 Ok(u32::from_be_bytes(buf))
540}
541
542#[cfg(test)]
543mod tests {
544 use super::*;
545
546 #[test]
547 fn test_header_roundtrip() {
548 let h = TacacsHeader::new(TacacsPacketType::Authentication, 1, 0xDEADBEEF, 42);
549 let bytes = h.to_bytes();
550 assert_eq!(bytes.len(), 12);
551 let h2 = TacacsHeader::from_bytes(&bytes).unwrap();
552 assert_eq!(h2.packet_type, TacacsPacketType::Authentication);
553 assert_eq!(h2.session_id, 0xDEADBEEF);
554 assert_eq!(h2.length, 42);
555 assert_eq!(h2.seq_no, 1);
556 }
557
558 #[test]
559 fn test_header_too_short() {
560 assert!(TacacsHeader::from_bytes(&[0; 5]).is_err());
561 }
562
563 #[test]
564 fn test_header_unknown_type() {
565 let mut bytes = TacacsHeader::new(TacacsPacketType::Authentication, 1, 1, 0).to_bytes();
566 bytes[1] = 0xFF;
567 assert!(TacacsHeader::from_bytes(&bytes).is_err());
568 }
569
570 #[test]
571 fn test_authen_start_body_serialization() {
572 let body = AuthenStartBody {
573 action: AuthenAction::Login,
574 authen_type: AuthenType::Pap,
575 authen_service: AuthenService::Login,
576 user: "admin".to_string(),
577 port: "tty0".to_string(),
578 remote_address: "10.0.0.1".to_string(),
579 data: b"password".to_vec(),
580 };
581 let bytes = body.to_bytes();
582 assert_eq!(bytes[0], AuthenAction::Login as u8);
583 assert_eq!(bytes[2], AuthenType::Pap as u8);
584 assert_eq!(bytes[4], 5); }
586
587 #[test]
588 fn test_authen_reply_parsing() {
589 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!");
593
594 let reply = AuthenReplyBody::from_bytes(&data).unwrap();
595 assert_eq!(reply.status, AuthenStatus::Pass);
596 assert_eq!(reply.server_msg, "OK!");
597 assert!(reply.data.is_empty());
598 }
599
600 #[test]
601 fn test_authen_reply_too_short() {
602 assert!(AuthenReplyBody::from_bytes(&[0x01, 0x00]).is_err());
603 }
604
605 #[test]
606 fn test_obfuscate_deobfuscate_roundtrip() {
607 let header = TacacsHeader::new(TacacsPacketType::Authentication, 1, 12345, 11);
608 let secret = b"shared-secret";
609 let original = b"hello world".to_vec();
610 let mut encrypted = original.clone();
611
612 obfuscate(&header, secret, &mut encrypted);
613 assert_ne!(encrypted, original, "obfuscation should change data");
614
615 obfuscate(&header, secret, &mut encrypted);
616 assert_eq!(
617 encrypted, original,
618 "double obfuscation should restore data"
619 );
620 }
621
622 #[test]
623 fn test_obfuscate_empty_secret_noop() {
624 let header = TacacsHeader::new(TacacsPacketType::Authentication, 1, 1, 5);
625 let mut data = b"hello".to_vec();
626 let orig = data.clone();
627 obfuscate(&header, b"", &mut data);
628 assert_eq!(data, orig);
629 }
630
631 #[test]
632 fn test_generate_session_id() {
633 let id1 = generate_session_id().unwrap();
634 let id2 = generate_session_id().unwrap();
635 assert!(id1 != 0 || id2 != 0);
638 }
639
640 #[test]
641 fn test_acct_flags() {
642 let start = AcctFlags::START;
643 assert!(start.is_start());
644 assert!(!start.is_stop());
645 assert!(!start.is_watchdog());
646
647 let stop = AcctFlags::STOP;
648 assert!(stop.is_stop());
649 }
650
651 #[test]
652 fn test_packet_type_values() {
653 assert_eq!(TacacsPacketType::Authentication as u8, 0x01);
654 assert_eq!(TacacsPacketType::Authorization as u8, 0x02);
655 assert_eq!(TacacsPacketType::Accounting as u8, 0x03);
656 }
657
658 #[test]
661 fn test_author_request_serialization() {
662 let body = AuthorRequestBody {
663 authen_method: 0x06, authen_type: AuthenType::Pap,
665 authen_service: AuthenService::Login,
666 user: "admin".to_string(),
667 port: "tty0".to_string(),
668 remote_address: "10.0.0.1".to_string(),
669 args: vec!["service=shell".to_string(), "cmd=show".to_string()],
670 };
671 let bytes = body.to_bytes();
672 assert_eq!(bytes[0], 0x06); assert_eq!(bytes[7], 2); assert_eq!(bytes[8], 13); assert_eq!(bytes[9], 8); }
678
679 #[test]
680 fn test_author_reply_parsing() {
681 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();
693 assert_eq!(reply.status, AuthorStatus::PassAdd);
694 assert_eq!(reply.server_msg, "OK");
695 assert_eq!(reply.args.len(), 2);
696 assert_eq!(reply.args[0], "priv=1");
697 assert_eq!(reply.args[1], "role=a");
698 }
699
700 #[test]
701 fn test_author_reply_too_short() {
702 assert!(AuthorReplyBody::from_bytes(&[0x01]).is_err());
703 }
704
705 #[test]
708 fn test_acct_request_serialization() {
709 let body = AcctRequestBody {
710 flags: AcctFlags::START,
711 authen_method: 0x06,
712 authen_type: AuthenType::Pap,
713 authen_service: AuthenService::Login,
714 user: "admin".to_string(),
715 port: "tty0".to_string(),
716 remote_address: "10.0.0.1".to_string(),
717 args: vec!["task_id=1".to_string()],
718 };
719 let bytes = body.to_bytes();
720 assert_eq!(bytes[0], AcctFlags::START.0); assert_eq!(bytes[8], 1); }
723
724 #[test]
725 fn test_acct_reply_parsing() {
726 let mut data = Vec::new();
727 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();
733 assert_eq!(reply.status, AcctStatus::Success);
734 assert_eq!(reply.server_msg, "Done");
735 }
736
737 #[test]
738 fn test_acct_reply_too_short() {
739 assert!(AcctReplyBody::from_bytes(&[0x00, 0x01]).is_err());
740 }
741}