firewall/mac_ip.py

83 lines
2.3 KiB
Python
Raw Permalink Normal View History

2019-03-12 21:06:21 +00:00
#! /usr/bin/python3
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
2019-12-20 18:18:10 +00:00
# Copyright © 2018-2019 Hugo Levy-Falk <hugo@klafyvel.me>
2019-03-12 21:06:21 +00:00
"""
Creates the nat set.
"""
2019-05-06 21:30:37 +00:00
import os
2019-03-12 21:06:21 +00:00
import logging
from configparser import ConfigParser
from re2oapi import Re2oAPIClient
from firewall import NetfilterSet
2019-05-06 21:30:37 +00:00
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
2019-03-12 21:06:21 +00:00
CONFIG = ConfigParser()
2019-05-06 21:30:37 +00:00
CONFIG.read(os.path.join(BASE_DIR, 'config.ini'))
2019-03-12 21:06:21 +00:00
api_hostname = CONFIG.get('Re2o', 'hostname')
api_password = CONFIG.get('Re2o', 'password')
api_username = CONFIG.get('Re2o', 'username')
def gen_ip_mac_set():
"""Generates the ip_mac set in nftables.
Returns:
A NetfilterSet object with the allowed ip - mac pairs.
"""
2020-01-20 10:26:04 +00:00
api_client = Re2oAPIClient(api_hostname, api_username, api_password)
2019-03-12 21:06:21 +00:00
hosts = api_client.list('dhcp/hostmacip')
2020-01-22 22:13:08 +00:00
for h in hosts:
print(h)
2019-03-12 21:06:21 +00:00
content = [
(h['ipv4'], h['mac_address'])
for h in hosts
2020-01-22 22:13:08 +00:00
if 'ipv4' in h and h['ipv4'] and h['mac_address']
2019-03-12 21:06:21 +00:00
]
return NetfilterSet(
target_content=content,
type_=('IPv4', 'MAC'),
name='ip_mac',
table_name='firewall',
)
def update_macip():
log = logging.getLogger(__name__)
if not log.hasHandlers():
handler = logging.StreamHandler()
formatter = logging.Formatter(
"%(asctime)s %(levelname)s %(name)s %(message)s"
)
handler.setFormatter(formatter)
log.addHandler(handler)
log.setLevel(logging.INFO)
log.info('Updating the ip - mac set...')
ip_mac = gen_ip_mac_set()
log.info('Applying modifications...')
ip_mac.manage()
log.info('Done')
if __name__=='__main__':
update_macip()