Skip to main content

HmacChainIntegrity

Struct HmacChainIntegrity 

Source
pub struct HmacChainIntegrity { /* private fields */ }
Expand description

Tamper-evident integrity using a keyed HMAC-SHA256 hash chain.

Each event is stamped with mac = HMAC(key, prev_mac || canonical(event)) and a chain_index. Because the MAC covers the entire canonical event and is keyed with a secret, an attacker cannot silently modify a field, and because it also covers the previous MAC, they cannot delete, reorder, or truncate entries without breaking every subsequent link.

§Key management

The key must be secret and must never be written to the log it protects. Load it from a KMS, a secrets manager, or an environment variable at startup. Use at least 32 bytes of random data.

§Limitations

This makes tampering detectable, not impossible. An attacker who obtains the key can rewrite the whole chain. To protect against that, ship entries off-box (or to WORM storage) promptly, so the attacker never controls the only copy.

§Examples

use ash_log::*;

let integrity = HmacChainIntegrity::new(b"a-32-byte-or-longer-secret-key!!");

let mut first = AuditEvent::builder()
    .event_type(AuditEventType::AuthenticationAttempt)
    .principal("alice@example.com")
    .result(AuditResult::Success)
    .build();
integrity.add_integrity(&mut first);

let mut second = AuditEvent::builder()
    .event_type(AuditEventType::MethodInvocation)
    .result(AuditResult::Success)
    .build();
integrity.add_integrity(&mut second);

// A verifier holding the same key can confirm the whole stream.
let verifier = HmacChainIntegrity::new(b"a-32-byte-or-longer-secret-key!!");
assert!(verifier.verify_chain(&[first, second]).is_ok());

Implementations§

Source§

impl HmacChainIntegrity

Source

pub fn new(key: &[u8]) -> Self

Create a chain starting from the genesis value.

Use a secret of at least 32 random bytes.

§Panics

Panics if key is empty. An empty key provides no security whatsoever, and silently accepting one would produce a log that looks protected but is not; failing loudly at construction is the safer behaviour.

Source

pub fn resume(key: &[u8], last_mac: impl Into<String>, last_index: u64) -> Self

Resume an existing chain from the last known MAC and index.

Use this when a process restarts and must continue an existing log rather than begin a new chain. Pass the mac and chain_index of the last entry already written, so the next entry links to it.

§Panics

Panics if key is empty, for the same reason as new.

Source

pub fn with_key_id<S: Into<String>>(self, key_id: S) -> Self

Name the key this chain signs with.

The identifier is stamped on every entry and covered by the MAC, so a verifier can tell which key to use without guessing, and an attacker cannot relabel an entry to point at a key they do control.

Required before rotate_to: rotation is meaningless if entries do not say which key signed them.

Source

pub fn writer<S: Into<String>>(self, writer: S) -> Self

Name the writer producing this chain.

Two processes must never share one chain: each keeps its own index and previous-MAC state, so their entries interleave into a stream that verifies as tampered. Giving each writer a distinct identity makes that mistake diagnosable — verify_chain reports ChainError::MixedWriters instead of a bare MAC mismatch, which would otherwise look exactly like an attack.

Give each process its own chain, its own key, or serialize writes through one process.

Source

pub fn rotate_to( &mut self, new_key: &[u8], new_key_id: impl Into<String>, ) -> Result<(), RotationError>

Begin signing with a new key, keeping the old one for verification.

The chain is not restarted: the next entry links to the previous MAC as usual, so continuity is preserved across the rotation. Entries signed before this call keep their original key_id and still verify, because the retired key is retained.

§Errors

Returns RotationError if this chain has no key id, if new_key is empty, or if new_key_id is already in use — reusing an identifier for a different key would make earlier entries unverifiable.

Source

pub fn key_id(&self) -> Option<&str>

The key identifier currently in use, if one was set.

Source

pub fn retired_key_ids(&self) -> Vec<&str>

Identifiers of keys retired by rotation, oldest first.

Source

pub fn current_mac(&self) -> String

The MAC most recently produced, or the genesis value if none yet.

Persist this alongside the index to later resume.

Source

pub fn next_index(&self) -> u64

The index the next stamped event will receive.

Source

pub fn verify_chain(&self, events: &[AuditEvent]) -> Result<usize, ChainError>

Verify a complete chain of events in order.

Returns the number of entries verified, or the first ChainError encountered. Verification starts from genesis, so pass the stream from its beginning; a mid-stream segment will report a mismatch at entry 0.

§Errors

Returns ChainError identifying the first entry that fails to verify.

Source

pub fn verify_unordered( &self, events: &[AuditEvent], ) -> Result<usize, ChainError>

Verify a chain whose entries may not be in chain order.

Concurrent producers stamp events under a lock but write them to the backend afterwards, so a log written by multiple threads can contain entries in a different order than they were stamped. Such a log is perfectly valid, but verify_chain rejects it because it checks position. This method sorts by the recorded chain_index first, then verifies.

Prefer this whenever more than one thread logs to the same chain. It requires every entry to carry a chain_index, and rejects duplicates, so it detects tampering just as strictly as verify_chain does.

§Errors

Returns ChainError identifying the first entry that fails to verify. Indices in the returned error refer to positions in chain order, not to positions in the slice that was passed in.

Trait Implementations§

Source§

impl AuditIntegrity for HmacChainIntegrity

Source§

fn verify(&self, event: &AuditEvent) -> bool

Verify a single event in isolation.

This only confirms that a MAC field is present and well-formed; a single event carries no proof of its position. Use verify_chain to actually detect tampering.

Source§

fn add_integrity(&self, event: &mut AuditEvent)

Add integrity metadata to event

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self> ⓘ

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self> ⓘ

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> Same for T

Source§

type Output = T

Should always be Self
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = !

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, !>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self> ⓘ
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self> ⓘ

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more