DDoS detection and remediation with Akvorado and Flowspec

Vincent Bernat

Akvo­rado col­lects sFlow and IPFIX flows, stores them in a Click­House data­base, and presents them in a web con­sole. Al­though it lacks built-in DDoS de­tec­tion, it’s pos­si­ble to cre­ate one by craft­ing cus­tom Click­House queries.

DDoS detection#

Let’s as­sume we want to de­tect DDoS tar­get­ing our cus­tomers. As an ex­am­ple, we con­sider a DDoS at­tack as a col­lec­tion of flows over one minute tar­get­ing a sin­gle cus­tomer IP ad­dress, from a sin­gle source port and match­ing one of these con­ditions:

  • an av­er­age band­width of 1 Gbps,
  • an av­er­age band­width of 200 Mbps when the pro­to­col is UDP,
  • more than 20 source IP ad­dresses and an av­er­age band­width of 100 Mbps, or
  • more than 10 source coun­tries and an av­er­age band­width of 100 Mbps.

Here is the SQL query to de­tect such at­tacks over the last 5 minutes:

SELECT *
FROM (
  SELECT
    toStartOfMinute(TimeReceived) AS TimeReceived,
    DstAddr,
    SrcPort,
    dictGetOrDefault('protocols', 'name', Proto, '???') AS Proto,
    SUM(((((Bytes * SamplingRate) * 8) / 1000) / 1000) / 1000) / 60 AS Gbps,
    uniq(SrcAddr) AS sources,
    uniq(SrcCountry) AS countries
  FROM flows
  WHERE TimeReceived > now() - INTERVAL 5 MINUTE
    AND DstNetRole = 'customers'
  GROUP BY
    TimeReceived,
    DstAddr,
    SrcPort,
    Proto
)
WHERE (Gbps > 1)
   OR ((Proto = 'UDP') AND (Gbps > 0.2)) 
   OR ((sources > 20) AND (Gbps > 0.1)) 
   OR ((countries > 10) AND (Gbps > 0.1))
ORDER BY
  TimeReceived DESC,
  Gbps DESC

Here is an ex­am­ple out­put1 where two of our users are un­der at­tack. One from what looks like an NTP am­pli­fi­ca­tion at­tack, the other from a DNS am­pli­fi­ca­tion attack:

TimeReceived DstAddr SrcPort Proto Gbps sources countries
2023-02-26 17:44:00 ::ffff:​203.0.113.206 123 UDP 0.102 109 13
2023-02-26 17:43:00 ::ffff:​203.0.113.206 123 UDP 0.130 133 17
2023-02-26 17:43:00 ::ffff:​203.0.113.68 53 UDP 0.129 364 63
2023-02-26 17:43:00 ::ffff:​203.0.113.206 123 UDP 0.113 129 21
2023-02-26 17:42:00 ::ffff:​203.0.113.206 123 UDP 0.139 50 14
2023-02-26 17:42:00 ::ffff:​203.0.113.206 123 UDP 0.105 42 14
2023-02-26 17:40:00 ::ffff:​203.0.113.68 53 UDP 0.121 340 65

DDoS remediation#

Once de­tected, there are at least two ways to stop the at­tack at the net­work level:

  • black­hole the traf­fic to the tar­geted user (RTBH), or
  • se­lec­tively drop pack­ets match­ing the at­tack pat­terns (Flowspec).

Traffic blackhole#

The eas­i­est method is to sac­ri­fice the at­tacked user. While this helps the at­tacker, this pro­tects your net­work. It is a method sup­ported by all routers. You can also off­load this pro­tec­tion to many tran­sit providers. This is use­ful if the at­tack vol­ume ex­ceeds your in­ter­net capacity.

This works by ad­ver­tis­ing with BGP a route to the at­tacked user with a spe­cific com­mu­nity. The bor­der router mod­i­fies the next hop ad­dress of these routes to a spe­cific IP ad­dress con­fig­ured to for­ward the traf­fic to a null in­ter­face. RFC 7999 de­fines 65535:666 for this pur­pose. This is known as a “re­mote-trig­gered black­hole” (RTBH) and is ex­plained in more de­tail in RFC 3882.

