u-siem 0.7.0

A framework for building custom SIEMs
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
use serde::de::{MapAccess, Visitor};
use serde::{de::DeserializeOwned, Deserialize, Deserializer, Serialize};
use std::collections::BTreeMap;
use std::fmt::Debug;
use std::marker::PhantomData;

use super::task::{SiemTask, SiemTaskResult};
use super::{
    command_types::{
        FilterDomain, FilterEmail, FilterIp, IsolateEndpoint, IsolateIp, LoggedOnUser, LoginUser,
        ParserDefinition, RuleDefinition, TaskDefinition, UseCaseDefinition,
    },
    common::{DatasetDefinition, UserRole},
};
use crate::events::field::SiemField;
use crate::prelude::types::LogString;

/// Define commands to be used by the users or other components.
#[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
#[allow(non_camel_case_types)]
#[non_exhaustive]
pub enum SiemFunctionType {
    STOP_COMPONENT,
    START_COMPONENT,
    LOG_QUERY,
    ISOLATE_IP,
    ISOLATE_ENDPOINT,
    FILTER_IP,
    FILTER_DOMAIN,
    FILTER_EMAIL_SENDER,
    LIST_USE_CASES,
    GET_USE_CASE,
    LIST_RULES,
    GET_RULE,
    LIST_TASKS,
    LIST_DATASETS,
    DOWNLOAD_QUERY,
    LOGIN_USER,
    LIST_PARSERS,
    START_TASK,
    GET_TASK_RESULT,
    /// Function name
    OTHER(LogString),
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct CommandDefinition {
    class: SiemFunctionType,
    name: LogString,
    description: LogString,
    min_permission: UserRole,
}
impl CommandDefinition {
    pub fn new(
        class: SiemFunctionType,
        name: LogString,
        description: LogString,
        min_permission: UserRole,
    ) -> CommandDefinition {
        CommandDefinition {
            class,
            name,
            description,
            min_permission,
        }
    }

