Skip to content

Commit

Permalink
Better validate VM NIC mac address
Browse files Browse the repository at this point in the history
(cherry picked from commit 55b9903)
  • Loading branch information
Qubad786 authored and bugclerk committed Oct 28, 2024
1 parent 4c1bb18 commit ab8bb2e
Show file tree
Hide file tree
Showing 2 changed files with 87 additions and 0 deletions.
4 changes: 4 additions & 0 deletions src/middlewared/middlewared/plugins/vm/devices/nic.py
Original file line number Diff line number Diff line change
Expand Up @@ -104,3 +104,7 @@ def _validate(self, device, verrors, old=None, vm_instance=None, update=True):
'attributes.trust_guest_rx_filters',
'This can only be set when "type" of NIC device is "VIRTIO"'
)

mac_address = device['attributes'].get('mac')
if mac_address and mac_address.lower().startswith('ff'):
verrors.add('attributes.mac', 'MAC address must not start with `ff`')
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
import pytest

from middlewared.plugins.vm.devices import NIC
from middlewared.pytest.unit.middleware import Middleware

from middlewared.service_exception import ValidationErrors


AVAILABLE_NIC_INTERFACES = ['br0', 'eth0']


@pytest.mark.parametrize('device_data,expected_error', [
(
{
'attributes': {
'type': 'VIRTIO',
'mac': '00:a0:99:7e:bb:8a',
'nic_attach': 'br0',
'trust_guest_rx_filters': False
},
'dtype': 'NIC',
},
''
),
(
{
'attributes': {
'type': 'VIRTIO',
'mac': '00:a0:99:7e:bb:8a',
'nic_attach': 'br2',
'trust_guest_rx_filters': False
},
'dtype': 'NIC',
},
'[EINVAL] attributes.nic_attach: Not a valid choice.'
),
(
{
'attributes': {
'type': 'VIRTIO',
'mac': 'ff:a0:99:7e:bb:8a',
'nic_attach': 'br0',
'trust_guest_rx_filters': False
},
'dtype': 'NIC',
},
'[EINVAL] attributes.mac: MAC address must not start with `ff`'
),
(
{
'attributes': {
'type': 'VIRTIO',
'mac': 'ff:a0:99:7e:bb:8a',
'nic_attach': 'br0',
'trust_guest_rx_filters': True
},
'dtype': 'NIC',
},
'[EINVAL] attributes.trust_guest_rx_filters: This can only be set when "nic_attach" is not a bridge device'
),
(
{
'attributes': {
'type': 'E1000',
'mac': 'ff:a0:99:7e:bb:8a',
'nic_attach': 'eth0',
'trust_guest_rx_filters': True
},
'dtype': 'NIC',
},
'[EINVAL] attributes.trust_guest_rx_filters: This can only be set when "type" of NIC device is "VIRTIO"'
),
])
def test_nic_device_validation(device_data, expected_error):
m = Middleware()
m['vm.device.nic_attach_choices'] = lambda *arg: AVAILABLE_NIC_INTERFACES
if expected_error:
with pytest.raises(ValidationErrors) as ve:
NIC(device_data, m).validate(device_data)

assert str(ve.value.errors[0]) == expected_error
else:
assert NIC(device_data, m).validate(device_data) is None

0 comments on commit ab8bb2e

Please sign in to comment.