]>
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
):
119 for lease
in FixLeases(self
.fix_leases_file
):
122 self
.unbound
.update_dhcp_leases(leases
)
124 def read_static_hosts(self
):
125 log
.info("Reading static hosts from %s" % self
.hosts_file
)
128 with
open(self
.hosts_file
) as f
:
129 for line
in f
.readlines():
133 enabled
, ipaddr
, hostname
, domainname
= line
.split(",")
135 log
.warning("Could not parse line: %s" % line
)
138 # Skip any disabled entries
139 if not enabled
== "on":
142 if hostname
and domainname
:
143 fqdn
= "%s.%s" % (hostname
, domainname
)
150 hosts
[fqdn
].append(ipaddr
)
153 hosts
[fqdn
] = [ipaddr
,]
155 # Dump everything in the logs
156 log
.debug("Static hosts:")
157 for hostname
, addresses
in hosts
.items():
158 log
.debug(" %-20s : %s" % (hostname
, ", ".join(addresses
)))
166 class DHCPLeases(object):
167 regex_leaseblock
= re
.compile(r
"lease (?P<ipaddr>\d+\.\d+\.\d+\.\d+) {(?P<config>[\s\S]+?)\n}")
169 def __init__(self
, path
):
172 self
._leases
= self
._parse
()
175 return iter(self
._leases
)
178 log
.info("Reading DHCP leases from %s" % self
.path
)
182 with
open(self
.path
) as f
:
183 # Read entire leases file
186 for match
in self
.regex_leaseblock
.finditer(data
):
187 block
= match
.groupdict()
189 ipaddr
= block
.get("ipaddr")
190 config
= block
.get("config")
192 properties
= self
._parse
_block
(config
)
194 # Skip any abandoned leases
195 if not "hardware" in properties
:
198 lease
= Lease(ipaddr
, properties
)
200 # Check if a lease for this Ethernet address already
201 # exists in the list of known leases. If so replace
202 # if with the most recent lease
203 for i
, l
in enumerate(leases
):
204 if l
.hwaddr
== lease
.hwaddr
:
205 leases
[i
] = max(lease
, l
)
213 def _parse_block(self
, block
):
216 for line
in block
.splitlines():
220 # Remove trailing ; from line
221 if line
.endswith(";"):
224 # Invalid line if it doesn't end with ;
228 # Remove any leading whitespace
231 # We skip all options and sets
232 if line
.startswith("option") or line
.startswith("set"):
235 # Split by first space
236 key
, val
= line
.split(" ", 1)
237 properties
[key
] = val
242 class FixLeases(object):
245 def __init__(self
, path
):
248 self
._leases
= self
.cache
[self
.path
] = self
._parse
()
251 return iter(self
._leases
)
254 log
.info("Reading fix leases from %s" % self
.path
)
257 now
= datetime
.datetime
.utcnow()
259 with
open(self
.path
) as f
:
260 for line
in f
.readlines():
264 hwaddr
, ipaddr
, enabled
, a
, b
, c
, hostname
= line
.split(",")
266 log
.warning("Could not parse line: %s" % line
)
269 # Skip any disabled leases
270 if not enabled
== "on":
274 "binding" : "state active",
275 "client-hostname" : hostname
,
276 "hardware" : "ethernet %s" % hwaddr
,
277 "starts" : now
.strftime("%w %Y/%m/%d %H:%M:%S"),
282 # Try finding any deleted leases
283 for lease
in self
.cache
.get(self
.path
, []):
287 # Free the deleted lease
295 def __init__(self
, ipaddr
, properties
):
297 self
._properties
= properties
300 return "<%s %s for %s (%s)>" % (self
.__class
__.__name
__,
301 self
.ipaddr
, self
.hwaddr
, self
.hostname
)
303 def __eq__(self
, other
):
304 return self
.ipaddr
== other
.ipaddr
and self
.hwaddr
== other
.hwaddr
306 def __gt__(self
, other
):
307 if not self
.ipaddr
== other
.ipaddr
:
310 if not self
.hwaddr
== other
.hwaddr
:
313 return self
.time_starts
> other
.time_starts
316 def binding_state(self
):
317 state
= self
._properties
.get("binding")
320 state
= state
.split(" ", 1)
324 self
._properties
.update({
325 "binding" : "state free",
330 return self
.binding_state
== "active"
334 hardware
= self
._properties
.get("hardware")
339 ethernet
, address
= hardware
.split(" ", 1)
345 hostname
= self
._properties
.get("client-hostname")
351 hostname
= hostname
.replace("\"", "")
353 # Only return valid hostnames
354 m
= re
.match(r
"^[A-Z0-9\-]{1,63}$", hostname
, re
.I
)
360 # Load ethernet settings
361 ethernet_settings
= self
.read_settings("/var/ipfire/ethernet/settings")
364 dhcp_settings
= self
.read_settings("/var/ipfire/dhcp/settings")
367 for zone
in ("GREEN", "BLUE"):
368 if not dhcp_settings
.get("ENABLE_%s" % zone
) == "on":
371 netaddr
= ethernet_settings
.get("%s_NETADDRESS" % zone
)
372 submask
= ethernet_settings
.get("%s_NETMASK" % zone
)
374 subnet
= ipaddress
.ip_network("%s/%s" % (netaddr
, submask
))
375 domain
= dhcp_settings
.get("DOMAIN_NAME_%s" % zone
)
377 subnets
[subnet
] = domain
379 address
= ipaddress
.ip_address(self
.ipaddr
)
381 for subnet
, domain
in subnets
.items():
382 if address
in subnet
:
385 # Fall back to localdomain if no match could be found
389 def read_settings(filename
):
392 with
open(filename
) as f
:
393 for line
in f
.readlines():
397 k
, v
= line
.split("=", 1)
405 return "%s.%s" % (self
.hostname
, self
.domain
)
409 return datetime
.datetime
.strptime(s
, "%w %Y/%m/%d %H:%M:%S")
412 def time_starts(self
):
413 starts
= self
._properties
.get("starts")
416 return self
._parse
_time
(starts
)
420 ends
= self
._properties
.get("ends")
422 if not ends
or ends
== "never":
425 return self
._parse
_time
(ends
)
429 if not self
.time_ends
:
430 return self
.time_starts
> datetime
.datetime
.utcnow()
432 return self
.time_starts
> datetime
.datetime
.utcnow() > self
.time_ends
436 # If the lease does not have a valid FQDN, we cannot create any RRs
437 if self
.fqdn
is None:
442 (self
.fqdn
, "%s" % LOCAL_TTL
, "IN A", self
.ipaddr
),
445 (ip_address_to_reverse_pointer(self
.ipaddr
), "%s" % LOCAL_TTL
,
446 "IN PTR", self
.fqdn
),
450 class UnboundConfigWriter(object):
451 def __init__(self
, path
):
455 def existing_leases(self
):
456 local_data
= self
._control
("list_local_data")
459 for line
in local_data
.splitlines():
461 hostname
, ttl
, x
, record_type
, content
= line
.split("\t")
465 # Ignore everything that is not A or PTR
466 if not record_type
in ("A", "PTR"):
469 if hostname
.endswith("."):
470 hostname
= hostname
[:-1]
472 if content
.endswith("."):
473 content
= content
[:-1]
475 if record_type
== "A":
476 ret
[hostname
] = content
477 elif record_type
== "PTR":
478 ret
[content
] = reverse_pointer_to_ip_address(hostname
)
482 def update_dhcp_leases(self
, leases
):
483 # Cache all expired or inactive leases
484 expired_leases
= [l
for l
in leases
if l
.expired
or not l
.active
]
486 # Find any leases that have expired or do not exist any more
487 # but are still in the unbound local data
489 for fqdn
, address
in self
.existing_leases
.items():
490 if fqdn
in (l
.fqdn
for l
in expired_leases
):
491 removed_leases
+= [fqdn
, address
]
493 # Strip all non-active or expired leases
494 leases
= [l
for l
in leases
if l
.active
and not l
.expired
]
496 # Find any leases that have been added
497 new_leases
= [l
for l
in leases
498 if l
.fqdn
not in self
.existing_leases
]
500 # End here if nothing has changed
501 if not new_leases
and not removed_leases
:
504 # Write out all leases
505 self
.write_dhcp_leases(leases
)
507 # Update unbound about changes
508 for hostname
in removed_leases
:
509 log
.debug("Removing all records for %s" % hostname
)
510 self
._control
("local_data_remove", hostname
)
514 log
.debug("Adding new record %s" % " ".join(rr
))
515 self
._control
("local_data", *rr
)
518 def write_dhcp_leases(self
, leases
):
519 with
open(self
.path
, "w") as f
:
522 f
.write("local-data: \"%s\"\n" % " ".join(rr
))
524 def _control(self
, *args
):
525 command
= ["unbound-control"]
529 return subprocess
.check_output(command
)
532 except subprocess
.CalledProcessError
as e
:
533 log
.critical("Could not run %s, error code: %s: %s" % (
534 " ".join(command
), e
.returncode
, e
.output
))
537 if __name__
== "__main__":
538 parser
= argparse
.ArgumentParser(description
="Bridge for DHCP Leases and Unbound DNS")
541 parser
.add_argument("--daemon", "-d", action
="store_true",
542 help="Launch as daemon in background")
543 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
546 parser
.add_argument("--dhcp-leases", default
="/var/state/dhcp/dhcpd.leases",
547 metavar
="PATH", help="Path to the DHCPd leases file")
548 parser
.add_argument("--unbound-leases", default
="/etc/unbound/dhcp-leases.conf",
549 metavar
="PATH", help="Path to the unbound configuration file")
550 parser
.add_argument("--fix-leases", default
="/var/ipfire/dhcp/fixleases",
551 metavar
="PATH", help="Path to the fix leases file")
552 parser
.add_argument("--hosts", default
="/var/ipfire/main/hosts",
553 metavar
="PATH", help="Path to static hosts file")
555 # Parse command line arguments
556 args
= parser
.parse_args()
559 if args
.verbose
== 1:
560 loglevel
= logging
.INFO
561 elif args
.verbose
>= 2:
562 loglevel
= logging
.DEBUG
564 loglevel
= logging
.WARN
566 setup_logging(loglevel
)
568 bridge
= UnboundDHCPLeasesBridge(args
.dhcp_leases
, args
.fix_leases
,
569 args
.unbound_leases
, args
.hosts
)
571 ctx
= daemon
.DaemonContext(detach_process
=args
.daemon
)
573 signal
.SIGHUP
: bridge
.update_dhcp_leases
,
574 signal
.SIGTERM
: bridge
.terminate
,