Skip to content

Commit 1cc594d

Browse files
[3.11] bpo-37013: Fix the error handling in socket.if_indextoname() (GH-13503) (GH-112598)
* 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 1162d29 commit 1cc594d

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
@@ -1066,7 +1066,20 @@ def testInterfaceNameIndex(self):
10661066
'socket.if_indextoname() not available.')
10671067
def testInvalidInterfaceIndexToName(self):
10681068
self.assertRaises(OSError, socket.if_indextoname, 0)
1069+
self.assertRaises(OverflowError, socket.if_indextoname, -1)
1070+
self.assertRaises(OverflowError, socket.if_indextoname, 2**1000)
10691071
self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF')
1072+
if hasattr(socket, 'if_nameindex'):
1073+
indices = dict(socket.if_nameindex())
1074+
for index in indices:
1075+
index2 = index + 2**32
1076+
if index2 not in indices:
1077+
with self.assertRaises((OverflowError, OSError)):
1078+
socket.if_indextoname(index2)
1079+
for index in 2**32-1, 2**64-1:
1080+
if index not in indices:
1081+
with self.assertRaises((OverflowError, OSError)):
1082+
socket.if_indextoname(index)
10701083

10711084
@unittest.skipUnless(hasattr(socket, 'if_nametoindex'),
10721085
'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
@@ -6943,17 +6943,23 @@ Returns the interface index corresponding to the interface name if_name.");
69436943
static PyObject *
69446944
socket_if_indextoname(PyObject *self, PyObject *arg)
69456945
{
6946+
unsigned long index_long = PyLong_AsUnsignedLong(arg);
6947+
if (index_long == (unsigned long) -1 && PyErr_Occurred()) {
6948+
return NULL;
6949+
}
6950+
69466951
#ifdef MS_WINDOWS
6947-
NET_IFINDEX index;
6952+
NET_IFINDEX index = (NET_IFINDEX)index_long;
69486953
#else
6949-
unsigned long index;
6954+
unsigned int index = (unsigned int)index_long;
69506955
#endif
6951-
char name[IF_NAMESIZE + 1];
69526956

6953-
index = PyLong_AsUnsignedLong(arg);
6954-
if (index == (unsigned long) -1)
6957+
if ((unsigned long)index != index_long) {
6958+
PyErr_SetString(PyExc_OverflowError, "index is too large");
69556959
return NULL;
6960+
}
69566961

6962+
char name[IF_NAMESIZE + 1];
69576963
if (if_indextoname(index, name) == NULL) {
69586964
PyErr_SetFromErrno(PyExc_OSError);
69596965
return NULL;

0 commit comments

Comments
 (0)