preg 0.1.0

Pure-Rust reader and writer for the Windows Group Policy Registry.pol (PReg) file format.
Documentation
//! Reader and writer for `Registry.pol` — the **PReg** file that carries the registry half
//! of a Group Policy Object.
//!
//! Every GPO stores its Administrative-Template settings as a `Registry.pol` under
//! `SYSVOL\<domain>\Policies\{GUID}\{Machine,User}\Registry.pol`. The format is a 8-byte
//! header followed by a flat list of `[key;value;type;size;data]` records, all strings
//! UTF-16LE and NUL-terminated.
//!
//! ```
//! use preg::{PolicyFile, RegData};
//!
//! let mut pol = PolicyFile::new();
//! pol.set(
//!     r"Software\Policies\Microsoft\Windows NT\DNSClient",
//!     "EnableMulticast",
//!     RegData::Dword(0),
//! );
//! let bytes = pol.to_bytes();
//! assert_eq!(PolicyFile::parse(&bytes).unwrap(), pol);
//! ```
//!
//! Parsing never panics on malformed input and never allocates on a length field it has not
//! validated against the buffer.

use std::fmt;

/// `PReg` — the 4-byte signature every policy file starts with.
pub const SIGNATURE: &[u8; 4] = b"PReg";
/// The only format version Windows writes or accepts.
pub const VERSION: u32 = 1;

#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum PolError {
    #[error("not a Registry.pol file: bad PReg signature")]
    BadSignature,
    #[error("unsupported PReg version {0}")]
    BadVersion(u32),
    #[error("truncated at offset {0}")]
    Truncated(usize),
    #[error("expected {expected:?} at offset {at}")]
    Expected { expected: char, at: usize },
    #[error("unterminated UTF-16 string at offset {0}")]
    UnterminatedString(usize),
    #[error("value data at offset {at} claims {len} bytes, {left} left in file")]
    BadDataLength { at: usize, len: usize, left: usize },
}

type Result<T> = std::result::Result<T, PolError>;

/// A registry value type as stored in the `type` field of a record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum RegData {
    /// `REG_SZ`
    Sz(String),
    /// `REG_EXPAND_SZ`
    ExpandSz(String),
    /// `REG_BINARY`
    Binary(Vec<u8>),
    /// `REG_DWORD` (little-endian on the wire)
    Dword(u32),
    /// `REG_DWORD_BIG_ENDIAN`
    DwordBe(u32),
    /// `REG_LINK`
    Link(String),
    /// `REG_MULTI_SZ`
    MultiSz(Vec<String>),
    /// `REG_QWORD`
    Qword(u64),
    /// Any other type code, kept verbatim so a round-trip is lossless.
    Other { ty: u32, bytes: Vec<u8> },
}

impl RegData {
    /// The `REG_*` type code.
    pub fn type_code(&self) -> u32 {
        match self {
            RegData::Sz(_) => 1,
            RegData::ExpandSz(_) => 2,
            RegData::Binary(_) => 3,
            RegData::Dword(_) => 4,
            RegData::DwordBe(_) => 5,
            RegData::Link(_) => 6,
            RegData::MultiSz(_) => 7,
            RegData::Qword(_) => 11,
            RegData::Other { ty, .. } => *ty,
        }
    }

    /// The value bytes exactly as they appear in the file.
    pub fn to_bytes(&self) -> Vec<u8> {
        match self {
            RegData::Sz(s) | RegData::ExpandSz(s) | RegData::Link(s) => utf16z(s),
            RegData::Binary(b) => b.clone(),
            RegData::Dword(v) => v.to_le_bytes().to_vec(),
            RegData::DwordBe(v) => v.to_be_bytes().to_vec(),
            RegData::Qword(v) => v.to_le_bytes().to_vec(),
            RegData::MultiSz(items) => {
                let mut out = Vec::new();
                for s in items {
                    out.extend_from_slice(&utf16z(s));
                }
                out.extend_from_slice(&[0, 0]); // extra NUL terminates the list
                out
            }
            RegData::Other { bytes, .. } => bytes.clone(),
        }
    }

