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
use std::str::FromStr;
use std::fs::{self, File};
use std::io::{self, Read};
use std::path::Path;
use std::collections::HashMap;
use std::collections::btree_map::BTreeMap;
// default log path: /usr/local/zeek or /opt/zeek or custom/path/
// https://docs.zeek.org/en/master/quickstart.html#filesystem-walkthrough
#[derive(Debug, PartialEq, Eq)]
pub enum
PathError
{
NotFound,
PrefixUnspecified,
}
#[derive(Debug)]
pub enum
LogType
{
CONN,
DNS,
HTTP,
FILES,
FTP,
SSL,
X509,
SMTP,
SSH,
PE,
DHCP,
NTP,
SMB,
IRC,
RDP,
LDAP,
QUIC,
TRACEROUTE,
TUNNEL,
DPD,
KNOWN,
SOFTWARE,
WEIRD,
NOTICE,
CAPTURE_LOSS,
REPORTER,
SIP,
}
impl std::str::FromStr for LogType
{
type Err = String;
fn from_str(name: &str) -> Result<LogType, Self::Err>
{
match name
{
"conn" => Ok(LogType::CONN),
"dns" => Ok(LogType::DNS),
"http" => Ok(LogType::HTTP),
"files" => Ok(LogType::FILES),
"ftp" => Ok(LogType::FTP),
"ssl" => Ok(LogType::SSL),
"x509" => Ok(LogType::X509),
"smtp" => Ok(LogType::SMTP),
"ssh" => Ok(LogType::SSH),
"pe" => Ok(LogType::PE),
"dhcp" => Ok(LogType::DHCP),
"ntp" => Ok(LogType::NTP),
"smb" => Ok(LogType::SMB),
"irc" => Ok(LogType::IRC),
"rdp" => Ok(LogType::RDP),
"ldap" => Ok(LogType::LDAP),
"quic" => Ok(LogType::QUIC),
"traceroute" => Ok(LogType::TRACEROUTE),
"tunnel" => Ok(LogType::TUNNEL),
"dpd" => Ok(LogType::DPD),
"known" => Ok(LogType::KNOWN),
"software" => Ok(LogType::SOFTWARE),
"weird" => Ok(LogType::WEIRD),
"notice" => Ok(LogType::NOTICE),
"capture_loss" => Ok(LogType::CAPTURE_LOSS),
"reporter" => Ok(LogType::REPORTER),
"sip" => Ok(LogType::SIP),
_ => Err("LogType not found".to_string()),
}
}
}
#[derive(Debug)]
pub struct
SearchParams<'a>
{
pub log_type: Option<LogType>,
pub ip: Option<&'a str>,
pub time_range: Option<&'a str>, // todo
}
impl<'a> SearchParams<'a>
{
pub fn new() -> Self
{
SearchParams {
log_type: None,
ip: None,
time_range: None,
}
}
}
#[derive(Debug,Clone,PartialEq,Eq)]
pub struct
LogHeader
{
pub separator: char,
pub set_separator: String,
pub empty_field: String,
pub unset_field: String,
pub path: String, // could turn this into a list to store multiple dates
pub open: String,
// field and types may be better used as a tuple.
// todo: (field_type_tuple)
pub fields: Vec<String>,
pub types: Vec<String>,
}
impl LogHeader
{
pub fn new(p : &std::path::Path) -> Self
{
let output = std::process::Command::new("zcat")
.arg(&p)
.output()
.expect("failed to zcat the log file");
let log_header = output.stdout;
let mut pos : u8 = 0;
let mut separator : char = ' ';
let mut set_separator = String::new();
let mut empty_field = String::new();
let mut unset_field = String::new();
let mut path = String::new();
let mut open = String::new();
let mut fields = Vec::<String>::new(); //todo: (field_type_tuple)
let mut types = Vec::<String>::new();
match std::str::from_utf8(&log_header)
{
Ok(v) => {
let mut buffer = String::new();
for c in v.chars() {
if c == '\n' {
match pos
{
0 => {
let result = buffer.split(' ')
.collect::<Vec<&str>>()[1]
.strip_prefix("\\x");
let result = u8::from_str_radix(result.unwrap(), 16)
.expect("LOG_SEPARATER_CHAR: ");
separator = char::from(result);
}
1 => {
set_separator = buffer.split(separator).collect::<Vec<_>>()[1].to_string();
}
2 => {
empty_field = buffer.split(separator).collect::<Vec<_>>()[1].to_string();
}
3 => {
unset_field = buffer.split(separator).collect::<Vec<_>>()[1].to_string();
}
4 => {
path = buffer.split(separator).collect::<Vec<_>>()[1].to_string();
}
5 => {
open = buffer.split(separator).collect::<Vec<_>>()[1].to_string();
}
6 => {
let s = buffer.split(separator).collect::<Vec<_>>();
for i in 1..s.len()
{
fields.push(s[i].to_string());
}
}
7 => {
let s = buffer.split(separator).collect::<Vec<_>>();
for i in 1..s.len()
{
types.push(s[i].to_string());
}
}
_ => {break;}
}
buffer.clear();
pos += 1;
continue; // ignore the newline char.
}
buffer.push(c);
}
}
Err(e) => {
eprintln!("{}",e.valid_up_to());
}
}
LogHeader {
separator,
set_separator,
empty_field,
unset_field,
path,
open,
fields,
types,
}
}
pub fn get_types(&self) -> &Vec<String>
{
&self.types
}
pub fn get_fields(&self) -> &Vec<String>
{
&self.fields
}
}
#[derive(Debug, PartialEq, Eq)]
struct
LogData<'a>
{
header: &'a LogHeader,
data: HashMap<&'a str, Vec<&'a str>>,
}
impl<'a> LogData<'a>
{
fn new(h: &'a LogHeader) -> Self
{
let fields = h.get_fields();
let mut f = HashMap::<&'a str, Vec<&'a str>>::new();
for field in fields
{
f.insert(&field, Vec::<&'a str>::new());
}
LogData {header: h, data: f}
}
fn add_field_entry(&mut self, key: &'a str, val: &'a str)
{
self.data.entry(key).or_insert(Vec::new()).push(val);
}
}
#[derive(Debug, PartialEq, Eq)]
pub struct
LogDirectory<'a>
{
day: &'a str,
path_prefix: Option<&'a str>,
pub files: BTreeMap<String, LogData<'a>>,
}
impl<'a> LogDirectory<'a>
{
fn check_date_format(p: &'a Path) -> bool
{
// The default path of zeek logs on debian is /opt/zeek/logs.
// The user is responsible for specifying a valid directory path to
// reach the path/to/zeek/logs/YYYY-MM-DD directories.
// The log directory the user should expect is the format yyyy-mm-dd.
let val = &p.to_str();
if let Some(v) = val
{
let v : Vec<_> = v.split('/').collect();
let v : Vec<_> = v[v.len()-1].split('-').collect();
if v.len() != 3
{
return false
}
for i in 0..v.len()
{
let number = u16::from_str(v[i]);
if let Err(e) = number
{
return false
}
}
return true
}
false
}
// Initializes structure to search through logs using the path_prefix/ as the
// parent log directory.
pub fn new(p: Option<&'a Path>) -> Result<Self, PathError>
{
match p
{
None => {
// check whether the default paths exist
let opt_zeek = std::path::Path::new("/opt/zeek/");
let usr_local_zeek = std::path::Path::new("/usr/local/zeek/");
if opt_zeek.is_dir()
{
return Ok(LogDirectory {
day: "may not need this field",
path_prefix: opt_zeek.to_str(),
files: BTreeMap::new(),
})
}
if usr_local_zeek.is_dir()
{
return Ok(LogDirectory {
day: "may not need this field",
path_prefix: usr_local_zeek.to_str(),
files: BTreeMap::new(),
})
}
return Err(PathError::PrefixUnspecified)
}
Some(path) => {
// check if the user oversupplied a path, (e.g: /path_prefix/yyyy-mm-dd)
// where yyyy-mm-dd should not have been supplied.
let check = Self::check_date_format(path);
dbg!(check,path);
println!("");
let parent_log_dir = std::path::Path::new(path);
if parent_log_dir.is_dir()
{
return Ok(LogDirectory {
day: "may not need this field",
path_prefix: path.to_str(),
files: BTreeMap::new(),
})
}
return Err(PathError::NotFound)
}
}
}
pub fn find_by_day(&mut self, params: SearchParams) -> std::io::Result<()>
{
match self.path_prefix
{
Some(path) => {
match params.log_type
{
Some(t) => {
println!("{} {t:?}", line!());
}
None => {}
}
}
None => {
println!("{}:{} -- {:?}",file!(),line!(), self.path_prefix);
todo!();
}
}
Ok(())
}
}
// Will use for data hits
fn
increment<'a>(val: &'a mut u32)
{
*val += 1;
}
fn
print_val<'a>(val: &'a u32)
{
println!("print_val : val is {}",val);
}
#[cfg(feature = "ip2location")]
pub fn ip2location()
{
dbg!("log_analysis::ip2location()");
}