use crate::base::Stix;
use crate::common::validation::is_exact_vocab_value;
use crate::cyber_observable_objects::vocab::WindowsRegistryDataTypeEnum;
use crate::error::{add_error, return_multiple_errors, CheckContext, StixError as Error};
use crate::types::{Identifier, Timestamp};
use regex::Regex;
use serde::{Deserialize, Serialize};
use serde_this_or_that::as_opt_i64;
use serde_with::skip_serializing_none;
use std::sync::OnceLock;
use stixflayer_derive::StixProperties;
fn windows_registry_key_re() -> &'static Regex {
static RE: OnceLock<Regex> = OnceLock::new();
RE.get_or_init(|| {
Regex::new(r"^(HKEY_LOCAL_MACHINE|HKEY_CURRENT_USER|HKEY_CLASSES_ROOT|HKEY_USERS|HKEY_CURRENT_CONFIG)(\\[a-zA-Z0-9_]+)*$")
.expect("Windows registry key regex is valid")
})
}
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, StixProperties)]
pub struct WindowsRegistryKey {
pub key: Option<String>,
pub values: Option<Vec<WindowsRegistryKeyType>>,
pub modified_time: Option<Timestamp>,
pub creator_user_ref: Option<Identifier>,
#[serde(default, deserialize_with = "as_opt_i64")]
pub number_of_subkeys: Option<i64>,
}
impl Stix for WindowsRegistryKey {
fn check(&self, ctx: &mut CheckContext) -> Result<(), Error> {
let mut errors = Vec::new();
if let Some(creator_user_ref) = &self.creator_user_ref {
creator_user_ref.check(ctx)?;
if creator_user_ref.get_type() != "user-account" {
errors.push(Error::ValidationError(
"creator_user_ref must be of type 'user-account'.".to_string(),
));
}
}
if let Some(key) = &self.key {
if !windows_registry_key_re().is_match(key) {
errors.push(Error::ValidationError(
"Registry key must begin with HKEY_LOCAL_MACHINE, HKEY_CURRENT_USER, HKEY_CLASSES_ROOT, HKEY_USERS, or HKEY_CURRENT_CONFIG.".to_string(),
));
}
}
if let Some(number_of_subkeys) = &self.number_of_subkeys {
number_of_subkeys.check(ctx)?;
}
if let Some(values) = &self.values {
add_error(&mut errors, values.check(ctx));
}
return_multiple_errors(errors)
}
}
#[skip_serializing_none]
#[derive(Clone, Debug, Default, PartialEq, Eq, Serialize, Deserialize, StixProperties)]
pub struct WindowsRegistryKeyType {
pub name: Option<String>,
pub data: Option<String>,
pub data_type: Option<String>,
}
impl Stix for WindowsRegistryKeyType {
fn check(&self, _ctx: &mut CheckContext) -> Result<(), Error> {
if let Some(data_type) = &self.data_type {
if !is_exact_vocab_value::<WindowsRegistryDataTypeEnum, _>(data_type) {
return Err(Error::ValidationError(
"data_type must come from the 'windows-registry-datatype-enum' enumeration."
.to_string(),
));
}
}
Ok(())
}
}
#[cfg(test)]
mod tests {
#![allow(unused_imports)]
use crate::cyber_observable_objects::sco::{CyberObject, CyberObjectBuilder};
use crate::extensions::{
ArchiveExtension, FileExtensions, HttpRequestExtension, IcmpExtension,
NetworkTrafficExtensions, ProcessExtensions, SocketExtenion, SpecialExtensions,
UnixAccountExtension, UserAccountExtensions, WindowsProcessExtension,
};
use crate::types::{DictionaryValue, Hashes, Identifier, StixDictionary, Timestamp};
use serde_json::Value;
use std::{collections::HashMap, str::FromStr};
use test_log::test;
#[test]
fn serialize_windows_registry_key() {
let windows_registry_key = CyberObjectBuilder::new("windows-registry-key")
.unwrap()
.key("HKEY_LOCAL_MACHINE".to_string())
.unwrap()
.number_of_subkeys(10000000.into())
.unwrap()
.creator_user_ref(
Identifier::from_str("user-account--cc7fa653-c35f-53db-afdd-dce4c3a241d5").unwrap(),
)
.unwrap()
.build()
.unwrap()
.test_id();
let result = serde_json::to_value(&windows_registry_key).unwrap();
let expected = r#"{
"key":"HKEY_LOCAL_MACHINE",
"id": "windows-registry-key--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
"number_of_subkeys": 10000000,
"creator_user_ref": "user-account--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
"spec_version": "2.1",
"type": "windows-registry-key"
}"#;
let expected_value: Value = serde_json::from_str(expected).unwrap();
assert_eq!(&result, &expected_value);
}
#[test]
fn deserialize_windows_registry_key() {
let json = r#"{
"key":"HKEY_LOCAL_MACHINE",
"id": "windows-registry-key--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
"number_of_subkeys": 10000000,
"creator_user_ref": "user-account--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
"spec_version": "2.1",
"type": "windows-registry-key"
}"#;
let result = CyberObject::from_json(json, false).unwrap();
let windows_registry_key = CyberObjectBuilder::new("windows-registry-key")
.unwrap()
.key("HKEY_LOCAL_MACHINE".to_string())
.unwrap()
.number_of_subkeys(10000000.into())
.unwrap()
.creator_user_ref(
Identifier::from_str("user-account--cc7fa653-c35f-53db-afdd-dce4c3a241d5").unwrap(),
)
.unwrap()
.build()
.unwrap()
.test_id();
assert_eq!(result, windows_registry_key)
}
#[test]
fn windows_registry_key_i64_invalid1() {
let json = r#"{
"key":"HKEY_LOCAL_MACHINE",
"id": "windows-registry-key--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
"number_of_subkeys": -9007199254740992,
"creator_user_ref": "user-account--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
"spec_version": "2.1",
"type": "windows-registry-key"
}"#;
let result = CyberObject::from_json(json, false);
assert!(result.is_err())
}
#[test]
fn windows_registry_key_i64_valid() {
let json = r#"{
"key":"HKEY_LOCAL_MACHINE",
"id": "windows-registry-key--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
"number_of_subkeys": 9007199254740990,
"creator_user_ref": "user-account--cc7fa653-c35f-53db-afdd-dce4c3a241d5",
"spec_version": "2.1",
"type": "windows-registry-key"
}"#;
let result = CyberObject::from_json(json, false);
assert!(result.is_ok());
}
#[test]
fn windows_registry_key_invalid() {
let windows_registry_key = CyberObjectBuilder::new("windows-registry-key")
.unwrap()
.key("HKEY_LOCAL_MACHINExx\\foo\\bar".to_string())
.unwrap()
.number_of_subkeys(10000000.into())
.unwrap()
.creator_user_ref(
Identifier::from_str("user-account--cc7fa653-c35f-53db-afdd-dce4c3a241d5").unwrap(),
)
.unwrap()
.build();
assert!(windows_registry_key.is_err())
}
}