Python netaddr.EUI Examples

The following are 30 code examples for showing how to use netaddr.EUI(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module netaddr , or try the search function .

Example 1
Project: tempest-lib   Author: openstack   File: data_utils.py    License: Apache License 2.0 6 votes vote down vote up
def get_ipv6_addr_by_EUI64(cidr, mac):
    """Generate a IPv6 addr by EUI-64 with CIDR and MAC

    :param str cidr: a IPv6 CIDR
    :param str mac: a MAC address
    :return: an IPv6 Address
    :rtype: netaddr.IPAddress
    """
    # Check if the prefix is IPv4 address
    is_ipv4 = netaddr.valid_ipv4(cidr)
    if is_ipv4:
        msg = "Unable to generate IP address by EUI64 for IPv4 prefix"
        raise TypeError(msg)
    try:
        eui64 = int(netaddr.EUI(mac).eui64())
        prefix = netaddr.IPNetwork(cidr)
        return netaddr.IPAddress(prefix.first + eui64 ^ (1 << 57))
    except (ValueError, netaddr.AddrFormatError):
        raise TypeError('Bad prefix or mac format for generating IPv6 '
                        'address by EUI-64: %(prefix)s, %(mac)s:'
                        % {'prefix': cidr, 'mac': mac})
    except TypeError:
        raise TypeError('Bad prefix type for generate IPv6 address by '
                        'EUI-64: %s' % cidr) 
Example 2
Project: yabgp   Author: smartbgp   File: evpn.py    License: Apache License 2.0 6 votes vote down vote up
def parse(cls, value, iswithdraw=False):
        route = dict()
        # rd
        offset = 8
        route['rd'] = cls.parse_rd(value[0:offset])
        # esi
        route['esi'] = int(binascii.b2a_hex(value[offset: offset+10]), 16)
        offset += 10
        # ethernet tag id
        route['eth_tag_id'] = struct.unpack('!I', value[offset: offset+4])[0]
        offset += 5
        # mac address
        route['mac'] = str(netaddr.EUI(int(binascii.b2a_hex(value[offset: offset+6]), 16)))
        offset += 6
        ip_addr_len = ord(value[offset: offset + 1])
        offset += 1
        # ip address
        if ip_addr_len != 0:
            route['ip'] = str(netaddr.IPAddress(
                int(binascii.b2a_hex(value[offset: offset + int(ip_addr_len / 8)]), 16)))
            offset += int(ip_addr_len / 8)
        # label
        route['label'] = MPLSVPN.parse_mpls_label_stack(value[offset:])
        return route 
Example 3
Project: EvilTwinFramework   Author: Esser420   File: aplauncher.py    License: GNU General Public License v2.0 6 votes vote down vote up
def __init__(self,  id=0, name=None, mac_address=None, ip_address=None,
                        connected_ssid=None, inactivity_time=None,
                        rx_packets=None, tx_packets=None,
                        rx_bitrate=None, tx_bitrate=None,
                        signal=None):

        self.id = id
        self.name = name
        self.mac_address = mac_address
        self.ip_address = ip_address
        self.connected_ssid = connected_ssid
        self.inactivity_time = inactivity_time
        self.rx_packets = rx_packets
        self.tx_packets = tx_packets
        self.tx_bitrate = tx_bitrate
        self.rx_bitrate = rx_bitrate
        self.signal = signal
        self.vendor = None
        try:
            self.vendor = EUI(mac_address).oui.registration().org      # OUI - Organizational Unique Identifier
        except Exception:
            pass 
Example 4
Project: cyber-security-framework   Author: black-security   File: mac-lookup.py    License: MIT License 6 votes vote down vote up
def run(self):
        mac = netaddr.EUI(int(self.arguments.mac) if self.arguments.mac.isdigit() else self.arguments.mac)
        info = mac.info["OUI"]
        print(f"[i] Media Access Control (MAC) Address Lookup Results For {mac}:")
        print(f" -  Extended Unique Identifier 64:       {mac.eui64()}", dark=True)
        print(f" -  Modified EUI64 Address:              {mac.modified_eui64()}", dark=True)
        print(f" -  Individual Access Block [IAB]:       {mac.iab if mac.is_iab() else 'Not an IAB'}", dark=True)
        print(f" -  Organizationally Unique Identifier:  {mac.oui}", dark=True)
        print(f" -  Extended Identifier [EI]:            {mac.ei}", dark=True)
        print(f" -  Local Link IPv6 Address:             {mac.ipv6_link_local()}", dark=True)
        print(f" -  Vendor Info.:")
        print(f"    - Organization: {info['org']}", dark=True)
        print( "    - Address:      {}".format("\n                    ".join(info["address"])), dark=True)
        print(f" -  OUI Info.:")
        print(f"    - Version: {mac.version}", dark=True)
        print(f"    - Offset:  {info['offset']}", dark=True)
        print(f"    - Size:    {info['size']}", dark=True)
        print(f"    - IDX:     {info['idx']}", dark=True)
        print(f"    - OUI:     {info['oui']}", dark=True)
        print(f" -  Packed Address:          {mac.packed}", dark=True)
        print(f" -  Hexadecimal Address:     {hex(mac)}", dark=True)
        print(f" -  48-bit Positive Integer: {mac.value}", dark=True)
        print(f" -  Octets:                  {', '.join(str(n) for n in mac.words)}", dark=True) 
Example 5
Project: upribox   Author: usableprivacy   File: base_extras.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_device_names(device):
    mac_vendor = None
    try:
        mac_vendor = EUI(device.mac).oui.registration().org
    except Exception:
        pass

    elems = [device.hostname]
    elems.extend([x.model for x in device.user_agent.all()])
    elems.append(mac_vendor)
    elems.append(device.mac)
    names = []
    # make unique sorted list
    [names.append(x) for x in elems if x not in names]

    return filter(lambda x: x not in IGNORE, names) 
Example 6
Project: dragonflow   Author: openstack   File: test_trunk_app.py    License: Apache License 2.0 6 votes vote down vote up
def get_expected_matches(self):
        return [
            {
                'reg6': test_app_base.fake_local_port2.unique_key,
                'eth_src': netaddr.EUI('fa:16:3e:00:00:01'),
                'eth_type': os_ken.lib.packet.ether_types.ETH_TYPE_IP,
                'ipv4_src': netaddr.IPAddress('192.168.18.3'),
            }, {
                'reg7': 33,
                'eth_type': os_ken.lib.packet.ether_types.ETH_TYPE_IP,
            }, {
                'reg6': test_app_base.fake_local_port2.unique_key,
                'eth_src': netaddr.EUI('fa:16:3e:00:00:01'),
                'eth_type': os_ken.lib.packet.ether_types.ETH_TYPE_ARP,
                'arp_sha': netaddr.EUI('fa:16:3e:00:00:01'),
                'arp_spa': netaddr.IPAddress('192.168.18.3'),
            }, {
                'reg7': 33,
                'eth_type': os_ken.lib.packet.ether_types.ETH_TYPE_ARP,
            }
        ] 
Example 7
Project: dragonflow   Author: openstack   File: test_trunk_app.py    License: Apache License 2.0 6 votes vote down vote up
def get_expected_actions(self):
        return [
            [
                SettingMock(reg6=33),
                SettingMock(metadata=17),
                SettingMock(eth_src=netaddr.EUI('fa:16:3e:00:00:01')),
                self.app.parser.NXActionResubmit(),
            ], [
                SettingMock(eth_dst=test_app_base.fake_local_port2.mac),
                SettingMock(reg7=test_app_base.fake_local_port2.unique_key),
                self.app.parser.NXActionResubmit(),
            ], [
                SettingMock(reg6=33),
                SettingMock(metadata=17),
                SettingMock(eth_src=netaddr.EUI('fa:16:3e:00:00:01')),
                SettingMock(arp_sha=netaddr.EUI('fa:16:3e:00:00:01')),
                self.app.parser.NXActionResubmit(),
            ], [
                SettingMock(eth_dst=test_app_base.fake_local_port2.mac),
                SettingMock(arp_tha=test_app_base.fake_local_port2.mac),
                SettingMock(reg7=test_app_base.fake_local_port2.unique_key),
                self.app.parser.NXActionResubmit(),
            ]
        ] 
Example 8
Project: dragonflow   Author: openstack   File: test_sg_app.py    License: Apache License 2.0 6 votes vote down vote up
def _get_another_local_lport(self):
        fake_local_port = test_app_base.make_fake_local_port(
            id='fake_port2',
            topic='fake_tenant1',
            name='',
            unique_key=5,
            version=2,
            ips=[netaddr.IPAddress('10.0.0.10'),
                 netaddr.IPAddress('2222:2222::2')],
            subnets=['fake_subnet1'],
            macs=[netaddr.EUI('fa:16:3e:8c:2e:12')],
            lswitch='fake_switch1',
            security_groups=['fake_security_group_id1'],
            allowed_address_pairs=[],
            port_security_enabled=True,
            device_owner='compute:None',
            device_id='fake_device_id',
            # 'binding_profile': {},
            # 'binding_vnic_type': 'normal',
        )
        return fake_local_port 
Example 9
Project: nmeta   Author: mattjhayes   File: tc_static.py    License: Apache License 2.0 6 votes vote down vote up
def is_valid_macaddress(self, value_to_check):
        """
        Passed a prospective MAC address and check that
        it is valid.
        Return 1 for is valid IP address and 0 for not valid
        """
        try:
            result = EUI(value_to_check)
            if result.version != 48:
                self.logger.debug("Check of is_valid_macaddress on %s "
                        "returned false", value_to_check)
                return 0
        except:
            self.logger.debug("Check of "
                    "is_valid_macaddress on %s raised an exception",
                    value_to_check)
            return 0
        return 1 
Example 10
Project: nmeta   Author: mattjhayes   File: tc_static.py    License: Apache License 2.0 6 votes vote down vote up
def is_match_macaddress(self, value_to_check1, value_to_check2):
        """
        Passed a two prospective MAC addresses and check to
        see if they are the same address.
        Return 1 for both the same MAC address and 0 for different
        """
        try:
            if not EUI(value_to_check1) == EUI(value_to_check2):
                self.logger.debug("Check of "
                        "is_match_macaddress on %s vs %s returned false",
                        value_to_check1, value_to_check2)
                return 0
        except:
            self.logger.debug("Check of "
                    "is_match_macaddress on %s vs %s raised an exception",
                    value_to_check1, value_to_check2)
            return 0
        return 1 
Example 11
Project: maas   Author: maas   File: network.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_eui_organization(eui):
    """Returns the registered organization for the specified EUI, if it can be
    determined. Otherwise, returns None.

    :param eui:A `netaddr.EUI` object.
    """
    try:
        registration = eui.oui.registration()
        # Note that `registration` is not a dictionary, so we can't use .get().
        return registration["org"]
    except UnicodeError:
        # See bug #1628761. Due to corrupt data in the OUI database, and/or
        # the fact that netaddr assumes all the data is ASCII, sometimes
        # netaddr will raise an exception during this process.
        return None
    except IndexError:
        # See bug #1748031; this is another way netaddr can fail.
        return None
    except NotRegisteredError:
        # This could happen for locally-administered MACs.
        return None 
Example 12
Project: maas   Author: maas   File: test_arp.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_properties(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "00:00:00:00:00:00"
        eth_src = "02:03:04:05:06:07"
        eth_dst = "ff:ff:ff:ff:ff:ff"
        arp_packet = make_arp_packet(
            pkt_sender_ip, pkt_sender_mac, pkt_target_ip, pkt_target_mac
        )
        arp = ARP(
            arp_packet,
            src_mac=hex_str_to_bytes(eth_src),
            dst_mac=hex_str_to_bytes(eth_dst),
        )
        self.assertThat(arp.source_eui, Equals(EUI(pkt_sender_mac)))
        self.assertThat(arp.target_eui, Equals(EUI(pkt_target_mac)))
        self.assertThat(arp.source_ip, Equals(IPAddress(pkt_sender_ip)))
        self.assertThat(arp.target_ip, Equals(IPAddress(pkt_target_ip))) 
Example 13
Project: maas   Author: maas   File: test_arp.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__returns_sender_for_request(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "00:00:00:00:00:00"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REQUEST,
            )
        )
        self.assertItemsEqual(
            arp.bindings(), [(IPAddress(pkt_sender_ip), EUI(pkt_sender_mac))]
        ) 
Example 14
Project: maas   Author: maas   File: test_arp.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__returns_sender_and_target_for_reply(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "02:03:04:05:06:07"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REPLY,
            )
        )
        self.assertItemsEqual(
            arp.bindings(),
            [
                (IPAddress(pkt_sender_ip), EUI(pkt_sender_mac)),
                (IPAddress(pkt_target_ip), EUI(pkt_target_mac)),
            ],
        ) 
