1#![deny(unsafe_code)]
51#![warn(missing_docs)]
52#![doc(html_root_url = "https://docs.rs/ccache-io/0.1.0")]
53
54use thiserror::Error;
55
56pub const V4_MAGIC: u16 = 0x0504;
60
61pub const NT_PRINCIPAL: u32 = 1;
63pub const NT_SRV_INST: u32 = 2;
65
66#[non_exhaustive]
69#[derive(Debug, Error, PartialEq, Eq)]
70pub enum CcacheError {
71 #[error("unsupported ccache version {found:#06x} (expected {expected:#06x})")]
73 UnsupportedVersion {
74 found: u16,
76 expected: u16,
78 },
79 #[error("truncated input: need {need} bytes at offset {at}, have {remaining}")]
82 Truncated {
83 need: usize,
85 at: usize,
87 remaining: usize,
89 },
90 #[error("component count {count} at offset {at} exceeds sane cap ({cap})")]
93 TooManyComponents {
94 count: u32,
96 at: usize,
98 cap: u32,
100 },
101 #[error("non-UTF-8 principal string at offset {at}: {source}")]
106 Utf8 {
107 at: usize,
109 #[source]
111 source: std::str::Utf8Error,
112 },
113}
114
115#[derive(Clone, Debug, PartialEq, Eq)]
118pub struct Principal {
119 pub realm: String,
121 pub name_type: u32,
123 pub components: Vec<String>,
126}
127
128impl Principal {
129 pub fn canonical(&self) -> String {
131 format!("{}@{}", self.components.join("/"), self.realm)
132 }
133}
134
135#[derive(Clone, Debug, PartialEq, Eq)]
139pub struct KeyBlock {
140 pub keytype: u16,
143 pub key: Vec<u8>,
145}
146
147#[derive(Clone, Debug, PartialEq, Eq)]
150pub struct Address {
151 pub addr_type: u16,
153 pub data: Vec<u8>,
155}
156
157#[derive(Clone, Debug, PartialEq, Eq)]
160pub struct AuthData {
161 pub ad_type: u16,
163 pub data: Vec<u8>,
165}
166
167#[derive(Clone, Debug, PartialEq, Eq)]
169pub struct Credential {
170 pub client: Principal,
172 pub server: Principal,
174 pub key: KeyBlock,
176 pub authtime: u32,
178 pub starttime: u32,
180 pub endtime: u32,
182 pub renew_till: u32,
184 pub is_skey: bool,
187 pub tktflags: u32,
189 pub addresses: Vec<Address>,
191 pub authdata: Vec<AuthData>,
193 pub ticket: Vec<u8>,
196 pub second_ticket: Vec<u8>,
198}
199
200#[derive(Clone, Debug, PartialEq, Eq)]
202pub struct Ccache {
203 pub header: Vec<u8>,
206 pub primary: Principal,
208 pub credentials: Vec<Credential>,
211}
212
213const MAX_COMPONENTS: u32 = 1024;
216const DEFAULT_HEADER: &[u8] = &[
219 0x00, 0x01, 0x00, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, ];
223
224impl Ccache {
225 pub fn parse(bytes: &[u8]) -> Result<Self, CcacheError> {
229 let mut r = Reader::new(bytes);
230 let version = r.u16()?;
231 if version != V4_MAGIC {
232 return Err(CcacheError::UnsupportedVersion {
233 found: version,
234 expected: V4_MAGIC,
235 });
236 }
237 let header_len = r.u16()? as usize;
238 let header = r.take(header_len)?.to_vec();
239 let primary = read_principal(&mut r)?;
240 let mut credentials = Vec::new();
241 while r.remaining() > 0 {
242 credentials.push(read_credential(&mut r)?);
243 }
244 Ok(Ccache {
245 header,
246 primary,
247 credentials,
248 })
249 }
250
251 pub fn to_bytes(&self) -> Vec<u8> {
253 let mut w = Writer::new();
254 w.u16(V4_MAGIC);
255 w.u16(self.header.len() as u16);
256 w.bytes(&self.header);
257 write_principal(&mut w, &self.primary);
258 for c in &self.credentials {
259 write_credential(&mut w, c);
260 }
261 w.take()
262 }
263
264 pub fn new(primary: Principal) -> Self {
267 Ccache {
268 header: DEFAULT_HEADER.to_vec(),
269 primary,
270 credentials: Vec::new(),
271 }
272 }
273}
274
275struct Reader<'a> {
278 b: &'a [u8],
279 pos: usize,
280}
281
282impl<'a> Reader<'a> {
283 fn new(b: &'a [u8]) -> Self {
284 Reader { b, pos: 0 }
285 }
286 fn remaining(&self) -> usize {
287 self.b.len() - self.pos
288 }
289 fn take(&mut self, n: usize) -> Result<&'a [u8], CcacheError> {
290 if n > self.remaining() {
291 return Err(CcacheError::Truncated {
292 need: n,
293 at: self.pos,
294 remaining: self.remaining(),
295 });
296 }
297 let slice = &self.b[self.pos..self.pos + n];
298 self.pos += n;
299 Ok(slice)
300 }
301 fn u16(&mut self) -> Result<u16, CcacheError> {
302 let b = self.take(2)?;
303 Ok(u16::from_be_bytes([b[0], b[1]]))
304 }
305 fn u32(&mut self) -> Result<u32, CcacheError> {
306 let b = self.take(4)?;
307 Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
308 }
309 fn u8(&mut self) -> Result<u8, CcacheError> {
310 Ok(self.take(1)?[0])
311 }
312 fn counted(&mut self) -> Result<&'a [u8], CcacheError> {
313 let n = self.u32()? as usize;
314 self.take(n)
315 }
316 fn counted_str(&mut self) -> Result<String, CcacheError> {
317 let at = self.pos;
318 let bytes = self.counted()?;
319 std::str::from_utf8(bytes)
320 .map(str::to_string)
321 .map_err(|source| CcacheError::Utf8 { at, source })
322 }
323}
324
325struct Writer(Vec<u8>);
326
327impl Writer {
328 fn new() -> Self {
329 Writer(Vec::with_capacity(512))
330 }
331 fn take(self) -> Vec<u8> {
332 self.0
333 }
334 fn u16(&mut self, v: u16) {
335 self.0.extend_from_slice(&v.to_be_bytes());
336 }
337 fn u32(&mut self, v: u32) {
338 self.0.extend_from_slice(&v.to_be_bytes());
339 }
340 fn u8(&mut self, v: u8) {
341 self.0.push(v);
342 }
343 fn bytes(&mut self, b: &[u8]) {
344 self.0.extend_from_slice(b);
345 }
346 fn counted(&mut self, b: &[u8]) {
347 self.u32(b.len() as u32);
348 self.bytes(b);
349 }
350}
351
352fn read_principal(r: &mut Reader) -> Result<Principal, CcacheError> {
353 let at = r.pos;
354 let name_type = r.u32()?;
355 let num = r.u32()?;
356 if num > MAX_COMPONENTS {
357 return Err(CcacheError::TooManyComponents {
358 count: num,
359 at,
360 cap: MAX_COMPONENTS,
361 });
362 }
363 let realm = r.counted_str()?;
364 let mut components = Vec::with_capacity(num as usize);
365 for _ in 0..num {
366 components.push(r.counted_str()?);
367 }
368 Ok(Principal {
369 realm,
370 name_type,
371 components,
372 })
373}
374
375fn write_principal(w: &mut Writer, p: &Principal) {
376 w.u32(p.name_type);
377 w.u32(p.components.len() as u32);
378 w.counted(p.realm.as_bytes());
379 for c in &p.components {
380 w.counted(c.as_bytes());
381 }
382}
383
384fn read_credential(r: &mut Reader) -> Result<Credential, CcacheError> {
385 let client = read_principal(r)?;
386 let server = read_principal(r)?;
387 let keytype = r.u16()?;
388 let _etype_unused = r.u16()?;
389 let key_bytes = r.counted()?.to_vec();
390 let authtime = r.u32()?;
391 let starttime = r.u32()?;
392 let endtime = r.u32()?;
393 let renew_till = r.u32()?;
394 let is_skey = r.u8()? != 0;
395 let tktflags = r.u32()?;
396 let num_addr = r.u32()? as usize;
397 if num_addr > MAX_COMPONENTS as usize {
398 return Err(CcacheError::TooManyComponents {
399 count: num_addr as u32,
400 at: r.pos,
401 cap: MAX_COMPONENTS,
402 });
403 }
404 let mut addresses = Vec::with_capacity(num_addr);
405 for _ in 0..num_addr {
406 let addr_type = r.u16()?;
407 let data = r.counted()?.to_vec();
408 addresses.push(Address { addr_type, data });
409 }
410 let num_ad = r.u32()? as usize;
411 if num_ad > MAX_COMPONENTS as usize {
412 return Err(CcacheError::TooManyComponents {
413 count: num_ad as u32,
414 at: r.pos,
415 cap: MAX_COMPONENTS,
416 });
417 }
418 let mut authdata = Vec::with_capacity(num_ad);
419 for _ in 0..num_ad {
420 let ad_type = r.u16()?;
421 let data = r.counted()?.to_vec();
422 authdata.push(AuthData { ad_type, data });
423 }
424 let ticket = r.counted()?.to_vec();
425 let second_ticket = r.counted()?.to_vec();
426 Ok(Credential {
427 client,
428 server,
429 key: KeyBlock {
430 keytype,
431 key: key_bytes,
432 },
433 authtime,
434 starttime,
435 endtime,
436 renew_till,
437 is_skey,
438 tktflags,
439 addresses,
440 authdata,
441 ticket,
442 second_ticket,
443 })
444}
445
446fn write_credential(w: &mut Writer, c: &Credential) {
447 write_principal(w, &c.client);
448 write_principal(w, &c.server);
449 w.u16(c.key.keytype);
450 w.u16(0); w.counted(&c.key.key);
452 w.u32(c.authtime);
453 w.u32(c.starttime);
454 w.u32(c.endtime);
455 w.u32(c.renew_till);
456 w.u8(if c.is_skey { 1 } else { 0 });
457 w.u32(c.tktflags);
458 w.u32(c.addresses.len() as u32);
459 for a in &c.addresses {
460 w.u16(a.addr_type);
461 w.counted(&a.data);
462 }
463 w.u32(c.authdata.len() as u32);
464 for a in &c.authdata {
465 w.u16(a.ad_type);
466 w.counted(&a.data);
467 }
468 w.counted(&c.ticket);
469 w.counted(&c.second_ticket);
470}
471
472#[doc(hidden)]
474pub mod tests_only {
475 use super::*;
476
477 pub fn sample_ccache_bytes() -> Vec<u8> {
481 let cc = Ccache {
482 header: DEFAULT_HEADER.to_vec(),
483 primary: Principal {
484 realm: "TESTLAB.LOCAL".into(),
485 name_type: NT_PRINCIPAL,
486 components: vec!["alice".into()],
487 },
488 credentials: vec![Credential {
489 client: Principal {
490 realm: "TESTLAB.LOCAL".into(),
491 name_type: NT_PRINCIPAL,
492 components: vec!["alice".into()],
493 },
494 server: Principal {
495 realm: "TESTLAB.LOCAL".into(),
496 name_type: NT_SRV_INST,
497 components: vec!["krbtgt".into(), "TESTLAB.LOCAL".into()],
498 },
499 key: KeyBlock {
500 keytype: 18, key: vec![0x11u8; 32],
502 },
503 authtime: 0x6600_0000,
504 starttime: 0x6600_0000,
505 endtime: 0x6600_A000,
506 renew_till: 0x6601_0000,
507 is_skey: false,
508 tktflags: 0x5010_0000, addresses: Vec::new(),
510 authdata: Vec::new(),
511 ticket: b"OPAQUE-DER-TICKET-BYTES".to_vec(),
512 second_ticket: Vec::new(),
513 }],
514 };
515 cc.to_bytes()
516 }
517}
518
519#[cfg(test)]
522mod tests {
523 use super::*;
524
525 #[test]
526 fn header_magic_is_be_0504() {
527 let bytes = tests_only::sample_ccache_bytes();
528 assert_eq!(&bytes[..2], &[0x05, 0x04]);
529 }
530
531 #[test]
532 fn roundtrip_byte_exact() {
533 let bytes = tests_only::sample_ccache_bytes();
534 let parsed = Ccache::parse(&bytes).expect("parse");
535 assert_eq!(parsed.primary.canonical(), "alice@TESTLAB.LOCAL");
536 assert_eq!(parsed.credentials.len(), 1);
537 let cred = &parsed.credentials[0];
538 assert_eq!(
539 cred.server.canonical(),
540 "krbtgt/TESTLAB.LOCAL@TESTLAB.LOCAL"
541 );
542 assert_eq!(cred.key.keytype, 18);
543 assert_eq!(cred.key.key.len(), 32);
544 assert_eq!(cred.tktflags, 0x5010_0000);
545 assert_eq!(&cred.ticket, b"OPAQUE-DER-TICKET-BYTES");
546 let re = parsed.to_bytes();
547 assert_eq!(re, bytes, "round-trip must be byte-identical");
548 }
549
550 #[test]
551 fn rejects_wrong_magic() {
552 let mut bytes = tests_only::sample_ccache_bytes();
553 bytes[0] = 0x05;
554 bytes[1] = 0x03; let err = Ccache::parse(&bytes).unwrap_err();
556 assert_eq!(
557 err,
558 CcacheError::UnsupportedVersion {
559 found: 0x0503,
560 expected: V4_MAGIC
561 }
562 );
563 }
564
565 #[test]
566 fn rejects_truncated_body() {
567 let bytes = tests_only::sample_ccache_bytes();
568 let short = &bytes[..bytes.len() - 5];
569 let err = Ccache::parse(short).unwrap_err();
570 assert!(matches!(err, CcacheError::Truncated { .. }));
571 }
572
573 #[test]
574 fn rejects_hostile_component_count() {
575 let mut w = Writer::new();
578 w.u16(V4_MAGIC);
579 w.u16(DEFAULT_HEADER.len() as u16);
580 w.bytes(DEFAULT_HEADER);
581 w.u32(NT_PRINCIPAL); w.u32(u32::MAX); w.counted(b"REALM");
584 let err = Ccache::parse(&w.take()).unwrap_err();
585 assert!(matches!(
586 err,
587 CcacheError::TooManyComponents {
588 count: u32::MAX,
589 ..
590 }
591 ));
592 }
593
594 #[test]
595 fn multi_credential_cache_roundtrips() {
596 let mut cc = Ccache::new(Principal {
597 realm: "CORP.LOCAL".into(),
598 name_type: NT_PRINCIPAL,
599 components: vec!["bob".into()],
600 });
601 for i in 0..5u32 {
602 cc.credentials.push(Credential {
603 client: cc.primary.clone(),
604 server: Principal {
605 realm: "CORP.LOCAL".into(),
606 name_type: NT_SRV_INST,
607 components: vec!["HOST".into(), format!("srv{i}.corp.local")],
608 },
609 key: KeyBlock {
610 keytype: 17,
611 key: vec![i as u8; 16],
612 },
613 authtime: 100 + i,
614 starttime: 100 + i,
615 endtime: 200 + i,
616 renew_till: 0,
617 is_skey: i.is_multiple_of(2),
618 tktflags: 0x40000000,
619 addresses: Vec::new(),
620 authdata: Vec::new(),
621 ticket: vec![i as u8; 32],
622 second_ticket: Vec::new(),
623 });
624 }
625 let bytes = cc.to_bytes();
626 let parsed = Ccache::parse(&bytes).unwrap();
627 assert_eq!(parsed.credentials.len(), 5);
628 assert_eq!(parsed.to_bytes(), bytes);
629 }
630
631 #[test]
632 fn utf8_realm_error_carries_offset() {
633 let mut w = Writer::new();
635 w.u16(V4_MAGIC);
636 w.u16(0);
637 w.u32(NT_PRINCIPAL);
638 w.u32(0); w.counted(&[0xFF, 0xFE]); let err = Ccache::parse(&w.take()).unwrap_err();
641 assert!(matches!(err, CcacheError::Utf8 { .. }));
642 }
643}