pyruse/pyruse/actions/action_nftBan.py

40 lines
1.4 KiB
Python
Raw Normal View History

# pyruse is intended as a replacement to both fail2ban and epylog
# Copyright © 20172018 Y. Gablin
# Full licensing information in the LICENSE file, or gnu.org/licences/gpl-3.0.txt if the file is missing.
2017-12-15 19:36:50 +01:00
import os
import subprocess
2018-03-17 17:46:22 +01:00
from pyruse import ban, base, config
2017-12-15 19:36:50 +01:00
2018-03-17 17:46:22 +01:00
class Action(base.Action, ban.NetfilterBan):
2017-12-15 19:36:50 +01:00
_storage = config.Config().asMap().get("storage", "/var/lib/pyruse") \
+ "/" + os.path.basename(__file__) + ".json"
_nft = config.Config().asMap().get("nftBan", {}).get("nft", ["/usr/bin/nft"])
def __init__(self, args):
2018-03-17 17:46:22 +01:00
base.Action.__init__(self)
ban.NetfilterBan.__init__(self, Action._storage)
if args is None:
return # on-boot configuration
2018-03-17 17:46:22 +01:00
ipv4Set = args["nftSetIPv4"]
ipv6Set = args["nftSetIPv6"]
field = args["IP"]
banSeconds = args.get("banSeconds", None)
self.initSelf(ipv4Set, ipv6Set, field, banSeconds)
2017-12-15 19:36:50 +01:00
def act(self, entry):
2018-03-17 17:46:22 +01:00
ban.NetfilterBan.act(self, entry)
2017-12-15 19:36:50 +01:00
2018-03-17 17:46:22 +01:00
def setBan(self, nfSet, ip, seconds):
if seconds == 0:
2017-12-15 19:36:50 +01:00
timeout = ""
else:
timeout = " timeout %ss" % seconds
2017-12-15 19:36:50 +01:00
cmd = list(Action._nft)
2018-03-17 17:46:22 +01:00
cmd.append("add element %s {%s%s}" % (nfSet, ip, timeout))
subprocess.run(cmd)
def cancelBan(self, nfSet, ip):
cmd = list(Action._nft)
cmd.append("delete element %s {%s}" % (nfSet, ip))
2017-12-15 19:36:50 +01:00
subprocess.run(cmd)