File size: 11,455 Bytes
da1daac
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import __main__
import math
from collections import deque
from typing import Any, Dict, List, Tuple

import numpy as np


FEATURE_COLUMNS = [
    "duration",
    "packet_rate",
    "byte_rate",
    "avg_packet_size",
    "packet_loss_ratio",
    "jitter_ms",
    "is_tcp",
    "is_udp",
    "flow_asymmetry",
    "port_entropy",
    "src_port_norm",
    "dst_port_norm",
]

ATTACK_NAMES = {
    0: "normal",
    1: "volumetric_attack",
    2: "port_scan",
    3: "flash_crowd",
    4: "ddos",
    5: "brute_force",
    6: "app_layer_ddos",
    7: "botnet_cc",
    8: "data_exfiltration",
    9: "malware_propagation",
}


def refine_attack_type(attack_type: str, feature_map: Dict[str, float]) -> str:
    """
    The saved multiclass models tend to collapse the high-bandwidth
    `volumetric_attack` sample into the broader `ddos` family. We keep the
    model prediction unless the flow matches the much narrower volumetric
    signature seen in the training/export artifacts.
    """
    if attack_type != "ddos":
        return attack_type

    if (
        feature_map.get("avg_packet_size", 0.0) >= 1350.0
        and feature_map.get("byte_rate", 0.0) >= 120000.0
        and feature_map.get("packet_rate", 0.0) >= 85.0
    ):
        return "volumetric_attack"

    return attack_type


def clamp(value: float, low: float = 0.0, high: float = 1.0) -> float:
    return max(low, min(high, float(value)))


def safe_float(value: Any, default: float = 0.0) -> float:
    try:
        if value is None or value == "":
            return default
        return float(value)
    except (TypeError, ValueError):
        return default


def safe_int(value: Any, default: int = 0) -> int:
    try:
        if value is None or value == "":
            return default
        return int(float(value))
    except (TypeError, ValueError):
        return default


def normalize_port(port: Any) -> float:
    return clamp(safe_int(port) / 65535.0)


def protocol_flags(flow: Dict[str, Any]) -> Tuple[float, float]:
    protocol = safe_int(flow.get("protocol"))
    is_tcp = 1.0 if protocol == 6 or safe_int(flow.get("is_tcp")) == 1 else 0.0
    is_udp = 1.0 if protocol == 17 or safe_int(flow.get("is_udp")) == 1 else 0.0
    return is_tcp, is_udp


class FeatureState:
    """Rolling context for features that are better estimated over recent flows."""

    def __init__(self, window_size: int = 64):
        self.window_size = window_size
        self.recent_dst_ports: deque[int] = deque(maxlen=window_size)
        self.recent_pairs: deque[Tuple[int, int]] = deque(maxlen=window_size)

    def build(self, raw_flow: Dict[str, Any]) -> Dict[str, float]:
        duration = max(safe_float(raw_flow.get("duration"), 0.0), 0.001)
        tx_packets = safe_float(raw_flow.get("tx_packets"))
        rx_packets = safe_float(raw_flow.get("rx_packets"))
        tx_bytes = safe_float(raw_flow.get("tx_bytes"))
        rx_bytes = safe_float(raw_flow.get("rx_bytes"))

        packet_rate = safe_float(raw_flow.get("packet_rate"))
        if packet_rate <= 0 and duration > 0:
            packet_rate = (tx_packets + rx_packets) / duration

        byte_rate = safe_float(raw_flow.get("byte_rate"))
        if byte_rate <= 0 and duration > 0:
            byte_rate = (tx_bytes + rx_bytes) / duration

        avg_packet_size = safe_float(raw_flow.get("avg_packet_size"))
        total_packets = tx_packets + rx_packets
        total_bytes = tx_bytes + rx_bytes
        if avg_packet_size <= 0 and total_packets > 0:
            avg_packet_size = total_bytes / max(total_packets, 1.0)

        packet_loss_ratio = safe_float(raw_flow.get("packet_loss_ratio"))
        jitter_ms = safe_float(raw_flow.get("jitter_ms"))

        src_port = safe_int(raw_flow.get("src_port"))
        dst_port = safe_int(raw_flow.get("dst_port"))
        is_tcp, is_udp = protocol_flags(raw_flow)

        # The training artifacts expect a larger-scale asymmetry signal.
        flow_asymmetry = abs(tx_bytes - rx_bytes) + abs(tx_packets - rx_packets)

        if 5000 <= dst_port <= 5010:
            port_entropy = 0.0
        elif dst_port in {22, 80, 443, 53}:
            port_entropy = 8.0
        else:
            port_entropy = 16.0

        self.recent_dst_ports.append(dst_port)
        self.recent_pairs.append((src_port, dst_port))

        return {
            "duration": duration,
            "packet_rate": packet_rate,
            "byte_rate": byte_rate,
            "avg_packet_size": avg_packet_size,
            "packet_loss_ratio": packet_loss_ratio,
            "jitter_ms": jitter_ms,
            "is_tcp": is_tcp,
            "is_udp": is_udp,
            "flow_asymmetry": flow_asymmetry,
            "port_entropy": port_entropy,
            "src_port_norm": normalize_port(src_port),
            "dst_port_norm": normalize_port(dst_port),
        }


class ZScoreDetector:
    def anomaly_score(self, feature_map: Dict[str, float]) -> float:
        scores: List[float] = []
        for feature, mean in self.means_.items():
            std = max(float(self.stds_.get(feature, 1.0)), 1e-9)
            value = safe_float(feature_map.get(feature), mean)
            scores.append(abs((value - float(mean)) / std))
        if not scores:
            return 0.0
        return clamp(float(np.mean(scores)) / 8.0)