It is also pos­si­ble to black­hole the source of the at­tacks by lever­ag­ing uni­cast Re­verse Path For­ward­ing (uRPF) from RFC 3704, as ex­plained in RFC 5635. How­ever, uRPF can be a se­ri­ous tax on your router re­sources. See “NCS5500 uRPF: Con­fig­u­ra­tion and Im­pact on Scale” for an ex­am­ple of the kind of re­stric­tions you have to ex­pect when en­abling uRPF.

On the ad­ver­tis­ing side, we can use BIRD. Here is a com­plete con­fig­u­ra­tion file to al­low any router to col­lect them:

log stderr all;
router id 192.0.2.1;

protocol device {
  scan time 10;
}

protocol bgp exporter {
  ipv4 {
    import none;
    export where proto = "blackhole4";
  };
  ipv6 {
    import none;
    export where proto = "blackhole6";
  };
  local as 64666;
  neighbor range 192.0.2.0/24 external;
  multihop;
  dynamic name "exporter";
  dynamic name digits 2;
  graceful restart yes;
  graceful restart time 0;
  long lived graceful restart yes;
  long lived stale time 3600;  # keep routes for 1 hour!
}

protocol static blackhole4 {
  ipv4;
  route 203.0.113.206/32 blackhole {
    bgp_community.add((65535, 666));
  };
  route 203.0.113.68/32 blackhole {
    bgp_community.add((65535, 666));
  };
}
protocol static blackhole6 {
  ipv6;
}

We use BGP long-lived grace­ful restart to en­sure routes are kept for one hour, even if the BGP con­nec­tion goes down, no­tably dur­ing main­tenance.

On the re­ceiver side, if you have a Cisco router run­ning IOS XR, you can use the fol­low­ing con­fig­u­ra­tion to black­hole traf­fic re­ceived on the BGP ses­sion. As the BGP ses­sion is ded­i­cated to this us­age, the com­mu­nity is not used, but you can also for­ward these routes to your tran­sit providers.

router static
 vrf public
  address-family ipv4 unicast
   192.0.2.1/32 Null0 description "BGP blackhole"
  !
  address-family ipv6 unicast
   2001:db8::1/128 Null0 description "BGP blackhole"
  !
 !
!
route-policy blackhole_ipv4_in_public
  if destination in (0.0.0.0/0 le 31) then
    drop
  endif
  set next-hop 192.0.2.1
  done
end-policy
!
route-policy blackhole_ipv6_in_public
  if destination in (::/0 le 127) then
    drop
  endif
  set next-hop 2001:db8::1
  done
end-policy
!
router bgp 12322
 neighbor-group BLACKHOLE_IPV4_PUBLIC
  remote-as 64666
  ebgp-multihop 255
  update-source Loopback10
  address-family ipv4 unicast
   maximum-prefix 100 90
   route-policy blackhole_ipv4_in_public in
   route-policy drop out
   long-lived-graceful-restart stale-time send 86400 accept 86400
  !
  address-family ipv6 unicast
   maximum-prefix 100 90
   route-policy blackhole_ipv6_in_public in
   route-policy drop out
   long-lived-graceful-restart stale-time send 86400 accept 86400
  !
 !
 vrf public
  neighbor 192.0.2.1
   use neighbor-group BLACKHOLE_IPV4_PUBLIC
   description akvorado-1

When the traf­fic is black­holed, it is still re­ported by IPFIX and sFlow. In Akvo­rado, use ForwardingStatus >= 128 as a filter.

While this method is com­pat­i­ble with all routers, it makes the at­tack suc­cess­ful as the tar­get is com­pletely un­reach­able. If your router sup­ports it, Flowspec can se­lec­tively fil­ter flows to stop the at­tack with­out im­pact­ing the customer.

Flowspec#

