
TL;DR
As cyberattacks grow in sophistication and frequency, proactive, efficient detection is critical. Security teams must sift through terabytes of logs to spot early indicators of compromise—work that rule-based systems can’t keep up with. Machine learning (ML) fills the gap.
For nearly two decades at organizations like Kaspersky, ML has been used to detect subtle, cross-dataset patterns and anomalies. Combining global threat telemetry (e.g., Kaspersky Security Network, KSN) with analyst expertise surfaces new IoCs and emerging vectors in near real time. This post explains how ML powers threat hunting across environments—from SMB to enterprise—including real-world examples and runnable code.
Security data spans endpoints, networks, and apps—often unstructured and huge. ML excels by:
Example: A Random Forest builds many decision trees and aggregates their votes for robust classification, improving accuracy and reducing overfitting vs. a single tree.
ML learns “normal” baselines from historical data to flag deviations:
Result: faster detection with fewer false positives so analysts focus on real threats.
Attackers evolve. ML models retrain on fresh data to keep pace. If malware slightly alters network behavior, a learned baseline can trigger alerts where static rules might fail.
Using KSN telemetry, ML improves detection accuracy and reduces time-to-detect—key to minimizing impact.
Collection
Preprocessing
Security data diversity (geos, industries, vendors) makes preprocessing pivotal.
Balance accuracy with interpretability so analysts trust and act on results.
Large infrastructures (e.g., KSN) distribute compute to meet throughput and latency targets.
Explainability builds trust and accelerates response.
Use on data you own or are authorized to test.
#!/bin/bash
# scan_logs.sh - quick grep-based anomaly prefilter
LOG_DIR="/var/log/cybersecurity_logs"
OUTPUT_FILE="anomalies_found.txt"
PATTERNS=("Failed password" "Invalid user" "unauthorized access" "error")
: > "$OUTPUT_FILE"
echo "Scanning log files in $LOG_DIR for potential anomalies..."
shopt -s nullglob
for logfile in "$LOG_DIR"/*.log; do
echo "Processing $logfile..."
for pattern in "${PATTERNS[@]}"; do
grep -i "$pattern" "$logfile" >> "$OUTPUT_FILE"
done
done
echo "Anomaly scanning completed. Results stored in $OUTPUT_FILE."
This prefilters suspicious lines for downstream ML analysis.
# ml_pipeline.py
import pandas as pd
from pathlib import Path
from sklearn.model_selection import train_test_split
from sklearn.ensemble import RandomForestClassifier
from sklearn.metrics import classification_report, confusion_matrix
import matplotlib.pyplot as plt
import seaborn as sns
# Load preprocessed CSV logs
log_file = Path("preprocessed_logs.csv")
data = pd.read_csv(log_file)
print("Dataset preview:")
print(data.head())
# Features & label (example columns)
features = data[['login_attempts', 'file_access_count', 'anomaly_score']]
target = data['label'] # 0 = normal, 1 = malicious
# Train/test split
X_train, X_test, y_train, y_test = train_test_split(
features, target, test_size=0.3, random_state=42, stratify=target
)
# Train Random Forest
model = RandomForestClassifier(n_estimators=200, random_state=42, n_jobs=-1)
model.fit(X_train, y_train)
# Predict & evaluate
pred = model.predict(X_test)
print("\nClassification Report:")
print(classification_report(y_test, pred, digits=4))
print("Confusion Matrix:")
cm = confusion_matrix(y_test, pred)
sns.heatmap(cm, annot=True, fmt='d', cmap='Blues')
plt.xlabel("Predicted"); plt.ylabel("Actual"); plt.title("Confusion Matrix")
plt.tight_layout(); plt.show()
# Feature importance
importances = pd.Series(model.feature_importances_, index=features.columns)
print("\nFeature Importances:")
print(importances.sort_values(ascending=False).round(4))
This script loads CSV logs, trains a Random Forest, evaluates performance, and prints feature importance—illustrating end-to-end ML application.
ML has transformed threat hunting by converting raw telemetry into actionable insights: higher accuracy, fewer false positives, and continuous adaptation. We covered the pipeline—preprocessing, training/validation, deployment, and explainability—with practical examples to get started.
Whether you’re building your first pipeline or tuning an enterprise system, combining ML with analyst expertise is the key to staying ahead of sophisticated adversaries.
Happy threat hunting!
If you found this content valuable, imagine what you could achieve with our comprehensive 47-week elite training program. Join 1,200+ students who've transformed their careers with Unit 8200 techniques.