import logging.handlers
import threading
import traceback
-import subprocess
import daemon
import daemon.runner
ICMPv6NDOptPrefixInfo, \
ICMPv6NDOptRDNSS
from scapy.layers.dhcp import BOOTP, DHCP
+from scapy.layers.dhcp6 import DHCP6_Reply, DHCP6OptDNSServers, \
+ DHCP6OptServerId, DHCP6OptClientId, \
+ DUID_LLT, DHCP6_InfoRequest, DHCP6OptDNSDomains
DEFAULT_CONFIG = "/etc/nfdhcpd/nfdhcpd.conf"
ra_period = integer(min=1, max=4294967295)
rs_queue = integer(min=0, max=65535)
ns_queue = integer(min=0, max=65535)
+dhcp_queue = integer(min=0, max=65535)
nameservers = ip_addr_list(family=6)
+domains = force_list(default=None)
"""
return indev_ifindex
-def get_binding(proxy, ifindex, mac):
- try:
- if proxy.mac_indexed_clients:
- logging.debug(" - Getting binding for mac %s", mac)
- b = proxy.clients[mac]
- else:
- logging.debug(" - Getting binding for ifindex %s", ifindex)
- b = proxy.clients[ifindex]
- return b
- except KeyError:
- logging.debug(" - No client found for mac / ifindex %s / %s",
- mac, ifindex)
- return None
-
-
def parse_binding_file(path):
""" Read a client configuration from a tap file
class Client(object):
- def __init__(self, tap=None, indev=None, mac=None, ip=None, hostname=None,
- subnet=None, gateway=None, subnet6=None, gateway6=None, eui64=None ):
+ def __init__(self, tap=None, indev=None,
+ mac=None, ip=None, hostname=None,
+ subnet=None, gateway=None,
+ subnet6=None, gateway6=None, eui64=None):
self.mac = mac
self.ip = ip
self.hostname = hostname
self.open_socket()
def is_valid(self):
- return self.mac is not None and self.ip is not None\
- and self.hostname is not None
+ return self.mac is not None and self.hostname is not None
def open_socket(self):
class VMNetProxy(object): # pylint: disable=R0902
def __init__(self, data_path, dhcp_queue_num=None, # pylint: disable=R0913
- rs_queue_num=None, ns_queue_num=None,
+ rs_queue_num=None, ns_queue_num=None, dhcpv6_queue_num=None,
dhcp_lease_lifetime=DEFAULT_LEASE_LIFETIME,
dhcp_lease_renewal=DEFAULT_LEASE_RENEWAL,
- dhcp_domain='',
+ dhcp_domain=None,
dhcp_server_ip=DHCP_DUMMY_SERVER_IP, dhcp_nameservers=None,
- ra_period=DEFAULT_RA_PERIOD, ipv6_nameservers=None):
+ ra_period=DEFAULT_RA_PERIOD, ipv6_nameservers=None,
+ dhcpv6_domains=None):
try:
getattr(nfqueue.payload, 'get_physindev')
else:
self.ipv6_nameservers = ipv6_nameservers
+ if dhcpv6_domains is None:
+ self.dhcpv6_domains = []
+ else:
+ self.dhcpv6_domains = dhcpv6_domains
+
self.ipv6_enabled = False
self.clients = {}
self._setup_nfqueue(ns_queue_num, AF_INET6, self.ns_response, 10)
self.ipv6_enabled = True
+ if dhcpv6_queue_num is not None:
+ self._setup_nfqueue(dhcpv6_queue_num, AF_INET6, self.dhcpv6_response, 10)
+ self.ipv6_enabled = True
+
+ def get_binding(self, ifindex, mac):
+ try:
+ if self.mac_indexed_clients:
+ logging.debug(" - Getting binding for mac %s", mac)
+ b = self.clients[mac]
+ else:
+ logging.debug(" - Getting binding for ifindex %s", ifindex)
+ b = self.clients[ifindex]
+ return b
+ except KeyError:
+ logging.debug(" - No client found for mac / ifindex %s / %s",
+ mac, ifindex)
+ return None
def _cleanup(self):
""" Free all resources for a graceful exit
logging.info("Cleaning up")
logging.debug(" - Closing netfilter queues")
- for q, num in self.nfq.values():
+ for q, _ in self.nfq.values():
q.close()
logging.debug(" - Stopping inotify watches")
self.nfq[q.get_fd()] = (q, pending)
logging.debug(" - Successfully set up NFQUEUE %d", queue_num)
- def sendp(self, data, binding):
- """ Send a raw packet using a layer-2 socket
-
- """
- logging.info(" - Sending raw packet on %s (%s)",
- binding.tap, binding.hostname)
- binding.sendp(data)
-
-
def build_config(self):
self.clients.clear()
if b.is_valid():
if self.mac_indexed_clients:
self.clients[b.mac] = b
+ k = b.mac
else:
self.clients[ifindex] = b
- logging.debug(" - Added client:")
- logging.debug(" + %5s: %10s %20s %7s %15s",
- ifindex, b.hostname, b.mac, b.tap, b.ip)
+ k = ifindex
+ logging.info(" - Added client:")
+ logging.info(" + %10s | %20s %20s %10s %20s %40s",
+ k, b.hostname, b.mac, b.tap, b.ip, b.eui64)
def remove_tap(self, tap):
""" Cleanup clients on a removed interface
if cl.tap == tap:
logging.info("Removing client %s and closing socket on %s",
cl.hostname, cl.tap)
- logging.debug(" - %10s | %10s %20s %10s %20s",
- k, cl.hostname, cl.mac, cl.tap, cl.ip)
+ logging.info(" - %10s | %20s %20s %10s %20s %40s",
+ k, cl.hostname, cl.mac, cl.tap, cl.ip, cl.eui64)
cl.socket.close()
del self.clients[k]
except:
logging.debug("Client on %s disappeared!!!", tap)
- def dhcp_response(self, dummy, payload): # pylint: disable=W0613,R0914
+ def dhcp_response(self, arg1, arg2=None): # pylint: disable=W0613,R0914
""" Generate a reply to bnetfilter-queue-deva BOOTP/DHCP request
"""
logging.info(" * Processing pending DHCP request")
+ # Workaround for supporting both squeezy's nfqueue-bindings-python
+ # and wheezy's python-nfqueue because for some reason the function's
+ # signature has changed and has broken compatibility
+ # See bug http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=718894
+ if arg2:
+ payload = arg2
+ else:
+ payload = arg1
# Decode the response - NFQUEUE relays IP packets
pkt = IP(payload.get_data())
#logging.debug(pkt.show())
indev = get_indev(payload)
- binding = get_binding(self, indev, mac)
+ binding = self.get_binding(indev, mac)
if binding is None:
# We don't know anything about this interface, so accept the packet
# and return
payload.set_verdict(nfqueue.NF_DROP)
if mac != binding.mac:
- logging.warn(" - Recieved spoofed DHCP request for mac %s from tap %s", mac, indev)
+ logging.warn(" - Recieved spoofed DHCP request: mac %s, indev %s",
+ mac, indev)
+ return
+
+ if not binding.ip:
+ logging.info(" - No IP found in binding file.")
return
- logging.info(" - Generating DHCP response for host %s (mac %s) on tap %s",
- binding.hostname, mac, binding.tap)
+ logging.info(" - Generating DHCP response:"
+ " host %s, mac %s, tap %s, indev %s",
+ binding.hostname, mac, binding.tap, indev)
resp = Ether(dst=mac, src=self.get_iface_hw_addr(binding.indev))/\
elif req_type == DHCPRELEASE:
# Log and ignore
- logging.info(" - DHCPRELEASE from %s on %s", binding.mac, binding.tap)
+ logging.info(" - DHCPRELEASE from %s on %s",
+ binding.hostname, binding.tap)
return
# Finally, always add the server identifier and end options
logging.info(" - %s to %s (%s) on %s", DHCP_TYPES[resp_type], mac,
binding.ip, binding.tap)
try:
- self.sendp(resp, binding)
+ binding.sendp(resp)
except socket.error, e:
logging.warn(" - DHCP response on %s (%s) failed: %s",
binding.tap, binding.hostname, str(e))
logging.warn(" - Unkown error during DHCP response on %s (%s): %s",
binding.tap, binding.hostname, str(e))
- def rs_response(self, dummy, payload): # pylint: disable=W0613
+ def dhcpv6_response(self, arg1, arg2=None): # pylint: disable=W0613
+
+ logging.info(" * Processing pending DHCPv6 request")
+ # Workaround for supporting both squeezy's nfqueue-bindings-python
+ # and wheezy's python-nfqueue because for some reason the function's
+ # signature has changed and has broken compatibility
+ # See bug http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=718894
+ if arg2:
+ payload = arg2
+ else:
+ payload = arg1
+ pkt = IPv6(payload.get_data())
+ indev = get_indev(payload)
+
+ #TODO: figure out how to find the src mac
+ mac = None
+ binding = self.get_binding(indev, mac)
+ if binding is None:
+ # We don't know anything about this interface, so accept the packet
+ # and return
+ logging.debug(" - Ignoring dhcpv6 request for mac %s", mac)
+ # We don't know what to do with this packet, so let the kernel
+ # handle it
+ payload.set_verdict(nfqueue.NF_ACCEPT)
+ return
+
+ # Signal the kernel that it shouldn't further process the packet
+ payload.set_verdict(nfqueue.NF_DROP)
+
+ subnet = binding.net6
+
+ if subnet.net is None:
+ logging.debug(" - No IPv6 network assigned for tap %s", binding.tap)
+ return
+
+ indevmac = self.get_iface_hw_addr(binding.indev)
+ ifll = subnet.make_ll64(indevmac)
+ if ifll is None:
+ return
+
+ ofll = subnet.make_ll64(binding.mac)
+ if ofll is None:
+ return
+
+ logging.info(" - Generating DHCPv6 response for host %s (mac %s) on tap %s",
+ binding.hostname, binding.mac, binding.tap)
+
+ if self.dhcpv6_domains:
+ domains = self.dhcpv6_domains
+ else:
+ domains = [binding.hostname.split('.', 1)[-1]]
+
+ # We do this in order not to caclulate optlen ourselves
+ dnsdomains = str(DHCP6OptDNSDomains(dnsdomains=domains))
+ dnsservers = str(DHCP6OptDNSServers(dnsservers=self.ipv6_nameservers))
+
+ resp = Ether(src=indevmac, dst=binding.mac)/\
+ IPv6(tc=192, src=str(ifll), dst=str(ofll))/\
+ UDP(sport=pkt.dport, dport=pkt.sport)/\
+ DHCP6_Reply(trid=pkt[DHCP6_InfoRequest].trid)/\
+ DHCP6OptClientId(duid=pkt[DHCP6OptClientId].duid)/\
+ DHCP6OptServerId(duid=DUID_LLT(lladdr=indevmac, timeval=time.time()))/\
+ DHCP6OptDNSDomains(dnsdomains)/\
+ DHCP6OptDNSServers(dnsservers)
+
+ try:
+ binding.sendp(resp)
+ except socket.error, e:
+ logging.warn(" - DHCPv6 on %s (%s) failed: %s",
+ binding.tap, binding.hostname, str(e))
+ except Exception, e:
+ logging.warn(" - Unkown error during DHCPv6 on %s (%s): %s",
+ binding.tap, binding.hostname, str(e))
+
+
+ def rs_response(self, arg1, arg2=None): # pylint: disable=W0613
""" Generate a reply to a BOOTP/DHCP request
"""
logging.info(" * Processing pending RS request")
+ # Workaround for supporting both squeezy's nfqueue-bindings-python
+ # and wheezy's python-nfqueue because for some reason the function's
+ # signature has changed and has broken compatibility
+ # See bug http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=718894
+ if arg2:
+ payload = arg2
+ else:
+ payload = arg1
pkt = IPv6(payload.get_data())
#logging.debug(pkt.show())
try:
indev = get_indev(payload)
- binding = get_binding(self, indev, mac)
+ binding = self.get_binding(indev, mac)
if binding is None:
# We don't know anything about this interface, so accept the packet
# and return
payload.set_verdict(nfqueue.NF_DROP)
if mac != binding.mac:
- logging.warn(" - Received spoofed RS request for mac %s from tap %s",
+ logging.warn(" - Received spoofed RS request: mac %s, tap %s",
mac, binding.tap)
return
binding.hostname, mac, binding.tap)
resp = Ether(src=indevmac)/\
- IPv6(src=str(ifll))/ICMPv6ND_RA(routerlifetime=14400)/\
+ IPv6(src=str(ifll))/ICMPv6ND_RA(O=1, routerlifetime=14400)/\
ICMPv6NDOptPrefixInfo(prefix=str(subnet.prefix),
prefixlen=subnet.prefixlen)
lifetime=self.ra_period * 3)
try:
- self.sendp(resp, binding)
+ binding.sendp(resp)
except socket.error, e:
logging.warn(" - RA on %s (%s) failed: %s",
binding.tap, binding.hostname, str(e))
logging.warn(" - Unkown error during RA on %s (%s): %s",
binding.tap, binding.hostname, str(e))
- def ns_response(self, dummy, payload): # pylint: disable=W0613
+ def ns_response(self, arg1, arg2=None): # pylint: disable=W0613
""" Generate a reply to an ICMPv6 neighbor solicitation
"""
logging.info(" * Processing pending NS request")
+ # Workaround for supporting both squeezy's nfqueue-bindings-python
+ # and wheezy's python-nfqueue because for some reason the function's
+ # signature has changed and has broken compatibility
+ # See bug http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=718894
+ if arg2:
+ payload = arg2
+ else:
+ payload = arg1
ns = IPv6(payload.get_data())
#logging.debug(ns.show())
indev = get_indev(payload)
- binding = get_binding(self, indev, mac)
+ binding = self.get_binding(indev, mac)
if binding is None:
# We don't know anything about this interface, so accept the packet
# and return
ICMPv6NDOptDstLLAddr(lladdr=indevmac)
try:
- self.sendp(resp, binding)
+ binding.sendp(resp)
except socket.error, e:
logging.warn(" - NA on %s (%s) failed: %s",
- bindig.tap, binding.hostname, str(e))
+ binding.tap, binding.hostname, str(e))
except Exception, e:
logging.warn(" - Unkown error during periodic NA to %s (%s): %s",
binding.tap, binding.hostname, str(e))
if ifll is None:
continue
resp = Ether(src=indevmac)/\
- IPv6(src=str(ifll))/ICMPv6ND_RA(routerlifetime=14400)/\
+ IPv6(src=str(ifll))/ICMPv6ND_RA(O=1, routerlifetime=14400)/\
ICMPv6NDOptPrefixInfo(prefix=str(subnet.prefix),
prefixlen=subnet.prefixlen)
if self.ipv6_nameservers:
resp /= ICMPv6NDOptRDNSS(dns=self.ipv6_nameservers,
lifetime=self.ra_period * 3)
try:
- self.sendp(resp, binding)
+ binding.sendp(resp)
except socket.error, e:
logging.warn(" - Periodic RA on %s (%s) failed: %s",
tap, binding.hostname, str(e))
while True:
try:
- rlist, _, xlist = select.select(self.nfq.keys() + [iwfd], [], [], timeout)
+ rlist, _, xlist = select.select(self.nfq.keys() + [iwfd],
+ [], [], timeout)
except select.error, e:
if e[0] == errno.EINTR:
logging.debug("select() got interrupted")
timeout = self.ra_period - (time.time() - start)
def print_clients(self):
- logging.info("%10s %20s %20s %10s %20s",'Key', 'Client', 'MAC', 'TAP', 'IP')
+ logging.info("%10s %20s %20s %10s %20s %40s",
+ 'Key', 'Client', 'MAC', 'TAP', 'IP', 'IPv6')
for k, cl in self.clients.items():
- logging.info("%10s | %20s %20s %10s %20s", k, cl.hostname, cl.mac, cl.tap, cl.ip)
+ logging.info("%10s | %20s %20s %10s %20s %40s",
+ k, cl.hostname, cl.mac, cl.tap, cl.ip, cl.eui64)
capng.CAP_SETPCAP)
# change uid
capng.capng_change_id(uid.pw_uid, uid.pw_gid,
- capng.CAPNG_DROP_SUPP_GRP | capng.CAPNG_CLEAR_BOUNDING)
+ capng.CAPNG_DROP_SUPP_GRP | \
+ capng.CAPNG_CLEAR_BOUNDING)
logger = logging.getLogger()
if opts.debug:
if config["ipv6"].as_bool("enable_ipv6"):
proxy_opts.update({
+ "dhcpv6_queue_num": config["ipv6"].as_int("dhcp_queue"),
"rs_queue_num": config["ipv6"].as_int("rs_queue"),
"ns_queue_num": config["ipv6"].as_int("ns_queue"),
"ra_period": config["ipv6"].as_int("ra_period"),
"ipv6_nameservers": config["ipv6"]["nameservers"],
+ "dhcpv6_domains": config["ipv6"]["domains"],
})
# pylint: disable=W0142
logging.info("Ready to serve requests")
- def handler(signum, frame):
- logging.debug('Received SIGUSR1. Printing current proxy state...')
+ def debug_handler(signum, _):
+ logging.debug('Received signal %d. Printing proxy state...', signum)
proxy.print_clients()
# Set the signal handler for debuging clients
- signal.signal(signal.SIGUSR1, handler)
+ signal.signal(signal.SIGUSR1, debug_handler)
signal.siginterrupt(signal.SIGUSR1, False)
try: