Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Deprecate f2bdiscord mod #965

Merged
merged 1 commit into from
Oct 10, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# F2B Discord Notification - Docker mod which allows Fail2Ban Discord embeds

>[!WARNING]
>This mod is deprecated

<details>

This mod enhances the swag container adding better Fail2Ban notifications for discord.

## Configuration
Expand Down Expand Up @@ -36,3 +41,5 @@ Action arguments:
## Example

![Example picture](.assets/Example.png)

<details/>
102 changes: 11 additions & 91 deletions root/AwesomeFolder/Fail2Ban.py
Original file line number Diff line number Diff line change
@@ -1,98 +1,18 @@
#!/usr/bin/env python3
import argparse
import collections
import datetime
import geoip2.database
import os
import requests

class Discord:
def __init__(self, data, action):
self.action = action
self.base = "https://discordapp.com/api/webhooks/"
self.data = data
self.token = os.getenv('DISC_HOOK', "") # If not setting enviroment variables, edit this
self.you = os.getenv('DISC_ME', "120970603556503552") # If not setting enviroment variables, edit this
base = "https://discordapp.com/api/webhooks/"
token = os.getenv('DISC_HOOK', False)
you = os.getenv('DISC_ME', False)

def create_payload(self):
webhook = {
"username":"Fail2Ban",
"content": f"<@{self.you}>",
"embeds": [{}]
}
webhook["embeds"][0]["author"] = {"name": "Fail2Ban"}
webhook["embeds"][0]["timestamp"] = f"{datetime.datetime.utcnow()}"
if "ban" in self.action.action:
webhook["embeds"][0]["url"] = f"https://db-ip.com/{self.data['ip']}"
webhook["embeds"][0]["image"] = {"url": f"{self.data['map-img']}"}
webhook["embeds"][0]["fields"] = [{}]
webhook["embeds"][0]["fields"][0]["name"] = f":flag_{self.data['iso'].lower()}:"
webhook["embeds"][0]["fields"][0]["value"] = self.data["city"] or self.data["name"]
if self.action.action == "ban":
webhook["embeds"][0]["fields"].append({"name": f"Map", "value": f"[Link]({self.data['map-url']})"})
webhook["embeds"][0]["fields"].append({"name": f"Unban cmd", "value": f"fail2ban-client unban {self.data['ip']}"})
webhook["embeds"][0]["title"] = f"New ban on `{self.action.jail}`"
webhook["embeds"][0]["description"] = f"**{self.data['ip']}** got banned for `{self.action.time}` hours after `{self.action.fail}` tries"
webhook["embeds"][0]["color"] = 16194076
elif self.action.action == "unban":
webhook["embeds"][0]["title"] = f"Revoked ban on `{self.action.jail}`"
webhook["embeds"][0]["description"] = f"**{self.data['ip']}** is now unbanned"
webhook["embeds"][0]["color"] = 845872
elif self.action.action == "start":
webhook["content"] = ""
webhook["embeds"][0]["description"] = f"Started `{self.action.jail}`"
webhook["embeds"][0]["color"] = 845872
elif self.action.action == "stopped":
webhook["content"] = ""
webhook["embeds"][0]["description"] = f"Stopped `{self.action.jail}`"
webhook["embeds"][0]["color"] = 16194076
elif self.action.action == "test":
webhook["content"] = ""
webhook["embeds"][0]["description"] = f"I am working"
webhook["embeds"][0]["color"] = 845872
else:
return None
return webhook
content = f"<@{you}> "
message = "The fail2ban to discord mod is deprecated. Please remove it from your container"

def send(self, payload):
r = requests.post(url=f"{self.base}{self.token}", json=payload)
webhook = {
"username":"Fail2Ban",
"content": content + message if you else message
}

class Helpers:
def __init__(self, ip):
self.data = {"ip": ip}
self.map_api = os.getenv('DISC_API', "") # If not setting enviroment variables, edit this
self.reader = geoip2.database.Reader('/config/geoip2db/GeoLite2-City.mmdb')
self.f2b()
self.map()
if token:
requests.post(url=f"{base}{token}", json=webhook)

def f2b(self):
r = self.reader.city(self.data['ip'])
self.data["iso"] = r.country.iso_code
self.data["name"] = r.country.name
self.data["city"] = r.city.name
self.data["lat"] = r.location.latitude
self.data["lon"] = r.location.longitude


def map(self):
img_params={"center":f"{self.data['lat']},{self.data['lon']}", "size":"500,300", "key": self.map_api}
img_r = requests.get('https://www.mapquestapi.com/staticmap/v5/map', params=img_params)
self.data["map-img"] = img_r.url
url_params={"center":f"{self.data['lat']},{self.data['lon']}", "size":"500,300"}
url_r = requests.get('https://mapquest.com/', params=url_params)
self.data["map-url"] = url_r.url

if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Discord notifier for F2B')
parser.add_argument('-a', '--action', help="Which F2B action triggered the script", required=True)
parser.add_argument('-i', '--ip', help="ip which triggered the action", default="8.8.8.8")
parser.add_argument('-j', '--jail', help="jail which triggered the action")
parser.add_argument('-t', '--time', help="The time the action is valid")
parser.add_argument('-f', '--fail', help="Amount of attempts done")

args = parser.parse_args()

data = Helpers(args.ip).data if "ban" in args.action else {}
disc = Discord(data, args)
if (payload := disc.create_payload()):
disc.send(payload)
Original file line number Diff line number Diff line change
@@ -1,20 +1,24 @@
#!/usr/bin/with-contenv bash
echo "_ _ _ "
echo "| | | |"
echo "| | | | The f2b to discord mod is deprecated"
echo "|_|_|_|"
echo "(_|_|_)"


if ! pip list 2>&1 | grep -q "geoip2"; then
if ! pip list 2>&1 | grep -q "requests"; then
echo '------------------------------------------------------------------------'
echo '| Adding required modules for swag-f2bdiscord to package install list'
echo '| Adding required modules for swag-f2bdiscord deprecation message'
echo '------------------------------------------------------------------------'
echo "\
requests \
argparse \
geoip2==3.0.0" >> /mod-pip-packages-to-install.list
echo "requests" >> /mod-pip-packages-to-install.list
fi

if [ ! -f /config/fail2ban/Fail2Ban.py.orig ] && [ -f /config/fail2ban/Fail2Ban.py ]; then
mv /config/fail2ban/Fail2Ban.py /config/fail2ban/Fail2Ban.py.orig
fi

if [ ! -f /config/fail2ban/Fail2Ban.py ]; then
cp /AwesomeFolder/Fail2Ban.py /config/fail2ban/
chmod +x /config/fail2ban/Fail2Ban.py
fi

if [ ! -f /config/fail2ban/action.d/discordEmbed.conf ]; then
cp /AwesomeFolder/discordEmbed.conf /config/fail2ban/action.d
fi