osquery-rust-ng 2.0.0

Rust bindings for Osquery
Documentation
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
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
//! Logger plugin support for osquery extensions.
//!
//! This module provides the infrastructure for creating logger plugins that integrate with osquery.
//! Logger plugins receive log data from osquery in various formats (status logs, query results, snapshots)
//! and are responsible for persisting or forwarding this data.
//!
//! # Example
//!
//! ```no_run
//! use osquery_rust_ng::plugin::{LoggerPlugin, LogStatus, Plugin};
//! use osquery_rust_ng::prelude::*;
//!
//! struct ConsoleLogger;
//!
//! impl LoggerPlugin for ConsoleLogger {
//!     fn name(&self) -> String {
//!         "console_logger".to_string()
//!     }
//!
//!     fn log_string(&self, message: &str) -> Result<(), String> {
//!         println!("{}", message);
//!         Ok(())
//!     }
//!
//!     fn log_status(&self, status: &LogStatus) -> Result<(), String> {
//!         println!("[{}] {}:{} - {}",
//!             status.severity, status.filename, status.line, status.message);
//!         Ok(())
//!     }
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let mut server = Server::new(None, "/path/to/socket").unwrap();
//! server.register_plugin(Plugin::logger(ConsoleLogger));
//! # Ok(())
//! # }
//! ```
//!
//! # Protocol Details
//!
//! osquery sends log data to logger plugins in two main formats:
//!
//! 1. **Status logs**: `{"log": "[{\"s\":0,\"f\":\"file.cpp\",\"i\":123,\"m\":\"message\"}]", "status": "true"}`
//!    - `s`: severity (0=Info, 1=Warning, 2=Error)
//!    - `f`: filename
//!    - `i`: line number
//!    - `m`: message
//!
//! 2. **Query results**: `{"log": "{...query results as JSON..."}`
//!    - Contains the results of scheduled queries
//!    - Automatically pretty-printed by the framework
//!
//! The logger plugin framework handles parsing these formats and calls the appropriate methods on your implementation.

use crate::_osquery::osquery::{ExtensionPluginRequest, ExtensionPluginResponse};
use crate::_osquery::osquery::{ExtensionResponse, ExtensionStatus};
use crate::plugin::OsqueryPlugin;
use crate::plugin::_enums::response::ExtensionResponseEnum;
use serde_json::Value;
use std::fmt;

/// Trait that logger plugins must implement.
///
/// # Example
///
/// ```no_run
/// use osquery_rust_ng::plugin::{LoggerPlugin, LogStatus, LogSeverity};
///
/// struct MyLogger;
///
/// impl LoggerPlugin for MyLogger {
///     fn name(&self) -> String {
///         "my_logger".to_string()
///     }
///
///     fn log_string(&self, message: &str) -> Result<(), String> {
///         println!("Log: {}", message);
///         Ok(())
///     }
/// }
/// ```
pub trait LoggerPlugin: Send + Sync + 'static {
    /// Returns the name of the logger plugin
    fn name(&self) -> String;

    /// Log a raw string message.
    ///
    /// This is called for general log entries and query results.
    fn log_string(&self, message: &str) -> Result<(), String>;

    /// Log structured status information.
    ///
    /// Called when osquery sends status logs with severity, file, line, and message.
    fn log_status(&self, status: &LogStatus) -> Result<(), String> {
        // Default implementation converts to string
        self.log_string(&status.to_string())
    }

    /// Log a snapshot (periodic state dump).
    ///
    /// Snapshots are periodic dumps of osquery's internal state.
    fn log_snapshot(&self, snapshot: &str) -> Result<(), String> {
        self.log_string(snapshot)
    }

    /// Initialize the logger.
    ///
    /// Called when the logger is first registered with osquery.
    fn init(&self, _name: &str) -> Result<(), String> {
        Ok(())
    }

    /// Health check for the logger.
    ///
    /// Called periodically to ensure the logger is still functioning.
    fn health(&self) -> Result<(), String> {
        Ok(())
    }

    /// Returns the features this logger supports.
    ///
    /// Override this method to advertise additional capabilities to osquery.
    /// By default, loggers advertise support for status logs.
    ///
    /// # Example
    ///
    /// ```
    /// use osquery_rust_ng::plugin::{LoggerPlugin, LoggerFeatures};
    ///
    /// struct MyLogger;
    ///
    /// impl LoggerPlugin for MyLogger {
    ///     fn name(&self) -> String { "my_logger".to_string() }
    ///     fn log_string(&self, _: &str) -> Result<(), String> { Ok(()) }
    ///
    ///     fn features(&self) -> i32 {
    ///         // Support both status logs and event forwarding
    ///         LoggerFeatures::LOG_STATUS | LoggerFeatures::LOG_EVENT
    ///     }
    /// }
    /// ```
    fn features(&self) -> i32 {
        LoggerFeatures::LOG_STATUS
    }

    /// Shutdown the logger.
    ///
    /// Called when the extension is shutting down.
    fn shutdown(&self) {}
}

/// Log status information from osquery.
///
/// Status logs contain structured information about osquery's internal state,
/// including error messages, warnings, and informational messages.
#[derive(Debug, Clone)]
pub struct LogStatus {
    /// The severity level of the log message
    pub severity: LogSeverity,
    /// The source file that generated the log
    pub filename: String,
    /// The line number in the source file
    pub line: u32,
    /// The log message text
    pub message: String,
}

impl fmt::Display for LogStatus {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "[{}] {}:{} - {}",
            self.severity, self.filename, self.line, self.message
        )
    }
}

/// Feature flags that logger plugins can advertise to osquery.
///
/// These flags tell osquery which additional log types the plugin supports.
/// When osquery sends a `{"action": "features"}` request, the plugin returns
/// a bitmask of these values in the response status code.
///
/// # Example
///
/// ```
/// use osquery_rust_ng::plugin::LoggerFeatures;
///
/// // Support both status logs and event forwarding
/// let features = LoggerFeatures::LOG_STATUS | LoggerFeatures::LOG_EVENT;
/// assert_eq!(features, 3);
/// ```
pub struct LoggerFeatures;

impl LoggerFeatures {
    /// No additional features - only query results are logged.
    pub const BLANK: i32 = 0;

    /// Plugin supports receiving osquery status logs (INFO/WARNING/ERROR).
    ///
    /// When enabled, osquery forwards its internal Glog status messages
    /// to the logger plugin via `log_status()`.
    pub const LOG_STATUS: i32 = 1;

    /// Plugin supports receiving event logs.
    ///
    /// When enabled, event subscribers forward events directly to the logger.
    pub const LOG_EVENT: i32 = 2;
}

/// Log severity levels used by osquery.
///
/// These map directly to osquery's internal severity levels.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogSeverity {
    /// Informational messages (severity 0)
    Info = 0,
    /// Warning messages (severity 1)
    Warning = 1,
    /// Error messages (severity 2)
    Error = 2,
}

impl fmt::Display for LogSeverity {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            LogSeverity::Info => write!(f, "INFO"),
            LogSeverity::Warning => write!(f, "WARNING"),
            LogSeverity::Error => write!(f, "ERROR"),
        }
    }
}

impl TryFrom<i64> for LogSeverity {
    type Error = String;

    fn try_from(value: i64) -> Result<Self, String> {
        match value {
            0 => Ok(LogSeverity::Info),
            1 => Ok(LogSeverity::Warning),
            2 => Ok(LogSeverity::Error),
            _ => Err(format!("Invalid severity level: {value}")),
        }
    }
}

/// Types of log requests that can be received from osquery.
///
/// This enum represents the different types of logging operations
/// that osquery can request from a logger plugin.
#[derive(Debug)]
enum LogRequestType {
    /// Status log with array of status entries
    StatusLog(Vec<StatusEntry>),
    /// Query result log (formatted as JSON)
    QueryResult(Value),
    /// Raw string log
    RawString(String),
    /// Snapshot log (periodic state dump)
    Snapshot(String),
    /// Logger initialization request
    Init(String),
    /// Health check request
    Health,
    /// Features query - osquery asks what log types we support
    Features,
}

/// A single status log entry from osquery
#[derive(Debug)]
struct StatusEntry {
    severity: LogSeverity,
    filename: String,
    line: u32,
    message: String,
}

/// Wrapper that adapts a LoggerPlugin to the OsqueryPlugin interface.
///
/// This wrapper handles the complexity of osquery's logger protocol,
/// parsing different request formats and calling the appropriate methods
/// on your LoggerPlugin implementation.
///
/// You typically don't need to interact with this directly - use
/// `Plugin::logger()` to create plugins.
pub struct LoggerPluginWrapper<L: LoggerPlugin> {
    logger: L,
}