Example 15
Project: maas   Author: maas   File: test_arp.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__skips_null_target_ip_in_reply(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "0.0.0.0"
        pkt_target_mac = "02:03:04:05:06:07"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REPLY,
            )
        )
        self.assertItemsEqual(
            arp.bindings(), [(IPAddress(pkt_sender_ip), EUI(pkt_sender_mac))]
        ) 
Example 16
Project: maas   Author: maas   File: test_arp.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__skips_null_source_eui_in_reply(self):
        pkt_sender_mac = "00:00:00:00:00:00"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "02:03:04:05:06:07"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REPLY,
            )
        )
        self.assertItemsEqual(
            arp.bindings(), [(IPAddress(pkt_target_ip), EUI(pkt_target_mac))]
        ) 
Example 17
Project: maas   Author: maas   File: test_arp.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_bindings__skips_null_target_eui_in_reply(self):
        pkt_sender_mac = "01:02:03:04:05:06"
        pkt_sender_ip = "192.168.0.1"
        pkt_target_ip = "192.168.0.2"
        pkt_target_mac = "00:00:00:00:00:00"
        arp = ARP(
            make_arp_packet(
                pkt_sender_ip,
                pkt_sender_mac,
                pkt_target_ip,
                pkt_target_mac,
                op=ARP_OPERATION.REPLY,
            )
        )
        self.assertItemsEqual(
            arp.bindings(), [(IPAddress(pkt_sender_ip), EUI(pkt_sender_mac))]
        ) 
