Exemple #1
0
 def findpairs( self, pfxset ):
     '''
     from a set of prefixes, finds the 'other half' of a prefix
     returns a list of tuples of prefix pairs
     '''
     pairs = []
     pfxset_copy = pfxset.copy()
     while len( pfxset_copy ) > 0:
         try:
             p1 = pfxset_copy.pop()
             # find the other half
             p1_net,p1_mask = p1.split('/')
             p1_mask = int( p1_mask )
             if p1_mask == 0:
                 continue
             this_half = None
             other_half = None
             if ':' in p1:
                 this_half = ipaddr.IPv6Address( p1_net )
                 other_half = ipaddr.IPv6Address( int(this_half) ^ 2 ** ( 128 - p1_mask ) )
             else:
                 this_half = ipaddr.IPv4Address( p1_net )
                 other_half = ipaddr.IPv4Address( int(this_half) ^ 2 ** ( 32  - p1_mask ) )
             other_half = "%s/%s" % ( other_half, p1_mask )
             if other_half in pfxset:
                 pairs.append( sorted([ p1, other_half ]) )
                 pfxset_copy.remove( other_half )
         except KeyError:
             break
     return pairs
Exemple #2
0
 def control_plane_icmpv6_handler(self, in_port, vlan, eth_src, ipv6_pkt,
                                  icmpv6_pkt):
     vid = self._vlan_vid(vlan, in_port)
     src_ip = ipaddr.IPv6Address(ipv6_pkt.src)
     dst_ip = ipaddr.IPv6Address(ipv6_pkt.dst)
     icmpv6_type = icmpv6_pkt.type_
     ofmsgs = []
     if (icmpv6_type == icmpv6.ND_NEIGHBOR_SOLICIT
             and vlan.ip_in_controller_subnet(src_ip)):
         nd_reply = valve_packet.nd_reply(self.faucet_mac, eth_src, vid,
                                          icmpv6_pkt.data.dst, src_ip,
                                          ipv6_pkt.hop_limit)
         ofmsgs.extend([valve_of.packetout(in_port, nd_reply.data)])
         ofmsgs.extend(self._add_host_fib_route(vlan, src_ip))
     elif (icmpv6_type == icmpv6.ND_NEIGHBOR_ADVERT
           and vlan.ip_in_controller_subnet(src_ip)):
         resolved_ip_gw = ipaddr.IPv6Address(icmpv6_pkt.data.dst)
         self.logger.info('ND response %s for %s', eth_src, resolved_ip_gw)
         ofmsgs.extend(self._update_nexthop(vlan, eth_src, resolved_ip_gw))
     elif icmpv6_type == icmpv6.ICMPV6_ECHO_REQUEST:
         icmpv6_echo_reply = valve_packet.icmpv6_echo_reply(
             self.faucet_mac, eth_src, vid, dst_ip, src_ip,
             ipv6_pkt.hop_limit, icmpv6_pkt.data.id, icmpv6_pkt.data.seq,
             icmpv6_pkt.data.data)
         ofmsgs.extend(
             [valve_of.packetout(in_port, icmpv6_echo_reply.data)])
     return ofmsgs
