Skip to content

Commit 32e7acd

Browse files
[3.10] bpo-37013: Fix the error handling in socket.if_indextoname() (GH-13503) (GH-112599)
* 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 b6535ea commit 32e7acd

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
@@ -1070,7 +1070,20 @@ def testInterfaceNameIndex(self):
10701070
'socket.if_indextoname() not available.')
10711071
def testInvalidInterfaceIndexToName(self):
10721072
self.assertRaises(OSError, socket.if_indextoname, 0)
1073+
self.assertRaises(OverflowError, socket.if_indextoname, -1)
1074+
self.assertRaises(OverflowError, socket.if_indextoname, 2**1000)
10731075
self.assertRaises(TypeError, socket.if_indextoname, '_DEADBEEF')
1076+
if hasattr(socket, 'if_nameindex'):
1077+
indices = dict(socket.if_nameindex())
1078+
for index in indices:
1079+
index2 = index + 2**32
1080+
if index2 not in indices:
1081+
with self.assertRaises((OverflowError, OSError)):
1082+
socket.if_indextoname(index2)
1083+
for index in 2**32-1, 2**64-1:
1084+
if index not in indices:
1085+
with self.assertRaises((OverflowError, OSError)):
1086+
socket.if_indextoname(index)
10741087

10751088
@unittest.skipUnless(hasattr(socket, 'if_nametoindex'),
10761089
'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
@@ -6827,17 +6827,23 @@ Returns the interface index corresponding to the interface name if_name.");
68276827
static PyObject *
68286828
socket_if_indextoname(PyObject *self, PyObject *arg)
68296829
{
6830+
unsigned long index_long = PyLong_AsUnsignedLong(arg);
6831+
if (index_long == (unsigned long) -1 && PyErr_Occurred()) {
6832+
return NULL;
6833+
}
6834+
68306835
#ifdef MS_WINDOWS
6831-
NET_IFINDEX index;
6836+
NET_IFINDEX index = (NET_IFINDEX)index_long;
68326837
#else
6833-
unsigned long index;
6838+
unsigned int index = (unsigned int)index_long;
68346839
#endif
6835-
char name[IF_NAMESIZE + 1];
68366840

6837-
index = PyLong_AsUnsignedLong(arg);
6838-
if (index == (unsigned long) -1)
6841+
if ((unsigned long)index != index_long) {
6842+
PyErr_SetString(PyExc_OverflowError, "index is too large");
68396843
return NULL;
6844+
}
68406845

6846+
char name[IF_NAMESIZE + 1];
68416847
if (if_indextoname(index, name) == NULL) {
68426848
PyErr_SetFromErrno(PyExc_OSError);
68436849
return NULL;

0 commit comments

Comments
 (0)