Skip to content

socket — no timeout

Synchronous Access of socket without Timeout

The function socket.create_connection() in Python establishes a TCP connection to a remote host. By default, this function operates synchronously, meaning it will block indefinitely if no timeout is specified. This behavior can lead to resource exhaustion or unresponsive applications if the remote host is slow or unresponsive, creating the risk of a Denial of Service (DoS).

This rule ensures that a timeout is always specified when using socket.create_connection() to prevent indefinite blocking and resource exhaustion.

Failing to specify a timeout in socket.create_connection() may cause the system or application to block indefinitely while waiting for a connection, consuming resources unnecessarily and potentially leading to system hangs or Denial of Service (DoS) vulnerabilities.

Example

socket_create_connection.py
1
2
3
4
5
6
import socket


s = socket.create_connection(("127.0.0.1", 80))
s.recv(1024)
s.close()
Example Output
> precli tests/unit/rules/python/stdlib/socket/examples/socket_create_connection.py
⚠️  Warning on line 9 in tests/unit/rules/python/stdlib/socket/examples/socket_create_connection.py
PY039: Synchronous Access of Remote Resource without Timeout
The function 'socket.create_connection' is used without a timeout, which may cause the application to block indefinitely if the remote server does not respond.

Remediation

Always provide a timeout parameter when calling socket.create_connection(). This ensures that if the remote host is unreachable or unresponsive, the connection attempt will fail after a certain period, releasing resources and preventing indefinite blocking.

Alternatively, the global default timeout can be set via socket.setdefaulttimeout(). This is a good option to enforce a consistent timeout for any network library that uses sockets.

socket_create_connection.py
1
2
3
4
5
6
import socket


s = socket.create_connection(("127.0.0.1", 80), timeout=5)
s.recv(1024)
s.close()

Default Configuration

enabled = true
level = "warning"

See also

New in version 0.6.7