Exemple #3
0
 def _control_plane_icmpv6_handler(self, pkt_meta, ipv6_pkt, icmpv6_pkt):
     vlan = pkt_meta.vlan
     src_ip = ipaddr.IPv6Address(ipv6_pkt.src)
     dst_ip = ipaddr.IPv6Address(ipv6_pkt.dst)
     icmpv6_type = icmpv6_pkt.type_
     ofmsgs = []
     if vlan.ip_in_vip_subnet(src_ip):
         in_port = pkt_meta.port.number
         vid = self._vlan_vid(vlan, in_port)
         eth_src = pkt_meta.eth_src
         if icmpv6_type == icmpv6.ND_NEIGHBOR_SOLICIT:
             solicited_ip = icmpv6_pkt.data.dst
             if vlan.is_faucet_vip(ipaddr.IPAddress(solicited_ip)):
                 ofmsgs.extend(self._add_host_fib_route(vlan, src_ip))
                 nd_reply = valve_packet.nd_reply(self.faucet_mac, eth_src,
                                                  vid, solicited_ip, src_ip,
                                                  ipv6_pkt.hop_limit)
                 ofmsgs.append(valve_of.packetout(in_port, nd_reply.data))
                 self.logger.info(
                     'Responded to ND solicit for %s to %s (%s)',
                     solicited_ip, src_ip, eth_src)
         elif icmpv6_type == icmpv6.ND_NEIGHBOR_ADVERT:
             ofmsgs.extend(
                 self._update_nexthop(vlan, in_port, eth_src, src_ip))
             self.logger.info('ND advert %s (%s)', src_ip, eth_src)
         elif vlan.from_connected_to_vip(src_ip, dst_ip):
             if (icmpv6_type == icmpv6.ICMPV6_ECHO_REQUEST
                     and pkt_meta.eth_dst == self.faucet_mac):
                 icmpv6_echo_reply = valve_packet.icmpv6_echo_reply(
                     self.faucet_mac, eth_src, vid, dst_ip, src_ip,
                     ipv6_pkt.hop_limit, icmpv6_pkt.data.id,
                     icmpv6_pkt.data.seq, icmpv6_pkt.data.data)
                 ofmsgs.append(
                     valve_of.packetout(in_port, icmpv6_echo_reply.data))
     return ofmsgs
    def testNetworkElementCaching(self):
        # V4 - make sure we're empty
        self.assertFalse(self.ipv4._cache.has_key('network'))
        self.assertFalse(self.ipv4._cache.has_key('broadcast'))
        self.assertFalse(self.ipv4._cache.has_key('hostmask'))

        # V4 - populate and test
        self.assertEqual(self.ipv4.network, ipaddr.IPv4Address('1.2.3.0'))
        self.assertEqual(self.ipv4.broadcast, ipaddr.IPv4Address('1.2.3.255'))
        self.assertEqual(self.ipv4.hostmask, ipaddr.IPv4Address('0.0.0.255'))

        # V4 - check we're cached
        self.assertTrue(self.ipv4._cache.has_key('network'))
        self.assertTrue(self.ipv4._cache.has_key('broadcast'))
        self.assertTrue(self.ipv4._cache.has_key('hostmask'))

        # V6 - make sure we're empty
        self.assertFalse(self.ipv6._cache.has_key('network'))
        self.assertFalse(self.ipv6._cache.has_key('broadcast'))
        self.assertFalse(self.ipv6._cache.has_key('hostmask'))

        # V6 - populate and test
        self.assertEqual(self.ipv6.network,
                         ipaddr.IPv6Address('2001:658:22a:cafe::'))
        self.assertEqual(
            self.ipv6.broadcast,
            ipaddr.IPv6Address('2001:658:22a:cafe:ffff:ffff:ffff:ffff'))
        self.assertEqual(self.ipv6.hostmask,
                         ipaddr.IPv6Address('::ffff:ffff:ffff:ffff'))

        # V6 - check we're cached
        self.assertTrue(self.ipv6._cache.has_key('network'))
        self.assertTrue(self.ipv6._cache.has_key('broadcast'))
        self.assertTrue(self.ipv6._cache.has_key('hostmask'))
