def mac_formatting(mac_address): mac = EUI(mac_address) mac.dialect = mac_cisco mac = str(mac) return mac
def get_scoreboard_data(): """ Returns the data used in scoreboard route """ count = [] data = get_unique_checkins() handles = {} for record in data: if record[0] not in handles.keys(): handle = get_handle_for_mac(record[0]) handles[record[0]] = handle if any(record[0] in x for x in count): continue result = [ record[0], sum(x.count(record[0]) for x in data), handles[record[0]] ] count.append(result) tally = {} for record in count: mac = EUI(record[0]) # Change the mac to a more display friendly format # with a ":" every two characters. mac.dialect = mac_unix tally[str(mac)] = [record[1], record[2]] sorted_tally = sorted(tally.items(), key=operator.itemgetter(1)) return list(reversed(sorted_tally))
def encode(key): hex_key = hex(key) mac_address = int(hex_key + '0000', 16) mac = EUI(mac_address) mac[0] = 0x90 mac.dialect = mac_unix_expanded key = str(mac) return key
def get_mac(): """Returns the device mac address in unix format @rtype: string @return: The mac address in unix format """ mac = EUI(getnode()) mac.dialect = mac_unix return str(mac)
def write_devices_for_micronet(self, outfile, micronetId): device_list = self.micronet_block['devices'][micronetId].items() for device_id, device in device_list: mac_addr = EUI(device['macAddress']['eui48']) mac_addr.dialect = netaddr.mac_unix_expanded outfile.write(" host {}\n".format(device_id)) outfile.write(" {\n") outfile.write(" hardware ethernet {};\n".format(mac_addr)) outfile.write(" fixed-address {};\n".format( device['networkAddress']['ipv4'])) outfile.write(" }\n")
def get_prep_value(self, value): if value is None: return None if not isinstance(value, EUI): value = EUI(value, dialect=default_dialect()) if self.integer: return int(value) return str(value) value.dialect = default_dialect(self) if self.integer: return int(value) return str(value)
def startAccessFromMacAddress(request, minutes, mac_address): try: eui = EUI(mac_address) except AddrFormatError: messages.add_message(request, messages.ERROR, "Invalid MAC Address! Please check again.") else: eui.dialect = mac_unix eui.dialect.word_fmt = "%.2X" _sendRaw(eui, int(minutes)) messages.add_message(request, messages.SUCCESS, "Internet access started for %s!" % mac_address)
def _getEUI(ipAddress, mac=""): """ Returns EUI from IPAddress """ if not isinstance(ipAddress, IPAddress): raise ValueError("Expected ipAddress to be of type netaddr.IPAddress") if mac == "": mac = _getMAC(ipAddress) # mac is None if testing on localhost if mac is None: return mac eui = EUI(mac) eui.dialect = mac_unix eui.dialect.word_fmt = "%.2X" return eui
def get_cm_mac_cmts_format(self, mac): """to convert mac adress to the format that to be used on cmts :param mac: mac address of CM in foramt XX:XX:XX:XX:XX:XX or XX-XX-XX-XX-XX-XX :type mac: string :return: the cm_mac in cmts format xxxx.xxxx.xxxx (lowercase) :rtype: string """ if mac is None: return None mac = EUI(mac) mac.dialect = mac_cisco return str(mac)
def generate(wifi): interface = wifi['intf'] # always stop hostapd service first before reconfiguring it call(f'systemctl stop hostapd@{interface}.service') # always stop wpa_supplicant service first before reconfiguring it call(f'systemctl stop wpa_supplicant@{interface}.service') # Delete config files if interface is removed if wifi['deleted']: if os.path.isfile(hostapd_conf.format(**wifi)): os.unlink(hostapd_conf.format(**wifi)) if os.path.isfile(wpa_suppl_conf.format(**wifi)): os.unlink(wpa_suppl_conf.format(**wifi)) return None if not wifi['mac']: # http://wiki.stocksy.co.uk/wiki/Multiple_SSIDs_with_hostapd # generate locally administered MAC address from used phy interface with open('/sys/class/ieee80211/{}/addresses'.format(wifi['phy']), 'r') as f: # some PHYs tend to have multiple interfaces and thus supply multiple MAC # addresses - we only need the first one for our calculation tmp = f.readline().rstrip() tmp = EUI(tmp).value # mask last nibble from the MAC address tmp &= 0xfffffffffff0 # set locally administered bit in MAC address tmp |= 0x020000000000 # we now need to add an offset to our MAC address indicating this # subinterfaces index tmp += int(findall(r'\d+', interface)[0]) # convert integer to "real" MAC address representation mac = EUI(hex(tmp).split('x')[-1]) # change dialect to use : as delimiter instead of - mac.dialect = mac_unix_expanded wifi['mac'] = str(mac) # render appropriate new config files depending on access-point or station mode if wifi['op_mode'] == 'ap': render(hostapd_conf.format(**wifi), 'wifi/hostapd.conf.tmpl', wifi) elif wifi['op_mode'] == 'station': render(wpa_suppl_conf.format(**wifi), 'wifi/wpa_supplicant.conf.tmpl', wifi) return None
def encode(port_list): mac_address = 0 mac = EUI(mac_address) mac[0] = 0x91 assert len(port_list) < 5 for idx, value in enumerate(port_list): mac[idx + 1] = value mac.dialect = mac_unix_expanded key = str(mac) return key
def get_ertr_ipv4(self, mac): '''Getting erouter ipv4 from CMTS ''' self.sendline("show cable modem %s cpe" % mac) self.expect(self.prompt) from netaddr import EUI import netaddr mac = EUI(mac) ertr_mac = EUI(int(mac) + 2) ertr_mac.dialect = netaddr.mac_cisco ertr_ipv4 = re.search('(%s) .* (%s)' % (ValidIpv4AddressRegex, ertr_mac), self.before) if ertr_ipv4: ipv4 = ertr_ipv4.group(1) return ipv4 else: return None
def normalize_mac(mac): """ Takes any valid MAC address and returns one formatted for the ERS API Args: mac (str): MAC address Returns: mac (str): MAC address in unix_expanded format: '00:00:00:00:00:00' Raises: AddrFormatError: Invalid MAC Address """ try: mac = EUI(mac) mac.dialect = mac_unix_expanded except netaddr.core.AddrFormatError as e: raise Exception(f"Invalid MAC Address! error: {e}") return str(mac)
def write_devices (self, outfile, devices): for micronet_id, devices in devices.items (): outfile.write ("# DEVICES FOR MICRONET: {}\n".format (micronet_id)) for device_id, device in devices.items (): mac_addr = EUI (device ['macAddress']['eui48']) mac_addr.dialect = netaddr.mac_unix_expanded ip_addr = IPv4Address (device ['networkAddress']['ipv4']) if 'leasePeriod' in device: lease_period = device ['leasePeriod'] else: lease_period = self.default_lease_period if 'outRules' in device: out_rules = json.dumps(device['outRules']) else: out_rules = [] if 'inRules' in device: in_rules = json.dumps(device['inRules']) else: in_rules = [] if 'allowHosts' in device: allow_hosts = json.dumps(device['allowHosts']) else: allow_hosts = [] if 'denyHosts' in device: deny_hosts = json.dumps(device['denyHosts']) else: deny_hosts = [] psk = device.get('psk',"") if (len(device_id) <= 12): short_device_id = device_id else: short_device_id = device_id[0:8]+device_id[-4:] outfile.write ("\n# Device: {}, inRules: {}, outRules: {}, allowHosts: {}, denyHosts: {},psk: {}\n" .format (device_id, out_rules, in_rules, allow_hosts, deny_hosts, psk)) # 08:00:27:3c:ae:02,micronet-client-2,set:micronet-client-2,10.50.0.43,2m outfile.write ("dhcp-host={},{},set:{},{},{}\n" .format (mac_addr, short_device_id, device_id, ip_addr, lease_period)) outfile.write ("\n")
def parse_conffile (self, infile): micronets = {} devices_list = {} prefix_micronet_id = None prefix_host_id = None for line in infile: infile.line_no += 1 if (blank_line_re.match (line)): continue dhcp_range_prefix_match_result = self.dhcp_range_prefix_re.match (line) if (dhcp_range_prefix_match_result): (prefix_micronet_id, prefix_interface, prefix_vlan) = dhcp_range_prefix_match_result.groups() continue dhcp_host_prefix_match = self.dhcp_device_prefix_re.match (line) if dhcp_host_prefix_match: prefix_host_id = dhcp_host_prefix_match.group(1) prefix_host_out_rules_str = dhcp_host_prefix_match.group(2) prefix_host_in_rules_str = dhcp_host_prefix_match.group(3) prefix_host_allow_hosts_str = dhcp_host_prefix_match.group(4) prefix_host_deny_hosts_str = dhcp_host_prefix_match.group(5) prefix_host_psk_str = dhcp_host_prefix_match.group(6) logger.info(f"DnsMasqAdapter.parse_conffile: Found host {prefix_host_id}: " f"outRules:{prefix_host_out_rules_str}, inRules:{prefix_host_in_rules_str}, " f"allowHosts:{prefix_host_out_rules_str}, denyHosts:{prefix_host_in_rules_str}, " f"psk:{prefix_host_psk_str}") prefix_host_out_rules = json.loads(prefix_host_out_rules_str) prefix_host_in_rules = json.loads(prefix_host_in_rules_str) prefix_host_allow_hosts = json.loads(prefix_host_allow_hosts_str) prefix_host_deny_hosts = json.loads(prefix_host_deny_hosts_str) logger.info(f"DnsMasqAdapter.parse_conffile: Found host {prefix_host_id}: " f"outRules:{prefix_host_out_rules}, inRules:{prefix_host_in_rules}, " f"allowHosts:{prefix_host_allow_hosts}, denyHosts:{prefix_host_deny_hosts}") if (comment_line_re.match (line)): continue dhcp_range_match_result = self.dhcp_range_re.match (line) if (dhcp_range_match_result): if not prefix_micronet_id: raise Exception ("Found dhcp-range without preceding '# Micronet:' line") micronet_id = dhcp_range_match_result.group (1) micronet_network = dhcp_range_match_result.group (2) micronet_netmask = dhcp_range_match_result.group (3) micronet_lease_duration = dhcp_range_match_result.group (4) if prefix_micronet_id != micronet_id: raise Exception(f"Found dhcp-range with mismatched micronet id ({micronet_id} != {prefix_micronet_id})") prefix_micronet_id = None network = IPv4Network (micronet_network + "/" + micronet_netmask, strict=True) logger.debug ("DnsMasqAdapter.parse_conffile: Found micronet range: {} {} {} {}" .format (micronet_id, micronet_network, micronet_netmask, micronet_lease_duration)) if micronet_id in micronets: raise Exception ("Duplicate micronet ID '{}'".format (micronet_id)) if not network: raise Exception ("Invalid micronet network/netmask '{}/{}'" .format (micronet_network, micronet_netmask)) micronet = {} micronet ['micronetId'] = micronet_id micronet ['ipv4Network'] = {'network' : str (network.network_address), 'mask' : str (network.netmask)} micronet ['interface'] = prefix_interface if prefix_vlan: micronet ['vlan'] = prefix_vlan micronets [micronet_id] = micronet devices_list [micronet_id] = {} prefix_micronet_id = None continue dhcp_range_router_match = self.dhcp_range_router_re.match (line) if (dhcp_range_router_match): micronet_id = dhcp_range_router_match.group (1) router_address = dhcp_range_router_match.group (2) logger.debug (f"DnsMasqAdapter.parse_conffile: Found router address: " f"{micronet_id} {router_address}") if not micronet_id in micronets: raise Exception ("Could not find micronet ID '{}'".format (micronet_id)) addr = IPv4Address (router_address) if not addr or addr.is_loopback or addr.is_multicast: raise Exception ("Invalid router/gateway address '{}'".format (router_address)) micronet = micronets [micronet_id] logger.debug (f"DnsMasqAdapter.parse_conffile: micronet {micronet_id}: {micronet}") micronet ['ipv4Network']['gateway'] = str (addr) continue dhcp_range_dns_server_match = self.dhcp_range_dns_server_re.match (line) if (dhcp_range_dns_server_match): micronet_id = dhcp_range_dns_server_match.group (1) dns_server_addresses = dhcp_range_dns_server_match.group (2) logger.debug (f"DnsMasqAdapter.parse_conffile: Found dns server addresses: " f"{micronet_id} {dns_server_addresses}") if not micronet_id in micronets: raise Exception ("Could not find micronet ID '{}'".format (micronet_id)) nameservers = [] for dns_server in dns_server_addresses.split (','): if not dns_server: continue logger.info (f"DnsMasqAdapter.parse_conffile: Found dns server address: {dns_server}") addr = IPv4Address (dns_server) if not addr or addr.is_loopback or addr.is_multicast: raise Exception ("Invalid DNS server address '{}'".format (router_address)) nameservers.append (str (addr)) logger.debug (f"DnsMasqAdapter.parse_conffile: DNS server list: {nameservers}") micronets [micronet_id]['nameservers'] = nameservers continue dhcp_host_match = self.dhcp_host_re.match (line) if (dhcp_host_match): if not prefix_host_id: raise Exception ("Found dhcp-host without preceding '# Device:' line") dhcp_host_mac = dhcp_host_match.group (1) dhcp_host_id = dhcp_host_match.group (2) dhcp_host_tag = dhcp_host_match.group (3) dhcp_host_ip = dhcp_host_match.group (4) dhcp_host_lease_duration = dhcp_host_match.group (5) logger.debug ("DnsMasqAdapter.parse_conffile: Found dhcp host entry: {} {} {} {} {}" .format (dhcp_host_mac, dhcp_host_id, dhcp_host_ip, dhcp_host_tag, dhcp_host_lease_duration)) if not netaddr.valid_mac (dhcp_host_mac): raise Exception ("Invalid host MAC address '{}'".format (dhcp_host_mac)) eui_mac_addr = EUI (dhcp_host_mac) eui_mac_addr.dialect = netaddr.mac_unix_expanded addr = IPv4Address (dhcp_host_ip) if not addr or addr.is_loopback or addr.is_multicast: raise Exception ("Invalid host IP address '{}'".format (dhcp_host_ip)) micronet_id = find_micronet_id_for_host (micronets, dhcp_host_ip) if not micronet_id: raise Exception ("Could not find a micronet compatible with host '{}'".format (addr)) device = {'deviceId': prefix_host_id} device ['macAddress'] = {'eui48': str(eui_mac_addr)} device ['networkAddress'] = {'ipv4': str (addr)} if len(prefix_host_out_rules) > 0: device ['outRules'] = prefix_host_out_rules if len(prefix_host_in_rules) > 0: device ['inRules'] = prefix_host_in_rules if len(prefix_host_allow_hosts) > 0: device ['allowHosts'] = prefix_host_allow_hosts if len(prefix_host_deny_hosts) > 0: device ['denyHosts'] = prefix_host_deny_hosts if prefix_host_psk_str: device ['psk'] = prefix_host_psk_str device_list = devices_list [micronet_id] device_list [prefix_host_id] = device prefix_host_id = None continue dhcp_hostfile_match = self.dhcp_hostfile_re.match (line) if (dhcp_hostfile_match): hostfile = dhcp_hostfile_match.group (1) logger.debug (f"DnsMasqAdapter.parse_conffile: Found dhcp hostfile entry: {hostfile}") continue dhcp_scriptfile_match = self.dhcp_scriptfile_re.match (line) if (dhcp_scriptfile_match): scriptfile = dhcp_scriptfile_match.group (1) logger.debug (f"DnsMasqAdapter.parse_conffile: Found dhcp script file entry: {scriptfile}") continue # If none of the REs match, bail out raise Exception ("Unrecognized dnsmasq config entry: {}".format (line.rstrip ())) logger.info ("DnsMasqAdapter.parse_conffile: Done reading {}".format (infile)) logger.info ("DnsMasqAdapter.parse_conffile: Micronets:") logger.info (json.dumps (micronets, indent=4)) return {'micronets': micronets, 'devices': devices_list}
except: print("") exit() callstation = ARG cs = callstation[2:] #print(cs) #Uncomment to debug fix = re.sub(r'-', ":", cs) fix2 = re.sub(r'00', '0', fix) fix3 = fix2.lower() remoteid = "a" + fix3 #print(remoteid) #Uncomment to debug mac = EUI(remoteid) mac.dialect = netaddr.mac_unix def send_request(): # Infoblox - Search by SM MAC URL = "https://infoblox.domain.tld/wapi/v2.6/lease" payload = { "_return_type": "json-pretty", "_return_fields": "address", "remote_id": mac } with requests.session() as s: try: s.auth = ('apiuser', 'secret-password')
def test_eui64_dialect_property_assignment(): mac = EUI('00-1B-77-49-54-FD-12-34') assert str(mac) == '00-1B-77-49-54-FD-12-34' mac.dialect = eui64_cisco assert str(mac) == '001b.7749.54fd.1234'
def to_unix(mac_address): mac = EUI(mac_address) mac.dialect = mac_unix_expanded return str(mac)
def main(args): parser = argparse.ArgumentParser( description='Find active users on the current wireless network.') parser.add_argument('-p', '--packets', default=1000, type=int, help='How many packets to capture.') parser.add_argument('-i', '--interface', default=None, type=str, help='Which wireless interface to use.') parser.add_argument('-s', '--ssid', default=None, type=str, help='Which SSID to use.') parser.add_argument('-r', '--results', default=None, type=int, help='How many results to show.') args = parser.parse_args() try: if args.interface: iface = args.interface else: wireless = Wireless() ifaces = wireless.interfaces() eprint('Available interfaces: {}'.format(', '.join(ifaces))) iface = ifaces[-1] eprint('Interface: {}'.format(iface)) if args.ssid: ssid = args.ssid else: wireless = Wireless() ssid = wireless.current() if ssid is None: eprint(NO_SSID) return eprint('SSID: {}'.format(ssid)) except: eprint(NO_WIRELESS) raise mac_re_str = '([\dA-F]{2}:){5}[\dA-F]{2}' mac_re = re.compile(mac_re_str, re.I) network_macs = set() try: gws = netifaces.gateways()[netifaces.AF_INET] gw_ifaces = ', '.join([gw[1] for gw in gws]) eprint('Available gateways: {}'.format(gw_ifaces)) gw_ip = next(gw[0] for gw in gws if gw[1] == iface) eprint('Gateway IP: {}'.format(gw_ip)) gw_arp = subprocess.check_output(['arp', '-n', str(gw_ip)]) gw_arp = gw_arp.decode('utf-8') gw_mac = EUI(mac_re.search(gw_arp).group(0)) gw_mac.dialect = mac_unix_expanded network_macs.add(gw_mac) eprint('Gateway MAC: {}'.format(gw_mac)) except StopIteration: eprint('No gateway for {}'.format(iface)) except KeyError: eprint('No gateways available: {}'.format(netifaces.gateways())) except: eprint(NO_GATEWAY_MAC) bssid_re = re.compile(' BSSID:(\S+) ') tcpdump_mac_re = re.compile('(SA|DA|BSSID):(' + mac_re_str + ')', re.I) length_re = re.compile(' length (\d+)') client_macs = set() data_totals = defaultdict(int) cmd = 'tcpdump -i {} -Ile -c {} -s 0'.format(iface, args.packets).split() try: bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}' progress = tqdm(run_process(cmd), total=args.packets, bar_format=bar_format) for line in progress: line = line.decode('utf-8') # find BSSID for SSID if ssid in line: bssid_matches = bssid_re.search(line) if bssid_matches: bssid = bssid_matches.group(1) if 'Broadcast' not in bssid: network_macs.add(EUI(bssid)) # count data packets length_match = length_re.search(line) if length_match: length = int(length_match.group(1)) mac_matches = tcpdump_mac_re.findall(line) if mac_matches: macs = set([EUI(match[1]) for match in mac_matches]) leftover = macs - network_macs if len(leftover) < len(macs): for mac in leftover: data_totals[mac] += length client_macs.add(mac) if progress.n < progress.total: eprint('Sniffing finished early.') except subprocess.CalledProcessError: eprint('Error collecting packets.') raise except KeyboardInterrupt: pass totals_sorted = sorted(data_totals.items(), key=lambda x: x[1], reverse=True) eprint('Total of {} user(s)'.format(len(totals_sorted))) for mac, total in reversed(totals_sorted[:args.results]): mac.dialect = mac_unix_expanded if total > 0: print('{}\t{} bytes'.format(mac, total))
def main(args): parser = argparse.ArgumentParser( description='Find active users on the current wireless network.') parser.add_argument('-p', '--packets', default=1000, type=int, help='How many packets to capture.') parser.add_argument('-r', '--results', default=None, type=int, help='How many results to show.') args = parser.parse_args() try: wireless = Wireless() ssid = wireless.current() if ssid is None: eprint( 'No SSID is currently available. Connect to the network first.' ) return eprint('SSID: {}'.format(ssid)) except: eprint('Couldn\'t get current wireless SSID.') raise network_macs = set() try: gw = netifaces.gateways()['default'][netifaces.AF_INET] iface = gw[1] gw_arp = subprocess.check_output(['arp', '-n', str(gw[0])]) gw_arp = gw_arp.decode('utf-8') gw_mac = EUI(re.search(' at (.+) on ', gw_arp).group(1)) gw_mac.dialect = mac_unix_expanded network_macs.add(gw_mac) eprint('Gateway: {}'.format(gw_mac)) except KeyError: eprint('No gateway is available: {}'.format(netifaces.gateways())) return except: eprint('Error getting gateway mac address.') bssid_re = re.compile(' BSSID:(\S+) ') da_re = re.compile(' DA:(\S+) ') sa_re = re.compile(' SA:(\S+) ') mac_re = re.compile('(SA|DA|BSSID):(([\dA-F]{2}:){5}[\dA-F]{2})', re.I) length_re = re.compile(' length (\d+)') client_macs = set() data_totals = defaultdict(int) cmd = 'tcpdump -i {} -Ile -c {}'.format(iface, args.packets).split() try: bar_format = '{n_fmt}/{total_fmt} {bar} {remaining}' for line in tqdm(run_process(cmd), total=args.packets, bar_format=bar_format): line = line.decode('utf-8') # find BSSID for SSID if ssid in line: bssid_matches = bssid_re.search(line) if bssid_matches: bssid = bssid_matches.group(1) if not 'Broadcast' in bssid: network_macs.add(EUI(bssid)) # count data packets length_match = length_re.search(line) if length_match: length = int(length_match.group(1)) mac_matches = mac_re.findall(line) if mac_matches: macs = set([EUI(match[1]) for match in mac_matches]) leftover = macs - network_macs if len(leftover) < len(macs): for mac in leftover: data_totals[mac] += length client_macs.add(mac) except subprocess.CalledProcessError: eprint('Error collecting packets.') raise except KeyboardInterrupt: pass print() totals_sorted = sorted(data_totals.items(), key=lambda x: x[1], reverse=True) eprint('Total of {} user(s)'.format(len(totals_sorted))) for mac, total in reversed(totals_sorted[:args.results]): mac.dialect = mac_unix_expanded if total > 0: print('{}\t{} bytes'.format(mac, total))
def convertMac(macaddress): mac = EUI(macaddress) mac.dialect = netaddr.mac_bare return str(mac)
def mk_mac(i): mac = EUI(i) mac.dialect = mac_unix return str(mac)
def convertMac(macaddress): mac = EUI(macaddress) mac.dialect = netaddr.mac_unix_expanded return str(mac)
help="Use telnet for connections") (options, args) = parser.parse_args() if not options.mac: print "MAC address required as argument to execute mactrace" parser.print_help() sys.exit(0) def die(msg): print msg sys.exit(1) MAC = EUI(options.mac) MAC.dialect = netaddr.mac_cisco start = 1 print "Search MAC: %s" % MAC next_switch_ip = options.next_switch_ip if not next_switch_ip or next_switch_ip == "": import json hostname = json.loads(clid("show hostname")) hostname = hostname["hostname"] out = json.loads(clid("show mac address-table address %s" % options.mac)) learnedmacport = out['TABLE_mac_address']['ROW_mac_address']["disp_port"] print "%d %s %s" % (start, hostname, learnedmacport) start += 1 mac_count = int(cli("show mac address-table interface %s | count" % learnedmacport)[1]) if mac_count <= 1:
in_file = sys.argv[1] def convert_mac(octet): return EUI(netaddr.strategy.eui48.packed_to_int(octet)) # take input here to act on later mac_type = input( "What do you want to convert to? Bare, Cisco, EUI48, or Unix: ").lower() with open(in_file, 'r') as i: # open and read file lines = i.readlines() for line in lines: mac = EUI(line) if mac_type == 'cisco': mac.dialect = netaddr.mac_cisco print(mac) elif mac_type == 'bare': mac.dialect = netaddr.mac_bare print(mac) elif mac_type == 'unix': mac.dialect = netaddr.mac_unix_expanded print(mac) elif mac_type == 'eui48': mac.dialect = netaddr.mac_eui48 print(mac) else: print("Your input is not recognized. This is probably due to " "inputting the incorrect MAC type or a typo.")
def recompose(self, value): if value is not None: v = EUI(value) v.dialect = self.mac_dialects[self.dialect] return str(v) return value
def test_eui_dialect_property_assignment(): mac = EUI('00-1B-77-49-54-FD') assert str(mac) == '00-1B-77-49-54-FD' mac.dialect = mac_pgsql assert str(mac) == '001b77:4954fd'
def _setup_vxlan_encap_decap(self): """ Sets up switches for VxLAN overlay P-TUN-P test. Create 2 bridges br-phy1 and br-phy2 (The bridge to connect physical ports. Two more bridges br-mod1 and br-mod2 to mangle and redirect the packets from one tunnel port to other. """ self._logger.debug('Setup using ' + str(self._vswitch_class)) try: self._vswitch.start() self._vswitch.add_switch(self.bridge_phy1) self._vswitch.add_switch(self.bridge_phy2) self._vswitch.add_switch( self.bridge_mod1, params=["other_config:hwaddr=" + self.br_mod_mac1]) self._vswitch.add_switch( self.bridge_mod2, params=["other_config:hwaddr=" + self.br_mod_mac2]) tasks.run_task(['sudo', 'iptables', '-F'], self._logger, 'Clean ip tables', False) tasks.run_task([ 'sudo', 'ip', 'addr', 'add', self.br_mod_ip1, 'dev', self.bridge_mod1 ], self._logger, 'Assign ' + self.br_mod_ip1 + ' to ' + self.bridge_mod1, False) tasks.run_task( ['sudo', 'ip', 'link', 'set', 'dev', self.bridge_mod1, 'up'], self._logger, 'Bring up ' + self.bridge_mod1, False) tasks.run_task([ 'sudo', 'ip', 'addr', 'add', self.br_mod_ip2, 'dev', self.bridge_mod2 ], self._logger, 'Assign ' + self.br_mod_ip2 + ' to ' + self.bridge_mod2, False) tasks.run_task( ['sudo', 'ip', 'link', 'set', 'dev', self.bridge_mod2, 'up'], self._logger, 'Bring up ' + self.bridge_mod2, False) tasks.run_task( ['sudo', 'ip', 'link', 'set', 'dev', self.bridge_phy1, 'up'], self._logger, 'Bring up ' + self.bridge_phy1, False) tasks.run_task( ['sudo', 'ip', 'link', 'set', 'dev', self.bridge_phy2, 'up'], self._logger, 'Bring up ' + self.bridge_phy2, False) self._vswitch.add_route(self.bridge_phy1, self.br_mod_ip1, self.bridge_mod1) self._vswitch.add_route(self.bridge_phy2, self.br_mod_ip2, self.bridge_mod2) # Create tunnel ip and mac from the bridge ips vxlan_local_ip1 = str(IPNetwork(self.br_mod_ip1).ip) vxlan_local_ip2 = str(IPNetwork(self.br_mod_ip2).ip) vxlan_rem_ip1 = str(IPNetwork(self.br_mod_ip1).ip + 1) vxlan_rem_ip2 = str(IPNetwork(self.br_mod_ip2).ip + 1) vxlan_rem_mac1 = EUI(int(EUI(self.br_mod_mac1)) + 1) vxlan_rem_mac1.dialect = mac_unix vxlan_rem_mac2 = EUI(int(EUI(self.br_mod_mac2)) + 1) vxlan_rem_mac2.dialect = mac_unix self._vswitch.set_tunnel_arp(vxlan_local_ip1, self.br_mod_mac1, self.bridge_phy1) self._vswitch.set_tunnel_arp(vxlan_local_ip2, self.br_mod_mac2, self.bridge_phy2) self._vswitch.set_tunnel_arp(vxlan_rem_ip1, str(vxlan_rem_mac1), self.bridge_mod1) self._vswitch.set_tunnel_arp(vxlan_rem_ip2, str(vxlan_rem_mac2), self.bridge_mod2) # Lets add the ports to bridges (_, phy1_number) = self._vswitch.add_phy_port(self.bridge_phy1) (_, phy2_number) = self._vswitch.add_phy_port(self.bridge_phy2) vxlan_vni = 'options:key=' + settings.getValue('VXLAN_VNI') (_, phy3_number) = self._vswitch.add_tunnel_port(self.bridge_phy1, vxlan_rem_ip1, "vxlan", params=[vxlan_vni]) (_, phy4_number) = self._vswitch.add_tunnel_port(self.bridge_phy2, vxlan_rem_ip2, "vxlan", params=[vxlan_vni]) [(_, phy5_number), (_, phy6_number)] = \ self._vswitch.add_veth_pair_port(self.bridge_mod1, self.bridge_mod2) # Set up flows for the switches self._vswitch.del_flow(self.bridge_phy1) self._vswitch.del_flow(self.bridge_phy2) self._vswitch.del_flow(self.bridge_mod1) self._vswitch.del_flow(self.bridge_mod2) flow = add_ports_to_flow(_FLOW_TEMPLATE, phy1_number, phy3_number) self._vswitch.add_flow(self.bridge_phy1, flow) flow = add_ports_to_flow(_FLOW_TEMPLATE, phy3_number, phy1_number) self._vswitch.add_flow(self.bridge_phy1, flow) flow = add_ports_to_flow(_FLOW_TEMPLATE, phy2_number, phy4_number) self._vswitch.add_flow(self.bridge_phy2, flow) flow = add_ports_to_flow(_FLOW_TEMPLATE, phy4_number, phy2_number) self._vswitch.add_flow(self.bridge_phy2, flow) flow = add_ports_to_flow(_FLOW_TEMPLATE, phy5_number, 'LOCAL') self._vswitch.add_flow(self.bridge_mod1, flow) mod_flow_template = _FLOW_TEMPLATE.copy() mod_flow_template.update({ 'ip': '', 'actions': [ 'mod_dl_src:' + str(vxlan_rem_mac2), 'mod_dl_dst:' + self.br_mod_mac2, 'mod_nw_src:' + vxlan_rem_ip2, 'mod_nw_dst:' + vxlan_local_ip2 ] }) flow = add_ports_to_flow(mod_flow_template, 'LOCAL', phy5_number) self._vswitch.add_flow(self.bridge_mod1, flow) flow = add_ports_to_flow(_FLOW_TEMPLATE, phy6_number, 'LOCAL') self._vswitch.add_flow(self.bridge_mod2, flow) mod_flow_template = _FLOW_TEMPLATE.copy() mod_flow_template.update({ 'ip': '', 'actions': [ 'mod_dl_src:' + str(vxlan_rem_mac1), 'mod_dl_dst:' + self.br_mod_mac1, 'mod_nw_src:' + vxlan_rem_ip1, 'mod_nw_dst:' + vxlan_local_ip1 ] }) flow = add_ports_to_flow(mod_flow_template, 'LOCAL', phy6_number) self._vswitch.add_flow(self.bridge_mod2, flow) except: self._vswitch.stop() raise
def generate(wifi): # Prepare Jinja2 template loader from files tmpl_path = os.path.join(vyos_data_dir["data"], "templates", "wifi") fs_loader = FileSystemLoader(tmpl_path) env = Environment(loader=fs_loader) # always stop hostapd service first before reconfiguring it pidfile = get_pid('hostapd', wifi['intf']) if process_running(pidfile): command = 'start-stop-daemon' command += ' --stop ' command += ' --quiet' command += ' --oknodo' command += ' --pidfile ' + pidfile run(command) # always stop wpa_supplicant service first before reconfiguring it pidfile = get_pid('wpa_supplicant', wifi['intf']) if process_running(pidfile): command = 'start-stop-daemon' command += ' --stop ' command += ' --quiet' command += ' --oknodo' command += ' --pidfile ' + pidfile run(command) # Delete config files if interface is removed if wifi['deleted']: if os.path.isfile(get_conf_file('hostapd', wifi['intf'])): os.unlink(get_conf_file('hostapd', wifi['intf'])) if os.path.isfile(get_conf_file('wpa_supplicant', wifi['intf'])): os.unlink(get_conf_file('wpa_supplicant', wifi['intf'])) return None if not wifi['mac']: # http://wiki.stocksy.co.uk/wiki/Multiple_SSIDs_with_hostapd # generate locally administered MAC address from used phy interface with open('/sys/class/ieee80211/{}/addresses'.format(wifi['phy']), 'r') as f: # some PHYs tend to have multiple interfaces and thus supply multiple MAC # addresses - we only need the first one for our calculation tmp = f.readline().rstrip() tmp = EUI(tmp).value # mask last nibble from the MAC address tmp &= 0xfffffffffff0 # set locally administered bit in MAC address tmp |= 0x020000000000 # we now need to add an offset to our MAC address indicating this # subinterfaces index tmp += int(findall(r'\d+', wifi['intf'])[0]) # convert integer to "real" MAC address representation mac = EUI(hex(tmp).split('x')[-1]) # change dialect to use : as delimiter instead of - mac.dialect = mac_unix_expanded wifi['mac'] = str(mac) # render appropriate new config files depending on access-point or station mode if wifi['op_mode'] == 'ap': tmpl = env.get_template('hostapd.conf.tmpl') config_text = tmpl.render(wifi) with open(get_conf_file('hostapd', wifi['intf']), 'w') as f: f.write(config_text) elif wifi['op_mode'] == 'station': tmpl = env.get_template('wpa_supplicant.conf.tmpl') config_text = tmpl.render(wifi) with open(get_conf_file('wpa_supplicant', wifi['intf']), 'w') as f: f.write(config_text) return None