Example 18
Project: maas   Author: maas   File: test_arp.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_new_binding(self):
        bindings = {}
        ip = IPAddress("192.168.0.1")
        mac = EUI("00:01:02:03:04:05")
        vid = None
        event = update_bindings_and_get_event(bindings, vid, ip, mac, 0)
        self.assertThat(bindings, Equals({(vid, ip): {"mac": mac, "time": 0}}))
        self.assertThat(
            event,
            Equals(
                dict(
                    event="NEW",
                    ip=str(ip),
                    mac=format_eui(mac),
                    time=0,
                    vid=vid,
                )
            ),
        ) 
Example 19
Project: maas   Author: maas   File: test_arp.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def test_moved_binding(self):
        bindings = {}
        ip = IPAddress("192.168.0.1")
        mac1 = EUI("00:01:02:03:04:05")
        mac2 = EUI("02:03:04:05:06:07")
        vid = None
        update_bindings_and_get_event(bindings, vid, ip, mac1, 0)
        event = update_bindings_and_get_event(bindings, vid, ip, mac2, 1)
        self.assertThat(
            bindings, Equals({(vid, ip): {"mac": mac2, "time": 1}})
        )
        self.assertThat(
            event,
            Equals(
                dict(
                    event="MOVED",
                    ip=str(ip),
                    mac=format_eui(mac2),
                    time=1,
                    previous_mac=format_eui(mac1),
                    vid=vid,
                )
            ),
        ) 