Exemple #5
0
 def test_lir_ipv6_lookup(self):
     self.assertEqual(self.database_cache.fetch_country_code('ipv6',
             'lir', int(ipaddr.IPv6Address('2001:0658:021A::'))), 'DE')
     self.assertEqual(self.database_cache.fetch_country_code('ipv6',
             'lir', int(ipaddr.IPv6Address('2001:67c:320::'))), 'DE')
     self.assertEqual(self.database_cache.fetch_country_code('ipv6',
             'lir', int(ipaddr.IPv6Address('2001:670:0085::'))), 'FI')
    def open(self):
        univention.admin.handlers.simpleLdap.open(self)
        self.oldinfo['a'] = []
        self.info['a'] = []
        if 'aRecord' in self.oldattr:
            self.oldinfo['a'].extend(self.oldattr['aRecord'])
            self.info['a'].extend(self.oldattr['aRecord'])
        if 'aAAARecord' in self.oldattr:
            self.oldinfo['a'].extend(
                map(lambda x: ipaddr.IPv6Address(x).exploded,
                    self.oldattr['aAAARecord']))
            self.info['a'].extend(
                map(lambda x: ipaddr.IPv6Address(x).exploded,
                    self.oldattr['aAAARecord']))

        soa = self.oldattr.get('sOARecord', [''])[0].split(' ')
        if len(soa) > 6:
            self['contact'] = unescapeSOAemail(soa[1])
            self['serial'] = soa[2]
            self['refresh'] = univention.admin.mapping.unmapUNIX_TimeInterval(
                soa[3])
            self['retry'] = univention.admin.mapping.unmapUNIX_TimeInterval(
                soa[4])
            self['expire'] = univention.admin.mapping.unmapUNIX_TimeInterval(
                soa[5])
            self['ttl'] = univention.admin.mapping.unmapUNIX_TimeInterval(
                soa[6])

        self.save()
Exemple #7
0
	def _ldap_modlist(self):  # IPv6
		ml = univention.admin.handlers.simpleLdap._ldap_modlist(self)
		oldAddresses = self.oldinfo.get('a')
		newAddresses = self.info.get('a')
		oldARecord = []
		newARecord = []
		oldAaaaRecord = []
		newAaaaRecord = []
		if oldAddresses != newAddresses:
			if oldAddresses:
				for address in oldAddresses:
					if ':' in address:  # IPv6
						oldAaaaRecord.append(address)
					else:
						oldARecord.append(address)
			if newAddresses:
				for address in newAddresses:
					if ':' in address:  # IPv6
						newAaaaRecord.append(ipaddr.IPv6Address(address).exploded)
					else:
						newARecord.append(address)

			# explode all IPv6 addresses and remove duplicates
			newAaaaRecord = list(set(map(lambda x: ipaddr.IPv6Address(x).exploded, newAaaaRecord)))

			ml.append(('aRecord', oldARecord, newARecord, ))
			ml.append(('aAAARecord', oldAaaaRecord, newAaaaRecord, ))
		return ml
 def test_byIPv4_none(self):
     """A bridge with no IPv4 addresses should cause filters.byIPv4() to
     return False.
     """
     self.bridge.address = ipaddr.IPv6Address('2006:2222::2222')
     self.bridge.orAddresses = [(ipaddr.IPv6Address('2006:3333::3333'),
                                 3333, 6)]
     self.assertFalse(filters.byIPv4(self.bridge))
    def __init__(self, *items, **updates):
        if 'source' in updates:
            self.source = int(ipaddr.IPv6Address(updates['source']))
            del updates['source']
        if 'destination' in updates:
            self.destination = int(ipaddr.IPv6Address(updates['destination']))
            del updates['destination']

        super(Ipv6Endpoints, self).__init__(*items, **updates)
        self._header.process = True
Exemple #10
0
def ip_convert(ip):
    if ip.startswith('4-'):
        return str(ipaddr.IPv4Address(int(ip[2:])))
    elif ip.startswith('6-'):
        return str(ipaddr.IPv6Address(long(ip[2:])))
    else:
        if re.match(".*:.*", ip):
            return str('6-') + str(int(ipaddr.IPv6Address(ip)))
        else:
            return str('4-') + str(int(ipaddr.IPv4Address(ip)))