    pub fn class(&self) -> &SiemFunctionType {
        &self.class
    }
    pub fn name(&self) -> &LogString {
        &self.name
    }
    pub fn description(&self) -> &LogString {
        &self.description
    }
    pub fn min_permission(&self) -> &UserRole {
        &self.min_permission
    }
}

#[derive(Serialize, Deserialize, Debug, Default)]
pub struct SiemCommandHeader {
    /// User that created the command
    pub user: String,
    /// Component ID that created the command or the response
    pub comp_id: u64,
    /// Internal command ID: serves as an internal mapping betwen components as to replay to a specific component
    ///
    /// COMMAND => (COMPONENT) CMP_ID ->(KERNEL)-> CMP_ID<=>CMP_KRNL_ID ->(OTHER COMPONENT) -> CMP_KRNL_ID
    ///
    ///
    /// RESPONSE => (OTHER COMPONENT) RSP_ID=CMP_KRNL_ID ->(KERNEL)-> RSP_ID=CMP_KRNL_ID<=>CMP_ID -> (COMPONENT) -> CMP_ID
    pub comm_id: u64,
}

impl SiemCommandHeader {
    pub fn new<S: Into<String>>(user: S, component: u64, command: u64) -> Self {
        Self {
            user: user.into(),
            comp_id: component,
            comm_id: command,
        }
    }
    pub fn for_user<S: Into<String>>(user: S) -> Self {
        Self {
            user: user.into(),
            ..Default::default()
        }
    }
}

/// Execute a command with parameters
#[derive(Serialize, Deserialize, Debug, Clone)]
#[allow(non_camel_case_types)]
#[non_exhaustive]
pub enum SiemCommandCall {
    /// Starts a component. Params: Component name
    START_COMPONENT(String),
    /// Stops a component. Params: Component name
    STOP_COMPONENT(String),
    /// Query in database format. Ex SQL,  Elastic
    LOG_QUERY(QueryInfo),
    /// IP of the device to isolate
    ISOLATE_IP(IsolateIp),
    /// IP of the device to isolate
    ISOLATE_ENDPOINT(IsolateEndpoint),
    /// Adds a IP to a BlockList with a comment or reference (IP, Comment)
    FILTER_IP(FilterIp),
    /// Adds a domain to a BlockList with a comment or reference (Domain, Comment)
    FILTER_DOMAIN(FilterDomain),
    /// Adds a email to a BlockList with a comment or reference (Email, Comment)
    FILTER_EMAIL_SENDER(FilterEmail),
    /// List use cases: offset, limit
    LIST_USE_CASES(Pagination),
    GET_USE_CASE(String),
    /// List rules: offset, limit
    LIST_RULES(Pagination),
    /// Get rule by name
    GET_RULE(String),
    /// List datasets: offset, limit
    LIST_DATASETS(Pagination),
    /// List tasks: offset, limit
    LIST_TASKS(Pagination),
    DOWNLOAD_QUERY(),
    LIST_PARSERS(Pagination),
    LOGIN_USER(LoginUser),
    START_TASK(SiemTask),
    GET_TASK_RESULT(u64),
    /// Allows new components to extend the functionality of uSIEM: Function name, Parameters
    OTHER(LogString, BTreeMap<LogString, LogString>),
}

impl SiemCommandCall {
    pub fn get_type(&self) -> SiemFunctionType {
        match self {
            SiemCommandCall::START_COMPONENT(_) => SiemFunctionType::START_COMPONENT,
            SiemCommandCall::STOP_COMPONENT(_) => SiemFunctionType::STOP_COMPONENT,
            SiemCommandCall::LOG_QUERY(_) => SiemFunctionType::LOG_QUERY,
            SiemCommandCall::ISOLATE_IP(_) => SiemFunctionType::ISOLATE_IP,
            SiemCommandCall::ISOLATE_ENDPOINT(_) => SiemFunctionType::ISOLATE_ENDPOINT,
            SiemCommandCall::FILTER_IP(_) => SiemFunctionType::FILTER_IP,
            SiemCommandCall::FILTER_DOMAIN(_) => SiemFunctionType::FILTER_DOMAIN,
            SiemCommandCall::FILTER_EMAIL_SENDER(_) => SiemFunctionType::FILTER_EMAIL_SENDER,
            SiemCommandCall::LIST_USE_CASES(_) => SiemFunctionType::LIST_USE_CASES,
            SiemCommandCall::GET_USE_CASE(_) => SiemFunctionType::GET_USE_CASE,
            SiemCommandCall::LIST_RULES(_) => SiemFunctionType::LIST_RULES,
            SiemCommandCall::GET_RULE(_) => SiemFunctionType::GET_RULE,
            SiemCommandCall::LIST_DATASETS(_) => SiemFunctionType::LIST_DATASETS,
            SiemCommandCall::LIST_TASKS(_) => SiemFunctionType::LIST_TASKS,
            SiemCommandCall::DOWNLOAD_QUERY() => SiemFunctionType::DOWNLOAD_QUERY,
            SiemCommandCall::LIST_PARSERS(_) => SiemFunctionType::LIST_PARSERS,
            SiemCommandCall::LOGIN_USER(_) => SiemFunctionType::LOGIN_USER,
            SiemCommandCall::START_TASK(_) => SiemFunctionType::START_TASK,
            SiemCommandCall::GET_TASK_RESULT(_) => SiemFunctionType::GET_TASK_RESULT,
            SiemCommandCall::OTHER(v, _) => SiemFunctionType::OTHER(v.clone()),
        }
    }
}

#[derive(Serialize, Deserialize, Debug, Clone)]
pub struct Pagination {
    pub offset: u32,
    pub limit: u32,
}

#[derive(Serialize, Deserialize, Debug, Clone)]
#[non_exhaustive]
pub enum CommandError {
    BadParameters(LogString),
    SyntaxError(LogString),
    NotFound(LogString),
}

/// The response of a command execution
#[derive(Serialize, Deserialize, Debug, Clone)]
#[allow(non_camel_case_types)]
#[non_exhaustive]
pub enum SiemCommandResponse {
    START_COMPONENT(CommandResult<String>),
    STOP_COMPONENT(CommandResult<String>),
    /// Query created with an ID
    LOG_QUERY(QueryInfo, CommandResult<Vec<BTreeMap<String, SiemField>>>),
    ISOLATE_IP(CommandResult<String>),
    ISOLATE_ENDPOINT(CommandResult<String>),
    /// (IP, Comment)
    FILTER_IP(CommandResult<String>),
    /// (Domain, Comment)
    FILTER_DOMAIN(CommandResult<String>),
    /// (Email, Comment)
    FILTER_EMAIL_SENDER(CommandResult<String>),
    /// List of UseCases: (Name,Description)
    LIST_USE_CASES(CommandResult<Vec<UseCaseDefinition>>),
    GET_USE_CASE(CommandResult<UseCaseDefinition>),
    LIST_RULES(CommandResult<Vec<RuleDefinition>>),
    GET_RULE(CommandResult<RuleDefinition>),
    LIST_DATASETS(CommandResult<Vec<DatasetDefinition>>),
    LIST_TASKS(CommandResult<Vec<TaskDefinition>>),
    LIST_PARSERS(CommandResult<Vec<ParserDefinition>>),
    LOGIN_USER(CommandResult<LoggedOnUser>),
    START_TASK(CommandResult<u64>),
    GET_TASK_RESULT(CommandResult<SiemTaskResult>),
    OTHER(LogString, CommandResult<BTreeMap<LogString, LogString>>),
    //TODO: Authentication command, to allow login using third party systems: LDAP...
}

#[derive(Serialize, Debug, Clone)]
pub enum CommandResult<T>
where
    T: Serialize + DeserializeOwned + std::fmt::Debug + Clone,
{
    #[serde(rename = "ok")]
    Ok(T),
    #[serde(rename = "err")]
    Err(CommandError),
}

impl<'de, T: Serialize + Clone + Debug + ?Sized + DeserializeOwned> Deserialize<'de>
    for CommandResult<T>
{
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_map(CommandResultVisitor::new())
    }
}

