#![deny(unsafe_code)]
#![warn(missing_docs)]
#![doc(html_root_url = "https://docs.rs/ccache-io/0.1.0")]
use thiserror::Error;
pub const V4_MAGIC: u16 = 0x0504;
pub const NT_PRINCIPAL: u32 = 1;
pub const NT_SRV_INST: u32 = 2;
#[non_exhaustive]
#[derive(Debug, Error, PartialEq, Eq)]
pub enum CcacheError {
#[error("unsupported ccache version {found:#06x} (expected {expected:#06x})")]
UnsupportedVersion {
found: u16,
expected: u16,
},
#[error("truncated input: need {need} bytes at offset {at}, have {remaining}")]
Truncated {
need: usize,
at: usize,
remaining: usize,
},
#[error("component count {count} at offset {at} exceeds sane cap ({cap})")]
TooManyComponents {
count: u32,
at: usize,
cap: u32,
},
#[error("non-UTF-8 principal string at offset {at}: {source}")]
Utf8 {
at: usize,
#[source]
source: std::str::Utf8Error,
},
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Principal {
pub realm: String,
pub name_type: u32,
pub components: Vec<String>,
}
impl Principal {
pub fn canonical(&self) -> String {
format!("{}@{}", self.components.join("/"), self.realm)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct KeyBlock {
pub keytype: u16,
pub key: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Address {
pub addr_type: u16,
pub data: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct AuthData {
pub ad_type: u16,
pub data: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Credential {
pub client: Principal,
pub server: Principal,
pub key: KeyBlock,
pub authtime: u32,
pub starttime: u32,
pub endtime: u32,
pub renew_till: u32,
pub is_skey: bool,
pub tktflags: u32,
pub addresses: Vec<Address>,
pub authdata: Vec<AuthData>,
pub ticket: Vec<u8>,
pub second_ticket: Vec<u8>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Ccache {
pub header: Vec<u8>,
pub primary: Principal,
pub credentials: Vec<Credential>,
}
const MAX_COMPONENTS: u32 = 1024;
const DEFAULT_HEADER: &[u8] = &[
0x00, 0x01, 0x00, 0x08, 0, 0, 0, 0, 0, 0, 0, 0, ];
impl Ccache {
pub fn parse(bytes: &[u8]) -> Result<Self, CcacheError> {
let mut r = Reader::new(bytes);
let version = r.u16()?;
if version != V4_MAGIC {
return Err(CcacheError::UnsupportedVersion {
found: version,
expected: V4_MAGIC,
});
}
let header_len = r.u16()? as usize;
let header = r.take(header_len)?.to_vec();
let primary = read_principal(&mut r)?;
let mut credentials = Vec::new();
while r.remaining() > 0 {
credentials.push(read_credential(&mut r)?);
}
Ok(Ccache {
header,
primary,
credentials,
})
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut w = Writer::new();
w.u16(V4_MAGIC);
w.u16(self.header.len() as u16);
w.bytes(&self.header);
write_principal(&mut w, &self.primary);
for c in &self.credentials {
write_credential(&mut w, c);
}
w.take()
}
pub fn new(primary: Principal) -> Self {
Ccache {
header: DEFAULT_HEADER.to_vec(),
primary,
credentials: Vec::new(),
}
}
}
struct Reader<'a> {
b: &'a [u8],
pos: usize,
}
impl<'a> Reader<'a> {
fn new(b: &'a [u8]) -> Self {
Reader { b, pos: 0 }
}
fn remaining(&self) -> usize {
self.b.len() - self.pos
}
fn take(&mut self, n: usize) -> Result<&'a [u8], CcacheError> {
if n > self.remaining() {
return Err(CcacheError::Truncated {
need: n,
at: self.pos,
remaining: self.remaining(),
});
}
let slice = &self.b[self.pos..self.pos + n];
self.pos += n;
Ok(slice)
}
fn u16(&mut self) -> Result<u16, CcacheError> {
let b = self.take(2)?;
Ok(u16::from_be_bytes([b[0], b[1]]))
}
fn u32(&mut self) -> Result<u32, CcacheError> {
let b = self.take(4)?;
Ok(u32::from_be_bytes([b[0], b[1], b[2], b[3]]))
}
fn u8(&mut self) -> Result<u8, CcacheError> {
Ok(self.take(1)?[0])
}
fn counted(&mut self) -> Result<&'a [u8], CcacheError> {
let n = self.u32()? as usize;
self.take(n)
}
fn counted_str(&mut self) -> Result<String, CcacheError> {
let at = self.pos;
let bytes = self.counted()?;
std::str::from_utf8(bytes)
.map(str::to_string)
.map_err(|source| CcacheError::Utf8 { at, source })
}
}
struct Writer(Vec<u8>);
impl Writer {
fn new() -> Self {
Writer(Vec::with_capacity(512))
}
fn take(self) -> Vec<u8> {
self.0
}
fn u16(&mut self, v: u16) {
self.0.extend_from_slice(&v.to_be_bytes());
}
fn u32(&mut self, v: u32) {
self.0.extend_from_slice(&v.to_be_bytes());
}
fn u8(&mut self, v: u8) {
self.0.push(v);
}
fn bytes(&mut self, b: &[u8]) {
self.0.extend_from_slice(b);
}
fn counted(&mut self, b: &[u8]) {
self.u32(b.len() as u32);
self.bytes(b);
}
}
fn read_principal(r: &mut Reader) -> Result<Principal, CcacheError> {
let at = r.pos;
let name_type = r.u32()?;
let num = r.u32()?;
if num > MAX_COMPONENTS {
return Err(CcacheError::TooManyComponents {
count: num,
at,
cap: MAX_COMPONENTS,
});
}
let realm = r.counted_str()?;
let mut components = Vec::with_capacity(num as usize);
for _ in 0..num {
components.push(r.counted_str()?);
}
Ok(Principal {
realm,
name_type,
components,
})
}
fn write_principal(w: &mut Writer, p: &Principal) {
w.u32(p.name_type);
w.u32(p.components.len() as u32);
w.counted(p.realm.as_bytes());
for c in &p.components {
w.counted(c.as_bytes());
}
}
fn read_credential(r: &mut Reader) -> Result<Credential, CcacheError> {
let client = read_principal(r)?;
let server = read_principal(r)?;
let keytype = r.u16()?;
let _etype_unused = r.u16()?;
let key_bytes = r.counted()?.to_vec();
let authtime = r.u32()?;
let starttime = r.u32()?;
let endtime = r.u32()?;
let renew_till = r.u32()?;
let is_skey = r.u8()? != 0;
let tktflags = r.u32()?;
let num_addr = r.u32()? as usize;
if num_addr > MAX_COMPONENTS as usize {
return Err(CcacheError::TooManyComponents {
count: num_addr as u32,
at: r.pos,
cap: MAX_COMPONENTS,
});
}
let mut addresses = Vec::with_capacity(num_addr);
for _ in 0..num_addr {
let addr_type = r.u16()?;
let data = r.counted()?.to_vec();
addresses.push(Address { addr_type, data });
}
let num_ad = r.u32()? as usize;
if num_ad > MAX_COMPONENTS as usize {
return Err(CcacheError::TooManyComponents {
count: num_ad as u32,
at: r.pos,
cap: MAX_COMPONENTS,
});
}
let mut authdata = Vec::with_capacity(num_ad);
for _ in 0..num_ad {
let ad_type = r.u16()?;
let data = r.counted()?.to_vec();
authdata.push(AuthData { ad_type, data });
}
let ticket = r.counted()?.to_vec();
let second_ticket = r.counted()?.to_vec();
Ok(Credential {
client,
server,
key: KeyBlock {
keytype,
key: key_bytes,
},
authtime,
starttime,
endtime,
renew_till,
is_skey,
tktflags,
addresses,
authdata,
ticket,
second_ticket,
})
}
fn write_credential(w: &mut Writer, c: &Credential) {
write_principal(w, &c.client);
write_principal(w, &c.server);
w.u16(c.key.keytype);
w.u16(0); w.counted(&c.key.key);
w.u32(c.authtime);
w.u32(c.starttime);
w.u32(c.endtime);
w.u32(c.renew_till);
w.u8(if c.is_skey { 1 } else { 0 });
w.u32(c.tktflags);
w.u32(c.addresses.len() as u32);
for a in &c.addresses {
w.u16(a.addr_type);
w.counted(&a.data);
}
w.u32(c.authdata.len() as u32);
for a in &c.authdata {
w.u16(a.ad_type);
w.counted(&a.data);
}
w.counted(&c.ticket);
w.counted(&c.second_ticket);
}
#[doc(hidden)]
pub mod tests_only {
use super::*;
pub fn sample_ccache_bytes() -> Vec<u8> {
let cc = Ccache {
header: DEFAULT_HEADER.to_vec(),
primary: Principal {
realm: "TESTLAB.LOCAL".into(),
name_type: NT_PRINCIPAL,
components: vec!["alice".into()],
},
credentials: vec![Credential {
client: Principal {
realm: "TESTLAB.LOCAL".into(),
name_type: NT_PRINCIPAL,
components: vec!["alice".into()],
},
server: Principal {
realm: "TESTLAB.LOCAL".into(),
name_type: NT_SRV_INST,
components: vec!["krbtgt".into(), "TESTLAB.LOCAL".into()],
},
key: KeyBlock {
keytype: 18, key: vec![0x11u8; 32],
},
authtime: 0x6600_0000,
starttime: 0x6600_0000,
endtime: 0x6600_A000,
renew_till: 0x6601_0000,
is_skey: false,
tktflags: 0x5010_0000, addresses: Vec::new(),
authdata: Vec::new(),
ticket: b"OPAQUE-DER-TICKET-BYTES".to_vec(),
second_ticket: Vec::new(),
}],
};
cc.to_bytes()
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn header_magic_is_be_0504() {
let bytes = tests_only::sample_ccache_bytes();
assert_eq!(&bytes[..2], &[0x05, 0x04]);
}
#[test]
fn roundtrip_byte_exact() {
let bytes = tests_only::sample_ccache_bytes();
let parsed = Ccache::parse(&bytes).expect("parse");
assert_eq!(parsed.primary.canonical(), "alice@TESTLAB.LOCAL");
assert_eq!(parsed.credentials.len(), 1);
let cred = &parsed.credentials[0];
assert_eq!(
cred.server.canonical(),
"krbtgt/TESTLAB.LOCAL@TESTLAB.LOCAL"
);
assert_eq!(cred.key.keytype, 18);
assert_eq!(cred.key.key.len(), 32);
assert_eq!(cred.tktflags, 0x5010_0000);
assert_eq!(&cred.ticket, b"OPAQUE-DER-TICKET-BYTES");
let re = parsed.to_bytes();
assert_eq!(re, bytes, "round-trip must be byte-identical");
}
#[test]
fn rejects_wrong_magic() {
let mut bytes = tests_only::sample_ccache_bytes();
bytes[0] = 0x05;
bytes[1] = 0x03; let err = Ccache::parse(&bytes).unwrap_err();
assert_eq!(
err,
CcacheError::UnsupportedVersion {
found: 0x0503,
expected: V4_MAGIC
}
);
}
#[test]
fn rejects_truncated_body() {
let bytes = tests_only::sample_ccache_bytes();
let short = &bytes[..bytes.len() - 5];
let err = Ccache::parse(short).unwrap_err();
assert!(matches!(err, CcacheError::Truncated { .. }));
}
#[test]
fn rejects_hostile_component_count() {
let mut w = Writer::new();
w.u16(V4_MAGIC);
w.u16(DEFAULT_HEADER.len() as u16);
w.bytes(DEFAULT_HEADER);
w.u32(NT_PRINCIPAL); w.u32(u32::MAX); w.counted(b"REALM");
let err = Ccache::parse(&w.take()).unwrap_err();
assert!(matches!(
err,
CcacheError::TooManyComponents {
count: u32::MAX,
..
}
));
}
#[test]
fn multi_credential_cache_roundtrips() {
let mut cc = Ccache::new(Principal {
realm: "CORP.LOCAL".into(),
name_type: NT_PRINCIPAL,
components: vec!["bob".into()],
});
for i in 0..5u32 {
cc.credentials.push(Credential {
client: cc.primary.clone(),
server: Principal {
realm: "CORP.LOCAL".into(),
name_type: NT_SRV_INST,
components: vec!["HOST".into(), format!("srv{i}.corp.local")],
},
key: KeyBlock {
keytype: 17,
key: vec![i as u8; 16],
},
authtime: 100 + i,
starttime: 100 + i,
endtime: 200 + i,
renew_till: 0,
is_skey: i.is_multiple_of(2),
tktflags: 0x40000000,
addresses: Vec::new(),
authdata: Vec::new(),
ticket: vec![i as u8; 32],
second_ticket: Vec::new(),
});
}
let bytes = cc.to_bytes();
let parsed = Ccache::parse(&bytes).unwrap();
assert_eq!(parsed.credentials.len(), 5);
assert_eq!(parsed.to_bytes(), bytes);
}
#[test]
fn utf8_realm_error_carries_offset() {
let mut w = Writer::new();
w.u16(V4_MAGIC);
w.u16(0);
w.u32(NT_PRINCIPAL);
w.u32(0); w.counted(&[0xFF, 0xFE]); let err = Ccache::parse(&w.take()).unwrap_err();
assert!(matches!(err, CcacheError::Utf8 { .. }));
}
}