-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathnfdhcpd
executable file
·1220 lines (1002 loc) · 40.3 KB
/
nfdhcpd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
#
# nfdcpd: A promiscuous, NFQUEUE-based DHCP server for virtual machine hosting
# Copyright (c) 2010, 2011, 2012, 2013, 2014 GRNET SA
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
import os
import signal
import errno
import re
import sys
import glob
import time
import logging
import logging.handlers
import threading
import traceback
import daemon
import daemon.runner
import daemon.pidlockfile
import nfqueue
import pyinotify
import setproctitle
from lockfile import LockTimeout
import IPy
import socket
import select
from socket import AF_INET, AF_INET6
from scapy.data import ETH_P_ALL
from scapy.packet import BasePacket
from scapy.layers.l2 import Ether
from scapy.layers.inet import IP, UDP
from scapy.layers.inet6 import IPv6, ICMPv6ND_RA, ICMPv6ND_NA, \
ICMPv6NDOptDstLLAddr, \
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"
DEFAULT_PATH = "/var/run/ganeti-dhcpd"
DEFAULT_USER = "nobody"
DEFAULT_LEASE_LIFETIME = 604800 # 1 week
DEFAULT_LEASE_RENEWAL = 600 # 10 min
DEFAULT_RA_PERIOD = 300 # seconds
DHCP_DUMMY_SERVER_IP = "1.2.3.4"
LOG_FILENAME = "nfdhcpd.log"
SYSFS_NET = "/sys/class/net"
LOG_FORMAT = "%(asctime)-15s %(levelname)-8s %(message)s"
# Configuration file specification (see configobj documentation)
CONFIG_SPEC = """
[general]
pidfile = string()
datapath = string()
logdir = string()
user = string()
[dhcp]
enable_dhcp = boolean(default=True)
lease_lifetime = integer(min=0, max=4294967295)
lease_renewal = integer(min=0, max=4294967295)
server_ip = ip_addr()
dhcp_queue = integer(min=0, max=65535)
nameservers = ip_addr_list(family=4)
domain = string(default=None)
[ipv6]
enable_ipv6 = boolean(default=True)
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)
"""
DHCPDISCOVER = 1
DHCPOFFER = 2
DHCPREQUEST = 3
DHCPDECLINE = 4
DHCPACK = 5
DHCPNAK = 6
DHCPRELEASE = 7
DHCPINFORM = 8
DHCP_TYPES = {
DHCPDISCOVER: "DHCPDISCOVER",
DHCPOFFER: "DHCPOFFER",
DHCPREQUEST: "DHCPREQUEST",
DHCPDECLINE: "DHCPDECLINE",
DHCPACK: "DHCPACK",
DHCPNAK: "DHCPNAK",
DHCPRELEASE: "DHCPRELEASE",
DHCPINFORM: "DHCPINFORM",
}
DHCP_REQRESP = {
DHCPDISCOVER: DHCPOFFER,
DHCPREQUEST: DHCPACK,
DHCPINFORM: DHCPACK,
}
def get_indev(payload):
try:
indev_ifindex = payload.get_physindev()
if indev_ifindex:
logging.debug(" - Incoming packet from bridge with ifindex %s",
indev_ifindex)
return indev_ifindex
except AttributeError:
#TODO: return error value
logging.debug("No get_physindev() supported")
return 0
indev_ifindex = payload.get_indev()
logging.debug(" - Incoming packet from tap with ifindex %s", indev_ifindex)
return indev_ifindex
def parse_binding_file(path):
""" Read a client configuration from a tap file
"""
logging.info("Parsing binding file %s", path)
try:
iffile = open(path, 'r')
except EnvironmentError, e:
logging.warn(" - Unable to open binding file %s: %s", path, str(e))
return None
tap = os.path.basename(path)
indev = None
mac = None
ip = None
hostname = None
subnet = None
gateway = None
subnet6 = None
gateway6 = None
eui64 = None
def get_value(line):
v = line.strip().split('=')[1]
if v == '':
return None
return v
for line in iffile:
if line.startswith("IP="):
ip = get_value(line)
elif line.startswith("MAC="):
mac = get_value(line)
elif line.startswith("HOSTNAME="):
hostname = get_value(line)
elif line.startswith("INDEV="):
indev = get_value(line)
elif line.startswith("SUBNET="):
subnet = get_value(line)
elif line.startswith("GATEWAY="):
gateway = get_value(line)
elif line.startswith("SUBNET6="):
subnet6 = get_value(line)
elif line.startswith("GATEWAY6="):
gateway6 = get_value(line)
elif line.startswith("EUI64="):
eui64 = get_value(line)
try:
return Client(tap=tap, mac=mac, ip=ip, hostname=hostname,
indev=indev, subnet=subnet, gateway=gateway,
subnet6=subnet6, gateway6=gateway6, eui64=eui64 )
except ValueError:
logging.warning(" - Cannot add client for host %s and IP %s on tap %s",
hostname, ip, tap)
return None
class ClientFileHandler(pyinotify.ProcessEvent):
def __init__(self, server):
pyinotify.ProcessEvent.__init__(self)
self.server = server
def process_IN_DELETE(self, event): # pylint: disable=C0103
""" Delete file handler
Currently this removes an interface from the watch list
"""
self.server.remove_tap(event.name)
def process_IN_CLOSE_WRITE(self, event): # pylint: disable=C0103
""" Add file handler
Currently this adds an interface to the watch list
"""
self.server.add_tap(os.path.join(event.path, event.name))
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):
self.mac = mac
self.ip = ip
self.hostname = hostname
self.indev = indev
self.tap = tap
self.subnet = subnet
self.gateway = gateway
self.net = Subnet(net=subnet, gw=gateway, dev=tap)
self.subnet6 = subnet6
self.gateway6 = gateway6
self.net6 = Subnet(net=subnet6, gw=gateway6, dev=tap)
self.eui64 = eui64
self.open_socket()
def is_valid(self):
return self.mac is not None and self.hostname is not None
def open_socket(self):
logging.info(" - Opening L2 socket and binding to %s", self.tap)
try:
s = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, ETH_P_ALL)
s.setsockopt(socket.SOL_SOCKET, socket.SO_RCVBUF, 0)
s.bind((self.tap, ETH_P_ALL))
self.socket = s
except socket.error, e:
logging.warning(" - Cannot open socket %s", e)
def sendp(self, data):
if isinstance(data, BasePacket):
data = str(data)
logging.debug(" - Sending raw packet %r", data)
try:
count = self.socket.send(data, socket.MSG_DONTWAIT)
except socket.error, e:
logging.warn(" - Send with MSG_DONTWAIT failed: %s", str(e))
self.socket.close()
self.open_socket()
raise e
ldata = len(data)
logging.debug(" - Sent %d bytes on %s", count, self.tap)
if count != ldata:
logging.warn(" - Truncated msg: %d/%d bytes sent",
count, ldata)
def __repr__(self):
ret = "hostname %s, tap %s, mac %s" % \
(self.hostname, self.tap, self.mac)
if self.ip:
ret += ", ip %s" % self.ip
if self.eui64:
ret += ", eui64 %s" % self.eui64
return ret
class Subnet(object):
def __init__(self, net=None, gw=None, dev=None):
if isinstance(net, str):
try:
self.net = IPy.IP(net)
except ValueError, e:
logging.warning(" - IPy error: %s", e)
raise e
else:
self.net = net
self.gw = gw
self.dev = dev
@property
def netmask(self):
""" Return the netmask in textual representation
"""
return str(self.net.netmask())
@property
def broadcast(self):
""" Return the broadcast address in textual representation
"""
return str(self.net.broadcast())
@property
def prefix(self):
""" Return the network as an IPy.IP
"""
return self.net.net()
@property
def prefixlen(self):
""" Return the prefix length as an integer
"""
return self.net.prefixlen()
@staticmethod
def _make_eui64(net, mac):
""" Compute an EUI-64 address from an EUI-48 (MAC) address
"""
if mac is None:
return None
comp = mac.split(":")
prefix = IPy.IP(net).net().strFullsize().split(":")[:4]
eui64 = comp[:3] + ["ff", "fe"] + comp[3:]
eui64[0] = "%02x" % (int(eui64[0], 16) ^ 0x02)
for l in range(0, len(eui64), 2):
prefix += ["".join(eui64[l:l+2])]
return IPy.IP(":".join(prefix))
def make_eui64(self, mac):
""" Compute an EUI-64 address from an EUI-48 (MAC) address in this
subnet.
"""
return self._make_eui64(self.net, mac)
def make_ll64(self, mac):
""" Compute an IPv6 Link-local address from an EUI-48 (MAC) address
"""
return self._make_eui64("fe80::", mac)
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, dhcpv6_queue_num=None,
dhcp_lease_lifetime=DEFAULT_LEASE_LIFETIME,
dhcp_lease_renewal=DEFAULT_LEASE_RENEWAL,
dhcp_domain=None,
dhcp_server_ip=DHCP_DUMMY_SERVER_IP, dhcp_nameservers=None,
ra_period=DEFAULT_RA_PERIOD, ipv6_nameservers=None,
dhcpv6_domains=None):
try:
getattr(nfqueue.payload, 'get_physindev')
self.mac_indexed_clients = False
except AttributeError:
self.mac_indexed_clients = True
self.data_path = data_path
self.lease_lifetime = dhcp_lease_lifetime
self.lease_renewal = dhcp_lease_renewal
self.dhcp_domain = dhcp_domain
self.dhcp_server_ip = dhcp_server_ip
self.ra_period = ra_period
if dhcp_nameservers is None:
self.dhcp_nameserver = []
else:
self.dhcp_nameservers = dhcp_nameservers
if ipv6_nameservers is None:
self.ipv6_nameservers = []
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.subnets = {}
#self.ifaces = {}
#self.v6nets = {}
self.nfq = {}
# Inotify setup
self.wm = pyinotify.WatchManager()
mask = pyinotify.EventsCodes.ALL_FLAGS["IN_DELETE"]
mask |= pyinotify.EventsCodes.ALL_FLAGS["IN_CLOSE_WRITE"]
inotify_handler = ClientFileHandler(self)
self.notifier = pyinotify.Notifier(self.wm, inotify_handler)
self.wm.add_watch(self.data_path, mask, rec=True)
# NFQUEUE setup
if dhcp_queue_num is not None:
self._setup_nfqueue(dhcp_queue_num, AF_INET, self.dhcp_response, 0)
if rs_queue_num is not None:
self._setup_nfqueue(rs_queue_num, AF_INET6, self.rs_response, 10)
self.ipv6_enabled = True
if ns_queue_num is not None:
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]
logging.info(" - Client found. %s", b)
return b
except KeyError:
logging.info(" - No client found. mac: %s, ifindex: %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, _ in self.nfq.values():
q.close()
logging.debug(" - Stopping inotify watches")
self.notifier.stop()
logging.info(" - Cleanup finished")
def _setup_nfqueue(self, queue_num, family, callback, pending):
logging.info("Setting up NFQUEUE for queue %d, AF %s",
queue_num, family)
q = nfqueue.queue()
q.set_callback(callback)
q.fast_open(queue_num, family)
q.set_queue_maxlen(5000)
# This is mandatory for the queue to operate
q.set_mode(nfqueue.NFQNL_COPY_PACKET)
self.nfq[q.get_fd()] = (q, pending)
logging.debug(" - Successfully set up NFQUEUE %d", queue_num)
def build_config(self):
self.clients.clear()
for path in glob.glob(os.path.join(self.data_path, "*")):
self.add_tap(path)
self.print_clients()
def get_ifindex(self, iface):
""" Get the interface index from sysfs
"""
logging.debug(" - Getting ifindex for interface %s from sysfs", iface)
path = os.path.abspath(os.path.join(SYSFS_NET, iface, "ifindex"))
if not path.startswith(SYSFS_NET):
return None
ifindex = None
try:
f = open(path, 'r')
except EnvironmentError:
logging.debug(" - %s is probably down, removing", iface)
self.remove_tap(iface)
return ifindex
try:
ifindex = f.readline().strip()
try:
ifindex = int(ifindex)
except ValueError, e:
logging.warn(" - Failed to get ifindex for %s, cannot parse"
" sysfs output '%s'", iface, ifindex)
except EnvironmentError, e:
logging.warn(" - Error reading %s's ifindex from sysfs: %s",
iface, str(e))
self.remove_tap(iface)
finally:
f.close()
return ifindex
def get_iface_hw_addr(self, iface):
""" Get the interface hardware address from sysfs
"""
logging.debug(" - Getting mac for iface %s", iface)
path = os.path.abspath(os.path.join(SYSFS_NET, iface, "address"))
if not path.startswith(SYSFS_NET):
return None
addr = None
try:
f = open(path, 'r')
except EnvironmentError:
logging.debug(" - %s is probably down, removing", iface)
self.remove_tap(iface)
return addr
try:
addr = f.readline().strip()
except EnvironmentError, e:
logging.warn(" - Failed to read hw address for %s from sysfs: %s",
iface, str(e))
finally:
f.close()
return addr
def add_tap(self, path):
""" Add an interface to monitor
"""
tap = os.path.basename(path)
logging.info("Updating configuration for %s", tap)
b = parse_binding_file(path)
if b is None:
return
ifindex = self.get_ifindex(b.tap)
if ifindex is None:
logging.warn(" - Stale configuration for %s found", tap)
else:
if b.is_valid():
if self.mac_indexed_clients:
self.clients[b.mac] = b
k = b.mac
else:
self.clients[ifindex] = b
k = ifindex
logging.info(" - Added client %s. %s", k, b)
def remove_tap(self, tap):
""" Cleanup clients on a removed interface
"""
try:
for k, cl in self.clients.items():
if cl.tap == tap:
cl.socket.close()
del self.clients[k]
logging.info("Removed client %s. %s", k, cl)
except:
logging.debug("Client on %s disappeared!!!", tap)
def dhcp_response(self, arg1, arg2=None): # pylint: disable=W0613,R0914
""" Generate a reply to bnetfilter-queue-deva BOOTP/DHCP request
"""
logging.info(" * DHCP: Processing pending 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())
# Get the client MAC address
resp = pkt.getlayer(BOOTP).copy()
hlen = resp.hlen
mac = resp.chaddr[:hlen].encode("hex")
mac, _ = re.subn(r'([0-9a-fA-F]{2})', r'\1:', mac, hlen - 1)
# Server responses are always BOOTREPLYs
resp.op = "BOOTREPLY"
del resp.payload
indev = get_indev(payload)
binding = self.get_binding(indev, mac)
if binding is None:
# We don't know anything about this interface, so accept the packet
# and return an 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)
if mac != binding.mac:
logging.warn(" - DHCP: Recieved spoofed request from %s (and not %s)",
mac, binding)
return
if not binding.ip:
logging.info(" - DHCP: No IP found in binding file %s.", binding)
return
if not DHCP in pkt:
logging.warn(" - DHCP: Invalid request with no DHCP payload found. %s", binding)
return
resp = Ether(dst=mac, src=self.get_iface_hw_addr(binding.indev))/\
IP(src=DHCP_DUMMY_SERVER_IP, dst=binding.ip)/\
UDP(sport=pkt.dport, dport=pkt.sport)/resp
subnet = binding.net
dhcp_options = []
requested_addr = binding.ip
for opt in pkt[DHCP].options:
if type(opt) is tuple and opt[0] == "message-type":
req_type = opt[1]
if type(opt) is tuple and opt[0] == "requested_addr":
requested_addr = opt[1]
logging.info(" - DHCP: %s from %s",
DHCP_TYPES.get(req_type, "UNKNOWN"), binding)
if self.dhcp_domain:
domainname = self.dhcp_domain
else:
domainname = binding.hostname.split('.', 1)[-1]
if req_type == DHCPREQUEST and requested_addr != binding.ip:
resp_type = DHCPNAK
logging.info(" - DHCP: Sending DHCPNAK to %s (because requested %s)",
binding, requested_addr)
elif req_type in (DHCPDISCOVER, DHCPREQUEST):
resp_type = DHCP_REQRESP[req_type]
resp.yiaddr = binding.ip
dhcp_options += [
("hostname", binding.hostname),
("domain", domainname),
("broadcast_address", str(subnet.broadcast)),
("subnet_mask", str(subnet.netmask)),
("renewal_time", self.lease_renewal),
("lease_time", self.lease_lifetime),
]
if subnet.gw:
dhcp_options += [("router", subnet.gw)]
dhcp_options += [("name_server", x) for x in self.dhcp_nameservers]
elif req_type == DHCPINFORM:
resp_type = DHCP_REQRESP[req_type]
dhcp_options += [
("hostname", binding.hostname),
("domain", domainname),
]
dhcp_options += [("name_server", x) for x in self.dhcp_nameservers]
elif req_type == DHCPRELEASE:
# Log and ignore
logging.info(" - DHCP: DHCPRELEASE from %s", binding)
return
# Finally, always add the server identifier and end options
dhcp_options += [
("message-type", resp_type),
("server_id", DHCP_DUMMY_SERVER_IP),
"end"
]
resp /= DHCP(options=dhcp_options)
logging.info(" - RESPONSE: %s for %s", DHCP_TYPES[resp_type], binding)
try:
binding.sendp(resp)
except socket.error, e:
logging.warn(" - DHCP: Response on %s failed: %s", binding, str(e))
except Exception, e:
logging.warn(" - DHCP: Unkown error during response on %s: %s",
binding, str(e))
def dhcpv6_response(self, arg1, arg2=None): # pylint: disable=W0613
logging.info(" * DHCPv6: Processing pending 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 and 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(" - DHCPv6: No IPv6 network assigned to %s", binding)
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
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)
logging.info(" - RESPONSE: DHCPv6 reply for %s", binding)
try:
binding.sendp(resp)
except socket.error, e:
logging.warn(" - DHCPv6: Response on %s failed: %s",
binding, str(e))
except Exception, e:
logging.warn(" - DHCPv6: Unkown error during response on %s: %s",
binding, str(e))
def rs_response(self, arg1, arg2=None): # pylint: disable=W0613
""" Generate a reply to an ICMPv6 router solicitation
"""
logging.info(" * RS: Processing pending 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:
mac = pkt.lladdr
except:
logging.debug(" - RS: Cannot obtain lladdr")
return
indev = get_indev(payload)
binding = self.get_binding(indev, mac)
if binding is None:
# We don't know anything about this interface, so accept the packet
# and return and 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)
if mac != binding.mac:
logging.warn(" - RS: Received spoofed request from %s (and not %s)",
mac, binding)
return
subnet = binding.net6
if subnet.net is None:
logging.debug(" - RS: No IPv6 network assigned to %s", binding)
return
indevmac = self.get_iface_hw_addr(binding.indev)
ifll = subnet.make_ll64(indevmac)
if ifll is None:
return
resp = Ether(src=indevmac)/\
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)
logging.info(" - RESPONSE: RA for %s", binding)
try:
binding.sendp(resp)
except socket.error, e:
logging.warn(" - RS: RA failed on %s: %s",
binding, str(e))
except Exception, e:
logging.warn(" - RS: Unkown error during RA on %s: %s",
binding, str(e))
def ns_response(self, arg1, arg2=None): # pylint: disable=W0613
""" Generate a reply to an ICMPv6 neighbor solicitation
"""
logging.info(" * NS: Processing pending 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())
try:
mac = ns.lladdr
except:
logging.debug(" - NS: Cannot obtain lladdr")
return
indev = get_indev(payload)
binding = self.get_binding(indev, mac)
if binding is None:
# We don't know anything about this interface, so accept the packet
# and return and let the kernel handle it
payload.set_verdict(nfqueue.NF_ACCEPT)
return
payload.set_verdict(nfqueue.NF_DROP)
if mac != binding.mac:
logging.warn(" - NS: Received spoofed request from %s (and not %s)",
mac, binding)
return
subnet = binding.net6
if subnet.net is None:
logging.debug(" - NS: No IPv6 network assigned to %s", binding)
return
indevmac = self.get_iface_hw_addr(binding.indev)
ifll = subnet.make_ll64(indevmac)
if ifll is None:
return
if not (subnet.net.overlaps(ns.tgt) or str(ns.tgt) == str(ifll)):
logging.debug(" - NS: Received NS for a non-routable IP (%s)", ns.tgt)
return 1
resp = Ether(src=indevmac, dst=binding.mac)/\
IPv6(src=str(ifll), dst=ns.src)/\
ICMPv6ND_NA(R=1, O=0, S=1, tgt=ns.tgt)/\
ICMPv6NDOptDstLLAddr(lladdr=indevmac)
logging.info(" - RESPONSE: NA for %s ", binding)
try:
binding.sendp(resp)
except socket.error, e:
logging.warn(" - NS: NA on %s failed: %s",
binding, str(e))
except Exception, e:
logging.warn(" - NS: Unkown error during NA to %s: %s",
binding, str(e))
def send_periodic_ra(self):
# Use a separate thread as this may take a _long_ time with
# many interfaces and we want to be responsive in the mean time
threading.Thread(target=self._send_periodic_ra).start()
def _send_periodic_ra(self):
logging.info(" * Periodic RA: Starting...")
start = time.time()
i = 0
for binding in self.clients.values():
tap = binding.tap
indev = binding.indev
# mac = binding.mac
subnet = binding.net6
if subnet.net is None:
logging.debug(" - Periodic RA: Skipping %s", binding)
continue
indevmac = self.get_iface_hw_addr(indev)
ifll = subnet.make_ll64(indevmac)
if ifll is None:
continue
resp = Ether(src=indevmac)/\
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)
logging.info(" - RESPONSE: NA for %s ", binding)
try:
binding.sendp(resp)
except socket.error, e:
logging.warn(" - Periodic RA: Failed on %s: %s",
binding, str(e))
except Exception, e:
logging.warn(" - Periodic RA: Unkown error on %s: %s",
binding, str(e))
i += 1
logging.info(" - Periodic RA: Sent %d RAs in %.2f seconds", i, time.time() - start)
def serve(self):
""" Safely perform the main loop, freeing all resources upon exit
"""
try:
self._serve()
finally:
self._cleanup()
def _serve(self):
""" Loop forever, serving DHCP requests
"""
self.build_config()
# Yes, we are accessing _fd directly, but it's the only way to have a
# single select() loop ;-)
iwfd = self.notifier._fd # pylint: disable=W0212
start = time.time()
if self.ipv6_enabled:
timeout = self.ra_period
self.send_periodic_ra()
else:
timeout = None
while True:
try:
rlist, _, xlist = select.select(self.nfq.keys() + [iwfd],
[], [], timeout)
except select.error, e:
if e[0] == errno.EINTR:
logging.debug("select() got interrupted")
continue
if xlist:
logging.warn("Warning: Exception on %s",
", ".join([str(fd) for fd in xlist]))
if rlist:
if iwfd in rlist:
# First check if there are any inotify (= configuration change)
# events
self.notifier.read_events()