impl<L: LoggerPlugin> LoggerPluginWrapper<L> {
    pub fn new(logger: L) -> Self {
        Self { logger }
    }

    /// Parse an osquery request into a structured log request type
    fn parse_request(&self, request: &ExtensionPluginRequest) -> LogRequestType {
        // Check for status logs first (most common in daemon mode)
        if let Some(log_data) = request.get("log") {
            if request.get("status").map(|s| s == "true").unwrap_or(false) {
                // Parse status log array
                if let Ok(entries) = self.parse_status_entries(log_data) {
                    return LogRequestType::StatusLog(entries);
                }
            }

            // Try to parse as JSON for pretty printing
            if let Ok(value) = serde_json::from_str::<Value>(log_data) {
                return LogRequestType::QueryResult(value);
            }

            // Fall back to raw string
            return LogRequestType::RawString(log_data.to_string());
        }

        // Check for other request types
        if let Some(snapshot) = request.get("snapshot") {
            return LogRequestType::Snapshot(snapshot.to_string());
        }

        if let Some(init_name) = request.get("init") {
            return LogRequestType::Init(init_name.to_string());
        }

        if request.contains_key("health") {
            return LogRequestType::Health;
        }

        // Check for features query
        if request
            .get("action")
            .map(|a| a == "features")
            .unwrap_or(false)
        {
            return LogRequestType::Features;
        }

        // Fallback for unknown request
        if let Some(string_log) = request.get("string") {
            return LogRequestType::RawString(string_log.to_string());
        }

        LogRequestType::RawString(String::new())
    }

    /// Parse status entries from JSON array string
    fn parse_status_entries(&self, log_data: &str) -> Result<Vec<StatusEntry>, String> {
        let entries: Vec<Value> = serde_json::from_str(log_data)
            .map_err(|e| format!("Failed to parse status log array: {e}"))?;

        let mut status_entries = Vec::new();

        for entry in entries {
            if let Some(obj) = entry.as_object() {
                let severity = obj
                    .get("s")
                    .and_then(|v| v.as_i64())
                    .unwrap_or(0)
                    .try_into()
                    .unwrap_or(LogSeverity::Info);

                let filename = obj
                    .get("f")
                    .and_then(|v| v.as_str())
                    .unwrap_or("unknown")
                    .to_string();

                let line = obj.get("i").and_then(|v| v.as_i64()).unwrap_or(0) as u32;

                let message = obj
                    .get("m")
                    .and_then(|v| v.as_str())
                    .unwrap_or("")
                    .to_string();

                status_entries.push(StatusEntry {
                    severity,
                    filename,
                    line,
                    message,
                });
            }
        }

        Ok(status_entries)
    }

    /// Handle a parsed log request
    fn handle_log_request(&self, request_type: LogRequestType) -> Result<(), String> {
        match request_type {
            LogRequestType::StatusLog(entries) => {
                for entry in entries {
                    let status = LogStatus {
                        severity: entry.severity,
                        filename: entry.filename,
                        line: entry.line,
                        message: entry.message,
                    };
                    self.logger.log_status(&status)?;
                }
                Ok(())
            }
            LogRequestType::QueryResult(value) => {
                let formatted =
                    serde_json::to_string_pretty(&value).unwrap_or_else(|_| value.to_string());
                self.logger.log_string(&formatted)
            }
            LogRequestType::RawString(s) => self.logger.log_string(&s),
            LogRequestType::Snapshot(s) => self.logger.log_snapshot(&s),
            LogRequestType::Init(name) => self.logger.init(&name),
            LogRequestType::Health => self.logger.health(),
            // Features is handled specially in handle_call before this is called
            LogRequestType::Features => Ok(()),
        }
    }
}

impl<L: LoggerPlugin> OsqueryPlugin for LoggerPluginWrapper<L> {
    fn name(&self) -> String {
        self.logger.name()
    }

    fn registry(&self) -> crate::plugin::Registry {
        crate::plugin::Registry::Logger
    }

    fn routes(&self) -> ExtensionPluginResponse {
        // Logger plugins don't expose routes like table plugins do
        ExtensionPluginResponse::new()
    }

