]>
git.ipfire.org Git - ipfire-2.x.git/blob - config/unbound/unbound-dhcp-leases-bridge
70da1e03180e7650e95b5621a2e04bc4333b590f
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 self
.unbound
.update_dhcp_leases(leases
)
128 def read_static_hosts(self
):
129 log
.info("Reading static hosts from %s" % self
.hosts_file
)
132 with
open(self
.hosts_file
) as f
:
133 for line
in f
.readlines():
137 enabled
, ipaddr
, hostname
, domainname
= line
.split(",")
139 log
.warning("Could not parse line: %s" % line
)
142 # Skip any disabled entries
143 if not enabled
== "on":
146 if hostname
and domainname
:
147 fqdn
= "%s.%s" % (hostname
, domainname
)
154 hosts
[fqdn
].append(ipaddr
)
157 hosts
[fqdn
] = [ipaddr
,]
159 # Dump everything in the logs
160 log
.debug("Static hosts:")
161 for hostname
, addresses
in hosts
.items():
162 log
.debug(" %-20s : %s" % (hostname
, ", ".join(addresses
)))
170 class DHCPLeases(object):
171 regex_leaseblock
= re
.compile(r
"lease (?P<ipaddr>\d+\.\d+\.\d+\.\d+) {(?P<config>[\s\S]+?)\n}")
173 def __init__(self
, path
):
176 self
._leases
= self
._parse
()
179 return iter(self
._leases
)
182 log
.info("Reading DHCP leases from %s" % self
.path
)
186 with
open(self
.path
) as f
:
187 # Read entire leases file
190 for match
in self
.regex_leaseblock
.finditer(data
):
191 block
= match
.groupdict()
193 ipaddr
= block
.get("ipaddr")
194 config
= block
.get("config")
196 properties
= self
._parse
_block
(config
)
198 # Skip any abandoned leases
199 if not "hardware" in properties
:
202 lease
= Lease(ipaddr
, properties
)
204 # Check if a lease for this Ethernet address already
205 # exists in the list of known leases. If so replace
206 # if with the most recent lease
207 for i
, l
in enumerate(leases
):
208 if l
.hwaddr
== lease
.hwaddr
:
209 leases
[i
] = max(lease
, l
)
217 def _parse_block(self
, block
):
220 for line
in block
.splitlines():
224 # Remove trailing ; from line
225 if line
.endswith(";"):
228 # Invalid line if it doesn't end with ;
232 # Remove any leading whitespace
235 # We skip all options and sets
236 if line
.startswith("option") or line
.startswith("set"):
239 # Split by first space
240 key
, val
= line
.split(" ", 1)
241 properties
[key
] = val
246 class FixLeases(object):
249 def __init__(self
, path
):
252 self
._leases
= self
.cache
[self
.path
] = self
._parse
()
255 return iter(self
._leases
)
258 log
.info("Reading fix leases from %s" % self
.path
)
261 now
= datetime
.datetime
.utcnow()
263 with
open(self
.path
) as f
:
264 for line
in f
.readlines():
268 hwaddr
, ipaddr
, enabled
, a
, b
, c
, hostname
= line
.split(",")
270 log
.warning("Could not parse line: %s" % line
)
273 # Skip any disabled leases
274 if not enabled
== "on":
278 "binding" : "state active",
279 "client-hostname" : hostname
,
280 "hardware" : "ethernet %s" % hwaddr
,
281 "starts" : now
.strftime("%w %Y/%m/%d %H:%M:%S"),
286 # Try finding any deleted leases
287 for lease
in self
.cache
.get(self
.path
, []):
291 # Free the deleted lease
299 def __init__(self
, ipaddr
, properties
):
301 self
._properties
= properties
304 return "<%s %s for %s (%s)>" % (self
.__class
__.__name
__,
305 self
.ipaddr
, self
.hwaddr
, self
.hostname
)
307 def __eq__(self
, other
):
308 return self
.ipaddr
== other
.ipaddr
and self
.hwaddr
== other
.hwaddr
310 def __gt__(self
, other
):
311 if not self
.ipaddr
== other
.ipaddr
:
314 if not self
.hwaddr
== other
.hwaddr
:
317 return self
.time_starts
> other
.time_starts
320 def binding_state(self
):
321 state
= self
._properties
.get("binding")
324 state
= state
.split(" ", 1)
328 self
._properties
.update({
329 "binding" : "state free",
334 return self
.binding_state
== "active"
338 hardware
= self
._properties
.get("hardware")
343 ethernet
, address
= hardware
.split(" ", 1)
349 hostname
= self
._properties
.get("client-hostname")
355 hostname
= hostname
.replace("\"", "")
357 # Only return valid hostnames
358 m
= re
.match(r
"^[A-Z0-9\-]{1,63}$", hostname
, re
.I
)
364 # Load ethernet settings
365 ethernet_settings
= self
.read_settings("/var/ipfire/ethernet/settings")
368 dhcp_settings
= self
.read_settings("/var/ipfire/dhcp/settings")
371 for zone
in ("GREEN", "BLUE"):
372 if not dhcp_settings
.get("ENABLE_%s" % zone
) == "on":
375 netaddr
= ethernet_settings
.get("%s_NETADDRESS" % zone
)
376 submask
= ethernet_settings
.get("%s_NETMASK" % zone
)
378 subnet
= ipaddress
.ip_network("%s/%s" % (netaddr
, submask
))
379 domain
= dhcp_settings
.get("DOMAIN_NAME_%s" % zone
)
381 subnets
[subnet
] = domain
383 address
= ipaddress
.ip_address(self
.ipaddr
)
385 for subnet
, domain
in subnets
.items():
386 if address
in subnet
:
389 # Fall back to localdomain if no match could be found
393 def read_settings(filename
):
396 with
open(filename
) as f
:
397 for line
in f
.readlines():
401 k
, v
= line
.split("=", 1)
409 return "%s.%s" % (self
.hostname
, self
.domain
)
413 return datetime
.datetime
.strptime(s
, "%w %Y/%m/%d %H:%M:%S")
416 def time_starts(self
):
417 starts
= self
._properties
.get("starts")
420 return self
._parse
_time
(starts
)
424 ends
= self
._properties
.get("ends")
426 if not ends
or ends
== "never":
429 return self
._parse
_time
(ends
)
433 if not self
.time_ends
:
434 return self
.time_starts
> datetime
.datetime
.utcnow()
436 return self
.time_starts
> datetime
.datetime
.utcnow() > self
.time_ends
440 # If the lease does not have a valid FQDN, we cannot create any RRs
441 if self
.fqdn
is None:
446 (self
.fqdn
, "%s" % LOCAL_TTL
, "IN A", self
.ipaddr
),
449 (ip_address_to_reverse_pointer(self
.ipaddr
), "%s" % LOCAL_TTL
,
450 "IN PTR", self
.fqdn
),
454 class UnboundConfigWriter(object):
455 def __init__(self
, path
):
459 def existing_leases(self
):
460 local_data
= self
._control
("list_local_data")
463 for line
in local_data
.splitlines():
465 hostname
, ttl
, x
, record_type
, content
= line
.split("\t")
469 # Ignore everything that is not A or PTR
470 if not record_type
in ("A", "PTR"):
473 if hostname
.endswith("."):
474 hostname
= hostname
[:-1]
476 if content
.endswith("."):
477 content
= content
[:-1]
479 if record_type
== "A":
480 ret
[hostname
] = content
481 elif record_type
== "PTR":
482 ret
[content
] = reverse_pointer_to_ip_address(hostname
)
486 def update_dhcp_leases(self
, leases
):
487 # Cache all expired or inactive leases
488 expired_leases
= [l
for l
in leases
if l
.expired
or not l
.active
]
490 # Find any leases that have expired or do not exist any more
491 # but are still in the unbound local data
493 for fqdn
, address
in self
.existing_leases
.items():
494 if fqdn
in (l
.fqdn
for l
in expired_leases
):
495 removed_leases
+= [fqdn
, address
]
497 # Strip all non-active or expired leases
498 leases
= [l
for l
in leases
if l
.active
and not l
.expired
]
500 # Find any leases that have been added
501 new_leases
= [l
for l
in leases
502 if l
.fqdn
not in self
.existing_leases
]
504 # End here if nothing has changed
505 if not new_leases
and not removed_leases
:
508 # Write out all leases
509 self
.write_dhcp_leases(leases
)
511 # Update unbound about changes
512 for hostname
in removed_leases
:
513 log
.debug("Removing all records for %s" % hostname
)
514 self
._control
("local_data_remove", hostname
)
518 log
.debug("Adding new record %s" % " ".join(rr
))
519 self
._control
("local_data", *rr
)
522 def write_dhcp_leases(self
, leases
):
523 with
open(self
.path
, "w") as f
:
526 f
.write("local-data: \"%s\"\n" % " ".join(rr
))
528 def _control(self
, *args
):
529 command
= ["unbound-control"]
533 return subprocess
.check_output(command
)
536 except subprocess
.CalledProcessError
as e
:
537 log
.critical("Could not run %s, error code: %s: %s" % (
538 " ".join(command
), e
.returncode
, e
.output
))
541 if __name__
== "__main__":
542 parser
= argparse
.ArgumentParser(description
="Bridge for DHCP Leases and Unbound DNS")
545 parser
.add_argument("--daemon", "-d", action
="store_true",
546 help="Launch as daemon in background")
547 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
550 parser
.add_argument("--dhcp-leases", default
="/var/state/dhcp/dhcpd.leases",
551 metavar
="PATH", help="Path to the DHCPd leases file")
552 parser
.add_argument("--unbound-leases", default
="/etc/unbound/dhcp-leases.conf",
553 metavar
="PATH", help="Path to the unbound configuration file")
554 parser
.add_argument("--fix-leases", default
="/var/ipfire/dhcp/fixleases",
555 metavar
="PATH", help="Path to the fix leases file")
556 parser
.add_argument("--hosts", default
="/var/ipfire/main/hosts",
557 metavar
="PATH", help="Path to static hosts file")
559 # Parse command line arguments
560 args
= parser
.parse_args()
563 if args
.verbose
== 1:
564 loglevel
= logging
.INFO
565 elif args
.verbose
>= 2:
566 loglevel
= logging
.DEBUG
568 loglevel
= logging
.WARN
570 setup_logging(loglevel
)
572 bridge
= UnboundDHCPLeasesBridge(args
.dhcp_leases
, args
.fix_leases
,
573 args
.unbound_leases
, args
.hosts
)
575 ctx
= daemon
.DaemonContext(detach_process
=args
.daemon
)
577 signal
.SIGHUP
: bridge
.update_dhcp_leases
,
578 signal
.SIGTERM
: bridge
.terminate
,