Skip to content

Commit

Permalink
feat: implement time module (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
RonnieSalomonsen authored Aug 18, 2023
1 parent c2e9703 commit 8d0a143
Show file tree
Hide file tree
Showing 4 changed files with 55 additions and 1 deletion.
4 changes: 3 additions & 1 deletion yara-x/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,9 @@ test_proto3-module = []
text-module = [
"dep:lingua"
]
# The Time module allows you to retrieve epoch in seconds that can
# be used in conditions of a rule to check againts other epoch time.
time-module = []

# Features that are enabled by default.
default = [
Expand Down Expand Up @@ -69,7 +72,6 @@ yara-x-proto = { workspace = true }

lingua = { version = "1.4.0", optional = true, default-features = false, features = ["english", "german", "french", "spanish"] }


[build-dependencies]
protobuf = { workspace = true }
protobuf-codegen = { workspace = true }
Expand Down
2 changes: 2 additions & 0 deletions yara-x/src/modules/modules.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,7 @@
pub mod text;
#[cfg(feature = "test_proto2-module")]
pub mod test_proto2;
#[cfg(feature = "time-module")]
pub mod time;
#[cfg(feature = "test_proto3-module")]
pub mod test_proto3;
13 changes: 13 additions & 0 deletions yara-x/src/modules/protos/time.proto
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
syntax = "proto2";

import "yara.proto";

option (yara.module_options) = {
name : "time"
root_message: "Time"
rust_module: "time"
};

message Time {
// This module contains only exported functions, and doesn't return any data
}
37 changes: 37 additions & 0 deletions yara-x/src/modules/time.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
use crate::modules::prelude::*;
use crate::modules::protos::time::*;
use std::time::{SystemTime, UNIX_EPOCH};

#[module_main]
fn main(_ctx: &ScanContext) -> Time {
// Nothing to do, but we have to return our protobuf
Time::new()
}

#[module_export]
fn now(ctx: &ScanContext) -> Option<i64> {
Some(SystemTime::now().duration_since(UNIX_EPOCH).ok()?.as_secs() as i64)
}

#[cfg(test)]
mod tests {
#[test]
fn end2end() {
let rules = crate::compiler::Compiler::new()
.add_source(
r#"import "time"
rule rule_1 { condition: time.now() >= 0 }
rule rule_2 { condition: time.now() <= 0 }
rule rule_3 { condition: time.now() != 0 }
rule rule_4 { condition: time.now() == 0 }
"#,
)
.unwrap()
.build()
.unwrap();

let mut scanner = crate::scanner::Scanner::new(&rules);

assert_eq!(scanner.scan(&[]).num_matching_rules(), 2);
}
}

0 comments on commit 8d0a143

Please sign in to comment.