Flowspec is de­fined in RFC 8955 and en­ables the trans­mis­sion of flow spec­i­fi­ca­tions in BGP ses­sions. A flow spec­i­fi­ca­tion is a set of match­ing cri­te­ria to ap­ply to IP traf­fic. These cri­te­ria in­clude the source and des­ti­na­tion pre­fix, the IP pro­to­col, the source and des­ti­na­tion port, and the packet length. Each flow spec­i­fi­ca­tion is as­so­ci­ated with an ac­tion, en­coded as an ex­tended com­mu­nity: traf­fic shap­ing, traf­fic mark­ing, or re­di­rection.

To an­nounce flow spec­i­fi­ca­tions with BIRD, we ex­tend our con­fig­u­ra­tion. The ex­tended com­mu­nity used shapes the match­ing traf­fic to 0 byte per second.

flow4 table flowtab4;
flow6 table flowtab6;

protocol bgp exporter {
  flow4 {
    import none;
    export where proto = "flowspec4";
  };
  flow6 {
    import none;
    export where proto = "flowspec6";
  };
  # […]
}

protocol static flowspec4 {
  flow4;
  route flow4 {
    dst 203.0.113.68/32;
    sport = 53;
    length >= 1476 && <= 1500;
    proto = 17;
  }{
    bgp_ext_community.add((generic, 0x80060000, 0x00000000));
  };
  route flow4 {
    dst 203.0.113.206/32;
    sport = 123;
    length = 468;
    proto = 17;
  }{
    bgp_ext_community.add((generic, 0x80060000, 0x00000000));
  };
}
protocol static flowspec6 {
  flow6;
}

If you have a Cisco router run­ning IOS XR, the con­fig­u­ra­tion may look like this:

vrf public
 address-family ipv4 flowspec
 address-family ipv6 flowspec
!
router bgp 12322
 address-family vpnv4 flowspec
 address-family vpnv6 flowspec
 neighbor-group FLOWSPEC_IPV4_PUBLIC
  remote-as 64666
  ebgp-multihop 255
  update-source Loopback10
  address-family ipv4 flowspec
   long-lived-graceful-restart stale-time send 86400 accept 86400
   route-policy accept in
   route-policy drop out
   maximum-prefix 100 90
   validation disable
  !
  address-family ipv6 flowspec
   long-lived-graceful-restart stale-time send 86400 accept 86400
   route-policy accept in
   route-policy drop out
   maximum-prefix 100 90
   validation disable
  !
 !
 vrf public
  address-family ipv4 flowspec
  address-family ipv6 flowspec
  neighbor 192.0.2.1
   use neighbor-group FLOWSPEC_IPV4_PUBLIC
   description akvorado-1

Then, you need to en­able Flowspec on all in­ter­faces with:

flowspec
 vrf public
  address-family ipv4
   local-install interface-all
  !
  address-family ipv6
   local-install interface-all
  !
 !
!

As with the RTBH setup, you can fil­ter dropped flows with ForwardingStatus >= 128.

DDoS detection (continued)#

In the ex­am­ple us­ing Flowspec, the flows were also fil­tered on the length of the packet:

route flow4 {
  dst 203.0.113.68/32;
  sport = 53;
  length >= 1476 && <= 1500;
  proto = 17;
}{
  bgp_ext_community.add((generic, 0x80060000, 0x00000000));
};

This is an im­por­tant ad­di­tion: le­git­i­mate DNS re­quests are smaller than this and there­fore not fil­tered.2 With Click­House, you can get the 10th and 90th per­centiles of the packet sizes with quantiles(0.1, 0.9)(Bytes/​Packets).

The last is­sue we need to tackle is how to op­ti­mize the re­quest: it may need sev­eral sec­onds to col­lect the data and it is likely to con­sume sub­stan­tial re­sources from your Click­House data­base. One so­lu­tion is to cre­ate a ma­te­ri­al­ized view to pre-ag­gre­gate results:

CREATE TABLE ddos_logs (
  TimeReceived DateTime,
  DstAddr IPv6,
  Proto UInt32,
  SrcPort UInt16,
  Gbps SimpleAggregateFunction(sum, Float64),
  Mpps SimpleAggregateFunction(sum, Float64),
  sources AggregateFunction(uniqCombined(12), IPv6),
  countries AggregateFunction(uniqCombined(12), FixedString(2)),
  size AggregateFunction(quantiles(0.1, 0.9), UInt64)
) ENGINE = SummingMergeTree
PARTITION BY toStartOfHour(TimeReceived)
ORDER BY (TimeReceived, DstAddr, Proto, SrcPort)
TTL toStartOfHour(TimeReceived) + INTERVAL 6 HOUR DELETE ;

CREATE MATERIALIZED VIEW ddos_logs_view TO ddos_logs AS
  SELECT
    toStartOfMinute(TimeReceived) AS TimeReceived,
    DstAddr,
    Proto,
    SrcPort,
    sum(((((Bytes * SamplingRate) * 8) / 1000) / 1000) / 1000) / 60 AS Gbps,
    sum(((Packets * SamplingRate) / 1000) / 1000) / 60 AS Mpps,
    uniqCombinedState(12)(SrcAddr) AS sources,
    uniqCombinedState(12)(SrcCountry) AS countries,
    quantilesState(0.1, 0.9)(toUInt64(Bytes/Packets)) AS size
  FROM flows
  WHERE DstNetRole = 'customers'
  GROUP BY
    TimeReceived,
    DstAddr,
    Proto,
    SrcPort

The ddos_​logs ta­ble is us­ing the SummingMergeTree en­gine. When the ta­ble re­ceives new data, Click­House re­places all the rows with the same sort­ing key, as de­fined by the ORDER BY di­rec­tive, with one row which con­tains sum­ma­rized val­ues us­ing ei­ther the sum() func­tion or the ex­plic­itly spec­i­fied ag­gre­gate func­tion (uniqCombined and quantiles in our ex­ample).3

Fi­nally, we can mod­ify our ini­tial query with the fol­lowing one:

SELECT *
FROM (
  SELECT
    TimeReceived,
    DstAddr,
    dictGetOrDefault('protocols', 'name', Proto, '???') AS Proto,
    SrcPort,
    sum(Gbps) AS Gbps,
    sum(Mpps) AS Mpps,
    uniqCombinedMerge(12)(sources) AS sources,
    uniqCombinedMerge(12)(countries) AS countries,
    quantilesMerge(0.1, 0.9)(size) AS size
  FROM ddos_logs
  WHERE TimeReceived > now() - INTERVAL 60 MINUTE
  GROUP BY
    TimeReceived,
    DstAddr,
    Proto,
    SrcPort
)
WHERE (Gbps > 1)
   OR ((Proto = 'UDP') AND (Gbps > 0.2)) 
   OR ((sources > 20) AND (Gbps > 0.1)) 
   OR ((countries > 10) AND (Gbps > 0.1))
ORDER BY
  TimeReceived DESC,
  Gbps DESC

Gluing everything together#

To sum up, build­ing an anti-DDoS sys­tem re­quires fol­low­ing these steps:

  1. de­fine a set of cri­te­ria to de­tect a DDoS attack,
  2. trans­late these cri­te­ria into SQL requests,
  3. pre-ag­gre­gate flows into SummingMergeTree tables,
  4. query and trans­form the re­sults to a BIRD con­fig­u­ra­tion file, and
  5. con­fig­ure your routers to pull the routes from BIRD.

A Python script like the fol­low­ing one can han­dle the fourth step. For each at­tacked tar­get, it gen­er­ates both a Flowspec rule and a black­hole route.

import socket
import types
from clickhouse_driver import Client as CHClient

# Put your SQL query here!
SQL_QUERY = "…"

# How many anti-DDoS rules we want at the same time?
MAX_DDOS_RULES = 20

