OVH mitigation to Discord notifier

Sadly, it's a common fact of life that some people have little better to do than try and ruin other peoples fun. An example of this, an old friend of mine asked me to throw up and configure some Linux servers for him. After a while I noticed some unusual behaviour on one of them, turned out to be a DDOS.

Thankfully, OVH have some decent anti-DDOS mitigation measures. They also provide a powerful API. Since the attacks were coming frequently I decided to setup a script to notify me if a server went into mitigation.

The first step I took was to figure out which endpoints I would require. It's a large API but we only need two, /ip and /ip/*/mitigation/*.

Next, read the API credentials from a toml file and call the /ip endpoint to retrieve the ips we want to check. I decided to use the python ipaddress package to check ip format, since the /ip/{ip}/mitigation/{ip} endpoint returns ipv6 addresses as well as ipv4.

import tomllib
import ovh

def _conn_from_toml():
    ...

def main():
    conn = _conn_from_toml()
    client = ovh.Client(
        **conn["ovh"],
    )

    ips = list(
        filter(
            lambda ip: ipaddress.ip_address(ip).version == 4,
            [ip.split("/")[0] for ip in client.get("/ip")],
        )
    )

if __name__ == "__main__":
    main()

Then we need our function that runs the mitigation check.

import ipaddress
...

mitigation_list = []

def check_ips_in_mitigation(webhook_url, client, ips):
    for ip in ips:
            try:
                _ = client.get(f"/ip/{ip}/mitigation/{ip}")

                if ip not in mitigation_list:
                    mitigation_list.append(ip)
            except ovh.exceptions.ResourceNotFoundError:
                if ip in mitigation_list:
                    mitigation_list.remove(ip)

Finally a function to send the discord notification:

from discord_webhook import DiscordWebhook
...

def send_webhook_message(webhook_url, msg):
    webhook = DiscordWebhook(
        url=webhook_url, username="ovh-servers-mitigation", content=msg
    )
    webhook.execute()

Check this gist for a complete version of the code.

Further notes: