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
use anyhow::{anyhow, Result};
use elasticsearch::{
auth::Credentials,
cat::CatIndicesParts,
cert::CertificateValidation,
http::{
transport::{SingleNodeConnectionPool, TransportBuilder},
Url,
},
indices::IndicesCreateParts,
Elasticsearch,
};
use serde_json::{json, Value};
use crate::es4forensics::{Protocol, index::Index};
pub struct IndexBuilder {
host: Option<String>,
port: Option<u16>,
protocol: Protocol,
index_name: String,
do_certificate_validation: bool,
credentials: Option<Credentials>,
}
const DEFAULT_HOST: &str = "localhost";
const DEFAULT_PORT: u16 = 9200;
pub trait WithHost<T> {
fn with_host(self, host: T) -> Self;
}
impl IndexBuilder {
pub fn with_name(index_name: String) -> Self {
Self {
host: None,
port: None,
protocol: Protocol::default(),
index_name,
do_certificate_validation: true,
credentials: None,
}
}
pub fn with_port(mut self, port: u16) -> Self {
self.port = Some(port);
self
}
pub fn with_protocol(mut self, protocol: Protocol) -> Self {
self.protocol = protocol;
self
}
pub fn without_certificate_validation(mut self) -> Self {
self.do_certificate_validation = false;
self
}
pub fn with_credentials(mut self, credentials: Credentials) -> Self {
self.credentials = Some(credentials);
self
}
pub fn host(&self) -> &str {
match self.host.as_ref() {
Some(h) => h,
None => DEFAULT_HOST,
}
}
pub fn port(&self) -> u16 {
match self.port.as_ref() {
Some(p) => *p,
None => DEFAULT_PORT,
}
}
pub async fn index_exists(&self) -> Result<bool> {
let client = self.create_client()?;
self.client_has_index(&client).await
}
pub async fn connect(self) -> Result<Index> {
let client = self.create_client()?;
Ok(Index::new(self.index_name, client))
}
pub async fn create_index(&self) -> Result<Index> {
let client = self.create_client()?;
if !self.client_has_index(&client).await? {
log::info!("create index with mappings");
let index_body = json!({
"mappings": {
"properties": {
"@timestamp": {
"type": "date",
"format": "epoch_millis"
},
"tags": {
"type": "keyword"
},
"file": {
"properties": {
"accessed": {
"type": "date",
"format": "epoch_millis"
},
"created": {
"type": "date",
"format": "epoch_millis"
},
"ctime": {
"type": "date",
"format": "epoch_millis"
},
"mtime": {
"type": "date",
"format": "epoch_millis"
},
"macb_short": {
"type": "keyword"
},
"macb_long": {
"type": "keyword"
}
}
}
}
}
});
let parts = IndicesCreateParts::Index(&self.index_name);
let response = client
.indices()
.create(parts)
.body(index_body)
.send()
.await?;
match response.error_for_status_code_ref() {
Ok(_response) => (),
Err(why) => {
log::error!(
"Error while creating index: {}",
response.text().await?
);
log::error!("error message was: {}", why);
return Err(anyhow!(why))
}
}
//let pipeline_id = format!("{}_pipeline", self.index_name());
//self.create_pipeline(&client, &pipeline_id).await?;
}
Ok(Index::new(self.index_name.clone(), client))
}
/*
async fn create_pipeline(&self, client: &Elasticsearch, pipeline_id: &str) -> Result<()> {
let pipeline_parts = IngestPutPipelineParts::Id(pipeline_id);
let set_timestamp = json!({
"description": "Creates a timestamp when a document is initially indexed",
"processors": [
{
"set": {
"field": "timestamp",
"value": "{{{_ingest.timestamp}}}"
}
}
]
});
let ingest_response = client
.ingest()
.put_pipeline(pipeline_parts)
.body(set_timestamp)
.send()
.await?;
match ingest_response.error_for_status_code_ref() {
Err(why) => {
log::error!(
"Error while creating pipeline: {}",
ingest_response.text().await?
);
log::error!("error message was: {}", why);
Err(anyhow!(why))
}
Ok(_response) => {
log::info!("sucessfully created pipeline {pipeline_id}");
Ok(())
}
}
}
*/
fn create_client(&self) -> Result<Elasticsearch> {
let url = Url::parse(&format!("{}://{}:{}", self.protocol, self.host(), self.port()))?;
let conn_pool = SingleNodeConnectionPool::new(url);
let mut transport_builder = TransportBuilder::new(conn_pool)
.cert_validation(if self.do_certificate_validation {
CertificateValidation::Default
} else {
CertificateValidation::None
})
.disable_proxy();
if let Some(credentials) = &self.credentials {
transport_builder = transport_builder.auth(credentials.clone());
}
let transport = transport_builder.build()?;
Ok(Elasticsearch::new(transport))
}
async fn client_has_index(&self, client: &Elasticsearch) -> Result<bool> {
log::info!("test if index '{}' exists", self.index_name);
let response = client
.cat()
.indices(CatIndicesParts::Index(&["*"]))
.format("json")
.send()
.await?;
response.error_for_status_code_ref()?;
if response.content_length().unwrap_or(0) == 0 {
log::debug!("empty result; index does not seem to exist");
Ok(false)
} else {
let response_body = response.json::<Value>().await?;
match response_body.as_array() {
None => {
log::debug!("index does not exist");
Ok(false)
}
Some(body) => Ok(body
.iter()
.any(|r| *r["index"].as_str().unwrap() == self.index_name)),
}
}
}
}
impl WithHost<String> for IndexBuilder {
fn with_host(mut self, host: String) -> Self {
self.host = Some(host);
self
}
}
impl WithHost<&str> for IndexBuilder {
fn with_host(mut self, host: &str) -> Self {
self.host = Some(host.to_owned());
self
}
}