Exemple #11
0
def ip_other_half( pfx ):
    pfx_net, pfx_mask = pfx.split('/')
    pfx_mask = int( pfx_mask )
    if ':' in pfx:
        this_half = ipaddr.IPv6Address( pfx_net )
        other_half = ipaddr.IPv6Address( int(this_half) ^ 2 ** ( 128 - pfx_mask ) )
    else:
        this_half = ipaddr.IPv4Address( pfx_net )
        other_half = ipaddr.IPv4Address( int(this_half) ^ 2 ** ( 32  - pfx_mask ) )
    return "%s/%s" % ( other_half, pfx_mask )
Exemple #12
0
	def open(self):
		univention.admin.handlers.simpleLdap.open(self)
		self.oldinfo['a'] = []
		self.info['a'] = []
		if 'aRecord' in self.oldattr:
			self.oldinfo['a'].extend(self.oldattr['aRecord'])
			self.info['a'].extend(self.oldattr['aRecord'])
		if 'aAAARecord' in self.oldattr:
			self.oldinfo['a'].extend(map(lambda x: ipaddr.IPv6Address(x).exploded, self.oldattr['aAAARecord']))
			self.info['a'].extend(map(lambda x: ipaddr.IPv6Address(x).exploded, self.oldattr['aAAARecord']))
Exemple #13
0
    def runTest(self):
        ing_port = flow_mods_port_map.keys()[0]
        egr_port = flow_mods_port_map.keys()[1]
        table_id = testutils.EX_L3_TABLE
        flow_count = 10

        testutils.delete_all_flows_one_table(self.controller, self.logger,
                                             table_id)
        match_fields_ls = []
        ipv6_src_addr = 'fe80::2420:52ff:fe8f:5188'
        metadata_val = 0xaa22334455667788
        for i in range(flow_count):
            match_fields_ls.append(match_list())
            match_fields_ls[i].add(match.eth_type(testutils.IPV6_ETHERTYPE))
            match_fields_ls[i].add(
                match.ipv6_src(ipaddr.IPv6Address(ipv6_src_addr)))
            ipv6_dst_addr = 'fe80::2420:52ff:fe8f:' + str(5190 + i)
            match_fields_ls[i].add(
                match.ipv6_dst(ipaddr.IPv6Address(ipv6_dst_addr)))
            match_fields_ls[i].add(match.metadata(metadata_val))

            request = testutils.flow_msg_create(
                self,
                None,
                ing_port=ing_port,
                match_fields=match_fields_ls[i],
                egr_port=egr_port,
                table_id=table_id)
            testutils.flow_msg_install(self, request, False)

        match_fields = match_list()
        match_fields.add(match.eth_type(testutils.IPV6_ETHERTYPE))
        match_fields.add(match.ipv6_src(ipaddr.IPv6Address(ipv6_src_addr)))

        response = testutils.flow_stats_get(self, table_id=table_id)
        self.assertTrue(
            len(response.stats) == flow_count,
            'Did not add all flows successfully! Get table entry num is %d' %
            len(response.stats))

        request = testutils.flow_msg_create(self,
                                            None,
                                            None,
                                            ing_port,
                                            match_fields,
                                            table_id=table_id)
        request.command = ofp.OFPFC_DELETE
        testutils.flow_msg_install(self, request, False)

        response = testutils.flow_stats_get(self, table_id=table_id)

        self.assertTrue(
            len(response.stats) == 0,
            'Switch did not del the flow entry! Current table entry num is %d'
            % len(response.stats))
