Skip to content

Commit 0daf555

Browse files
authored
bpo-37013: Fix the error handling in socket.if_indextoname() (pythonGH-13503)
* Fix a crash when pass UINT_MAX. * Fix an integer overflow on 64-bit non-Windows platforms.
1 parent 70a38ff commit 0daf555

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
@@ -7071,17 +7071,23 @@ _socket_socket_if_nametoindex_impl(PySocketSockObject *self, PyObject *oname)
70717071
static PyObject *
70727072
socket_if_indextoname(PyObject *self, PyObject *arg)
70737073
{
7074+
unsigned long index_long = PyLong_AsUnsignedLong(arg);
7075+
if (index_long == (unsigned long) -1 && PyErr_Occurred()) {
7076+
return NULL;
7077+
}
7078+
70747079
#ifdef MS_WINDOWS
7075-
NET_IFINDEX index;
7080+
NET_IFINDEX index = (NET_IFINDEX)index_long;
70767081
#else
7077-
unsigned long index;
7082+
unsigned int index = (unsigned int)index_long;
70787083
#endif
7079-
char name[IF_NAMESIZE + 1];
70807084

7081-
index = PyLong_AsUnsignedLong(arg);
7082-
if (index == (unsigned long) -1)
7085+
if ((unsigned long)index != index_long) {
7086+
PyErr_SetString(PyExc_OverflowError, "index is too large");
70837087
return NULL;
7088+
}
70847089

7090+
char name[IF_NAMESIZE + 1];
70857091
if (if_indextoname(index, name) == NULL) {
70867092
PyErr_SetFromErrno(PyExc_OSError);
70877093
return NULL;

0 commit comments

Comments
 (0)