struct CommandResultVisitor<T> {
    marker: PhantomData<fn() -> T>,
}

impl<T> CommandResultVisitor<T> {
    fn new() -> Self {
        CommandResultVisitor {
            marker: PhantomData,
        }
    }
}

impl<'de, T> Visitor<'de> for CommandResultVisitor<T>
where
    T: DeserializeOwned + Debug + Serialize + Clone,
{
    // The type that our Visitor is going to produce.
    type Value = CommandResult<T>;

    // Deserialize MyMap from an abstract "map" provided by the
    // Deserializer. The MapAccess input is a callback provided by
    // the Deserializer to let us see each entry in the map.
    fn visit_map<M>(self, mut access: M) -> Result<Self::Value, M::Error>
    where
        M: MapAccess<'de>,
    {
        // While there are entries remaining in the input, add them
        // into our map.
        if let Some(key) = access.next_key::<&str>()? {
            if key == "ok" {
                let val: T = access.next_value()?;
                Ok(CommandResult::Ok(val))
            } else if key == "err" {
                let val: CommandError = access.next_value()?;
                Ok(CommandResult::Err(val))
            } else {
                Err(serde::de::Error::missing_field("No ok/err field available"))
            }
        } else {
            Err(serde::de::Error::missing_field("No ok/err field available"))
        }
    }

    fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
        write!(formatter, "A valid command result")
    }
}
// */
#[derive(Serialize, Deserialize, Debug, Clone, Default)]
pub struct QueryInfo {
    /// The user that created the query pettition
    pub user: String,
    /// Use storage native query language: SQL, Elastic
    pub is_native: bool,
    /// If there are alredy a query resolved, make a query agaist it
    pub query_id: Option<String>,
    /// Starting time for event_created: Unix datetime from 1970
    pub from: i64,
    /// Ending time for event_created: Unix datetime from 1970
    pub to: i64,
    /// Number of rows returned
    pub limit: usize,
    /// Offseting the query
    pub offset: usize,
    /// Time to live of the query results
    pub ttl: i64,
    /// If empty and query_id has something, then return the stored query
    pub query: String,
    /// List of fields to be returned, empty for all
    pub fields: Vec<String>,
}

