Skip to content

Commit fc7e67f

Browse files
[3.12] bpo-37013: Fix the error handling in socket.if_indextoname() (GH-13503) (GH-112597)
* Fix a crash when pass UINT_MAX. * Fix an integer overflow on 64-bit non-Windows platforms. (cherry picked from commit 0daf555) Co-authored-by: Zackery Spytz <[email protected]>
1 parent bdad5c3 commit fc7e67f

File tree

3 files changed

+27
-5
lines changed

3 files changed

+27
-5
lines changed

Lib/test/test_socket.py

+13
Original file line numberDiff line numberDiff line change
@@ -1082,7 +1082,20 @@ def testInterfaceNameIndex(self):
10821082
'socket.if_indextoname() not available.')
10831083
def testInvalidInterfaceIndexToName(self):
10841084
self.assertRaises(OSError, socket.if_indextoname, 0)
1085+
self.assertRaises(OverflowError, socket.if_indextoname, -1)
1086+
self.assertRaises(OverflowError, socket.if_indextoname, 2**1000)
10851087
self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF')
1088+
if hasattr(socket, 'if_nameindex'):
1089+
indices = dict(socket.if_nameindex())
1090+
for index in indices:
1091+
index2 = index + 2**32
1092+
if index2 not in indices:
1093+
with self.assertRaises((OverflowError, OSError)):
1094+
socket.if_indextoname(index2)
1095+
for index in 2**32-1, 2**64-1:
1096+
if index not in indices:
1097+
with self.assertRaises((OverflowError, OSError)):
1098+
socket.if_indextoname(index)
10861099

10871100
@unittest.skipUnless(hasattr(socket, 'if_nametoindex'),
10881101
'socket.if_nametoindex() not available.')
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
Fix a crash in :func:`socket.if_indextoname` with specific value (UINT_MAX).
2+
Fix an integer overflow in :func:`socket.if_indextoname` on 64-bit
3+
non-Windows platforms.

Modules/socketmodule.c

+11-5
Original file line numberDiff line numberDiff line change
@@ -7085,17 +7085,23 @@ Returns the interface index corresponding to the interface name if_name.");
70857085
static PyObject *
70867086
socket_if_indextoname(PyObject *self, PyObject *arg)
70877087
{
7088+
unsigned long index_long = PyLong_AsUnsignedLong(arg);
7089+
if (index_long == (unsigned long) -1 && PyErr_Occurred()) {
7090+
return NULL;
7091+
}
7092+
70887093
#ifdef MS_WINDOWS
7089-
NET_IFINDEX index;
7094+
NET_IFINDEX index = (NET_IFINDEX)index_long;
70907095
#else
7091-
unsigned long index;
7096+
unsigned int index = (unsigned int)index_long;
70927097
#endif
7093-
char name[IF_NAMESIZE + 1];
70947098

7095-
index = PyLong_AsUnsignedLong(arg);
7096-
if (index == (unsigned long) -1)
7099+
if ((unsigned long)index != index_long) {
7100+
PyErr_SetString(PyExc_OverflowError, "index is too large");
70977101
return NULL;
7102+
}
70987103

7104+
char name[IF_NAMESIZE + 1];
70997105
if (if_indextoname(index, name) == NULL) {
71007106
PyErr_SetFromErrno(PyExc_OSError);
71017107
return NULL;

0 commit comments

Comments
 (0)