use std::collections::HashMap;
use std::path::Path;
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct Krb5Config {
pub default_realm: Option<String>,
pub realms: HashMap<String, RealmConfig>,
pub domain_realm: HashMap<String, String>,
}
#[non_exhaustive]
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct RealmConfig {
pub kdcs: Vec<String>,
pub admin_server: Option<String>,
}
impl Krb5Config {
pub fn from_path(path: impl AsRef<Path>) -> Result<Self, ConfigError> {
let text = std::fs::read_to_string(path.as_ref())
.map_err(|e| ConfigError::Io(e.to_string()))?;
Self::parse(&text)
}
pub fn parse(text: &str) -> Result<Self, ConfigError> {
let mut out = Krb5Config::default();
let mut section: Option<String> = None;
let mut lines = text.lines().enumerate().peekable();
while let Some((lineno, raw)) = lines.next() {
let line = trim_comment(raw).trim();
if line.is_empty() {
continue;
}
if let Some(name) = section_header(line) {
section = Some(name.to_ascii_lowercase());
continue;
}
let s = section.as_deref().ok_or_else(|| ConfigError::UnexpectedLine {
line: lineno + 1,
content: line.to_string(),
})?;
match s {
"libdefaults" => {
if let Some((k, v)) = split_kv(line) {
if k.eq_ignore_ascii_case("default_realm") {
out.default_realm = Some(v.to_ascii_uppercase());
}
}
}
"realms" => {
if let Some((k, v)) = split_kv(line) {
if v.trim_start().starts_with('{') {
let realm_key = k.to_ascii_uppercase();
let mut realm = out.realms.remove(&realm_key).unwrap_or_default();
let rest = v.trim_start().trim_start_matches('{');
let mut done = read_realm_body(rest.trim(), &mut realm);
while !done {
let (n, r) = lines.next().ok_or(ConfigError::UnclosedSubsection {
line: lineno + 1,
realm: realm_key.clone(),
})?;
let inner = trim_comment(r).trim();
if inner.is_empty() {
continue;
}
done = read_realm_body(inner, &mut realm);
let _ = n;
}
out.realms.insert(realm_key, realm);
}
}
}
"domain_realm" => {
if let Some((k, v)) = split_kv(line) {
out.domain_realm.insert(k.to_string(), v.to_ascii_uppercase());
}
}
_ => {
}
}
}
Ok(out)
}
#[must_use]
pub fn default_realm(&self) -> Option<&str> {
self.default_realm.as_deref()
}
#[must_use]
pub fn kdcs_for(&self, realm: &str) -> &[String] {
self.realms
.get(&realm.to_ascii_uppercase())
.map(|r| r.kdcs.as_slice())
.unwrap_or(&[])
}
#[must_use]
pub fn admin_server_for(&self, realm: &str) -> Option<&str> {
self.realms
.get(&realm.to_ascii_uppercase())
.and_then(|r| r.admin_server.as_deref())
}
#[must_use]
pub fn realm_for_host(&self, hostname: &str) -> Option<&str> {
if let Some(r) = self.domain_realm.get(hostname) {
return Some(r.as_str());
}
let lower = hostname.to_ascii_lowercase();
let mut idx = 0;
while let Some(dot) = lower[idx..].find('.') {
idx += dot;
let suffix = &lower[idx..];
if let Some(r) = self.domain_realm.get(suffix) {
return Some(r.as_str());
}
idx += 1;
}
None
}
}
#[non_exhaustive]
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ConfigError {
Io(String),
UnexpectedLine {
line: usize,
content: String,
},
UnclosedSubsection {
line: usize,
realm: String,
},
}
impl std::fmt::Display for ConfigError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
ConfigError::Io(msg) => write!(f, "read krb5.conf: {msg}"),
ConfigError::UnexpectedLine { line, content } => {
write!(f, "line {line}: content before any [section]: {content:?}")
}
ConfigError::UnclosedSubsection { line, realm } => {
write!(f, "line {line}: unclosed {{ ... }} for realm {realm}")
}
}
}
}
impl std::error::Error for ConfigError {}
fn trim_comment(line: &str) -> &str {
match line.find('#') {
Some(i) => &line[..i],
None => line,
}
}
fn section_header(line: &str) -> Option<&str> {
let l = line.strip_prefix('[')?;
let end = l.find(']')?;
Some(l[..end].trim())
}
fn split_kv(line: &str) -> Option<(&str, &str)> {
let eq = line.find('=')?;
let k = line[..eq].trim();
let v = line[eq + 1..].trim();
if k.is_empty() {
None
} else {
Some((k, v))
}
}
fn read_realm_body(body: &str, realm: &mut RealmConfig) -> bool {
let (payload, closing) = match body.rfind('}') {
Some(i) => (body[..i].trim(), true),
None => (body.trim(), false),
};
for chunk in payload.split(['\n', ';']) {
if let Some((k, v)) = split_kv(chunk.trim()) {
match k.to_ascii_lowercase().as_str() {
"kdc" => realm.kdcs.push(v.to_string()),
"admin_server" => realm.admin_server = Some(v.to_string()),
_ => {} }
}
}
closing
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_canonical_mit_shape() {
let src = r#"
# comment line
[libdefaults]
default_realm = corp.local
[realms]
CORP.LOCAL = {
kdc = dc01.corp.local
kdc = dc02.corp.local:88
admin_server = dc01.corp.local
default_domain = corp.local
}
[domain_realm]
.corp.local = CORP.LOCAL
corp.local = CORP.LOCAL
"#;
let conf = Krb5Config::parse(src).unwrap();
assert_eq!(conf.default_realm(), Some("CORP.LOCAL"));
assert_eq!(
conf.kdcs_for("corp.local"), &["dc01.corp.local".to_string(), "dc02.corp.local:88".to_string()]
);
assert_eq!(conf.admin_server_for("CORP.LOCAL"), Some("dc01.corp.local"));
assert_eq!(conf.realm_for_host("web.corp.local"), Some("CORP.LOCAL"));
assert_eq!(conf.realm_for_host("corp.local"), Some("CORP.LOCAL"));
}
#[test]
fn multiple_realms() {
let src = r#"
[realms]
A.LOCAL = {
kdc = a-dc
}
B.LOCAL = {
kdc = b-dc-1
kdc = b-dc-2
}
"#;
let conf = Krb5Config::parse(src).unwrap();
assert_eq!(conf.kdcs_for("A.LOCAL"), &["a-dc".to_string()]);
assert_eq!(conf.kdcs_for("B.LOCAL").len(), 2);
}
#[test]
fn unknown_sections_are_ignored() {
let src = r#"
[appdefaults]
kinit = { renewable = true }
[libdefaults]
default_realm = X.LOCAL
"#;
let conf = Krb5Config::parse(src).unwrap();
assert_eq!(conf.default_realm(), Some("X.LOCAL"));
}
#[test]
fn realm_for_host_walks_suffixes() {
let src = r#"
[domain_realm]
.corp.local = CORP.LOCAL
"#;
let conf = Krb5Config::parse(src).unwrap();
assert_eq!(
conf.realm_for_host("very.deep.host.corp.local"),
Some("CORP.LOCAL")
);
assert_eq!(conf.realm_for_host("stranger.example.net"), None);
}
#[test]
fn rejects_content_before_first_section() {
let src = "default_realm = X\n";
assert!(matches!(
Krb5Config::parse(src).unwrap_err(),
ConfigError::UnexpectedLine { line: 1, .. }
));
}
#[test]
fn comment_stripping() {
let src = r#"
[libdefaults]
default_realm = A.LOCAL # inline comment
"#;
let conf = Krb5Config::parse(src).unwrap();
assert_eq!(conf.default_realm(), Some("A.LOCAL"));
}
#[test]
fn empty_file_yields_default() {
let conf = Krb5Config::parse("").unwrap();
assert_eq!(conf, Krb5Config::default());
}
}