    fn from_raw(ty: u32, bytes: &[u8]) -> RegData {
        match ty {
            1 => RegData::Sz(utf16_lossy(bytes)),
            2 => RegData::ExpandSz(utf16_lossy(bytes)),
            3 => RegData::Binary(bytes.to_vec()),
            4 if bytes.len() >= 4 => {
                RegData::Dword(u32::from_le_bytes(bytes[..4].try_into().unwrap()))
            }
            5 if bytes.len() >= 4 => {
                RegData::DwordBe(u32::from_be_bytes(bytes[..4].try_into().unwrap()))
            }
            6 => RegData::Link(utf16_lossy(bytes)),
            7 => RegData::MultiSz(
                utf16_lossy(bytes)
                    .split('\0')
                    .filter(|s| !s.is_empty())
                    .map(str::to_string)
                    .collect(),
            ),
            11 if bytes.len() >= 8 => {
                RegData::Qword(u64::from_le_bytes(bytes[..8].try_into().unwrap()))
            }
            _ => RegData::Other {
                ty,
                bytes: bytes.to_vec(),
            },
        }
    }
}

/// What a record instructs the client to do, decoded from the magic `**` value prefixes
/// (`[MS-GPREG] §2.2.1`). Anything without a prefix simply sets a value.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Directive<'a> {
    /// Set `value` under `key`.
    Set,
    /// `**del.<name>` — delete a single value.
    DeleteValue(&'a str),
    /// `**delvals.` — delete every value under the key.
    DeleteAllValues,
    /// `**deletekeys` — delete the listed subkeys.
    DeleteKeys,
    /// `**soft.<name>` — set the value only if it does not exist yet.
    Soft(&'a str),
    /// `**SecureKey` — apply the security descriptor carried in the data.
    SecureKey,
}

/// One `[key;value;type;size;data]` record.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PolicyEntry {
    pub key: String,
    pub value: String,
    pub data: RegData,
}

impl PolicyEntry {
    pub fn new(key: impl Into<String>, value: impl Into<String>, data: RegData) -> Self {
        PolicyEntry {
            key: key.into(),
            value: value.into(),
            data,
        }
    }

    /// Decode the `**`-prefixed instruction, if any.
    pub fn directive(&self) -> Directive<'_> {
        let v = self.value.as_str();
        if let Some(rest) = strip_prefix_ci(v, "**del.") {
            return Directive::DeleteValue(rest);
        }
        if let Some(rest) = strip_prefix_ci(v, "**soft.") {
            return Directive::Soft(rest);
        }
        if strip_prefix_ci(v, "**delvals").is_some() {
            return Directive::DeleteAllValues;
        }
        if strip_prefix_ci(v, "**deletekeys").is_some() {
            return Directive::DeleteKeys;
        }
        if strip_prefix_ci(v, "**securekey").is_some() {
            return Directive::SecureKey;
        }
        Directive::Set
    }
}

impl fmt::Display for PolicyEntry {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}\\{} = {:?}", self.key, self.value, self.data)
    }
}

/// A parsed `Registry.pol`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PolicyFile {
    pub entries: Vec<PolicyEntry>,
}

impl PolicyFile {
    pub fn new() -> Self {
        PolicyFile::default()
    }

    /// Parse a `Registry.pol` buffer.
    pub fn parse(b: &[u8]) -> Result<PolicyFile> {
        if b.len() < 8 {
            return Err(PolError::Truncated(0));
        }
        if &b[..4] != SIGNATURE {
            return Err(PolError::BadSignature);
        }
        let version = u32::from_le_bytes(b[4..8].try_into().unwrap());
        if version != VERSION {
            return Err(PolError::BadVersion(version));
        }

        let mut entries = Vec::new();
        let mut cur = 8;
        while cur < b.len() {
            // Windows tolerates trailing padding; anything shorter than a delimiter is padding.
            if b.len() - cur < 2 {
                break;
            }
            expect_char(b, &mut cur, '[')?;
            let key = read_utf16z(b, &mut cur)?;
            expect_char(b, &mut cur, ';')?;
            let value = read_utf16z(b, &mut cur)?;
            expect_char(b, &mut cur, ';')?;
            let ty = read_u32(b, &mut cur)?;
            expect_char(b, &mut cur, ';')?;
            let size = read_u32(b, &mut cur)? as usize;
            expect_char(b, &mut cur, ';')?;

            let left = b.len().saturating_sub(cur);
            if size > left {
                return Err(PolError::BadDataLength {
                    at: cur,
                    len: size,
                    left,
                });
            }
            let data = RegData::from_raw(ty, &b[cur..cur + size]);
            cur += size;
            expect_char(b, &mut cur, ']')?;

            entries.push(PolicyEntry { key, value, data });
        }
        Ok(PolicyFile { entries })
    }

