Skip to main content

Synchronous Access of socket without Timeout

PY039
no_timeout
CWE-1088
⚠️ Warning

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

import socket


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

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.

import socket


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

False Positives

In the case of a false positive the rule can be suppressed. Simply add a trailing or preceding comment line with either the rule ID (PY039) or rule category name (no_timeout).

Fix Iconfix
import socket


# suppress: PY039
s = socket.create_connection(("127.0.0.1", 80))
s.recv(1024)
s.close()

See also