forked from jaysoffian/eap_proxy
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy patheap_proxy.py
executable file
·786 lines (670 loc) · 26.5 KB
/
eap_proxy.py
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
#!/usr/bin/env python
"""
Inspired by 1x_prox as posted here:
http://www.dslreports.com/forum/r30693618-
AT&T Residential Gateway Bypass - True bridge mode!
usage: eap_proxy [-h] [--ping-gateway] [--ignore-when-wan-up] [--ignore-start]
[--ignore-logoff] [--restart-dhcp] [--set-mac] [--daemon]
[--pidfile [PIDFILE]] [--syslog] [--promiscuous] [--debug]
[--debug-packets]
IF_WAN IF_ROUTER
positional arguments:
IF_WAN interface of the AT&T ONT/WAN
IF_ROUTER interface of the AT&T router
optional arguments:
-h, --help show this help message and exit
checking whether WAN is up:
--ping-gateway normally the WAN is considered up if IF_WAN.0 has an
IP address; this option additionally requires that
there is a default route gateway that responds to a
ping
ignoring router packets:
--ignore-when-wan-up ignore router packets when WAN is up (see --ping-
gateway)
--ignore-start always ignore EAPOL-Start from router
--ignore-logoff always ignore EAPOL-Logoff from router
configuring IF_WAN.0 VLAN:
--restart-dhcp check whether WAN is up after receiving EAP-Success on
IF_WAN (see --ping-gateway); if not, restart system's
DHCP client on IF_WAN.0
--set-mac set IF_WAN.0's MAC (ether) address to router's MAC
address
daemonization:
--daemon become a daemon; implies --syslog
--pidfile [PIDFILE] record pid to PIDFILE; default: /var/run/eap_proxy.pid
--syslog log to syslog instead of stderr
debugging:
--promiscuous place interfaces into promiscuous mode instead of
multicast
--debug enable debug-level logging
--debug-packets print packets in hex format to assist with debugging;
implies --debug
"""
# pylint:disable=invalid-name,missing-docstring
import argparse
import array
import atexit
import ctypes
import ctypes.util
import logging
import logging.handlers
import os
import random
import re
import select
import signal
import socket
import struct
import subprocess
import sys
import time
import traceback
from collections import namedtuple
from fcntl import ioctl
from functools import partial
### Constants
EAP_MULTICAST_ADDR = (0x01, 0x80, 0xc2, 0x00, 0x00, 0x03)
ETH_P_PAE = 0x888e # IEEE 802.1X (Port Access Entity)
IFF_PROMISC = 0x100
PACKET_ADD_MEMBERSHIP = 1
PACKET_MR_MULTICAST = 0
PACKET_MR_PROMISC = 1
SIOCGIFADDR = 0x8915
SIOCGIFFLAGS = 0x8913
SIOCSIFFLAGS = 0x8914
SOL_PACKET = 263
### Sockets / Network Interfaces
class struct_packet_mreq(ctypes.Structure):
# pylint:disable=too-few-public-methods
_fields_ = (
("mr_ifindex", ctypes.c_int),
("mr_type", ctypes.c_ushort),
("mr_alen", ctypes.c_ushort),
("mr_address", ctypes.c_ubyte * 8))
if_nametoindex = ctypes.CDLL(ctypes.util.find_library('c')).if_nametoindex
def addsockaddr(sock, address):
"""Configure physical-layer multicasting or promiscuous mode for `sock`.
If `addr` is None, promiscuous mode is configured. Otherwise `addr`
should be a tuple of up to 8 bytes to configure that multicast address.
"""
# pylint:disable=attribute-defined-outside-init
mreq = struct_packet_mreq()
mreq.mr_ifindex = if_nametoindex(getifname(sock))
if address is None:
mreq.mr_type = PACKET_MR_PROMISC
else:
mreq.mr_type = PACKET_MR_MULTICAST
mreq.mr_alen = len(address)
mreq.mr_address = address
sock.setsockopt(SOL_PACKET, PACKET_ADD_MEMBERSHIP, mreq)
def rawsocket(ifname, poll=None, promisc=False):
"""Return raw socket listening for 802.1X packets on `ifname` interface.
The socket is configured for multicast mode on EAP_MULTICAST_ADDR.
Specify `promisc` to enable promiscuous mode instead.
Provide `poll` object to register socket to it POLLIN events.
"""
s = socket.socket(
socket.PF_PACKET, # pylint:disable=no-member
socket.SOCK_RAW,
socket.htons(ETH_P_PAE))
s.bind((ifname, 0))
addsockaddr(s, None if promisc else EAP_MULTICAST_ADDR)
if poll is not None:
poll.register(s, select.POLLIN) # pylint:disable=no-member
return s
def getifname(sock):
"""Return interface name of `sock`"""
return sock.getsockname()[0]
def getifaddr(ifname):
"""Return IP addr of `ifname` interface in 1.2.3.4 notation
or None if no IP is assigned or other IOError occurs.
"""
# pylint:disable=attribute-defined-outside-init
ifreq = "%-32s" % (ifname + "\0")
try:
result = ioctl(socket.socket(), SIOCGIFADDR, ifreq)
except IOError:
return None
return socket.inet_ntoa(result[20:24])
def getifhwaddr(ifname):
"""Return MAC address for `ifname` as a packed string."""
with open("/sys/class/net/%s/address" % ifname) as f:
s = f.readline()
octets = s.split(':')
return ''.join(chr(int(x, 16)) for x in octets)
def getdefaultgatewayaddr():
"""Return IP of default route gateway (next hop) in 1.2.3.4 notation
or None if there is not default route.
"""
search = re.compile(r"^\S+\s+00000000\s+([0-9a-fA-F]{8})").search
with open("/proc/net/route") as f:
for line in f:
m = search(line)
if m:
hexaddr = m.group(1)
octets = (hexaddr[i:i + 2] for i in xrange(0, 7, 2))
ipaddr = '.'.join(str(int(octet, 16)) for octet in octets)
return ipaddr
### Ping
def ipchecksum(packet):
"""Return IP checksum of `packet`"""
# c.f. https://tools.ietf.org/html/rfc1071
arr = array.array('H', packet + '\0' if len(packet) % 2 else packet)
chksum = sum(arr)
chksum = (chksum >> 16) + (chksum & 0xffff) # add high and low 16 bits
chksum += chksum >> 16 # add carry
chksum = ~chksum & 0xffff # invert and truncate
return socket.htons(chksum) # per RFC 1071
def pingaddr(ipaddr, data='', timeout=1.0, strict=False):
"""Return True if `ipaddr` replies to an ICMP ECHO request within
`timeout` seconds else False. Provide optional `data` to include in
the request. Any reply from `ipaddr` will suffice. Use `strict` to
accept only a reply matching the request.
"""
# pylint:disable=too-many-locals
# construct packet
if len(data) > 2000:
raise ValueError("data too large")
icmp_struct = struct.Struct("!BBHHH")
echoid = os.getpid() & 0xffff
seqnum = random.randint(0, 0xffff)
chksum = ipchecksum(icmp_struct.pack(8, 0, 0, echoid, seqnum) + data)
packet = icmp_struct.pack(8, 0, chksum, echoid, seqnum) + data
# send it and check reply
sock = socket.socket(socket.AF_INET, socket.SOCK_RAW, 1)
sock.sendto(packet, (ipaddr, 1))
t0 = time.time()
while time.time() - t0 < timeout:
ready, __, __ = select.select([sock], (), (), timeout)
if not ready:
return False
packet, peer = sock.recvfrom(2048)
if peer[0] != ipaddr:
continue
if not strict:
return True
# verify it's a reply to the packet we just sent
packet = packet[20:] # strip IP header
fields = icmp_struct.unpack(packet[:8])
theirs = fields[-2:] + (packet[8:],)
if theirs == (echoid, seqnum, data):
return True
return False
### Helpers
def strbuf(buf):
"""Return `buf` formatted as a hex dump (like tcpdump -xx)."""
out = []
for i in xrange(0, len(buf), 16):
octets = (ord(x) for x in buf[i:i + 16])
pairs = []
for octet in octets:
pad = '' if len(pairs) % 2 else ' '
pairs.append("%s%02x" % (pad, octet))
out.append("0x%04x: %s" % (i, '' .join(pairs)))
return '\n'.join(out)
def strmac(mac):
"""Return packed string `mac` formatted like aa:bb:cc:dd:ee:ff."""
return ':'.join("%02x" % ord(b) for b in mac[:6])
def strexc():
"""Return current exception formatted as a single line suitable
for logging.
"""
try:
exc_type, exc_value, tb = sys.exc_info()
if exc_type is None:
return ''
# find last frame in this script
lineno, func = 0, ''
for frame in traceback.extract_tb(tb):
if frame[0] != __file__:
break
lineno, func = frame[1:3]
return "exception in %s line %s (%s: %s)" % (
func, lineno, exc_type.__name__, exc_value)
finally:
del tb
def killpidfile(pidfile, signum):
"""Send `signum` to PID recorded in `pidfile`.
Return PID if successful, else return None.
"""
try:
with open(pidfile) as f:
pid = int(f.readline())
os.kill(pid, signum)
return pid
except (EnvironmentError, ValueError):
pass
def checkpidfile(pidfile):
"""Check whether a process is running with the PID in `pidfile`.
Return PID if successful, else return None.
"""
return killpidfile(pidfile, 0)
def safe_unlink(path):
"""rm -f `path`"""
try:
os.unlink(path)
except EnvironmentError:
pass
def writepidfile(pidfile):
"""Write current pid to `pidfile`."""
with open(pidfile, 'w') as f:
f.write("%s\n" % os.getpid())
# NOTE: called on normal Python exit, but not on SIGTERM.
@atexit.register
def removepidfile(_remove=os.remove): # pylint:disable=unused-variable
try:
_remove(pidfile)
except Exception: # pylint:disable=broad-except
pass
def daemonize():
"""Convert process into a daemon."""
if os.fork():
sys.exit(0)
os.chdir("/")
os.setsid()
os.umask(0)
if os.fork():
sys.exit(0)
sys.stdout.flush()
sys.stderr.flush()
nullin = open('/dev/null', 'r')
nullout = open('/dev/null', 'a+')
nullerr = open('/dev/null', 'a+', 0)
os.dup2(nullin.fileno(), sys.stdin.fileno())
os.dup2(nullout.fileno(), sys.stdout.fileno())
os.dup2(nullerr.fileno(), sys.stderr.fileno())
def make_logger(use_syslog=False, debug=False):
"""Return new logging.Logger object."""
if use_syslog:
formatter = logging.Formatter("eap_proxy[%(process)d]: %(message)s")
formatter.formatException = lambda *__: '' # no stack trace to syslog
SysLogHandler = logging.handlers.SysLogHandler
handler = SysLogHandler("/dev/log", facility=SysLogHandler.LOG_LOCAL7)
handler.setFormatter(formatter)
else:
formatter = logging.Formatter("[%(asctime)s]: %(message)s")
handler = logging.StreamHandler()
handler.setFormatter(formatter)
logger = logging.getLogger("eap_proxy")
if debug:
logger.setLevel(logging.DEBUG)
else:
logger.setLevel(logging.INFO)
logger.addHandler(handler)
return logger
def network_interface(ifname, ifdir="/sys/class/net/"):
"""A `type` for ArgumentParser.add_argument(). Return
`ifname` if `ifname` is the name of a physical network
interface, else raise argparse.ArgumentTypeError.
"""
# only physical and virtual devices are in /sys/class/net/, no aliases
physifs = [name for name in os.listdir(ifdir)
if "virtual" not in os.path.realpath(ifdir + name)]
if ifname not in physifs:
err = (("\"%s\" isn't a physical network interface; "
"you probably meant one of: %s") %
(ifname, " ".join(sorted(physifs))))
raise argparse.ArgumentTypeError(err)
return ifname
def wan_network_interface(ifname, ifdir="/sys/class/net/"):
"""Same as network_interface(), but a VLAN called
`ifname`.0 must also exist on the interface.
"""
# NOTE: the VLAN doesn't need to be named IF_WAN.0, it just needs to be on
# top of IF_WAN with VLAN ID 0. However, Debian autoconfigures VLANs using
# /etc/network/if-pre-up.d/vlan, which tries (not always successfully;
# "auto eth0.0" results in a VLAN named eth0.0000) to derive underlying
# interface, VLAN ID, and name padding arguments for vconfig from things
# named <thing>.<digits> it finds in /etc/network/interfaces.
#
# A workaround is to edit vlan and add a special case exactly matching the
# desired VLAN interface name of IF_WAN.0, as in the example below. The
# IF_VLAN_RAW_DEVICE line is only necessary if "vlan-raw-device eth0" is
# not in the "iface eth0.0 inet dhcp" section in /etc/network/interfaces.
#
# case "$IFACE" in
# [ ... ]
# # for eap_proxy: special case to create eth0.0 properly
# eth0.0)
# vconfig set_name_type DEV_PLUS_VID_NO_PAD
# VLANID=0
# IF_VLAN_RAW_DEVICE=eth0
# ;;
# [ ... ]
ifname = network_interface(ifname)
ifvlan = ifname + ".0"
# being sure of VLAN ID would require parsing /proc/net/vlan/config; just
# assume it's 0 from the device name and match values of iflink in sysfs
# c.f. https://www.kernel.org/doc/Documentation/ABI/testing/sysfs-class-net
if ifvlan in os.listdir(ifdir):
try:
with open(ifdir + ifname + "/iflink") as f, \
open(ifdir + ifvlan + "/iflink") as g:
if int(f.readline()) == int(g.readline()):
return ifname
except Exception: # pylint:disable=broad-except
pass
err = "no VLAN %s exists on interface \"%s\"" % (ifvlan, ifname)
raise argparse.ArgumentTypeError(err)
### Linux
class LinuxOS(object):
def __init__(self, log):
self.log = log
def run(self, shellcmd):
try:
# subprocess.check_output(args) ignores stderr, but for some reason
# check_output(args, stderr=subprocess.STDOUT) isn't working, at
# least when running as a daemon, with the following syslog output:
# eap_proxy[nnn]: exception in run line nnn (AttributeError: 'list'
# object has no attribute 'rfind'); restarting in 10 seconds
# Workaround by passing the command + arguments as one string and
# shell=True to check_output(). Also, validate IF_WAN and IF_ROUTER
# when parsing script arguments to prevent shell injection.
return 0, subprocess.check_output(shellcmd,
stderr=subprocess.STDOUT,
universal_newlines=True,
shell=True)
except subprocess.CalledProcessError as ex:
self.log.warn("%s exited %d", shellcmd, ex.returncode)
return ex.returncode, ex.output
def restart_dhcp_client(self, name):
"""Restart the system's DHCP client on the `name` interface."""
# On Debian, setting an interface to use DHCP in /etc/network/interfaces
# makes ifupdown generate the proper commands (including PID, lease, and
# DUID file options) for running a supported DHCP client on it from
# templates hardcoded into the binary at compile time. Capture them.
search = re.compile(r"dhclient|pump|udhcpc|dhcpcd").search
def call_ifupdown(ifupdown): # path to ifupdown binary
__, output = self.run("%s --force --verbose --no-act %s" %
(ifupdown, name)) # prints to stderr
client_call = False
for line in output.splitlines():
if search(line): # ifupdown would run a DHCP client
self.run(line)
client_call = True
if not client_call:
self.log.warn("`%s %s` does not run a DHCP client; disable "
"NetworkManager on %s if enabled",
ifupdown,
name,
name)
self.log.warn("DHCP client was not restarted on %s", name)
call_ifupdown("/sbin/ifdown") # calling ifupdown as ifdown
call_ifupdown("/sbin/ifup")
def setmac(self, ifname, mac):
"""Set interface `ifname` mac to `mac`, which may be either a packed
string or in "aa:bb:cc:dd:ee:ff" format."""
if len(mac) == 6:
mac = strmac(mac)
# iproute2. ifupdown probably shouldn't apply configs, e.g. if-up.d/*
self.run("/bin/ip link set dev %s down" % ifname)
self.run("/bin/ip %s hw ether %s" % (ifname, mac))
self.run("/bin/ip link set dev %s up" % ifname)
@staticmethod
def getmac(ifname):
"""Return MAC address for `ifname` as a packed string."""
return getifhwaddr(ifname)
### EAP frame/packet decoding
# c.f. https://github.com/the-tcpdump-group/tcpdump/blob/master/print-eap.c
class EAPFrame(namedtuple("EAPFrame", "dst src version type length packet")):
__slots__ = ()
_struct = struct.Struct("!6s6sHBBH") # includes ethernet header
TYPE_PACKET = 0
TYPE_START = 1
TYPE_LOGOFF = 2
TYPE_KEY = 3
TYPE_ENCAP_ASF_ALERT = 4
_types = {
TYPE_PACKET: "EAP packet",
TYPE_START: "EAPOL start",
TYPE_LOGOFF: "EAPOL logoff",
TYPE_KEY: "EAPOL key",
TYPE_ENCAP_ASF_ALERT: "Encapsulated ASF alert"
}
@classmethod
def from_buf(cls, buf):
unpack, size = cls._struct.unpack, cls._struct.size
dst, src, etype, ver, ptype, length = unpack(buf[:size])
if etype != ETH_P_PAE:
raise ValueError("invalid ethernet type: 0x%04x" % etype)
if ptype == cls.TYPE_PACKET:
packet = EAPPacket.from_buf(buf[size:size + length])
else:
packet = None
return cls(dst, src, ver, ptype, length, packet)
@property
def type_name(self):
return self._types.get(self.type, "???")
@property
def is_start(self):
return self.type == self.TYPE_START
@property
def is_logoff(self):
return self.type == self.TYPE_LOGOFF
@property
def is_success(self):
return self.packet and self.packet.is_success
def __str__(self):
return "%s > %s, %s (%d) v%d, len %d%s" % (
strmac(self.src), strmac(self.dst),
self.type_name, self.type, self.version, self.length,
", " + str(self.packet) if self.packet else '')
class EAPPacket(namedtuple("EAPPacket", "code id length data")):
__slots__ = ()
_struct = struct.Struct("!BBH")
REQUEST, RESPONSE, SUCCESS, FAILURE = 1, 2, 3, 4
_codes = {
REQUEST: "Request",
RESPONSE: "Response",
SUCCESS: "Success",
FAILURE: "Failure"
}
@classmethod
def from_buf(cls, buf):
unpack, size = cls._struct.unpack, cls._struct.size
code, id_, length = unpack(buf[:size])
data = buf[size:size + length - 4]
return cls(code, id_, length, data)
@property
def code_name(self):
return self._codes.get(self.code, "???")
@property
def is_success(self):
return self.code == self.SUCCESS
def __str__(self):
return "%s (%d) id %d, len %d [%d]" % (
self.code_name, self.code, self.id, self.length, len(self.data))
### EAP Proxy
class EAPProxy(object):
def __init__(self, args, log):
self.args = args
self.os = LinuxOS(log)
self.log = log
def proxy_forever(self):
log = self.log
while True:
try:
log.info("proxy_loop starting")
self.proxy_loop()
except KeyboardInterrupt:
return
except Exception as ex: # pylint:disable=broad-except
log.warn("%s; restarting in 10 seconds", strexc(), exc_info=ex)
else:
log.warn("proxy_loop exited; restarting in 10 seconds")
time.sleep(10)
def proxy_loop(self):
args = self.args
poll = select.poll() # pylint:disable=no-member
s_rtr = rawsocket(args.if_rtr, poll=poll, promisc=args.promiscuous)
s_wan = rawsocket(args.if_wan, poll=poll, promisc=args.promiscuous)
socks = {s.fileno(): s for s in (s_rtr, s_wan)}
on_poll_event = partial(self.on_poll_event, s_rtr=s_rtr, s_wan=s_wan)
while True:
ready = poll.poll()
for fd, event in ready:
on_poll_event(socks[fd], event)
def on_poll_event(self, sock_in, event, s_rtr, s_wan):
log = self.log
ifname = getifname(sock_in)
if event != select.POLLIN: # pylint:disable=no-member
raise IOError("[%s] unexpected poll event: %d", ifname, event)
buf = sock_in.recv(2048)
if self.args.debug_packets:
log.debug("%s: recv %d bytes:\n%s", ifname, len(buf), strbuf(buf))
eap = EAPFrame.from_buf(buf)
log.debug("%s: %s", ifname, eap)
if sock_in == s_rtr:
sock_out = s_wan
self.on_router_eap(eap)
if self.should_ignore_router_eap(eap):
log.debug("%s: ignoring %s", ifname, eap)
return
else:
sock_out = s_rtr
self.on_wan_eap(eap)
log.info("%s: %s > %s", ifname, eap, getifname(sock_out))
nbytes = sock_out.send(buf)
log.debug("%s: sent %d bytes", getifname(sock_out), nbytes)
def should_ignore_router_eap(self, eap):
args = self.args
if args.ignore_start and eap.is_start:
return True
if args.ignore_logoff and eap.is_logoff:
return True
if args.ignore_when_wan_up:
return self.check_wan_is_up()
return False
def on_router_eap(self, eap):
args = self.args
if not args.set_mac:
return
if_vlan = args.if_wan + ".0"
if self.os.getmac(if_vlan) == eap.src:
return
self.log.info("%s: setting mac to %s", if_vlan, strmac(eap.src))
self.os.setmac(if_vlan, eap.src)
def on_wan_eap(self, eap):
if not self.should_restart_dhcp(eap):
return
if_vlan = self.args.if_wan + ".0"
self.log.info("%s: restarting DHCP client", if_vlan)
self.os.restart_dhcp_client(if_vlan)
def should_restart_dhcp(self, eap):
if self.args.restart_dhcp and eap.is_success:
return not self.check_wan_is_up()
return False
def check_wan_is_up(self):
args, log = self.args, self.log
if_vlan = args.if_wan + ".0"
ipaddr = getifaddr(if_vlan)
if ipaddr:
log.debug("%s: %s", if_vlan, ipaddr)
return self.ping_gateway() if args.ping_gateway else True
log.debug("%s: no IP address", if_vlan)
return False
def ping_gateway(self):
log = self.log
ipaddr = getdefaultgatewayaddr()
if not ipaddr:
log.debug("ping: no default route gateway")
return False
rv = pingaddr(ipaddr)
log.debug("ping: %s %s", ipaddr, "success" if rv else "failed")
return rv
### Main
def parse_args():
p = argparse.ArgumentParser("eap_proxy")
# interface arguments
p.add_argument(
"if_wan", metavar="IF_WAN", help="interface of the AT&T ONT/WAN",
type=wan_network_interface)
p.add_argument(
"if_rtr", metavar="IF_ROUTER", help="interface of the AT&T router",
type=network_interface)
# checking whether WAN is up
g = p.add_argument_group("checking whether WAN is up")
g.add_argument(
"--ping-gateway", action="store_true", help=
"normally the WAN is considered up if IF_WAN.0 has an IP address; "
"this option additionally requires that there is a default route "
"gateway that responds to a ping")
# ignoring packet options
g = p.add_argument_group("ignoring router packets")
g.add_argument(
"--ignore-when-wan-up", action="store_true", help=
"ignore router packets when WAN is up (see --ping-gateway)")
g.add_argument(
"--ignore-start", action="store_true", help=
"always ignore EAPOL-Start from router")
g.add_argument(
"--ignore-logoff", action="store_true", help=
"always ignore EAPOL-Logoff from router")
# configuring IF_WAN.0 VLAN options
g = p.add_argument_group("configuring IF_WAN.0 VLAN")
g.add_argument(
"--restart-dhcp", action="store_true", help=
"check whether WAN is up after receiving EAP-Success on IF_WAN "
"(see --ping-gateway); if not, restart system's DHCP client on "
"IF_WAN.0")
g.add_argument(
"--set-mac", action="store_true", help=
"set IF_WAN.0's MAC (ether) address to router's MAC address")
# daemonization options
g = p.add_argument_group("daemonization")
g.add_argument(
"--daemon", action="store_true", help=
"become a daemon; implies --syslog")
g.add_argument(
"--pidfile", nargs="?", const="/var/run/eap_proxy.pid", help=
"record pid to PIDFILE; default: /var/run/eap_proxy.pid")
g.add_argument(
"--syslog", action="store_true", help=
"log to syslog instead of stderr")
# debugging options
g = p.add_argument_group("debugging")
g.add_argument(
"--promiscuous", action="store_true", help=
"place interfaces into promiscuous mode instead of multicast")
g.add_argument(
"--debug", action="store_true", help=
"enable debug-level logging")
g.add_argument(
"--debug-packets", action="store_true", help=
"print packets in hex format to assist with debugging; "
"implies --debug")
args = p.parse_args()
if args.daemon:
args.syslog = True
if args.debug_packets:
if args.syslog:
p.error("--debug-packets not allowed with --syslog")
args.debug = True
return args
def main():
args = parse_args()
log = make_logger(args.syslog, args.debug)
if args.pidfile:
pid = checkpidfile(args.pidfile)
if pid:
log.error("eap_proxy already running with pid %s?", pid)
return 1
if args.daemon:
try:
daemonize()
except Exception: # pylint:disable=broad-except
log.exception("could not become daemon: %s", strexc())
return 1
# ensure cleanup (atexit, etc) occurs when we're killed via SIGTERM
def on_sigterm(signum, __):
log.info("exiting on signal %d", signum)
raise SystemExit(0)
signal.signal(signal.SIGTERM, on_sigterm)
if args.pidfile:
try:
writepidfile(args.pidfile)
except EnvironmentError: # pylint:disable=broad-except
log.exception("could not write pidfile: %s", strexc())
EAPProxy(args, log).proxy_forever()
if __name__ == "__main__":
sys.exit(main())