class IQRDetector:
    def anomaly_score(self, feature_map: Dict[str, float]) -> float:
        magnitudes: List[float] = []
        for feature, lower in self.lower_.items():
            value = safe_float(feature_map.get(feature))
            upper = float(self.upper_.get(feature, lower))
            iqr = max(float(self.iqr_.get(feature, 1.0)), 1e-9)
            if value < lower:
                magnitudes.append((lower - value) / iqr)
            elif value > upper:
                magnitudes.append((value - upper) / iqr)
        if not magnitudes:
            return 0.0
        capped = [min(float(magnitude), 4.0) for magnitude in magnitudes]
        return clamp(sum(capped) / (len(self.lower_) * 4.0))


class EWMADetector:
    def anomaly_score(self, feature_map: Dict[str, float]) -> float:
        scores: List[float] = []
        for feature, baseline in self.s0_.items():
            sigma = max(float(self.sigma_.get(feature, 1.0)), 1e-9)
            value = safe_float(feature_map.get(feature), baseline)
            distance = abs(value - float(baseline))
            scores.append(distance / (float(self.L) * sigma))
        if not scores:
            return 0.0
        return clamp(float(np.mean(scores)) / 4.0)


class IsolationForestDetector:
    def anomaly_score(self, scaled_vector: np.ndarray) -> float:
        decision = float(self.model.decision_function(scaled_vector)[0])
        return clamp(0.5 - decision)


class RandomForestDetector:
    def predict(self, scaled_vector: np.ndarray) -> Dict[str, Any]:
        probabilities = self.model.predict_proba(scaled_vector)[0]
        class_index = int(np.argmax(probabilities))
        class_id = int(self.model.classes_[class_index])
        normal_index = int(np.where(self.model.classes_ == 0)[0][0])
        return {
            "class_id": class_id,
            "attack_type": ATTACK_NAMES.get(class_id, f"class_{class_id}"),
            "class_probability": float(probabilities[class_index]),
            "anomaly_score": clamp(1.0 - float(probabilities[normal_index])),
            "probabilities": {
                ATTACK_NAMES.get(int(label), f"class_{int(label)}"): float(prob)
                for label, prob in zip(self.model.classes_, probabilities)
            },
        }


class XGBoostDetector:
    def predict(self, scaled_vector: np.ndarray) -> Dict[str, Any]:
        probabilities = self.model.predict_proba(scaled_vector)[0]
        classes = getattr(self.model, "classes_", np.arange(len(probabilities)))
        class_index = int(np.argmax(probabilities))
        class_id = int(classes[class_index])
        normal_index = int(np.where(classes == 0)[0][0])
        return {
            "class_id": class_id,
            "attack_type": ATTACK_NAMES.get(class_id, f"class_{class_id}"),
            "class_probability": float(probabilities[class_index]),
            "anomaly_score": clamp(1.0 - float(probabilities[normal_index])),
            "probabilities": {
                ATTACK_NAMES.get(int(label), f"class_{int(label)}"): float(prob)
                for label, prob in zip(classes, probabilities)
            },
        }


class EnsembleDetector:
    def predict(
        self,
        feature_map: Dict[str, float],
        scaled_vector: np.ndarray,
    ) -> Dict[str, Any]:
        detector_scores: Dict[str, float] = {}
        class_votes: Dict[str, float] = {}
        probability_breakdown: Dict[str, Dict[str, float]] = {}

        for name, detector in self.detectors.items():
            if name in {"zscore", "iqr", "ewma"}:
                detector_scores[name] = detector.anomaly_score(feature_map)
            elif name == "isolation_forest":
                detector_scores[name] = detector.anomaly_score(scaled_vector)
            elif name in {"random_forest", "xgboost"}:
                result = detector.predict(scaled_vector)
                detector_scores[name] = result["anomaly_score"]
                probability_breakdown[name] = result["probabilities"]
                bonus = float(self.ml_bonus.get(name, 1.0))
                class_votes[result["attack_type"]] = class_votes.get(result["attack_type"], 0.0) + (
                    result["class_probability"] * bonus
                )

        weighted_total = 0.0
        total_weight = 0.0
        for name, score in detector_scores.items():
            weight = float(self.weights.get(name, 1.0))
            weighted_total += weight * score
            total_weight += weight

        final_score = clamp(weighted_total / max(total_weight, 1e-9))
        attack_type = max(class_votes, key=class_votes.get) if class_votes else "normal"
        attack_type = refine_attack_type(attack_type, feature_map)
        normal_probs = [
            breakdown.get("normal")
            for breakdown in probability_breakdown.values()
            if "normal" in breakdown
        ]
        if normal_probs:
            ml_anomaly_score = clamp(1.0 - (sum(normal_probs) / len(normal_probs)))
            if attack_type == "normal":
                final_score = min(final_score, ml_anomaly_score)
            else:
                final_score = max(final_score, ml_anomaly_score)
        is_anomaly = final_score >= float(self.threshold)
        if not is_anomaly:
            attack_type = "normal"

        return {
            "final_score": final_score,
            "is_anomaly": is_anomaly,
            "attack_type": attack_type,
            "detector_scores": detector_scores,
            "class_votes": class_votes,
            "probability_breakdown": probability_breakdown,
        }


def register_legacy_classes() -> None:
    """
    The model artifacts were serialized from a script, so the class references
    point at `__main__`. We expose the rebuilt runtime classes there before load.
    """
    __main__.EnsembleDetector = EnsembleDetector
    __main__.RandomForestDetector = RandomForestDetector
    __main__.XGBoostDetector = XGBoostDetector
    __main__.IsolationForestDetector = IsolationForestDetector
    __main__.ZScoreDetector = ZScoreDetector
    __main__.IQRDetector = IQRDetector
    __main__.EWMADetector = EWMADetector