    /// Serialize back to the on-disk format.
    pub fn to_bytes(&self) -> Vec<u8> {
        let mut out = Vec::with_capacity(8 + self.entries.len() * 64);
        out.extend_from_slice(SIGNATURE);
        out.extend_from_slice(&VERSION.to_le_bytes());
        for e in &self.entries {
            let data = e.data.to_bytes();
            push_char(&mut out, '[');
            out.extend_from_slice(&utf16z(&e.key));
            push_char(&mut out, ';');
            out.extend_from_slice(&utf16z(&e.value));
            push_char(&mut out, ';');
            out.extend_from_slice(&e.data.type_code().to_le_bytes());
            push_char(&mut out, ';');
            out.extend_from_slice(&(data.len() as u32).to_le_bytes());
            push_char(&mut out, ';');
            out.extend_from_slice(&data);
            push_char(&mut out, ']');
        }
        out
    }

    /// First entry matching `key`/`value`, case-insensitively (registry keys are).
    pub fn get(&self, key: &str, value: &str) -> Option<&PolicyEntry> {
        self.entries
            .iter()
            .find(|e| e.key.eq_ignore_ascii_case(key) && e.value.eq_ignore_ascii_case(value))
    }

    /// Convenience: the `REG_DWORD` at `key`/`value`, if present and of that type.
    pub fn dword(&self, key: &str, value: &str) -> Option<u32> {
        match self.get(key, value)?.data {
            RegData::Dword(v) => Some(v),
            RegData::DwordBe(v) => Some(v),
            _ => None,
        }
    }

    /// Every entry under `key` (exact key match, case-insensitive).
    pub fn under<'a>(&'a self, key: &'a str) -> impl Iterator<Item = &'a PolicyEntry> + 'a {
        self.entries
            .iter()
            .filter(move |e| e.key.eq_ignore_ascii_case(key))
    }

    /// Insert or replace `key`/`value`.
    pub fn set(&mut self, key: &str, value: &str, data: RegData) {
        match self
            .entries
            .iter_mut()
            .find(|e| e.key.eq_ignore_ascii_case(key) && e.value.eq_ignore_ascii_case(value))
        {
            Some(e) => e.data = data,
            None => self.entries.push(PolicyEntry::new(key, value, data)),
        }
    }

    /// Remove every entry matching `key`/`value`; returns how many went.
    pub fn remove(&mut self, key: &str, value: &str) -> usize {
        let before = self.entries.len();
        self.entries
            .retain(|e| !(e.key.eq_ignore_ascii_case(key) && e.value.eq_ignore_ascii_case(value)));
        before - self.entries.len()
    }
}

// ── encoding helpers ──────────────────────────────────────────────────────────

fn utf16z(s: &str) -> Vec<u8> {
    let mut out: Vec<u8> = s.encode_utf16().flat_map(u16::to_le_bytes).collect();
    out.extend_from_slice(&[0, 0]);
    out
}

fn utf16_lossy(b: &[u8]) -> String {
    let units: Vec<u16> = b
        .chunks_exact(2)
        .map(|c| u16::from_le_bytes([c[0], c[1]]))
        .collect();
    let trimmed = match units.iter().rposition(|&u| u != 0) {
        Some(i) => &units[..=i],
        None => &[][..],
    };
    String::from_utf16_lossy(trimmed)
}

fn push_char(out: &mut Vec<u8>, c: char) {
    out.extend_from_slice(&(c as u16).to_le_bytes());
}

fn expect_char(b: &[u8], cur: &mut usize, c: char) -> Result<()> {
    let got = b
        .get(*cur..*cur + 2)
        .ok_or(PolError::Truncated(*cur))
        .map(|s| u16::from_le_bytes([s[0], s[1]]))?;
    if got != c as u16 {
        return Err(PolError::Expected {
            expected: c,
            at: *cur,
        });
    }
    *cur += 2;
    Ok(())
}

/// Read a NUL-terminated UTF-16LE string, leaving `cur` past the terminator.
fn read_utf16z(b: &[u8], cur: &mut usize) -> Result<String> {
    let start = *cur;
    let mut units = Vec::new();
    loop {
        let s = b
            .get(*cur..*cur + 2)
            .ok_or(PolError::UnterminatedString(start))?;
        let u = u16::from_le_bytes([s[0], s[1]]);
        *cur += 2;
        if u == 0 {
            return Ok(String::from_utf16_lossy(&units));
        }
        units.push(u);
    }
}

fn read_u32(b: &[u8], cur: &mut usize) -> Result<u32> {
    let s = b.get(*cur..*cur + 4).ok_or(PolError::Truncated(*cur))?;
    *cur += 4;
    Ok(u32::from_le_bytes(s.try_into().unwrap()))
}

fn strip_prefix_ci<'a>(s: &'a str, prefix: &str) -> Option<&'a str> {
    (s.len() >= prefix.len() && s[..prefix.len()].eq_ignore_ascii_case(prefix))
        .then(|| &s[prefix.len()..])
}