Exemple #14
0
 def testAddressIntMath(self):
     self.assertEqual(
         ipaddr.IPv4Address('1.1.1.1') + 255, ipaddr.IPv4Address('1.1.2.0'))
     self.assertEqual(
         ipaddr.IPv4Address('1.1.1.1') - 256, ipaddr.IPv4Address('1.1.0.1'))
     self.assertEqual(
         ipaddr.IPv6Address('::1') + (2**16 - 2),
         ipaddr.IPv6Address('::ffff'))
     self.assertEqual(
         ipaddr.IPv6Address('::ffff') - (2**16 - 2),
         ipaddr.IPv6Address('::1'))
    def testCopyConstructor(self):
        addr1 = ipaddr.IPNetwork('10.1.1.0/24')
        addr2 = ipaddr.IPNetwork(addr1)
        addr3 = ipaddr.IPNetwork('2001:658:22a:cafe:200::1/64')
        addr4 = ipaddr.IPNetwork(addr3)
        addr5 = ipaddr.IPv4Address('1.1.1.1')
        addr6 = ipaddr.IPv6Address('2001:658:22a:cafe:200::1')

        self.assertEqual(addr1, addr2)
        self.assertEqual(addr3, addr4)
        self.assertEqual(addr5, ipaddr.IPv4Address(addr5))
        self.assertEqual(addr6, ipaddr.IPv6Address(addr6))
Exemple #16
0
 def addIp(self, pfx, cc, recursive=False):
     if not recursive:
         rtype = 'v4'
         if pfx.count(':'):
             rtype = 'v6'
         if cc in self.cc:
             if rtype in self.cc[cc]:
                 self.cc[cc][rtype] += 1
             else:
                 self.cc[cc][rtype] = 1
         else:
             self.cc[cc] = {rtype: 1}
     r = self.radix.add(pfx)
     r.data['cc'] = cc
     # find other half of the first covering prefix
     other_half = None
     if r.family == socket.AF_INET:
         this_half = ipaddr.IPv4Address(r.network)
         other_half = ipaddr.IPv4Address(
             int(this_half) ^ 2**(32 - r.prefixlen))
     elif r.family == socket.AF_INET6:
         this_half = ipaddr.IPv6Address(r.network)
         other_half = ipaddr.IPv6Address(
             int(this_half) ^ 2**(128 - r.prefixlen))
     else:
         raise RuntimeException('unknown ip address family: %s' %
                                (rnode.family))
     #print "other half %s %s %s" % ( r.network, other_half, r.prefixlen )
     if self.radix.search_exact(str(other_half), r.prefixlen):
         r_oh = self.radix.search_exact(str(other_half), r.prefixlen)
         if r_oh.data['cc'] == r.data['cc']:
             # delete the 2 halves and add the supernet
             sup_pfxlen = r.prefixlen - 1
             sup_addr = None
             if r.family == socket.AF_INET:
                 sup_addr = ipaddr.IPv4Address(
                     int(other_half) & ~2**(32 - r.prefixlen))
             elif r.family == socket.AF_INET6:
                 sup_addr = ipaddr.IPv6Address(
                     int(other_half) & ~2**(128 - r.prefixlen))
             else:
                 raise RuntimeException('unknown ip address family: %s' %
                                        (rnode.family))
             #print "merging %s %s (%s) => %s (%s) " % ( r.network, r_oh.network, r.prefixlen, sup_addr, sup_pfxlen )
             r_sup = self.addIp('/'.join([str(sup_addr),
                                          str(sup_pfxlen)]),
                                cc,
                                recursive=True)
             self.radix.delete(r.network, r.prefixlen)
             self.radix.delete(r_oh.network, r_oh.prefixlen)
     return r
