//! Reading TSIG keys written in BIND `named.conf` syntax, so key files can be copied //! from an existing BIND server and included unchanged: //! //! ```text //! key "ddns-key.example.com" { //! algorithm hmac-sha512; //! secret "base64 secret"; //! }; //! ``` //! //! Only `key` statements are accepted (anything else is reported as an error rather than //! silently ignored). Comments `#`, `//` and `/* */` are allowed. use crate::KeyConfig; #[derive(Debug, Clone, PartialEq)] enum Tok { Word(String), Str(String), Open, Close, Semi, } fn tokenize(text: &str) -> Result, (usize, String)> { let b: Vec = text.chars().collect(); let (mut i, mut line) = (0usize, 1usize); let mut out = Vec::new(); while i < b.len() { let c = b[i]; match c { '\n' => { line += 1; i += 1; } c if c.is_whitespace() => i += 1, '#' => { while i < b.len() && b[i] != '\n' { i += 1; } } '/' if b.get(i + 1) == Some(&'/') => { while i < b.len() && b[i] != '\n' { i += 1; } } '/' if b.get(i + 1) == Some(&'*') => { let start = line; i += 2; loop { if i + 1 >= b.len() { return Err((start, "unterminated /* comment".into())); } if b[i] == '\n' { line += 1; } if b[i] == '*' && b[i + 1] == '/' { i += 2; break; } i += 1; } } '{' => { out.push((Tok::Open, line)); i += 1; } '}' => { out.push((Tok::Close, line)); i += 1; } ';' => { out.push((Tok::Semi, line)); i += 1; } '"' => { let start = line; i += 1; let mut s = String::new(); while i < b.len() && b[i] != '"' { if b[i] == '\n' { line += 1; } s.push(b[i]); i += 1; } if i >= b.len() { return Err((start, "unterminated string".into())); } i += 1; out.push((Tok::Str(s), start)); } _ => { let mut s = String::new(); while i < b.len() && !b[i].is_whitespace() && !matches!(b[i], '{' | '}' | ';' | '"') { s.push(b[i]); i += 1; } out.push((Tok::Word(s), line)); } } } Ok(out) } /// True when the first statement of `text` is a BIND `key` statement. pub(crate) fn looks_like_bind_keys(text: &str) -> bool { matches!(tokenize(text).ok().and_then(|t| t.into_iter().next()), Some((Tok::Word(w), _)) if w == "key") } /// Parse `key` statements. Errors carry the line number. pub(crate) fn parse_keys(text: &str, file: &str) -> Result, (usize, String)> { let toks = tokenize(text)?; let mut it = toks.into_iter().peekable(); let mut keys = Vec::new(); while let Some((t, line)) = it.next() { match t { Tok::Word(w) if w == "key" => {} Tok::Semi => continue, other => return Err((line, format!("only `key` statements are supported in BIND-format includes, found {other:?}"))), } let name = match it.next() { Some((Tok::Str(s) | Tok::Word(s), _)) => s, _ => return Err((line, "key: expected a name".into())), }; if !matches!(it.next(), Some((Tok::Open, _))) { return Err((line, format!("key \"{name}\": expected '{{'"))); } let (mut algorithm, mut secret) = (None, None); loop { let (t, l) = it.next().ok_or((line, format!("key \"{name}\": missing '}}'")))?; match t { Tok::Close => break, Tok::Semi => {} Tok::Word(opt) => { let value = match it.next() { Some((Tok::Str(v) | Tok::Word(v), _)) => v, _ => return Err((l, format!("key \"{name}\": {opt} needs a value"))), }; if !matches!(it.next(), Some((Tok::Semi, _))) { return Err((l, format!("key \"{name}\": expected ';' after {opt}"))); } match opt.as_str() { "algorithm" => algorithm = Some(value.to_ascii_lowercase()), "secret" => secret = Some(value.split_whitespace().collect::()), other => return Err((l, format!("key \"{name}\": unsupported option '{other}'"))), } } other => return Err((l, format!("key \"{name}\": unexpected {other:?}"))), } } if !matches!(it.peek(), Some((Tok::Semi, _))) { return Err((line, format!("key \"{name}\": expected ';' after '}}'"))); } let algorithm = algorithm.ok_or((line, format!("key \"{name}\": missing algorithm")))?; let secret = secret.ok_or((line, format!("key \"{name}\": missing secret")))?; keys.push(KeyConfig { name, algorithm, secret: format!("base64:{secret}"), imported_from: Some(file.to_string()) }); } Ok(keys) } #[cfg(test)] #[allow(clippy::unwrap_used)] mod tests { use super::*; const KEYS: &str = r#" # copied from /etc/bind/keys.conf key "wildcard.example.org" { algorithm hmac-sha512; secret "c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0c2VjcmV0"; }; // second key key certbot-key. { algorithm HMAC-SHA256; secret "c2VjcmV0c2Vj cmV0c2VjcmV0"; }; /* block comment */ "#; #[test] fn parses_bind_key_statements() { assert!(looks_like_bind_keys(KEYS)); assert!(!looks_like_bind_keys("keys: []\n")); let k = parse_keys(KEYS, "keys.conf").unwrap(); assert_eq!(k.len(), 2); assert_eq!(k[0].name, "wildcard.example.org"); assert_eq!(k[0].algorithm, "hmac-sha512"); assert!(k[0].secret.starts_with("base64:c2Vj")); assert_eq!(k[1].name, "certbot-key."); assert_eq!(k[1].algorithm, "hmac-sha256"); assert_eq!(k[1].secret, "base64:c2VjcmV0c2VjcmV0c2VjcmV0"); // whitespace inside the secret removed } #[test] fn rejects_other_statements_with_line() { let e = parse_keys("key \"a\" { algorithm hmac-sha256; secret \"eA==\"; };\nzone \"x\" { };\n", "f").unwrap_err(); assert_eq!(e.0, 2); let e = parse_keys("key \"a\" { algorithm hmac-sha256; };", "f").unwrap_err(); assert!(e.1.contains("missing secret")); assert!(parse_keys("key \"a\" { algorithm hmac-sha256; secret \"x\" }", "f").is_err()); } }