impl QueryInfo {
    pub fn new<S: Into<String>>(query: S) -> Self {
        Self {
            query: query.into(),
            is_native: true,
            from: 0,
            to: i64::MAX,
            limit: 128,
            offset: 0,
            ttl: 3_600_000,
            ..Default::default()
        }
    }
}

#[cfg(test)]
mod de_ser {

    use crate::prelude::{types::LogString, DatasetDefinition};

    use super::SiemCommandResponse;

    #[test]
    fn should_serialize_and_deserialize_command_response() {
        let res =
            SiemCommandResponse::FILTER_IP(super::CommandResult::Ok(format!("Ip was filtered")));
        let str = serde_json::to_string(&res).unwrap();
        let res2: SiemCommandResponse = serde_json::from_str(&str).unwrap();

        match (res, res2) {
            (SiemCommandResponse::FILTER_IP(ip1), SiemCommandResponse::FILTER_IP(ip2)) => {
                match (ip1, ip2) {
                    (super::CommandResult::Ok(v1), super::CommandResult::Ok(v2)) => {
                        assert_eq!(v1, v2)
                    }
                    (super::CommandResult::Err(v1), super::CommandResult::Err(v2)) => {
                        match (v1, v2) {
                            (
                                super::CommandError::BadParameters(v1),
                                super::CommandError::BadParameters(v2),
                            ) => assert_eq!(v1, v2),
                            (
                                super::CommandError::SyntaxError(v1),
                                super::CommandError::SyntaxError(v2),
                            ) => assert_eq!(v1, v2),
                            (
                                super::CommandError::NotFound(v1),
                                super::CommandError::NotFound(v2),
                            ) => assert_eq!(v1, v2),
                            _ => panic!("Error must be the same"),
                        }
                    }
                    _ => panic!("Both responses must be the same"),
                }
            }
            _ => panic!("Must not happen"),
        }

        let res = SiemCommandResponse::LIST_DATASETS(super::CommandResult::Ok(vec![
            DatasetDefinition::new(
                crate::prelude::SiemDatasetType::CustomIpMap(LogString::Borrowed("")),
                LogString::Borrowed("Description"),
                crate::prelude::UserRole::Administrator,
            ),
        ]));
        let str = serde_json::to_string(&res).unwrap();
        let res2: SiemCommandResponse = serde_json::from_str(&str).unwrap();

        match (res, res2) {
            (SiemCommandResponse::LIST_DATASETS(ip1), SiemCommandResponse::LIST_DATASETS(ip2)) => {
                match (ip1, ip2) {
                    (super::CommandResult::Ok(v1), super::CommandResult::Ok(v2)) => {
                        assert_eq!(v1, v2)
                    }
                    (super::CommandResult::Err(v1), super::CommandResult::Err(v2)) => {
                        match (v1, v2) {
                            (
                                super::CommandError::BadParameters(v1),
                                super::CommandError::BadParameters(v2),
                            ) => assert_eq!(v1, v2),
                            (
                                super::CommandError::SyntaxError(v1),
                                super::CommandError::SyntaxError(v2),
                            ) => assert_eq!(v1, v2),
                            (
                                super::CommandError::NotFound(v1),
                                super::CommandError::NotFound(v2),
                            ) => assert_eq!(v1, v2),
                            _ => panic!("Error must be the same"),
                        }
                    }
                    _ => panic!("Both responses must be the same"),
                }
            }
            _ => panic!("Must not happen"),
        }
    }
}