Debian Codegraph @

neutron_lib/utils/net.py

raw
1 # Licensed under the Apache License, Version 2.0 (the "License");
2 # you may not use this file except in compliance with the License.
3 # You may obtain a copy of the License at
4 #
5 # http://www.apache.org/licenses/LICENSE-2.0
6 #
7 # Unless required by applicable law or agreed to in writing, software
8 # distributed under the License is distributed on an "AS IS" BASIS,
9 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10 # implied.
11 # See the License for the specific language governing permissions and
12 # limitations under the License.
13
14 import random
15 import socket
16
17 import netaddr
18
19 from neutron_lib import constants
20
21
22 def get_hostname():
23 """Get the hostname of the system.
24
25 :returns: The hostname of the system.
26 """
27 return socket.gethostname()
28
29
30 def get_random_mac(base_mac):
31 """Get a random MAC address string of the specified base format.
32
33 The first 3 octets will remain unchanged. If the 4th octet is not
34 00, it will also be used. The others will be randomly generated.
35
36 :param base_mac: Base MAC address represented by an array of 6 strings/int
37 :returns: The MAC address string.
38 """
39
40 mac = [int(base_mac[0], 16), int(base_mac[1], 16),
41 int(base_mac[2], 16), random.getrandbits(8),
42 random.getrandbits(8), random.getrandbits(8)]
43 if base_mac[3] != '00':
44 mac[3] = int(base_mac[3], 16)
45 return ':'.join([f"{x:02x}" for x in mac])
46
47
48 def random_mac_generator(base_mac):
49 """Generates random mac addresses from a specified base format.
50
51 The first 3 octets of each MAC address will remain unchanged. If the 4th
52 octet is not 00, it will also be used. The others will be randomly
53 generated.
54
55 :param base_mac: Base mac address represented by an array of 6 strings.
56 :returns: A mac address string generator.
57 """
58 fixed = list(base_mac[0:3])
59 to_generate = 3
60 if base_mac[3] != '00':
61 fixed = list(base_mac[0:4])
62 to_generate = 2
63 beginning = ':'.join(fixed) + ':'
64
65 form = '{}' + ':'.join('{:02x}' for _ in range(to_generate))
66 max_macs = 2 ** (to_generate * 8)
67 seen = set()
68 while len(seen) < max_macs:
69 numbers = [random.getrandbits(8) for _ in range(to_generate)]
70 mac = form.format(beginning, *numbers)
71 if mac in seen:
72 continue
73 seen.add(mac)
74 yield mac
75
76
77 def is_port_trusted(port):
78 """Used to determine if port can be trusted not to attack network.
79
80 Trust is currently based on the device_owner field starting with 'network:'
81 since we restrict who can use that in the default policy.yaml file.
82
83 :param port: The port dict to inspect the 'device_owner' for.
84 :returns: True if the port dict's 'device_owner' value starts with the
85 networking prefix. False otherwise.
86 """
87 return port['device_owner'].startswith(
88 constants.DEVICE_OWNER_NETWORK_PREFIX)
89
90
91 class _AuthenticBase:
92 def __init__(self, addr, **kwargs):
93 super().__init__(addr, **kwargs)
94 self._initial_value = addr
95
96 def __str__(self):
97 if isinstance(self._initial_value, str):
98 return self._initial_value
99 return super().__str__()
100
101 # NOTE(ihrachys): override deepcopy because netaddr.* classes are
102 # slot-based and hence would not copy _initial_value
103 def __deepcopy__(self, memo):
104 return self.__class__(self._initial_value)
105
106
107 class AuthenticIPNetwork(_AuthenticBase, netaddr.IPNetwork):
108 '''AuthenticIPNetwork class
109
110 This class retains the format of the IP network string passed during
111 initialization.
112
113 This is useful when we want to make sure that we retain the format passed
114 by a user through API.
115 '''
116
117
118 class AuthenticEUI(_AuthenticBase, netaddr.EUI):
119 '''AuthenticEUI class
120
121 This class retains the format of the MAC address string passed during
122 initialization.
123
124 This is useful when we want to make sure that we retain the format passed
125 by a user through API.
126 '''