]>
git.ipfire.org Git - ipfire-2.x.git/blob - config/unbound/unbound-dhcp-leases-bridge
2 ###############################################################################
4 # IPFire.org - A linux based firewall #
5 # Copyright (C) 2016 Michael Tremer #
7 # This program is free software: you can redistribute it and/or modify #
8 # it under the terms of the GNU General Public License as published by #
9 # the Free Software Foundation, either version 3 of the License, or #
10 # (at your option) any later version. #
12 # This program is distributed in the hope that it will be useful, #
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
15 # GNU General Public License for more details. #
17 # You should have received a copy of the GNU General Public License #
18 # along with this program. If not, see <http://www.gnu.org/licenses/>. #
20 ###############################################################################
27 import logging
.handlers
32 import inotify
.adapters
36 def setup_logging(loglevel
=logging
.INFO
):
37 log
= logging
.getLogger("dhcp")
38 log
.setLevel(loglevel
)
40 handler
= logging
.handlers
.SysLogHandler(address
="/dev/log", facility
="daemon")
41 handler
.setLevel(loglevel
)
43 formatter
= logging
.Formatter("%(name)s[%(process)d]: %(message)s")
44 handler
.setFormatter(formatter
)
46 log
.addHandler(handler
)
50 log
= logging
.getLogger("dhcp")
52 def ip_address_to_reverse_pointer(address
):
53 parts
= address
.split(".")
56 return "%s.in-addr.arpa" % ".".join(parts
)
58 def reverse_pointer_to_ip_address(rr
):
61 # Only take IP address part
62 parts
= reversed(parts
[0:4])
64 return ".".join(parts
)
66 class UnboundDHCPLeasesBridge(object):
67 def __init__(self
, dhcp_leases_file
, fix_leases_file
, unbound_leases_file
, hosts_file
):
68 self
.leases_file
= dhcp_leases_file
69 self
.fix_leases_file
= fix_leases_file
70 self
.hosts_file
= hosts_file
72 self
.unbound
= UnboundConfigWriter(unbound_leases_file
)
76 log
.info("Unbound DHCP Leases Bridge started on %s" % self
.leases_file
)
80 self
.hosts
= self
.read_static_hosts()
81 self
.update_dhcp_leases()
83 i
= inotify
.adapters
.Inotify([
89 for event
in i
.event_gen():
90 # End if we are requested to terminate
97 header
, type_names
, watch_path
, filename
= event
99 # Update leases after leases file has been modified
100 if "IN_MODIFY" in type_names
:
102 if watch_path
== self
.hosts_file
:
103 self
.hosts
= self
.read_static_hosts()
105 self
.update_dhcp_leases()
107 # If the file is deleted, we re-add the watcher
108 if "IN_IGNORED" in type_names
:
109 i
.add_watch(watch_path
)
111 log
.info("Unbound DHCP Leases Bridge terminated")
113 def update_dhcp_leases(self
):
116 for lease
in DHCPLeases(self
.leases_file
):
117 # Don't bother with any leases that don't have a hostname
123 for lease
in FixLeases(self
.fix_leases_file
):
126 # Skip any leases that also are a static host
127 leases
= [l
for l
in leases
if not l
.fqdn
in self
.hosts
]
129 # Remove any inactive or expired leases
130 leases
= [l
for l
in leases
if l
.active
and not l
.expired
]
134 log
.debug("DHCP Leases:")
136 log
.debug(" %s:" % lease
.fqdn
)
137 log
.debug(" State: %s" % lease
.binding_state
)
138 log
.debug(" Start: %s" % lease
.time_starts
)
139 log
.debug(" End : %s" % lease
.time_ends
)
141 log
.debug(" Expired")
143 self
.unbound
.update_dhcp_leases(leases
)
145 def read_static_hosts(self
):
146 log
.info("Reading static hosts from %s" % self
.hosts_file
)
149 with
open(self
.hosts_file
) as f
:
150 for line
in f
.readlines():
154 enabled
, ipaddr
, hostname
, domainname
= line
.split(",")
156 log
.warning("Could not parse line: %s" % line
)
159 # Skip any disabled entries
160 if not enabled
== "on":
163 if hostname
and domainname
:
164 fqdn
= "%s.%s" % (hostname
, domainname
)
171 hosts
[fqdn
].append(ipaddr
)
174 hosts
[fqdn
] = [ipaddr
,]
176 # Dump everything in the logs
177 log
.debug("Static hosts:")
178 for hostname
, addresses
in hosts
.items():
179 log
.debug(" %-20s : %s" % (hostname
, ", ".join(addresses
)))
187 class DHCPLeases(object):
188 regex_leaseblock
= re
.compile(r
"lease (?P<ipaddr>\d+\.\d+\.\d+\.\d+) {(?P<config>[\s\S]+?)\n}")
190 def __init__(self
, path
):
193 self
._leases
= self
._parse
()
196 return iter(self
._leases
)
199 log
.info("Reading DHCP leases from %s" % self
.path
)
203 with
open(self
.path
) as f
:
204 # Read entire leases file
207 for match
in self
.regex_leaseblock
.finditer(data
):
208 block
= match
.groupdict()
210 ipaddr
= block
.get("ipaddr")
211 config
= block
.get("config")
213 properties
= self
._parse
_block
(config
)
215 # Skip any abandoned leases
216 if not "hardware" in properties
:
219 lease
= Lease(ipaddr
, properties
)
221 # Check if a lease for this Ethernet address already
222 # exists in the list of known leases. If so replace
223 # if with the most recent lease
224 for i
, l
in enumerate(leases
):
225 if l
.ipaddr
== lease
.ipaddr
:
226 leases
[i
] = max(lease
, l
)
234 def _parse_block(self
, block
):
237 for line
in block
.splitlines():
241 # Remove trailing ; from line
242 if line
.endswith(";"):
245 # Invalid line if it doesn't end with ;
249 # Remove any leading whitespace
252 # We skip all options and sets
253 if line
.startswith("option") or line
.startswith("set"):
256 # Split by first space
257 key
, val
= line
.split(" ", 1)
258 properties
[key
] = val
263 class FixLeases(object):
266 def __init__(self
, path
):
269 self
._leases
= self
.cache
[self
.path
] = self
._parse
()
272 return iter(self
._leases
)
275 log
.info("Reading fix leases from %s" % self
.path
)
278 now
= datetime
.datetime
.utcnow()
280 with
open(self
.path
) as f
:
281 for line
in f
.readlines():
285 hwaddr
, ipaddr
, enabled
, a
, b
, c
, hostname
= line
.split(",")
287 log
.warning("Could not parse line: %s" % line
)
290 # Skip any disabled leases
291 if not enabled
== "on":
295 "binding" : "state active",
296 "client-hostname" : hostname
,
297 "hardware" : "ethernet %s" % hwaddr
,
298 "starts" : now
.strftime("%w %Y/%m/%d %H:%M:%S"),
303 # Try finding any deleted leases
304 for lease
in self
.cache
.get(self
.path
, []):
308 # Free the deleted lease
316 def __init__(self
, ipaddr
, properties
):
318 self
._properties
= properties
321 return "<%s %s for %s (%s)>" % (self
.__class
__.__name
__,
322 self
.ipaddr
, self
.hwaddr
, self
.hostname
)
324 def __eq__(self
, other
):
325 return self
.ipaddr
== other
.ipaddr
and self
.hwaddr
== other
.hwaddr
327 def __gt__(self
, other
):
328 if not self
.ipaddr
== other
.ipaddr
:
331 if not self
.hwaddr
== other
.hwaddr
:
334 return self
.time_starts
> other
.time_starts
337 def binding_state(self
):
338 state
= self
._properties
.get("binding")
341 state
= state
.split(" ", 1)
345 self
._properties
.update({
346 "binding" : "state free",
351 return self
.binding_state
== "active"
355 hardware
= self
._properties
.get("hardware")
360 ethernet
, address
= hardware
.split(" ", 1)
366 hostname
= self
._properties
.get("client-hostname")
372 hostname
= hostname
.replace("\"", "")
374 # Only return valid hostnames
375 m
= re
.match(r
"^[A-Z0-9\-]{1,63}$", hostname
, re
.I
)
381 # Load ethernet settings
382 ethernet_settings
= self
.read_settings("/var/ipfire/ethernet/settings")
385 dhcp_settings
= self
.read_settings("/var/ipfire/dhcp/settings")
388 for zone
in ("GREEN", "BLUE"):
389 if not dhcp_settings
.get("ENABLE_%s" % zone
) == "on":
392 netaddr
= ethernet_settings
.get("%s_NETADDRESS" % zone
)
393 submask
= ethernet_settings
.get("%s_NETMASK" % zone
)
395 subnet
= ipaddress
.ip_network("%s/%s" % (netaddr
, submask
))
396 domain
= dhcp_settings
.get("DOMAIN_NAME_%s" % zone
)
398 subnets
[subnet
] = domain
400 address
= ipaddress
.ip_address(self
.ipaddr
)
402 for subnet
, domain
in subnets
.items():
403 if address
in subnet
:
406 # Fall back to localdomain if no match could be found
410 def read_settings(filename
):
413 with
open(filename
) as f
:
414 for line
in f
.readlines():
418 k
, v
= line
.split("=", 1)
426 return "%s.%s" % (self
.hostname
, self
.domain
)
430 return datetime
.datetime
.strptime(s
, "%w %Y/%m/%d %H:%M:%S")
433 def time_starts(self
):
434 starts
= self
._properties
.get("starts")
437 return self
._parse
_time
(starts
)
441 ends
= self
._properties
.get("ends")
443 if not ends
or ends
== "never":
446 return self
._parse
_time
(ends
)
450 if not self
.time_ends
:
451 return self
.time_starts
> datetime
.datetime
.utcnow()
453 return self
.time_starts
> datetime
.datetime
.utcnow() > self
.time_ends
457 # If the lease does not have a valid FQDN, we cannot create any RRs
458 if self
.fqdn
is None:
463 (self
.fqdn
, "%s" % LOCAL_TTL
, "IN A", self
.ipaddr
),
466 (ip_address_to_reverse_pointer(self
.ipaddr
), "%s" % LOCAL_TTL
,
467 "IN PTR", self
.fqdn
),
471 class UnboundConfigWriter(object):
472 def __init__(self
, path
):
475 self
._cached
_leases
= []
477 def update_dhcp_leases(self
, leases
):
478 # Find any leases that have expired or do not exist any more
479 # but are still in the unbound local data
480 removed_leases
= [l
for l
in self
._cached
_leases
if not l
in leases
]
482 # Find any leases that have been added
483 new_leases
= [l
for l
in leases
if l
not in self
._cached
_leases
]
485 # End here if nothing has changed
486 if not new_leases
and not removed_leases
:
489 # Write out all leases
490 self
.write_dhcp_leases(leases
)
492 # Update unbound about changes
493 for l
in removed_leases
:
495 for name
, ttl
, type, content
in l
.rrset
:
496 log
.debug("Removing records for %s" % name
)
497 self
._control
("local_data_remove", name
)
499 # If the lease cannot be removed we will try the next one
503 # If the removal was successful, we will remove it from the cache
505 self
._cached
_leases
.remove(l
)
510 log
.debug("Adding new record %s" % " ".join(rr
))
511 self
._control
("local_data", *rr
)
513 # If the lease cannot be added we will try the next one
517 # Add lease to cache when successfully added
519 self
._cached
_leases
.append(l
)
521 def write_dhcp_leases(self
, leases
):
522 with
open(self
.path
, "w") as f
:
525 f
.write("local-data: \"%s\"\n" % " ".join(rr
))
527 def _control(self
, *args
):
528 command
= ["unbound-control"]
532 subprocess
.check_output(command
)
535 except subprocess
.CalledProcessError
as e
:
536 log
.critical("Could not run %s, error code: %s: %s" % (
537 " ".join(command
), e
.returncode
, e
.output
))
542 if __name__
== "__main__":
543 parser
= argparse
.ArgumentParser(description
="Bridge for DHCP Leases and Unbound DNS")
546 parser
.add_argument("--daemon", "-d", action
="store_true",
547 help="Launch as daemon in background")
548 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
551 parser
.add_argument("--dhcp-leases", default
="/var/state/dhcp/dhcpd.leases",
552 metavar
="PATH", help="Path to the DHCPd leases file")
553 parser
.add_argument("--unbound-leases", default
="/etc/unbound/dhcp-leases.conf",
554 metavar
="PATH", help="Path to the unbound configuration file")
555 parser
.add_argument("--fix-leases", default
="/var/ipfire/dhcp/fixleases",
556 metavar
="PATH", help="Path to the fix leases file")
557 parser
.add_argument("--hosts", default
="/var/ipfire/main/hosts",
558 metavar
="PATH", help="Path to static hosts file")
560 # Parse command line arguments
561 args
= parser
.parse_args()
564 if args
.verbose
== 1:
565 loglevel
= logging
.INFO
566 elif args
.verbose
>= 2:
567 loglevel
= logging
.DEBUG
569 loglevel
= logging
.WARN
571 setup_logging(loglevel
)
573 bridge
= UnboundDHCPLeasesBridge(args
.dhcp_leases
, args
.fix_leases
,
574 args
.unbound_leases
, args
.hosts
)
576 ctx
= daemon
.DaemonContext(detach_process
=args
.daemon
)
578 signal
.SIGHUP
: bridge
.update_dhcp_leases
,
579 signal
.SIGTERM
: bridge
.terminate
,