Example 20
Project: NetworkML   Author: CyberReboot   File: test_funcs_host.py    License: Apache License 2.0 6 votes vote down vote up
def test_host_keys():
    test_data = {field: None for field in WS_FIELDS}
    eth_src = '0e:00:00:00:00:01'
    eth_src_int = int(netaddr.EUI(eth_src))
    src_ip = ipaddress.ip_address('192.168.0.1')
    dst_ip = ipaddress.ip_address('192.168.0.2')
    test_data.update({
        'ip.version': 4,
        'eth.src': eth_src_int,
        'eth.dst': eth_src_int,
        'ip.src': str(int(src_ip)),
        'ip.dst': str(int(dst_ip)),
        'tcp.srcport': 999,
        'tcp.dstport': 1001,
        'frame.protocols': 'eth:ip',
    })
    row = nan_row_dict(test_data)
    instance = Host()
    assert instance._host_key(row)[1:] == (str(src_ip), str(dst_ip), 1, 0, 1)
    instance = SessionHost()
    assert instance._host_key(row)[1:] == (str(src_ip), str(dst_ip), 1, 0, 1) 
Example 21
Project: neutron-lib   Author: openstack   File: __init__.py    License: Apache License 2.0 6 votes vote down vote up
def validate_mac_address(data, valid_values=None):
    """Validate data is a MAC address.

    :param data: The data to validate.
    :param valid_values: Not used!
    :returns: None if the data is a valid MAC address, otherwise a human
        readable message as to why validation failed.
    """
    try:
        valid_mac = netaddr.valid_mac(validate_no_whitespace(data))
    except Exception:
        valid_mac = False

    if valid_mac:
        valid_mac = (not netaddr.EUI(data) in
                     map(netaddr.EUI, constants.INVALID_MAC_ADDRESSES))
    # TODO(arosen): The code in this file should be refactored
    # so it catches the correct exceptions. validate_no_whitespace
    # raises AttributeError if data is None.
    if not valid_mac:
        msg = _("'%s' is not a valid MAC address") % data
        LOG.debug(msg)
        return msg 