Exemple #17
0
    def _do_generic_update_test(self, record, new_name, new_ip, ip_type):
        if new_ip:
            if ip_type == '4':
                ip_upper, ip_lower = 0, ipaddr.IPv4Address(new_ip).__int__()
            else:
                ip_upper, ip_lower = ipv6_to_longs(new_ip)
        else:
            ip_upper, ip_lower = record.ip_upper, record.ip_lower

        if new_name is not None and new_ip is not None:
            aret = AddressRecord.objects.filter(label=new_name,
                                                ip_upper=ip_upper,
                                                ip_lower=ip_lower,
                                                ip_type=ip_type)[0]
        elif new_name is not None:
            # Just new_name
            aret = AddressRecord.objects.filter(label=new_name,
                                                ip_upper=ip_upper,
                                                ip_lower=ip_lower,
                                                ip_type=ip_type)[0]
        else:
            # Just new_ip
            aret = AddressRecord.objects.filter(label=new_name,
                                                ip_upper=ip_upper,
                                                ip_lower=ip_lower,
                                                ip_type=ip_type)[0]
        if new_name:
            self.assertEqual(aret.label, new_name)
        if new_ip:
            if ip_type == '4':
                self.assertEqual(aret.ip_str,
                                 ipaddr.IPv4Address(new_ip).__str__())
            else:
                self.assertEqual(aret.ip_str,
                                 ipaddr.IPv6Address(new_ip).__str__())
Exemple #18
0
def fix_datatype(row):
    for key, value in row.items():
        try:
            if key in ['AnalyzerIPV4', 'SourceIPV4', 'TargetIPV4']:
                if value is not None:
                    row[key] = str(ipaddr.IPv4Address(abs(value)))
            elif key in ['AnalyzerIPV6', 'SourceIPV6', 'TargetIPV6']:
                if value is not None:
                    row[key] = str(ipaddr.IPv6Address(ipaddr.Bytes(value)))
            elif value is None:
                row[key] = 'NULL'
            elif type(value) is bytes:
                row[key] = unicodedata.normalize('NFKD', value).encode(
                    'ascii', 'ignore')
            elif type(value) is datetime.datetime:
                row[key] = value.isoformat()
            elif type(value) is uuid.UUID:
                row[key] = value.hex
            elif 'java class' in str(type(value)):
                try:
                    row[key] = value.toString()
                except:
                    row[key] = value
        except Exception as e:
            logger.warning(f"value of '{key}' is not valid. Warning: {e}")
    return row
Exemple #19
0
def validate_network_params(subnet, gateway=None, subnet6=None, gateway6=None):
    try:
        # Use strict option to not all subnets with host bits set
        network = ipaddr.IPv4Network(subnet, strict=True)
    except ValueError:
        raise faults.BadRequest("Invalid network IPv4 subnet")

    # Check that network size is allowed!
    if not validate_network_size(network.prefixlen):
        raise faults.OverLimit(
            message="Unsupported network size",
            details="Network mask must be in range (%s, 29]" % MAX_CIDR_BLOCK)

    # Check that gateway belongs to network
    if gateway:
        try:
            gateway = ipaddr.IPv4Address(gateway)
        except ValueError:
            raise faults.BadRequest("Invalid network IPv4 gateway")
        if not gateway in network:
            raise faults.BadRequest("Invalid network IPv4 gateway")

    if subnet6:
        try:
            # Use strict option to not all subnets with host bits set
            network6 = ipaddr.IPv6Network(subnet6, strict=True)
        except ValueError:
            raise faults.BadRequest("Invalid network IPv6 subnet")
        if gateway6:
            try:
                gateway6 = ipaddr.IPv6Address(gateway6)
            except ValueError:
                raise faults.BadRequest("Invalid network IPv6 gateway")
            if not gateway6 in network6:
                raise faults.BadRequest("Invalid network IPv6 gateway")
Exemple #20
0
 def add_host_fib_route_from_pkt(self, vlan, pkt):
     ipv6_pkt = pkt.get_protocol(ipv6.ipv6)
     if not ipv6_pkt:
         return
     src_ip = ipaddr.IPv6Address(ipv6_pkt.src)
     if src_ip and vlan.ip_in_controller_subnet(src_ip):
         return self._add_host_fib_route(vlan, src_ip)