def empty_ruleset():
    ruleset = types.SimpleNamespace()
    ruleset.flowspec = types.SimpleNamespace()
    ruleset.blackhole = types.SimpleNamespace()
    ruleset.flowspec.v4 = []
    ruleset.flowspec.v6 = []
    ruleset.blackhole.v4 = []
    ruleset.blackhole.v6 = []
    return ruleset

current_ruleset = empty_ruleset()

client = CHClient(host="clickhouse.akvorado.net")
while True:
    results = client.execute(SQL_QUERY)
    seen = {}
    new_ruleset = empty_ruleset()
    for (t, addr, proto, port, gbps, mpps, sources, countries, size) in results:
        if (addr, proto, port) in seen:
            continue
        seen[(addr, proto, port)] = True

        # Flowspec
        if addr.ipv4_mapped:
            address = addr.ipv4_mapped
            rules = new_ruleset.flowspec.v4
            table = "flow4"
            mask = 32
            nh = "proto"
        else:
            address = addr
            rules = new_ruleset.flowspec.v6
            table = "flow6"
            mask = 128
            nh = "next header"
        if size[0] == size[1]:
            length = f"length = {int(size[0])}"
        else:
            length = f"length >= {int(size[0])} && <= {int(size[1])}"
        header = f"""
# Time: {t}
# Source: {address}, protocol: {proto}, port: {port}
# Gbps/Mpps: {gbps:.3}/{mpps:.3}, packet size: {int(size[0])}<=X<={int(size[1])}
# Flows: {flows}, sources: {sources}, countries: {countries}
"""
        rules.append(
                f"""{header}
route {table} {{
  dst {address}/{mask};
  sport = {port};
  {length};
  {nh} = {socket.getprotobyname(proto)};
}}{{
  bgp_ext_community.add((generic, 0x80060000, 0x00000000));
}};
"""
        )

        # Blackhole
        if addr.ipv4_mapped:
            rules = new_ruleset.blackhole.v4
        else:
            rules = new_ruleset.blackhole.v6
        rules.append(
            f"""{header}
route {address}/{mask} blackhole {{
  bgp_community.add((65535, 666));
}};
"""
        )

        new_ruleset.flowspec.v4 = list(
            set(new_ruleset.flowspec.v4[:MAX_DDOS_RULES])
        )
        new_ruleset.flowspec.v6 = list(
            set(new_ruleset.flowspec.v6[:MAX_DDOS_RULES])
        )

        # TODO: advertise changes by mail, chat, ...

        current_ruleset = new_ruleset
        changes = False
        for rules, path in (
            (current_ruleset.flowspec.v4, "v4-flowspec"),
            (current_ruleset.flowspec.v6, "v6-flowspec"),
            (current_ruleset.blackhole.v4, "v4-blackhole"),
            (current_ruleset.blackhole.v6, "v6-blackhole"),
        ):
            path = os.path.join("/etc/bird/", f"{path}.conf")
            with open(f"{path}.tmp", "w") as f:
                for r in rules:
                    f.write(r)
            changes = (
                changes or not os.path.exists(path) or not samefile(path, f"{path}.tmp")
            )
            os.rename(f"{path}.tmp", path)

        if not changes:
            continue

        proc = subprocess.Popen(
            ["birdc", "configure"],
            stdin=subprocess.DEVNULL,
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE,
        )
        stdout, stderr = proc.communicate(None)
        stdout = stdout.decode("utf-8", "replace")
        stderr = stderr.decode("utf-8", "replace")
        if proc.returncode != 0:
            logger.error(
                "{} error:\n{}\n{}".format(
                    "birdc reconfigure",
                    "\n".join(
                        [" O: {}".format(line) for line in stdout.rstrip().split("\n")]
                    ),
                    "\n".join(
                        [" E: {}".format(line) for line in stderr.rstrip().split("\n")]
                    ),
                )
            )

Un­til Akvo­rado in­te­grates DDoS de­tec­tion and mit­i­ga­tion, the ideas pre­sented in this blog post pro­vide a solid foun­da­tion to get started with your own anti-DDoS system. 🛡️