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
use chrono::prelude::*;
use crossbeam_channel::TryRecvError;
use crossbeam_channel::{Receiver, Sender};
use std::borrow::Cow;
use std::boxed::Box;
use std::time::{Duration, Instant};
use usiem::components::common::{
CommandDefinition, SiemComponentCapabilities, SiemComponentStateStorage, SiemCommandCall,
SiemFunctionType, SiemMessage, UserRole,
};
use usiem::components::SiemComponent;
use usiem::events::field::SiemField;
use usiem::events::SiemLog;
#[derive(Clone)]
pub struct ElasticOuputConfig {
pub commit_max_messages: usize,
pub cache_size: usize,
pub commit_timeout: u64,
pub commit_time: u64,
pub elastic_address: String,
pub elastic_stream: String,
pub bearer_token : Option<String>,
}
pub struct ElasticSearchOutput {
comp_id : u64,
kernel_sender: Sender<SiemMessage>,
local_chnl_rcv: Receiver<SiemMessage>,
local_chnl_snd: Sender<SiemMessage>,
log_receiver: Receiver<SiemLog>,
conn: Option<Box<dyn SiemComponentStateStorage>>,
config: ElasticOuputConfig,
}
impl ElasticSearchOutput {
pub fn new(config: ElasticOuputConfig) -> ElasticSearchOutput {
let (kernel_sender, _receiver) = crossbeam_channel::bounded(1000);
let (local_chnl_snd, local_chnl_rcv) = crossbeam_channel::unbounded();
let (_sndr, log_receiver) = crossbeam_channel::unbounded();
return ElasticSearchOutput {
comp_id : 0,
kernel_sender,
local_chnl_rcv,
local_chnl_snd,
log_receiver,
config,
conn: None,
};
}
pub fn register_schema(&mut self) {
}
}
impl SiemComponent for ElasticSearchOutput {
fn name(&self) -> &str {
"ElasticSearchOutput"
}
fn local_channel(&self) -> Sender<SiemMessage> {
self.local_chnl_snd.clone()
}
fn set_log_channel(&mut self, _sender: Sender<SiemLog>, receiver: Receiver<SiemLog>) {
self.log_receiver = receiver;
}
fn set_kernel_sender(&mut self, sender: Sender<SiemMessage>) {
self.kernel_sender = sender;
}
fn run(&mut self) {
let receiver = self.local_chnl_rcv.clone();
let log_receiver = self.log_receiver.clone();
let client = reqwest::blocking::Client::new();
let config = &self.config;
let elastic_url = format!(
"{}/{}/_bulk",
&self.config.elastic_address[..],
&self.config.elastic_stream[..]
);
let max_commit = self.config.commit_max_messages;
let commit_time = Duration::from_millis(self.config.commit_time);
let mut log_cache = Vec::with_capacity(self.config.cache_size);
let mut last_commit = Instant::now();
loop {
loop {
let rcv_action = receiver.try_recv();
match rcv_action {
Ok(msg) => match msg {
SiemMessage::Command(_hdr,cmd) => match cmd {
SiemCommandCall::STOP_COMPONENT(_n) => return,
_ => {}
},
SiemMessage::Log(mut msg) => {
let time = format!("{:?}", Utc.timestamp_millis(msg.event_created()));
msg.add_field("@timestamp", SiemField::Text(Cow::Owned(time)));
log_cache.push(msg);
if log_cache.len() > max_commit || last_commit.elapsed() > commit_time {
break;
}
}
_ => {}
},
Err(e) => match e {
TryRecvError::Empty => {
break;
}
TryRecvError::Disconnected => {
std::thread::sleep(Duration::from_millis(10));
}
},
}
}
let mut log_count = 0;
if log_cache.len() < max_commit {
loop {
let rcv_action = log_receiver.try_recv();
match rcv_action {
Ok(mut msg) => {
let time = format!("{:?}", Utc.timestamp_millis(msg.event_created()));
msg.add_field("@timestamp", SiemField::Text(Cow::Owned(time)));
log_cache.push(msg);
if log_cache.len() > max_commit || last_commit.elapsed() > commit_time {
break;
}
}
Err(e) => {
match e {
TryRecvError::Empty => {
break;
}
TryRecvError::Disconnected => {
println!("Error???");
return;
}
}
}
}
if log_count >= config.commit_max_messages {
break;
}
log_count += 1;
}
}
let mut bulking: String = String::with_capacity(64_000);
let mut err_cache = 0;
for i in 0..max_commit {
let msg = log_cache.get(i);
match msg {
Some(msg) => {
err_cache = i;
let stringify = serde_json::to_string(&msg);
match stringify {
Ok(content) => {
let tmp = format!("{{\"create\":{{}}}}\n{}\n", content);
bulking.push_str(&tmp[..]);
}
Err(_) => {
}
}
}
None => {
break;
}
}
}
if err_cache > 0 {
bulking.push_str(&(format!("\n"))[..]);
let mut req = client.put(&elastic_url[..]).header("Content-Type", "application/json");
match &config.bearer_token {
Some(tkn) => {
req = req.header("Authorization", format!("Bearer {}", tkn));
},
None => {}
};
match req .body(bulking).send()
{
Ok(resp) => {
println!("PUT Logs");
println!("{:?}", resp.text().unwrap());
log_cache.drain(0..err_cache);
last_commit = Instant::now();
}
Err(err) => {
println!("{:?}", err);
}
}
}
}
}
fn set_storage(&mut self, conn: Box<dyn SiemComponentStateStorage>) {
self.conn = Some(conn);
}
fn capabilities(&self) -> SiemComponentCapabilities {
let datasets = Vec::new();
let mut commands = Vec::new();
let stop_component = CommandDefinition::new(SiemFunctionType::STOP_COMPONENT,Cow::Borrowed("Stop ElasticSearch Output") ,Cow::Borrowed("This allows stopping all ElasticSearch components.\nUse only when really needed, like mantaining ElasticSearch.") , UserRole::Administrator);
commands.push(stop_component);
let start_component = CommandDefinition::new(
SiemFunctionType::START_COMPONENT,
Cow::Borrowed("Start ElasticSearch Output"),
Cow::Borrowed("This allows sending logs to ElasticSearch."),
UserRole::Administrator,
);
commands.push(start_component);
SiemComponentCapabilities::new(
Cow::Borrowed("ElasticSearchOutput"),
Cow::Borrowed("Send logs to elasticsearch"),
Cow::Borrowed(""),
datasets,
commands,
vec![]
)
}
fn set_id(&mut self, id: u64) {
self.comp_id = id;
}
fn duplicate(&self) -> Box<dyn SiemComponent> {
let mut comp = ElasticSearchOutput::new(self.config.clone());
comp.kernel_sender = self.kernel_sender.clone();
comp.log_receiver = self.log_receiver.clone();
comp.conn = self.conn.clone();
Box::from(comp)
}
fn set_datasets(&mut self, _datasets : Vec<usiem::components::dataset::SiemDataset>) {
}
}