]>
git.ipfire.org Git - ipfire-2.x.git/blob - config/unbound/unbound-dhcp-leases-bridge
e3da4860bd1718b835d7a53d9be6b89222f36fef
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
35 import inotify
.adapters
39 def setup_logging(loglevel
=logging
.INFO
):
40 log
= logging
.getLogger("dhcp")
41 log
.setLevel(loglevel
)
43 handler
= logging
.handlers
.SysLogHandler(address
="/dev/log", facility
="daemon")
44 handler
.setLevel(loglevel
)
46 formatter
= logging
.Formatter("%(name)s[%(process)d]: %(message)s")
47 handler
.setFormatter(formatter
)
49 log
.addHandler(handler
)
53 log
= logging
.getLogger("dhcp")
55 def ip_address_to_reverse_pointer(address
):
56 parts
= address
.split(".")
59 return "%s.in-addr.arpa" % ".".join(parts
)
61 def reverse_pointer_to_ip_address(rr
):
64 # Only take IP address part
65 parts
= reversed(parts
[0:4])
67 return ".".join(parts
)
69 class UnboundDHCPLeasesBridge(object):
70 def __init__(self
, dhcp_leases_file
, fix_leases_file
, unbound_leases_file
, hosts_file
):
71 self
.leases_file
= dhcp_leases_file
72 self
.fix_leases_file
= fix_leases_file
73 self
.hosts_file
= hosts_file
75 self
.unbound
= UnboundConfigWriter(unbound_leases_file
)
79 log
.info("Unbound DHCP Leases Bridge started on %s" % self
.leases_file
)
83 self
.hosts
= self
.read_static_hosts()
84 self
.update_dhcp_leases()
86 i
= inotify
.adapters
.Inotify([
92 for event
in i
.event_gen():
93 # End if we are requested to terminate
100 header
, type_names
, watch_path
, filename
= event
102 # Update leases after leases file has been modified
103 if "IN_MODIFY" in type_names
:
105 if watch_path
== self
.hosts_file
:
106 self
.hosts
= self
.read_static_hosts()
108 self
.update_dhcp_leases()
110 # If the file is deleted, we re-add the watcher
111 if "IN_IGNORED" in type_names
:
112 i
.add_watch(watch_path
)
114 log
.info("Unbound DHCP Leases Bridge terminated")
116 def update_dhcp_leases(self
):
119 for lease
in DHCPLeases(self
.leases_file
):
120 # Don't bother with any leases that don't have a hostname
126 for lease
in FixLeases(self
.fix_leases_file
):
129 # Skip any leases that also are a static host
130 leases
= [l
for l
in leases
if not l
.fqdn
in self
.hosts
]
132 # Remove any inactive or expired leases
133 leases
= [l
for l
in leases
if l
.active
and not l
.expired
]
137 log
.debug("DHCP Leases:")
139 log
.debug(" %s:" % lease
.fqdn
)
140 log
.debug(" State: %s" % lease
.binding_state
)
141 log
.debug(" Start: %s" % lease
.time_starts
)
142 log
.debug(" End : %s" % lease
.time_ends
)
144 log
.debug(" Expired")
146 self
.unbound
.update_dhcp_leases(leases
)
148 def read_static_hosts(self
):
149 log
.info("Reading static hosts from %s" % self
.hosts_file
)
152 with
open(self
.hosts_file
) as f
:
153 for line
in f
.readlines():
157 enabled
, ipaddr
, hostname
, domainname
, generateptr
= line
.split(",")
159 log
.warning("Could not parse line: %s" % line
)
162 # Skip any disabled entries
163 if not enabled
== "on":
166 if hostname
and domainname
:
167 fqdn
= "%s.%s" % (hostname
, domainname
)
174 hosts
[fqdn
].append(ipaddr
)
177 hosts
[fqdn
] = [ipaddr
,]
179 # Dump everything in the logs
180 log
.debug("Static hosts:")
181 for hostname
, addresses
in hosts
.items():
182 log
.debug(" %-20s : %s" % (hostname
, ", ".join(addresses
)))
190 class DHCPLeases(object):
191 regex_leaseblock
= re
.compile(r
"lease (?P<ipaddr>\d+\.\d+\.\d+\.\d+) {(?P<config>[\s\S]+?)\n}")
193 def __init__(self
, path
):
196 self
._leases
= self
._parse
()
199 return iter(self
._leases
)
202 log
.info("Reading DHCP leases from %s" % self
.path
)
206 with
open(self
.path
) as f
:
207 # Read entire leases file
210 for match
in self
.regex_leaseblock
.finditer(data
):
211 block
= match
.groupdict()
213 ipaddr
= block
.get("ipaddr")
214 config
= block
.get("config")
216 properties
= self
._parse
_block
(config
)
218 # Skip any abandoned leases
219 if not "hardware" in properties
:
222 lease
= Lease(ipaddr
, properties
)
224 # Check if a lease for this Ethernet address already
225 # exists in the list of known leases. If so replace
226 # if with the most recent lease
227 for i
, l
in enumerate(leases
):
228 if l
.ipaddr
== lease
.ipaddr
:
229 leases
[i
] = max(lease
, l
)
237 def _parse_block(self
, block
):
240 for line
in block
.splitlines():
244 # Remove trailing ; from line
245 if line
.endswith(";"):
248 # Invalid line if it doesn't end with ;
252 # Remove any leading whitespace
255 # We skip all options and sets
256 if line
.startswith("option") or line
.startswith("set"):
259 # Split by first space
260 key
, val
= line
.split(" ", 1)
261 properties
[key
] = val
266 class FixLeases(object):
269 def __init__(self
, path
):
272 self
._leases
= self
.cache
[self
.path
] = self
._parse
()
275 return iter(self
._leases
)
278 log
.info("Reading fix leases from %s" % self
.path
)
281 now
= datetime
.datetime
.utcnow()
283 with
open(self
.path
) as f
:
284 for line
in f
.readlines():
288 hwaddr
, ipaddr
, enabled
, a
, b
, c
, hostname
= line
.split(",")
290 log
.warning("Could not parse line: %s" % line
)
293 # Skip any disabled leases
294 if not enabled
== "on":
298 "binding" : "state active",
299 "client-hostname" : hostname
,
300 "hardware" : "ethernet %s" % hwaddr
,
301 "starts" : now
.strftime("%w %Y/%m/%d %H:%M:%S"),
306 # Try finding any deleted leases
307 for lease
in self
.cache
.get(self
.path
, []):
311 # Free the deleted lease
319 def __init__(self
, ipaddr
, properties
):
321 self
._properties
= properties
324 return "<%s %s for %s (%s)>" % (self
.__class
__.__name
__,
325 self
.ipaddr
, self
.hwaddr
, self
.hostname
)
327 def __eq__(self
, other
):
328 return self
.ipaddr
== other
.ipaddr
and self
.hwaddr
== other
.hwaddr
330 def __gt__(self
, other
):
331 if not self
.ipaddr
== other
.ipaddr
:
334 if not self
.hwaddr
== other
.hwaddr
:
337 return self
.time_starts
> other
.time_starts
340 def binding_state(self
):
341 state
= self
._properties
.get("binding")
344 state
= state
.split(" ", 1)
348 self
._properties
.update({
349 "binding" : "state free",
354 return self
.binding_state
== "active"
358 hardware
= self
._properties
.get("hardware")
363 ethernet
, address
= hardware
.split(" ", 1)
369 hostname
= self
._properties
.get("client-hostname")
375 hostname
= hostname
.replace("\"", "")
377 # Only return valid hostnames
378 m
= re
.match(r
"^[A-Z0-9\-]{1,63}$", hostname
, re
.I
)
384 # Load ethernet settings
385 ethernet_settings
= self
.read_settings("/var/ipfire/ethernet/settings")
388 dhcp_settings
= self
.read_settings("/var/ipfire/dhcp/settings")
391 for zone
in ("GREEN", "BLUE"):
392 if not dhcp_settings
.get("ENABLE_%s" % zone
) == "on":
395 netaddr
= ethernet_settings
.get("%s_NETADDRESS" % zone
)
396 submask
= ethernet_settings
.get("%s_NETMASK" % zone
)
398 subnet
= ipaddress
.ip_network("%s/%s" % (netaddr
, submask
))
399 domain
= dhcp_settings
.get("DOMAIN_NAME_%s" % zone
)
401 subnets
[subnet
] = domain
403 address
= ipaddress
.ip_address(self
.ipaddr
)
405 for subnet
, domain
in subnets
.items():
406 if address
in subnet
:
409 # Fall back to localdomain if no match could be found
413 def read_settings(filename
):
416 with
open(filename
) as f
:
417 for line
in f
.readlines():
421 k
, v
= line
.split("=", 1)
429 return "%s.%s" % (self
.hostname
, self
.domain
)
433 return datetime
.datetime
.strptime(s
, "%w %Y/%m/%d %H:%M:%S")
436 def time_starts(self
):
437 starts
= self
._properties
.get("starts")
440 return self
._parse
_time
(starts
)
444 ends
= self
._properties
.get("ends")
446 if not ends
or ends
== "never":
449 return self
._parse
_time
(ends
)
453 if not self
.time_ends
:
454 return self
.time_starts
> datetime
.datetime
.utcnow()
456 return self
.time_starts
> datetime
.datetime
.utcnow() > self
.time_ends
460 # If the lease does not have a valid FQDN, we cannot create any RRs
461 if self
.fqdn
is None:
466 (self
.fqdn
, "%s" % LOCAL_TTL
, "IN A", self
.ipaddr
),
469 (ip_address_to_reverse_pointer(self
.ipaddr
), "%s" % LOCAL_TTL
,
470 "IN PTR", self
.fqdn
),
474 class UnboundConfigWriter(object):
475 def __init__(self
, path
):
478 self
._cached
_leases
= []
480 def update_dhcp_leases(self
, leases
):
481 # Find any leases that have expired or do not exist any more
482 # but are still in the unbound local data
483 removed_leases
= [l
for l
in self
._cached
_leases
if not l
in leases
]
485 # Find any leases that have been added
486 new_leases
= [l
for l
in leases
if l
not in self
._cached
_leases
]
488 # End here if nothing has changed
489 if not new_leases
and not removed_leases
:
492 # Write out all leases
493 self
.write_dhcp_leases(leases
)
495 # Update unbound about changes
496 for l
in removed_leases
:
498 for name
, ttl
, type, content
in l
.rrset
:
499 log
.debug("Removing records for %s" % name
)
500 self
._control
("local_data_remove", name
)
502 # If the lease cannot be removed we will try the next one
506 # If the removal was successful, we will remove it from the cache
508 self
._cached
_leases
.remove(l
)
513 log
.debug("Adding new record %s" % " ".join(rr
))
514 self
._control
("local_data", *rr
)
516 # If the lease cannot be added we will try the next one
520 # Add lease to cache when successfully added
522 self
._cached
_leases
.append(l
)
524 def write_dhcp_leases(self
, leases
):
525 with tempfile
.NamedTemporaryFile(mode
="w", delete
=False) as f
:
530 f
.write("local-data: \"%s\"\n" % " ".join(rr
))
532 # Make file readable for everyone
533 os
.fchmod(f
.fileno(), stat
.S_IRUSR|stat
.S_IWUSR|stat
.S_IRGRP|stat
.S_IROTH
)
535 os
.rename(filename
, self
.path
)
537 def _control(self
, *args
):
538 command
= ["unbound-control"]
542 subprocess
.check_output(command
)
545 except subprocess
.CalledProcessError
as e
:
546 log
.critical("Could not run %s, error code: %s: %s" % (
547 " ".join(command
), e
.returncode
, e
.output
))
552 if __name__
== "__main__":
553 parser
= argparse
.ArgumentParser(description
="Bridge for DHCP Leases and Unbound DNS")
556 parser
.add_argument("--daemon", "-d", action
="store_true",
557 help="Launch as daemon in background")
558 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
561 parser
.add_argument("--dhcp-leases", default
="/var/state/dhcp/dhcpd.leases",
562 metavar
="PATH", help="Path to the DHCPd leases file")
563 parser
.add_argument("--unbound-leases", default
="/etc/unbound/dhcp-leases.conf",
564 metavar
="PATH", help="Path to the unbound configuration file")
565 parser
.add_argument("--fix-leases", default
="/var/ipfire/dhcp/fixleases",
566 metavar
="PATH", help="Path to the fix leases file")
567 parser
.add_argument("--hosts", default
="/var/ipfire/main/hosts",
568 metavar
="PATH", help="Path to static hosts file")
570 # Parse command line arguments
571 args
= parser
.parse_args()
574 if args
.verbose
== 1:
575 loglevel
= logging
.INFO
576 elif args
.verbose
>= 2:
577 loglevel
= logging
.DEBUG
579 loglevel
= logging
.WARN
581 setup_logging(loglevel
)
583 bridge
= UnboundDHCPLeasesBridge(args
.dhcp_leases
, args
.fix_leases
,
584 args
.unbound_leases
, args
.hosts
)
586 ctx
= daemon
.DaemonContext(detach_process
=args
.daemon
)
588 signal
.SIGHUP
: bridge
.update_dhcp_leases
,
589 signal
.SIGTERM
: bridge
.terminate
,