Example 22
Project: neutron-lib   Author: openstack   File: test_sqlalchemytypes.py    License: Apache License 2.0 6 votes vote down vote up
def test_crud(self):
        mac_addresses = ['FA:16:3E:00:00:01', 'FA:16:3E:00:00:02']

        for mac in mac_addresses:
            mac = netaddr.EUI(mac)
            self._add_row(id=uuidutils.generate_uuid(), mac=mac)
            obj = self._get_one(mac)
            self.assertEqual(mac, obj['mac'])
            random_mac = netaddr.EUI(net.get_random_mac(
                ['fe', '16', '3e', '00', '00', '00']))
            self._update_row(mac, random_mac)
            obj = self._get_one(random_mac)
            self.assertEqual(random_mac, obj['mac'])

        objs = self._get_all()
        self.assertEqual(len(mac_addresses), len(objs))
        self._delete_rows()
        objs = self._get_all()
        self.assertEqual(0, len(objs)) 
Example 23
Project: Chiron   Author: aatlasis   File: attacks.py    License: GNU General Public License v3.0 5 votes vote down vote up
def DHCPv6_Response(mac_source, source_ip, macdst, ipv6dst, Trid, ClientID_len, ClientID_duid, IaId, type_of_message, assigned_IPv6_addresses_cache, myinterface, dhcpv6_preference, prefered_lft,valid_lft,DNS_Domain_name,DNS_Servers, list_of_unfragmented_ext_headers,list_of_fragmented_ext_headers,size_of_extheaders, number_of_fragments,list_of_next_headers,list_of_offsets,list_of_fragment_lengths,list_of_fragment_m_bits,myprefix,unfragmentable_part,size_of_unfragmentable_part,first_next_header_value,fragmentable_extension_headers,size_of_fragmentable_extension_headers,s):
	iana = scapy.layers.dhcp6.DHCP6OptIA_NA()
	iana.iaid=IaId
	iana.T1 = 0
	iana.T2 = 0
	iana.optlen=12 + 28 #12 for the DHCP6OptIA_NA and 28 for one DHCP6OptIAAddress 
	ia_address = scapy.layers.dhcp6.DHCP6OptIAAddress()
	ia_address.preflft = prefered_lft 
	ia_address.validlft = valid_lft
	ClientID=scapy.layers.dhcp6.DHCP6OptClientId(optlen=ClientID_len, duid=ClientID_duid)
	ServerID=scapy.layers.dhcp6.DHCP6OptServerId()
	ServerID.duid = ("00030001"+ str(netaddr.EUI(mac_source)).replace("-","")).decode("hex")
	DNSDomains=scapy.layers.dhcp6.DHCP6OptDNSDomains()
	DNSDomains.dnsdomains=[DNS_Domain_name]
	DNSServers=scapy.layers.dhcp6.DHCP6OptDNSServers()
	DNSServers.dnsservers=[DNS_Servers]

	provided_IPv6_address=assigned_IPv6_addresses_cache.get(macdst)
	if not provided_IPv6_address:
		provided_IPv6_address=address_generators.generate_random_ipv6(myprefix)
		assigned_IPv6_addresses_cache[macdst]=provided_IPv6_address
	ia_address.addr= provided_IPv6_address

	if type_of_message=="Advertise":
		message_type = scapy.layers.dhcp6.DHCP6_Advertise(trid=Trid)
		print "DHCPv6 Advertise packet sent with Transaction ID", Trid,"to",macdst,"with IPv6 Address",provided_IPv6_address
	elif type_of_message=="Reply":
		message_type = scapy.layers.dhcp6.DHCP6_Reply(trid=Trid)
		print "DHCPv6 Reply packet sent with Transaction ID", Trid,"to",macdst,"with IPv6 Address",provided_IPv6_address
	dhcpv6pkt = message_type/iana/ia_address/ClientID/scapy.layers.dhcp6.DHCP6OptPref(prefval= dhcpv6_preference)/ServerID/DNSServers/DNSDomains
	packets=create_extension_headers_chain.create_datagram(mac_source,macdst,int(number_of_fragments),list_of_next_headers,list_of_offsets,list_of_fragment_lengths,list_of_fragment_m_bits,-1,unfragmentable_part,size_of_unfragmentable_part,first_next_header_value,fragmentable_extension_headers,size_of_fragmentable_extension_headers,create_layer4.udp_packet_id(546,dhcpv6pkt,547))
	create_extension_headers_chain.send_packets(s,packets,0)

