]>
git.ipfire.org Git - people/mfischer/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
37 import inotify
.adapters
41 log
= logging
.getLogger("dhcp")
42 log
.setLevel(logging
.DEBUG
)
44 def setup_logging(daemon
=True, loglevel
=logging
.INFO
):
45 log
.setLevel(loglevel
)
47 # Log to syslog by default
48 handler
= logging
.handlers
.SysLogHandler(address
="/dev/log", facility
="daemon")
49 log
.addHandler(handler
)
52 formatter
= logging
.Formatter("%(name)s[%(process)d]: %(message)s")
53 handler
.setFormatter(formatter
)
55 handler
.setLevel(loglevel
)
57 # If we are running in foreground, we should write everything to the console, too
59 handler
= logging
.StreamHandler()
60 log
.addHandler(handler
)
62 handler
.setLevel(loglevel
)
66 def ip_address_to_reverse_pointer(address
):
67 parts
= address
.split(".")
70 return "%s.in-addr.arpa" % ".".join(parts
)
72 def reverse_pointer_to_ip_address(rr
):
75 # Only take IP address part
76 parts
= reversed(parts
[0:4])
78 return ".".join(parts
)
80 class UnboundDHCPLeasesBridge(object):
81 def __init__(self
, dhcp_leases_file
, fix_leases_file
, unbound_leases_file
, hosts_file
):
82 self
.leases_file
= dhcp_leases_file
83 self
.fix_leases_file
= fix_leases_file
84 self
.hosts_file
= hosts_file
87 self
.leases_file
: inotify
.constants
.IN_MODIFY
,
88 self
.fix_leases_file
: 0,
92 self
.unbound
= UnboundConfigWriter(unbound_leases_file
)
96 log
.info("Unbound DHCP Leases Bridge started on %s" % self
.leases_file
)
99 i
= inotify
.adapters
.Inotify()
101 # Add watches for the directories of every relevant file
102 for f
, mask
in self
.watches
.items():
105 mask | inotify
.constants
.IN_CLOSE_WRITE | inotify
.constants
.IN_MOVED_TO
,
108 # Enabled so that we update hosts and leases on startup
109 update_hosts
= update_leases
= True
112 log
.debug("Wakeup of main loop")
114 # Process the entire inotify queue and identify what we need to do
115 for event
in i
.event_gen():
121 header
, type_names
, path
, filename
= event
123 file = os
.path
.join(path
, filename
)
125 log
.debug("inotify event received for %s: %s", file, " ".join(type_names
))
127 # Did the hosts file change?
128 if self
.hosts_file
== file:
131 # We will need to update the leases on any change
134 # Update hosts (if needed)
136 self
.hosts
= self
.read_static_hosts()
138 # Update leases (if needed)
140 self
.update_dhcp_leases()
143 update_hosts
= update_leases
= False
145 # Wait a moment before we start the next iteration
148 log
.info("Unbound DHCP Leases Bridge terminated")
150 def update_dhcp_leases(self
):
153 for lease
in DHCPLeases(self
.leases_file
):
154 # Don't bother with any leases that don't have a hostname
160 for lease
in FixLeases(self
.fix_leases_file
):
163 # Skip any leases that also are a static host
164 leases
= [l
for l
in leases
if not l
.fqdn
in self
.hosts
]
166 # Remove any inactive or expired leases
167 leases
= [l
for l
in leases
if l
.active
and not l
.expired
]
171 log
.debug("DHCP Leases:")
173 log
.debug(" %s:" % lease
.fqdn
)
174 log
.debug(" State: %s" % lease
.binding_state
)
175 log
.debug(" Start: %s" % lease
.time_starts
)
176 log
.debug(" End : %s" % lease
.time_ends
)
178 log
.debug(" Expired")
180 self
.unbound
.update_dhcp_leases(leases
)
182 def read_static_hosts(self
):
183 log
.info("Reading static hosts from %s" % self
.hosts_file
)
186 with
open(self
.hosts_file
) as f
:
187 for line
in f
.readlines():
191 enabled
, ipaddr
, hostname
, domainname
, generateptr
= line
.split(",")
193 log
.warning("Could not parse line: %s" % line
)
196 # Skip any disabled entries
197 if not enabled
== "on":
200 if hostname
and domainname
:
201 fqdn
= "%s.%s" % (hostname
, domainname
)
208 hosts
[fqdn
].append(ipaddr
)
211 hosts
[fqdn
] = [ipaddr
,]
213 # Dump everything in the logs
214 log
.debug("Static hosts:")
216 log
.debug(" %-20s : %s" % (name
, ", ".join(hosts
[name
])))
224 class DHCPLeases(object):
225 regex_leaseblock
= re
.compile(r
"lease (?P<ipaddr>\d+\.\d+\.\d+\.\d+) {(?P<config>[\s\S]+?)\n}")
227 def __init__(self
, path
):
230 self
._leases
= self
._parse
()
233 return iter(self
._leases
)
236 log
.info("Reading DHCP leases from %s" % self
.path
)
240 with
open(self
.path
) as f
:
241 # Read entire leases file
244 for match
in self
.regex_leaseblock
.finditer(data
):
245 block
= match
.groupdict()
247 ipaddr
= block
.get("ipaddr")
248 config
= block
.get("config")
250 properties
= self
._parse
_block
(config
)
252 # Skip any abandoned leases
253 if not "hardware" in properties
:
256 lease
= Lease(ipaddr
, properties
)
258 # Check if a lease for this Ethernet address already
259 # exists in the list of known leases. If so replace
260 # if with the most recent lease
261 for i
, l
in enumerate(leases
):
262 if l
.ipaddr
== lease
.ipaddr
:
263 leases
[i
] = max(lease
, l
)
271 def _parse_block(self
, block
):
274 for line
in block
.splitlines():
278 # Remove trailing ; from line
279 if line
.endswith(";"):
282 # Invalid line if it doesn't end with ;
286 # Remove any leading whitespace
289 # We skip all options and sets
290 if line
.startswith("option") or line
.startswith("set"):
293 # Split by first space
294 key
, val
= line
.split(" ", 1)
295 properties
[key
] = val
300 class FixLeases(object):
303 def __init__(self
, path
):
306 self
._leases
= self
.cache
[self
.path
] = self
._parse
()
309 return iter(self
._leases
)
312 log
.info("Reading fix leases from %s" % self
.path
)
315 now
= datetime
.datetime
.utcnow()
317 with
open(self
.path
) as f
:
318 for line
in f
.readlines():
322 hwaddr
, ipaddr
, enabled
, a
, b
, c
, hostname
= line
.split(",")
324 log
.warning("Could not parse line: %s" % line
)
327 # Skip any disabled leases
328 if not enabled
== "on":
332 "binding" : "state active",
333 "client-hostname" : hostname
,
334 "hardware" : "ethernet %s" % hwaddr
,
335 "starts" : now
.strftime("%w %Y/%m/%d %H:%M:%S"),
340 # Try finding any deleted leases
341 for lease
in self
.cache
.get(self
.path
, []):
345 # Free the deleted lease
353 def __init__(self
, ipaddr
, properties
):
355 self
._properties
= properties
358 return "<%s %s for %s (%s)>" % (self
.__class
__.__name
__,
359 self
.ipaddr
, self
.hwaddr
, self
.hostname
)
361 def __eq__(self
, other
):
362 return self
.ipaddr
== other
.ipaddr
and self
.hwaddr
== other
.hwaddr
364 def __gt__(self
, other
):
365 if not self
.ipaddr
== other
.ipaddr
:
368 if not self
.hwaddr
== other
.hwaddr
:
371 return self
.time_starts
> other
.time_starts
374 def binding_state(self
):
375 state
= self
._properties
.get("binding")
378 state
= state
.split(" ", 1)
382 self
._properties
.update({
383 "binding" : "state free",
388 return self
.binding_state
== "active"
392 hardware
= self
._properties
.get("hardware")
397 ethernet
, address
= hardware
.split(" ", 1)
403 hostname
= self
._properties
.get("client-hostname")
409 hostname
= hostname
.replace("\"", "")
411 # Only return valid hostnames
412 m
= re
.match(r
"^[A-Z0-9\-]{1,63}$", hostname
, re
.I
)
418 # Load ethernet settings
419 ethernet_settings
= self
.read_settings("/var/ipfire/ethernet/settings")
422 dhcp_settings
= self
.read_settings("/var/ipfire/dhcp/settings")
425 for zone
in ("GREEN", "BLUE"):
426 if not dhcp_settings
.get("ENABLE_%s" % zone
) == "on":
429 netaddr
= ethernet_settings
.get("%s_NETADDRESS" % zone
)
430 submask
= ethernet_settings
.get("%s_NETMASK" % zone
)
432 subnet
= ipaddress
.ip_network("%s/%s" % (netaddr
, submask
))
433 domain
= dhcp_settings
.get("DOMAIN_NAME_%s" % zone
)
435 subnets
[subnet
] = domain
437 address
= ipaddress
.ip_address(self
.ipaddr
)
439 for subnet
in subnets
:
440 if address
in subnet
:
441 return subnets
[subnet
]
443 # Fall back to localdomain if no match could be found
447 def read_settings(filename
):
450 with
open(filename
) as f
:
451 for line
in f
.readlines():
455 k
, v
= line
.split("=", 1)
463 return "%s.%s" % (self
.hostname
, self
.domain
)
467 return datetime
.datetime
.strptime(s
, "%w %Y/%m/%d %H:%M:%S")
470 def time_starts(self
):
471 starts
= self
._properties
.get("starts")
474 return self
._parse
_time
(starts
)
478 ends
= self
._properties
.get("ends")
480 if not ends
or ends
== "never":
483 return self
._parse
_time
(ends
)
487 if not self
.time_ends
:
488 return self
.time_starts
> datetime
.datetime
.utcnow()
490 return self
.time_starts
> datetime
.datetime
.utcnow() > self
.time_ends
494 # If the lease does not have a valid FQDN, we cannot create any RRs
495 if self
.fqdn
is None:
500 (self
.fqdn
, "%s" % LOCAL_TTL
, "IN A", self
.ipaddr
),
503 (ip_address_to_reverse_pointer(self
.ipaddr
), "%s" % LOCAL_TTL
,
504 "IN PTR", self
.fqdn
),
508 class UnboundConfigWriter(object):
509 def __init__(self
, path
):
512 self
._cached
_leases
= []
514 def update_dhcp_leases(self
, leases
):
515 # Find any leases that have expired or do not exist any more
516 # but are still in the unbound local data
517 removed_leases
= [l
for l
in self
._cached
_leases
if not l
in leases
]
519 # Find any leases that have been added
520 new_leases
= [l
for l
in leases
if l
not in self
._cached
_leases
]
522 # End here if nothing has changed
523 if not new_leases
and not removed_leases
:
526 # Write out all leases
527 self
.write_dhcp_leases(leases
)
529 # Update unbound about changes
530 for l
in removed_leases
:
532 for name
, ttl
, type, content
in l
.rrset
:
533 log
.debug("Removing records for %s" % name
)
534 self
._control
("local_data_remove", name
)
536 # If the lease cannot be removed we will try the next one
540 # If the removal was successful, we will remove it from the cache
542 self
._cached
_leases
.remove(l
)
547 log
.debug("Adding new record %s" % " ".join(rr
))
548 self
._control
("local_data", *rr
)
550 # If the lease cannot be added we will try the next one
554 # Add lease to cache when successfully added
556 self
._cached
_leases
.append(l
)
558 def write_dhcp_leases(self
, leases
):
559 with tempfile
.NamedTemporaryFile(mode
="w", delete
=False) as f
:
564 f
.write("local-data: \"%s\"\n" % " ".join(rr
))
566 # Make file readable for everyone
567 os
.fchmod(f
.fileno(), stat
.S_IRUSR|stat
.S_IWUSR|stat
.S_IRGRP|stat
.S_IROTH
)
569 os
.rename(filename
, self
.path
)
571 def _control(self
, *args
):
572 command
= ["unbound-control"]
576 subprocess
.check_output(command
)
579 except subprocess
.CalledProcessError
as e
:
580 log
.critical("Could not run %s, error code: %s: %s" % (
581 " ".join(command
), e
.returncode
, e
.output
))
586 if __name__
== "__main__":
587 parser
= argparse
.ArgumentParser(description
="Bridge for DHCP Leases and Unbound DNS")
590 parser
.add_argument("--daemon", "-d", action
="store_true",
591 help="Launch as daemon in background")
592 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
595 parser
.add_argument("--dhcp-leases", default
="/var/state/dhcp/dhcpd.leases",
596 metavar
="PATH", help="Path to the DHCPd leases file")
597 parser
.add_argument("--unbound-leases", default
="/etc/unbound/dhcp-leases.conf",
598 metavar
="PATH", help="Path to the unbound configuration file")
599 parser
.add_argument("--fix-leases", default
="/var/ipfire/dhcp/fixleases",
600 metavar
="PATH", help="Path to the fix leases file")
601 parser
.add_argument("--hosts", default
="/var/ipfire/main/hosts",
602 metavar
="PATH", help="Path to static hosts file")
604 # Parse command line arguments
605 args
= parser
.parse_args()
608 loglevel
= logging
.WARN
611 if args
.verbose
== 1:
612 loglevel
= logging
.INFO
613 elif args
.verbose
>= 2:
614 loglevel
= logging
.DEBUG
616 setup_logging(daemon
=args
.daemon
, loglevel
=loglevel
)
618 bridge
= UnboundDHCPLeasesBridge(args
.dhcp_leases
, args
.fix_leases
,
619 args
.unbound_leases
, args
.hosts
)
621 ctx
= daemon
.DaemonContext(detach_process
=args
.daemon
, stderr
=sys
.stderr
)
623 signal
.SIGHUP
: bridge
.update_dhcp_leases
,
624 signal
.SIGTERM
: bridge
.terminate
,