Exemple #21
0
def calc_rev(ip, subnet):
    """
	>>> calc_rev(ip='1.2.3.4', subnet='1.2')
	'4.3'
	>>> calc_rev(ip='0001:0002:0003:0004:0005:0006:0007:0008', subnet='0001:0002:0003:0')
	'8.0.0.0.7.0.0.0.6.0.0.0.5.0.0.0.4.0.0'
	>>> calc_rev(ip='1:2:3:4:5:6:7:8', subnet='0001:0002:0003:0')
	'8.0.0.0.7.0.0.0.6.0.0.0.5.0.0.0.4.0.0'
	"""
    if ':' in subnet:
        string = ''.join(subnet.split(':'))
        prefix = len(string)
        assert 1 <= prefix < 32
        string += '0' * (32 - prefix)
        net = ipaddr.IPv6Network('%s/%d' % (ipv6(string), 4 * prefix))
        addr = ipaddr.IPv6Address(ip)
        host = ''.join(addr.exploded.split(':'))
    else:
        octets = subnet.split('.')
        prefix = len(octets)
        assert 1 <= prefix < 4
        octets += ['0'] * (4 - prefix)
        net = ipaddr.IPv4Network('%s/%d' % ('.'.join(octets), 8 * prefix))
        addr = ipaddr.IPv4Address(ip)
        host = addr.exploded.split('.')
    if addr not in net:
        raise ValueError()
    return '.'.join(reversed(host[prefix:]))
Exemple #22
0
 def __check_address(self):
     '''        Analyse target address setting, resolve it to IP        '''
     if not self.address:
         raise RuntimeError("Target address not specified")
     try:
         ipaddr.IPv6Address(self.address)
         self.ipv6 = True
     except AddressValueError:
         self.log.debug("Not ipv6 address: %s", self.address)
         self.ipv6 = False
         address_port = self.address.split(":")
         self.address = address_port[0]
         if len(address_port) > 1:
             self.port = address_port[1]
         try:
             ipaddr.IPv4Address(self.address)
         except AddressValueError:
             self.log.debug("Not ipv4 address: %s", self.address)
             ip_addr = socket.gethostbyname(self.address)
             reverse_name = socket.gethostbyaddr(ip_addr)[0]
             self.log.debug("Address %s ip_addr: %s, reverse-resolve: %s",
                            self.address, ip_addr, reverse_name)
             if reverse_name.startswith(self.address):
                 self.address = ip_addr
             else:
                 raise ValueError(
                     "Address %s reverse-resolved to %s, but must match" %
                     (self.address, reverse_name))
def IsValidIPV6(ip):
    """Accepts an ipv6 address in string form and returns True if valid."""
    try:
        ipaddr.IPv6Address(ip)
    except ipaddr.AddressValueError:
        return False
    return True
Exemple #24
0
def addaddr(msg):
    try:
        if msg['ipv4'] != '':
            ip = int(ipaddr.IPv4Address(msg['ipv4']))
        elif msg['ipv6'] != '':
            ip = int(ipaddr.IPv6Address(msg['ipv6']))
        else:
            logging.exception("NoIpNode:")
            logging.exception(msg)
            return

        session = Session()
        node = session.query(Node).filter_by(ip=ip).first()
        if not node:
            node = Node()
        else:
            return

        node.port = msg['port']
        node.timestamp = msg['timestamp']
        node.services = msg['services']

        session.add(node)
        session.commit()

    except:
        logging.exception("AddAddr:")
Exemple #25
0
def addNode(msg):
    try:

        if msg['from_addr']['ipv4'] != '':
            ip = int(ipaddr.IPv4Address(msg['from_addr']['ipv4']))
        elif msg['from_addr']['ipv6'] != '':
            ip = int(ipaddr.IPv6Address(msg['from_addr']['ipv6']))
        else:
            logging.exception("NoIpNode:")
            logging.exception(msg)
            return

        session = Session()
        node = session.query(Node).filter_by(ip=ip).first()
        if not node:
            node = Node()

        node.ip = ip
        node.port = msg['from_addr']['port']
        node.version = msg['version']
        node.height = msg['start_height']
        node.timestamp = msg['timestamp']
        node.services = msg['services']
        node.agent = msg['user_agent']

        session.add(node)
        session.commit()

    except:
        logging.exception("AddNode:")
