Skip to content

Commit 63ba5cc

Browse files
authored
bpo-40121: Fixes audit event raised on creating a new socket (GH-19238)
1 parent ef67512 commit 63ba5cc

File tree

4 files changed

+39
-3
lines changed

4 files changed

+39
-3
lines changed

Lib/test/audit-tests.py

+22
Original file line numberDiff line numberDiff line change
@@ -327,6 +327,28 @@ def hook(event, args):
327327
CloseKey(kv)
328328

329329

330+
def test_socket():
331+
import socket
332+
333+
def hook(event, args):
334+
if event.startswith("socket."):
335+
print(event, *args)
336+
337+
sys.addaudithook(hook)
338+
339+
socket.gethostname()
340+
341+
# Don't care if this fails, we just want the audit message
342+
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
343+
try:
344+
# Don't care if this fails, we just want the audit message
345+
sock.bind(('127.0.0.1', 8080))
346+
except error:
347+
pass
348+
finally:
349+
sock.close()
350+
351+
330352
if __name__ == "__main__":
331353
from test.libregrtest.setup import suppress_msvcrt_asserts
332354

Lib/test/test_audit.py

+12
Original file line numberDiff line numberDiff line change
@@ -118,6 +118,18 @@ def test_winreg(self):
118118
self.assertSequenceEqual(["winreg.EnumKey", " ", f"{expected} 10000"], events[3])
119119
self.assertSequenceEqual(["winreg.PyHKEY.Detach", " ", expected], events[4])
120120

121+
def test_socket(self):
122+
support.import_module("socket")
123+
returncode, events, stderr = self.run_python("test_socket")
124+
if returncode:
125+
self.fail(stderr)
126+
127+
if support.verbose:
128+
print(*events, sep='\n')
129+
self.assertEqual(events[0][0], "socket.gethostname")
130+
self.assertEqual(events[1][0], "socket.__new__")
131+
self.assertEqual(events[2][0], "socket.bind")
132+
self.assertTrue(events[2][2].endswith("('127.0.0.1', 8080)"))
121133

122134
if __name__ == "__main__":
123135
unittest.main()
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fixes audit events raised on creating a new socket.

Modules/socketmodule.c

+4-3
Original file line numberDiff line numberDiff line change
@@ -5099,7 +5099,7 @@ sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
50995099

51005100
#ifdef MS_WINDOWS
51015101
/* In this case, we don't use the family, type and proto args */
5102-
if (fdobj != NULL && fdobj != Py_None)
5102+
if (fdobj == NULL || fdobj == Py_None)
51035103
#endif
51045104
{
51055105
if (PySys_Audit("socket.__new__", "Oiii",
@@ -5121,8 +5121,9 @@ sock_initobj(PyObject *self, PyObject *args, PyObject *kwds)
51215121
}
51225122
memcpy(&info, PyBytes_AS_STRING(fdobj), sizeof(info));
51235123

5124-
if (PySys_Audit("socket()", "iii", info.iAddressFamily,
5125-
info.iSocketType, info.iProtocol) < 0) {
5124+
if (PySys_Audit("socket.__new__", "Oiii", s,
5125+
info.iAddressFamily, info.iSocketType,
5126+
info.iProtocol) < 0) {
51265127
return -1;
51275128
}
51285129

0 commit comments

Comments
 (0)