]>
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
):
68 self
.leases_file
= dhcp_leases_file
69 self
.fix_leases_file
= fix_leases_file
71 self
.unbound
= UnboundConfigWriter(unbound_leases_file
)
75 log
.info("Unbound DHCP Leases Bridge started on %s" % self
.leases_file
)
78 # Initially read leases file
79 self
.update_dhcp_leases()
81 i
= inotify
.adapters
.Inotify([self
.leases_file
, self
.fix_leases_file
])
83 for event
in i
.event_gen():
84 # End if we are requested to terminate
91 header
, type_names
, watch_path
, filename
= event
93 # Update leases after leases file has been modified
94 if "IN_MODIFY" in type_names
:
95 self
.update_dhcp_leases()
97 # If the file is deleted, we re-add the watcher
98 if "IN_IGNORED" in type_names
:
99 i
.add_watch(watch_path
)
101 log
.info("Unbound DHCP Leases Bridge terminated")
103 def update_dhcp_leases(self
):
106 for lease
in DHCPLeases(self
.leases_file
):
109 for lease
in FixLeases(self
.fix_leases_file
):
112 self
.unbound
.update_dhcp_leases(leases
)
118 class DHCPLeases(object):
119 regex_leaseblock
= re
.compile(r
"lease (?P<ipaddr>\d+\.\d+\.\d+\.\d+) {(?P<config>[\s\S]+?)\n}")
121 def __init__(self
, path
):
124 self
._leases
= self
._parse
()
127 return iter(self
._leases
)
130 log
.info("Reading DHCP leases from %s" % self
.path
)
134 with
open(self
.path
) as f
:
135 # Read entire leases file
138 for match
in self
.regex_leaseblock
.finditer(data
):
139 block
= match
.groupdict()
141 ipaddr
= block
.get("ipaddr")
142 config
= block
.get("config")
144 properties
= self
._parse
_block
(config
)
146 # Skip any abandoned leases
147 if not "hardware" in properties
:
150 lease
= Lease(ipaddr
, properties
)
152 # Check if a lease for this Ethernet address already
153 # exists in the list of known leases. If so replace
154 # if with the most recent lease
155 for i
, l
in enumerate(leases
):
156 if l
.hwaddr
== lease
.hwaddr
:
157 leases
[i
] = max(lease
, l
)
165 def _parse_block(self
, block
):
168 for line
in block
.splitlines():
172 # Remove trailing ; from line
173 if line
.endswith(";"):
176 # Invalid line if it doesn't end with ;
180 # Remove any leading whitespace
183 # We skip all options and sets
184 if line
.startswith("option") or line
.startswith("set"):
187 # Split by first space
188 key
, val
= line
.split(" ", 1)
189 properties
[key
] = val
194 class FixLeases(object):
197 def __init__(self
, path
):
200 self
._leases
= self
.cache
[self
.path
] = self
._parse
()
203 return iter(self
._leases
)
206 log
.info("Reading fix leases from %s" % self
.path
)
209 now
= datetime
.datetime
.utcnow()
211 with
open(self
.path
) as f
:
212 for line
in f
.readlines():
216 hwaddr
, ipaddr
, enabled
, a
, b
, c
, hostname
= line
.split(",")
218 log
.warning("Could not parse line: %s" % line
)
221 # Skip any disabled leases
222 if not enabled
== "on":
226 "binding" : "state active",
227 "client-hostname" : hostname
,
228 "hardware" : "ethernet %s" % hwaddr
,
229 "starts" : now
.strftime("%w %Y/%m/%d %H:%M:%S"),
234 # Try finding any deleted leases
235 for lease
in self
.cache
.get(self
.path
, []):
239 # Free the deleted lease
247 def __init__(self
, ipaddr
, properties
):
249 self
._properties
= properties
252 return "<%s %s for %s (%s)>" % (self
.__class
__.__name
__,
253 self
.ipaddr
, self
.hwaddr
, self
.hostname
)
255 def __eq__(self
, other
):
256 return self
.ipaddr
== other
.ipaddr
and self
.hwaddr
== other
.hwaddr
258 def __gt__(self
, other
):
259 if not self
.ipaddr
== other
.ipaddr
:
262 if not self
.hwaddr
== other
.hwaddr
:
265 return self
.time_starts
> other
.time_starts
268 def binding_state(self
):
269 state
= self
._properties
.get("binding")
272 state
= state
.split(" ", 1)
276 self
._properties
.update({
277 "binding" : "state free",
282 return self
.binding_state
== "active"
286 hardware
= self
._properties
.get("hardware")
291 ethernet
, address
= hardware
.split(" ", 1)
297 hostname
= self
._properties
.get("client-hostname")
303 hostname
= hostname
.replace("\"", "")
305 # Only return valid hostnames
306 m
= re
.match(r
"^[A-Z0-9\-]{1,63}$", hostname
, re
.I
)
312 # Load ethernet settings
313 ethernet_settings
= self
.read_settings("/var/ipfire/ethernet/settings")
316 dhcp_settings
= self
.read_settings("/var/ipfire/dhcp/settings")
319 for zone
in ("GREEN", "BLUE"):
320 if not dhcp_settings
.get("ENABLE_%s" % zone
) == "on":
323 netaddr
= ethernet_settings
.get("%s_NETADDRESS" % zone
)
324 submask
= ethernet_settings
.get("%s_NETMASK" % zone
)
326 subnet
= ipaddress
.ip_network("%s/%s" % (netaddr
, submask
))
327 domain
= dhcp_settings
.get("DOMAIN_NAME_%s" % zone
)
329 subnets
[subnet
] = domain
331 address
= ipaddress
.ip_address(self
.ipaddr
)
333 for subnet
, domain
in subnets
.items():
334 if address
in subnet
:
337 # Fall back to localdomain if no match could be found
341 def read_settings(filename
):
344 with
open(filename
) as f
:
345 for line
in f
.readlines():
349 k
, v
= line
.split("=", 1)
357 return "%s.%s" % (self
.hostname
, self
.domain
)
361 return datetime
.datetime
.strptime(s
, "%w %Y/%m/%d %H:%M:%S")
364 def time_starts(self
):
365 starts
= self
._properties
.get("starts")
368 return self
._parse
_time
(starts
)
372 ends
= self
._properties
.get("ends")
374 if not ends
or ends
== "never":
377 return self
._parse
_time
(ends
)
381 if not self
.time_ends
:
382 return self
.time_starts
> datetime
.datetime
.utcnow()
384 return self
.time_starts
> datetime
.datetime
.utcnow() > self
.time_ends
388 # If the lease does not have a valid FQDN, we cannot create any RRs
389 if self
.fqdn
is None:
394 (self
.fqdn
, "%s" % LOCAL_TTL
, "IN A", self
.ipaddr
),
397 (ip_address_to_reverse_pointer(self
.ipaddr
), "%s" % LOCAL_TTL
,
398 "IN PTR", self
.fqdn
),
402 class UnboundConfigWriter(object):
403 def __init__(self
, path
):
407 def existing_leases(self
):
408 local_data
= self
._control
("list_local_data")
411 for line
in local_data
.splitlines():
413 hostname
, ttl
, x
, record_type
, content
= line
.split("\t")
417 # Ignore everything that is not A or PTR
418 if not record_type
in ("A", "PTR"):
421 if hostname
.endswith("."):
422 hostname
= hostname
[:-1]
424 if content
.endswith("."):
425 content
= content
[:-1]
427 if record_type
== "A":
428 ret
[hostname
] = content
429 elif record_type
== "PTR":
430 ret
[content
] = reverse_pointer_to_ip_address(hostname
)
434 def update_dhcp_leases(self
, leases
):
435 # Cache all expired or inactive leases
436 expired_leases
= [l
for l
in leases
if l
.expired
or not l
.active
]
438 # Find any leases that have expired or do not exist any more
439 # but are still in the unbound local data
441 for fqdn
, address
in self
.existing_leases
.items():
442 if fqdn
in (l
.fqdn
for l
in expired_leases
):
443 removed_leases
+= [fqdn
, address
]
445 # Strip all non-active or expired leases
446 leases
= [l
for l
in leases
if l
.active
and not l
.expired
]
448 # Find any leases that have been added
449 new_leases
= [l
for l
in leases
450 if l
.fqdn
not in self
.existing_leases
]
452 # End here if nothing has changed
453 if not new_leases
and not removed_leases
:
456 # Write out all leases
457 self
.write_dhcp_leases(leases
)
459 # Update unbound about changes
460 for hostname
in removed_leases
:
461 log
.debug("Removing all records for %s" % hostname
)
462 self
._control
("local_data_remove", hostname
)
466 log
.debug("Adding new record %s" % " ".join(rr
))
467 self
._control
("local_data", *rr
)
470 def write_dhcp_leases(self
, leases
):
471 with
open(self
.path
, "w") as f
:
474 f
.write("local-data: \"%s\"\n" % " ".join(rr
))
476 def _control(self
, *args
):
477 command
= ["unbound-control"]
481 return subprocess
.check_output(command
)
484 except subprocess
.CalledProcessError
as e
:
485 log
.critical("Could not run %s, error code: %s: %s" % (
486 " ".join(command
), e
.returncode
, e
.output
))
489 if __name__
== "__main__":
490 parser
= argparse
.ArgumentParser(description
="Bridge for DHCP Leases and Unbound DNS")
493 parser
.add_argument("--daemon", "-d", action
="store_true",
494 help="Launch as daemon in background")
495 parser
.add_argument("--verbose", "-v", action
="count", help="Be more verbose")
498 parser
.add_argument("--dhcp-leases", default
="/var/state/dhcp/dhcpd.leases",
499 metavar
="PATH", help="Path to the DHCPd leases file")
500 parser
.add_argument("--unbound-leases", default
="/etc/unbound/dhcp-leases.conf",
501 metavar
="PATH", help="Path to the unbound configuration file")
502 parser
.add_argument("--fix-leases", default
="/var/ipfire/dhcp/fixleases",
503 metavar
="PATH", help="Path to the fix leases file")
505 # Parse command line arguments
506 args
= parser
.parse_args()
509 if args
.verbose
== 1:
510 loglevel
= logging
.INFO
511 elif args
.verbose
>= 2:
512 loglevel
= logging
.DEBUG
514 loglevel
= logging
.WARN
516 setup_logging(loglevel
)
518 bridge
= UnboundDHCPLeasesBridge(args
.dhcp_leases
, args
.fix_leases
, args
.unbound_leases
)
520 ctx
= daemon
.DaemonContext(detach_process
=args
.daemon
)
522 signal
.SIGHUP
: bridge
.update_dhcp_leases
,
523 signal
.SIGTERM
: bridge
.terminate
,