fix: reject MAC address octets with a sign or whitespace (#424)

MacAddress.validate_mac_address parsed each octet with int(part, 16),
which also accepts a leading +/- sign and surrounding whitespace. As a
result strings like -a:-b:-c:-d:-e:-f, +a:+b:+c:+d:+e:+f and
" a: b: c: d: e: f" were accepted, with the sign/whitespace variants
silently normalized into a valid-looking MAC the caller never supplied.

Require both characters of each octet to be hex digits before the int()
conversion so malformed octets raise the mac_address_format error like
other invalid input.
This commit is contained in:
dualfroz committed 2026-09-06 00:23:06 +01:00
1 parent dfa8240f1f
commit 996db5006c
3 files changed
+14 -1

No files matched your search

+7 -1
View File
@@ -4,6 +4,7 @@ formats, such as IEEE 802 MAC-48, EUI-48, EUI-64, or a 20-octet format.
from __future__ import annotations
import string
from typing import Any
from pydantic import GetCoreSchemaHandler
@@ -100,7 +101,12 @@ class MacAddress(str):
mac_bytes: list[int] = []
for part in parts:
for i in range(0, chunk_len, 2):
mac_bytes.append(int(part[i : i + 2], base=16))
octet = part[i : i + 2]
# int(octet, 16) also accepts a sign or whitespace,
# which are not valid MAC octets.
if not all(char in string.hexdigits for char in octet):
raise ValueError(octet)
mac_bytes.append(int(octet, base=16))
except ValueError as exc:
raise PydanticCustomError('mac_address_format', 'Unrecognized format') from exc