    fn ping(&self) -> ExtensionStatus {
        // Health check - always return OK for now
        ExtensionStatus::default()
    }

    fn handle_call(&self, request: crate::_osquery::ExtensionPluginRequest) -> ExtensionResponse {
        // Parse the request into a structured type
        let request_type = self.parse_request(&request);

        // Features request needs special handling - return features as status code
        if matches!(request_type, LogRequestType::Features) {
            return ExtensionResponseEnum::SuccessWithCode(self.logger.features()).into();
        }

        // Handle the request and return the appropriate response
        match self.handle_log_request(request_type) {
            Ok(()) => ExtensionResponseEnum::Success().into(),
            Err(e) => ExtensionResponseEnum::Failure(e).into(),
        }
    }

    fn shutdown(&self) {
        self.logger.shutdown();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::plugin::OsqueryPlugin;
    use std::collections::BTreeMap;

    /// A minimal logger for testing
    struct TestLogger {
        custom_features: Option<i32>,
    }

    impl TestLogger {
        fn new() -> Self {
            Self {
                custom_features: None,
            }
        }

        fn with_features(features: i32) -> Self {
            Self {
                custom_features: Some(features),
            }
        }
    }

    impl LoggerPlugin for TestLogger {
        fn name(&self) -> String {
            "test_logger".to_string()
        }

        fn log_string(&self, _message: &str) -> Result<(), String> {
            Ok(())
        }

        fn features(&self) -> i32 {
            self.custom_features.unwrap_or(LoggerFeatures::LOG_STATUS)
        }
    }

    #[test]
    fn test_features_request_returns_default_log_status() {
        let logger = TestLogger::new();
        let wrapper = LoggerPluginWrapper::new(logger);

        // Simulate osquery sending {"action": "features"}
        let mut request: BTreeMap<String, String> = BTreeMap::new();
        request.insert("action".to_string(), "features".to_string());

        let response = wrapper.handle_call(request);

        // The status code should be LOG_STATUS (1)
        let status = response.status.as_ref();
        assert!(status.is_some(), "response should have status");
        assert_eq!(
            status.and_then(|s| s.code),
            Some(LoggerFeatures::LOG_STATUS)
        );
    }

    #[test]
    fn test_features_request_returns_custom_features() {
        // Logger that supports both status logs and event forwarding
        let features = LoggerFeatures::LOG_STATUS | LoggerFeatures::LOG_EVENT;
        let logger = TestLogger::with_features(features);
        let wrapper = LoggerPluginWrapper::new(logger);

        let mut request: BTreeMap<String, String> = BTreeMap::new();
        request.insert("action".to_string(), "features".to_string());

        let response = wrapper.handle_call(request);

        // The status code should be 3 (LOG_STATUS | LOG_EVENT)
        let status = response.status.as_ref();
        assert!(status.is_some(), "response should have status");
        assert_eq!(status.and_then(|s| s.code), Some(3));
    }

    #[test]
    fn test_features_request_returns_blank_when_no_features() {
        let logger = TestLogger::with_features(LoggerFeatures::BLANK);
        let wrapper = LoggerPluginWrapper::new(logger);

        let mut request: BTreeMap<String, String> = BTreeMap::new();
        request.insert("action".to_string(), "features".to_string());

        let response = wrapper.handle_call(request);

        // The status code should be 0 (BLANK)
        let status = response.status.as_ref();
        assert!(status.is_some(), "response should have status");
        assert_eq!(status.and_then(|s| s.code), Some(LoggerFeatures::BLANK));
    }

    #[test]
    fn test_parse_request_recognizes_features_action() {
        let logger = TestLogger::new();
        let wrapper = LoggerPluginWrapper::new(logger);

        let mut request: BTreeMap<String, String> = BTreeMap::new();
        request.insert("action".to_string(), "features".to_string());

        let request_type = wrapper.parse_request(&request);
        assert!(matches!(request_type, LogRequestType::Features));
    }

    #[test]
    fn test_parse_request_ignores_other_actions() {
        let logger = TestLogger::new();
        let wrapper = LoggerPluginWrapper::new(logger);

        let mut request: BTreeMap<String, String> = BTreeMap::new();
        request.insert("action".to_string(), "unknown".to_string());

        let request_type = wrapper.parse_request(&request);
        // Should fall through to default (RawString)
        assert!(matches!(request_type, LogRequestType::RawString(_)));
    }
}