1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
//! Multi-protocol anomaly correlation harness.
//!
//! Built on top of [`ProtocolEvent`](crate::protocol::ProtocolEvent),
//! `AnomalyMonitor` lets you compose detectors as small typed rules
//! (each implementing the [`AnomalyRule`] trait), feed them events
//! and periodic ticks, and collect their findings as
//! [`Anomaly`] records.
//!
//! Compared to writing each detector as a hand-rolled
//! `tokio::select!` over multiple streams (see
//! `examples/anomaly/dns_resolved_no_connection.rs`), the harness
//! collapses the boilerplate to:
//!
//! 1. one `ProtocolMonitorBuilder` to declare which protocols to
//! observe,
//! 2. one `AnomalyMonitor` populated via `.with_rule(...)`, and
//! 3. one event-loop calling `monitor.observe(&evt)` + a tick that
//! calls `monitor.on_tick(now)`.
//!
//! ```no_run
//! # #[cfg(all(feature = "tokio", feature = "flow"))]
//! # async fn _ex() -> Result<(), Box<dyn std::error::Error>> {
//! use std::time::Duration;
//! use futures::StreamExt;
//! use flowscope::Timestamp;
//! use netring::anomaly::{Anomaly, AnomalyMonitor, AnomalyRule, Severity};
//! use netring::flow::extract::{FiveTuple, FiveTupleKey};
//! use netring::protocol::{ProtocolEvent, ProtocolMonitorBuilder};
//!
//! struct AlwaysFires;
//! impl AnomalyRule<FiveTupleKey> for AlwaysFires {
//! fn name(&self) -> &'static str { "always_fires" }
//! fn observe(&mut self, evt: &ProtocolEvent<FiveTupleKey>, emit: &mut Vec<Anomaly<FiveTupleKey>>) {
//! emit.push(Anomaly::new(self.name(), Severity::Info, evt.timestamp())
//! .with_key_opt(evt.key().cloned()));
//! }
//! }
//!
//! let mut monitor = ProtocolMonitorBuilder::new()
//! .interface("eth0")
//! .flow()
//! .build(FiveTuple::bidirectional())?;
//!
//! let mut rules = AnomalyMonitor::<FiveTupleKey>::new()
//! .with_rule(AlwaysFires);
//!
//! let mut sweep = tokio::time::interval(Duration::from_secs(1));
//! loop {
//! tokio::select! {
//! Some(evt) = monitor.next() => {
//! for a in rules.observe(&evt?) { println!("{}", a.kind); }
//! }
//! _ = sweep.tick() => {
//! for a in rules.on_tick(Timestamp::default()) { println!("{}", a.kind); }
//! }
//! }
//! }
//! # }
//! ```
pub use FlowAnomalyRule;
pub use AnomalyMonitor;
pub use ;