Exemple #26
0
 def session(self,
             action=None,
             source=None,
             mac=None,
             ipv4=None,
             ipv6=None,
             time=None):
     if cherrypy.request.method != 'POST':
         return "Invalid request method"
     if source not in ('arp', 'nd', 'radius', 'dhcp'):
         return "Invalid source"
     self.authenticate_session_request()
     mac = MAC(mac)
     if ipv4:
         ipv4 = ipaddr.IPv4Address(ipv4)
     if ipv6:
         ipv6 = ipaddr.IPv6Address(ipv6)
     time = datetime.datetime.strptime(time, "%Y-%m-%dT%H:%M:%S")
     if action == 'start':
         sessions.session_started(source, mac, time, ipv4, ipv6)
     elif action == 'end':
         sessions.session_ended(source, mac, time, ipv4, ipv6)
     else:
         return "Invalid action"
     return "Success"
Exemple #27
0
def pb2dict(pb, pretty=False, is_hex=False):
    """
	Convert protobuf msg to dictionary.
	Takes a protobuf message and returns a dict.
	"""
    d = collections.OrderedDict() if pretty else {}
    for field, value in pb.ListFields():
        if field.label == FD.LABEL_REPEATED:
            d_val = []
            if pretty and _marked_as_ip(field):
                if len(value) == 1:
                    v = socket.ntohl(value[0])
                    addr = ipaddr.IPv4Address(v)
                else:
                    v = 0 + (socket.ntohl(value[0]) << (32 * 3)) + \
                     (socket.ntohl(value[1]) << (32 * 2)) + \
                     (socket.ntohl(value[2]) << (32 * 1)) + \
                     (socket.ntohl(value[3]))
                    addr = ipaddr.IPv6Address(v)

                d_val.append(addr.compressed)
            else:
                for v in value:
                    d_val.append(_pb2dict_cast(field, v, pretty, is_hex))
        else:
            d_val = _pb2dict_cast(field, value, pretty, is_hex)

        d[field.name] = d_val
    return d
Exemple #28
0
def is_ipv6_address(addr):
    try:
        ipaddr.IPv6Address(addr)
    except:
        return False
    else:
        return True
 def test_byIPv6_orAddress(self):
     """A bridge with an IPv6 address in its orAddresses address should
     cause filters.byIPv6() to return True.
     """
     self.bridge.orAddresses = [(ipaddr.IPv6Address('2006:3333::3333'),
                                 3333, 6)]
     self.assertTrue(filters.byIPv6(self.bridge))
Exemple #30
0
    def validate_ip6(self):
        # validate IPv6
        if not self.ip6dynamic:
            for address, prefix, identifier in self.ip6:
                # validate IP address
                try:
                    int(ipaddr.IPv6Address(address))
                except ipaddr.AddressValueError:
                    raise DeviceError(
                        _('Invalid IPv6 address: %r') % (address), self.name)

                # validate IPv6 netmask
                try:
                    ipaddr.IPv6Network('%s/%s' % (address, prefix))
                except (ValueError, ipaddr.NetmaskValueError,
                        ipaddr.AddressValueError):
                    raise DeviceError(
                        _('Invalid IPv6 netmask: %r') % (prefix), self.name)

                # validate IPv6 identifier
                if not RE_IPV6_ID.match(identifier):
                    raise DeviceError(
                        _('Invalid IPv6 identifier: %r') % (identifier),
                        self.name)

            # There must be a 'default' identifier
            if self.ip6 and not any(
                    identifier == 'default'
                    for address, prefix, identifier in self.ip6):
                raise DeviceError(_('Missing IPv6 default identifier'),
                                  self.name)