###################################################################
###################### CVE 2012-2744###############################
################################################################### 
Example 24
Project: EvilTwinFramework   Author: Esser420   File: packet.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_vendor(mac):
        if mac != "":
            maco = EUI(mac)                         # EUI - Extended Unique Identifier
            try:
                return maco.oui.registration().org  # OUI - Organizational Unique Identifier
            except:                                 # OUI not registered exception
                return None
        return None 
Example 25
Project: EvilTwinFramework   Author: Esser420   File: aircracker.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, id=0, ssid=None, client_mac=None, location=None):
        self.id = id
        self.ssid = ssid
        self.client_mac = client_mac
        self.location = location
        self.client_org = None
        try:
            self.client_org = EUI(self.client_mac).oui.registration().org   # OUI - Organizational Unique Identifier
        except: pass                                                        # OUI not registered exception 
Example 26
Project: EvilTwinFramework   Author: Esser420   File: aircracker.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, id=0, ssid=None, bssid=None, date=None, location=None):
        self.id = id
        self.ssid = ssid
        self.bssid = bssid
        self.date = date
        self.location = location
        self.ap_org = None
        try:
            self.ap_org = EUI(self.bssid).oui.registration().org    # OUI - Organizational Unique Identifier
        except: pass 
Example 27
Project: EvilTwinFramework   Author: Esser420   File: aircracker.py    License: GNU General Public License v2.0 5 votes vote down vote up
def __init__(self, id=0, ssid=None, client_mac=None, date=None, location=None):
        self.id = id
        self.ssid = ssid
        self.client_mac = client_mac
        self.date = date
        self.location = location
        self.client_org = None
        try:
            self.client_org = EUI(self.client_mac).oui.registration().org    # OUI - Organizational Unique Identifier
        except: pass 
Example 28
Project: stethoscope   Author: Netflix-Skunkworks   File: macmanufacturer.py    License: Apache License 2.0 5 votes vote down vote up
def get_org(macaddr):
  """Return the IEEE-registered organization for the given MAC address (or `None` if none)."""

  mac = netaddr.EUI(macaddr)

  if mac.is_iab():
    try:
      return mac.iab.registration()['org']
    except netaddr.core.NotRegisteredError:
      pass

  try:
    return mac.oui.registration().org
  except netaddr.core.NotRegisteredError:
    return None 
Example 29
Project: upribox   Author: usableprivacy   File: base_extras.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_device_name(device):
    mac_vendor = None
    try:
        mac_vendor = EUI(device.mac).oui.registration().org
    except Exception:
        pass

    names = [device.hostname]
    if device.user_agent.filter(model__isnull=False).first():
        names.append(device.user_agent.filter(model__isnull=False).first().model)
    names.extend([mac_vendor, device.mac])
    try:
        return device.chosen_name or filter(lambda x: x not in IGNORE, names)[0]
    except IndexError:
        return None 
Example 30
Project: upribox   Author: usableprivacy   File: stats.py    License: GNU General Public License v3.0 5 votes vote down vote up
def get_queries_for_device(mac, week, sort=False, limit=None):

    device_queries = redis.hgetall(_DELIMITER.join((_PREFIX, _DEVICE, _QUERIED, str(EUI(mac)), _WEEK, str(week), _DOMAIN)))
    blocked = redis.hgetall(_DELIMITER.join((_PREFIX, _DNSMASQ, _BLOCKED, _WEEK, str(week), _DOMAIN)))
    blocked_queries = list()
    queries = list()

    if sort:
        device_queries = sorted(device_queries.items(), cmp=lambda x, y: int(x) - int(y), key=operator.itemgetter(1), reverse=True)
    else:
        device_queries = device_queries.items()

    for domain, count in device_queries:
        if domain in blocked:
            blocked_queries.append([domain, count])
        elif 'upri.box' not in domain:
            queries.append([domain, count])

    if len(blocked_queries) > 0:
        blocked_queries_num = sum(float(query[1]) for query in blocked_queries)
        device_queries_num = sum(float(query[1]) for query in device_queries)
        block_percent = round(blocked_queries_num / (device_queries_num + blocked_queries_num) * 100.00, 2)
    else:
        block_percent = 0

    return queries[:limit], blocked_queries[:limit], block_percent