You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于机器学习检测DDoS后如何在Ryu控制器中实现攻击流量丢弃

Ryu控制器DDoS攻击流量丢弃实现指导

现有代码问题定位

你当前的代码仅完成了DDoS攻击检测逻辑,缺少下发丢弃流表的核心步骤,且存在两处逻辑缺陷:

  • 预测结果遍历逻辑错误:直接用预测值i作为索引取数据集行,无法正确获取攻击流的匹配字段
  • 无主动向交换机下发高优先级丢弃流表的逻辑,检测到攻击后没有对应的流量处置动作

实现步骤

步骤1:新增丢弃流表下发函数

在你的SimpleMonitor13类中添加如下专用函数,用于向交换机下发高优先级丢弃流表:

def add_drop_flow(self, datapath, ip_src, ip_dst, ip_proto, tp_src=None, tp_dst=None, idle_timeout=300, hard_timeout=1800):
    ofproto = datapath.ofproto
    parser = datapath.ofproto_parser

    # 构造流表匹配项
    match = parser.OFPMatch(
        eth_type=0x0800,
        ipv4_src=ip_src,
        ipv4_dst=ip_dst,
        ip_proto=ip_proto
    )
    # 补充传输层端口匹配规则
    if ip_proto == 6 and tp_src and tp_dst:
        match.set_tcp_src(int(tp_src))
        match.set_tcp_dst(int(tp_dst))
    elif ip_proto == 17 and tp_src and tp_dst:
        match.set_udp_src(int(tp_src))
        match.set_udp_dst(int(tp_dst))

    # 空动作即为丢弃流量
    actions = []
    inst = [parser.OFPInstructionActions(ofproto.OFPIT_APPLY_ACTIONS, actions)]
    # 流表优先级设为100,高于你现有正常转发流表的优先级1,确保优先匹配
    flow_mod = parser.OFPFlowMod(
        datapath=datapath,
        priority=100,
        match=match,
        instructions=inst,
        idle_timeout=idle_timeout,
        hard_timeout=hard_timeout,
        cookie=0xdeadbeef,
        command=ofproto.OFPFC_ADD
    )
    datapath.send_msg(flow_mod)
    self.logger.info(f"下发丢弃流表:{ip_src}:{tp_src} -> {ip_dst}:{tp_dst} 协议:{ip_proto}")

步骤2:修正预测逻辑,集成流表下发

替换你flow_predict函数中遍历预测结果的代码段:
原错误代码:

for i in y_flow_pred:
    if i == 0:
        legitimate_trafic = legitimate_trafic + 1
    else:
        ddos_trafic = ddos_trafic + 1
        victim = int(predict_flow_dataset.iloc[i, 5]) % 20

替换为:

for idx, pred in enumerate(y_flow_pred):
    if pred == 0:
        legitimate_trafic += 1
    else:
        ddos_trafic += 1
        # 提取攻击流完整匹配字段
        flow_row = predict_flow_dataset.iloc[idx]
        dp_id = flow_row['datapath_id']
        if dp_id in self.datapaths:
            self.add_drop_flow(
                datapath = self.datapaths[dp_id],
                ip_src = flow_row['ip_src'],
                ip_dst = flow_row['ip_dst'],
                ip_proto = flow_row['ip_proto'],
                tp_src = flow_row['tp_src'],
                tp_dst = flow_row['tp_dst']
            )
# 统一计算受害主机
if ddos_trafic > 0:
    victim = int(predict_flow_dataset.iloc[y_flow_pred == 1, 5].values[0].replace('.', '')) % 20

步骤3:可选优化

  • 可以将_monitor函数中的hub.sleep(5)调整为更小的值(比如1),降低检测到攻击后的处置延迟
  • 去掉flow_predict中的空except块,添加异常日志打印,方便排查问题
  • 可以定期清理过期的丢弃流表,避免交换机流表溢出

内容的提问来源于stack exchange,提问作者Estrella Brillante

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 22:00:01