]>
git.ipfire.org Git - people/pmueller/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
36 import inotify
.adapters
40 log
= logging
.getLogger("dhcp")
41 log
.setLevel(logging
.DEBUG
)
43 def setup_logging(daemon
=True, loglevel
=logging
.INFO
):
44 log
.setLevel(loglevel
)
46 # Log to syslog by default
47 handler
= logging
.handlers
.SysLogHandler(address
="/dev/log", facility
="daemon")
48 log
.addHandler(handler
)
51 formatter
= logging
.Formatter("%(name)s[%(process)d]: %(message)s")
52 handler
.setFormatter(formatter
)
54 handler
.setLevel(loglevel
)
56 # If we are running in foreground, we should write everything to the console, too
58 handler
= logging
.StreamHandler()
59 log
.addHandler(handler
)
61 handler
.setLevel(loglevel
)
65 def ip_address_to_reverse_pointer(address
):
66 parts
= address
.split(".")
69 return "%s.in-addr.arpa" % ".".join(parts
)
71 def reverse_pointer_to_ip_address(rr
):
74 # Only take IP address part
75 parts
= reversed(parts
[0:4])
77 return ".".join(parts
)
79 class UnboundDHCPLeasesBridge(object):
80 def __init__(self
, dhcp_leases_file
, fix_leases_file
, unbound_leases_file
, hosts_file
):
81 self
.leases_file
= dhcp_leases_file
82 self
.fix_leases_file
= fix_leases_file
83 self
.hosts_file
= hosts_file
85 self
.unbound
= UnboundConfigWriter(unbound_leases_file
)
89 log
.info("Unbound DHCP Leases Bridge started on %s" % self
.leases_file
)
93 self
.hosts
= self
.read_static_hosts()
94 self
.update_dhcp_leases()
96 i
= inotify
.adapters
.Inotify([
102 for event
in i
.event_gen():
103 # End if we are requested to terminate
110 header
, type_names
, watch_path
, filename
= event
112 # Update leases after leases file has been modified
113 if "IN_MODIFY" in type_names
:
115 if watch_path
== self
.hosts_file
:
116 self
.hosts
= self
.read_static_hosts()
118 self
.update_dhcp_leases()
120 # If the file is deleted, we re-add the watcher
121 if "IN_IGNORED" in type_names
:
122 i
.add_watch(watch_path
)
124 log
.info("Unbound DHCP Leases Bridge terminated")
126 def update_dhcp_leases(self
):
129 for lease
in DHCPLeases(self
.leases_file
):
130 # Don't bother with any leases that don't have a hostname
136 for lease
in FixLeases(self
.fix_leases_file
):
139 # Skip any leases that also are a static host
140 leases
= [l
for l
in leases
if not l
.fqdn
in self
.hosts
]
142 # Remove any inactive or expired leases
143 leases
= [l
for l
in leases
if l
.active
and not l
.expired
]
147 log
.debug("DHCP Leases:")
149 log
.debug(" %s:" % lease
.fqdn
)
150 log
.debug(" State: %s" % lease
.binding_state
)
151 log
.debug(" Start: %s" % lease
.time_starts
)
152 log
.debug(" End : %s" % lease
.time_ends
)
154 log
.debug(" Expired")
156 self
.unbound
.update_dhcp_leases(leases
)
158 def read_static_hosts(self
):
159 log
.info("Reading static hosts from %s" % self
.hosts_file
)
162 with
open(self
.hosts_file
) as f
:
163 for line
in f
.readlines():
167 enabled
, ipaddr
, hostname
, domainname
, generateptr
= line
.split(",")
169 log
.warning("Could not parse line: %s" % line
)
172 # Skip any disabled entries
173 if not enabled
== "on":
176 if hostname
and domainname
:
177 fqdn
= "%s.%s" % (hostname
, domainname
)
184 hosts
[fqdn
].append(ipaddr
)
187 hosts
[fqdn
] = [ipaddr
,]
189 # Dump everything in the logs
190 log
.debug("Static hosts:")
192 log
.debug(" %-20s : %s" % (name
, ", ".join(hosts
[name
])))
200 class DHCPLeases(object):
201 regex_leaseblock
= re
.compile(r
"lease (?P<ipaddr>\d+\.\d+\.\d+\.\d+) {(?P<config>[\s\S]+?)\n}")
203 def __init__(self
, path
):
206 self
._leases
= self
._parse
()
209 return iter(self
._leases
)
212 log
.info("Reading DHCP leases from %s" % self
.path
)
216 with
open(self
.path
) as f
:
217 # Read entire leases file
220 for match
in self
.regex_leaseblock
.finditer(data
):
221 block
= match
.groupdict()
223 ipaddr
= block
.get("ipaddr")
224 config
= block
.get("config")
226 properties
= self
._parse
_block
(config
)
228 # Skip any abandoned leases
229 if not "hardware" in properties
:
232 lease
= Lease(ipaddr
, properties
)
234 # Check if a lease for this Ethernet address already
235 # exists in the list of known leases. If so replace
236 # if with the most recent lease
237 for i
, l
in enumerate(leases
):
238 if l
.ipaddr
== lease
.ipaddr
:
239 leases
[i
] = max(lease
, l
)
247 def _parse_block(self
, block
):
250 for line
in block
.splitlines():
254 # Remove trailing ; from line
255 if line
.endswith(";"):
258 # Invalid line if it doesn't end with ;
262 # Remove any leading whitespace
265 # We skip all options and sets
266 if line
.startswith("option") or line
.startswith("set"):
269 # Split by first space
270 key
, val
= line
.split(" ", 1)
271 properties
[key
] = val
276 class FixLeases(object):
279 def __init__(self
, path
):
282 self
._leases
= self
.cache
[self
.path
] = self
._parse
()
285 return iter(self
._leases
)
288 log
.info("Reading fix leases from %s" % self
.path
)
291 now
= datetime
.datetime
.utcnow()
293 with
open(self
.path
) as f
:
294 for line
in f
.readlines():
298 hwaddr
, ipaddr
, enabled
, a
, b
, c
, hostname
= line
.split(",")
300 log
.warning("Could not parse line: %s" % line
)
303 # Skip any disabled leases
304 if not enabled
== "on":
308 "binding" : "state active",
309 "client-hostname" : hostname
,
310 "hardware" : "ethernet %s" % hwaddr
,
311 "starts" : now
.strftime("%w %Y/%m/%d %H:%M:%S"),
316 # Try finding any deleted leases
317 for lease
in self
.cache
.get(self
.path
, []):
321 # Free the deleted lease
329 def __init__(self
, ipaddr
, properties
):
331 self
._properties
= properties
334 return "<%s %s for %s (%s)>" % (self
.__class
__.__name
__,
335 self
.ipaddr
, self
.hwaddr
, self
.hostname
)
337 def __eq__(self
, other
):
338 return self
.ipaddr
== other
.ipaddr
and self
.hwaddr
== other
.hwaddr
340 def __gt__(self
, other
):
341 if not self
.ipaddr
== other
.ipaddr
:
344 if not self
.hwaddr
== other
.hwaddr
:
347 return self
.time_starts
> other
.time_starts
350 def binding_state(self
):
351 state
= self
._properties
.get("binding")
354 state
= state
.split(" ", 1)
358 self
._properties
.update({
359 "binding" : "state free",
364 return self
.binding_state
== "active"
368 hardware
= self
._properties
.get("hardware")
373 ethernet
, address
= hardware
.split(" ", 1)
379 hostname
= self
._properties
.get("client-hostname")
385 hostname
= hostname
.replace("\"", "")
387 # Only return valid hostnames
388 m
= re
.match(r
"^[A-Z0-9\-]{1,63}$", hostname
, re
.I
)
394 # Load ethernet settings
395 ethernet_settings
= self
.read_settings("/var/ipfire/ethernet/settings")
398 dhcp_settings
= self
.read_settings("/var/ipfire/dhcp/settings")
401 for zone
in ("GREEN", "BLUE"):
402 if not dhcp_settings
.get("ENABLE_%s" % zone
) == "on":
405 netaddr
= ethernet_settings
.get("%s_NETADDRESS" % zone
)
406 submask
= ethernet_settings
.get("%s_NETMASK" % zone
)
408 subnet
= ipaddress
.ip_network("%s/%s" % (netaddr
, submask
))
409 domain
= dhcp_settings
.get("DOMAIN_NAME_%s" % zone
)
411 subnets
[subnet
] = domain
413 address
= ipaddress
.ip_address(self
.ipaddr
)
415 for subnet
in subnets
:
416 if address
in subnet
:
417 return subnets
[subnet
]
419 # Fall back to localdomain if no match could be found
423 def read_settings(filename
):
426 with
open(filename
) as f
:
427 for line
in f
.readlines():
431 k
, v
= line
.split("=", 1)
439 return "%s.%s" % (self
.hostname
, self
.domain
)
443 return datetime
.datetime
.strptime(s
, "%w %Y/%m/%d %H:%M:%S")
446 def time_starts(self
):
447 starts
= self
._properties
.get("starts")
450 return self
._parse
_time
(starts
)
454 ends
= self
._properties
.get("ends")
456 if not ends
or ends
== "never":
459 return self
._parse
_time
(ends
)
463 if not self
.time_ends
:
464 return self
.time_starts
> datetime
.datetime
.utcnow()
466 return self
.time_starts
> datetime
.datetime
.utcnow() > self
.time_ends
470 # If the lease does not have a valid FQDN, we cannot create any RRs
471 if self
.fqdn
is None:
476 (self
.fqdn
, "%s" % LOCAL_TTL
, "IN A", self
.ipaddr
),
479 (ip_address_to_reverse_pointer(self
.ipaddr
), "%s" % LOCAL_TTL
,
480 "IN PTR", self
.fqdn
),
484 class UnboundConfigWriter(object):
485 def __init__(self
, path
):
488 self
._cached
_leases
= []
490 def update_dhcp_leases(self
, leases
):
491 # Find any leases that have expired or do not exist any more
492 # but are still in the unbound local data
493 removed_leases
= [l
for l
in self
._cached
_leases
if not l
in leases
]
495 # Find any leases that have been added
496 new_leases
= [l
for l
in leases
if l
not in self
._cached
_leases
]
498 # End here if nothing has changed
499 if not new_leases
and not removed_leases
:
502 # Write out all leases
503 self
.write_dhcp_leases(leases
)
505 # Update unbound about changes
506 for l
in removed_leases
:
508 for name
, ttl
, type, content
in l
.rrset
:
509 log
.debug("Removing records for %s" % name
)
510 self
._control
("local_data_remove", name
)
512 # If the lease cannot be removed we will try the next one
516 # If the removal was successful, we will remove it from the cache
518 self
._cached
_leases
.remove(l
)
523 log
.debug("Adding new record %s" % " ".join(rr
))
524 self
._control
("local_data", *rr
)
526 # If the lease cannot be added we will try the next one
530 # Add lease to cache when successfully added
532 self
._cached
_leases
.append(l
)
534 def write_dhcp_leases(self
, leases
):
535 with tempfile
.NamedTemporaryFile(mode
="w", delete
=False) as f
:
540 f
.write("local-data: \"%s\"\n" % " ".join(rr
))
542 # Make file readable for everyone
543 os
.fchmod(f
.fileno(), stat
.S_IRUSR|stat
.S_IWUSR|stat
.S_IRGRP|stat
.S_IROTH
)
545 os
.rename(filename
, self
.path
)
547 def _control(self
, *args
):
548 command
= ["unbound-control"]
552 subprocess
.check_output(command
)
555 except subprocess
.CalledProcessError
as e
:
556 log
.critical("Could not run %s, error code: %s: %s" % (
557 " ".join(command
), e
.returncode
, e
.output
))
562 if __name__
== "__main__":
563 parser
= argparse
.ArgumentParser(description
="Bridge for DHCP Leases and Unbound DNS")
566 parser
.add_argument("--daemon", "-d", action
="store_true",
567 help="Launch as daemon in background")
568 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
571 parser
.add_argument("--dhcp-leases", default
="/var/state/dhcp/dhcpd.leases",
572 metavar
="PATH", help="Path to the DHCPd leases file")
573 parser
.add_argument("--unbound-leases", default
="/etc/unbound/dhcp-leases.conf",
574 metavar
="PATH", help="Path to the unbound configuration file")
575 parser
.add_argument("--fix-leases", default
="/var/ipfire/dhcp/fixleases",
576 metavar
="PATH", help="Path to the fix leases file")
577 parser
.add_argument("--hosts", default
="/var/ipfire/main/hosts",
578 metavar
="PATH", help="Path to static hosts file")
580 # Parse command line arguments
581 args
= parser
.parse_args()
584 loglevel
= logging
.WARN
587 if args
.verbose
== 1:
588 loglevel
= logging
.INFO
589 elif args
.verbose
>= 2:
590 loglevel
= logging
.DEBUG
592 setup_logging(daemon
=args
.daemon
, loglevel
=loglevel
)
594 bridge
= UnboundDHCPLeasesBridge(args
.dhcp_leases
, args
.fix_leases
,
595 args
.unbound_leases
, args
.hosts
)
597 ctx
= daemon
.DaemonContext(detach_process
=args
.daemon
, stderr
=sys
.stderr
)
599 signal
.SIGHUP
: bridge
.update_dhcp_leases
,
600 signal
.SIGTERM
: bridge
.terminate
,