Using sockets is security-sensitive. It has led in the past to the following vulnerabilities:
Sockets are vulnerable in multiple ways:
- They enable a software to interact with the outside world. As this world is full of attackers it is necessary to check that they cannot receive
sensitive information or inject dangerous input.
- The number of sockets is limited and can be exhausted. Which makes the application unresponsive to users who need additional sockets.
This rules flags code that creates sockets. It matches only the direct use of sockets, not use through frameworks or high-level APIs such as the
use of http connections.
Ask Yourself Whether
- sockets are created without any limit every time a user performs an action.
- input received from sockets is used without being sanitized.
- sensitive data is sent via sockets without being encrypted.
You are at risk if you answered yes to any of these questions.
Recommended Secure Coding Practices
- In many cases there is no need to open a socket yourself. Use instead libraries and existing protocols.
- Encrypt all data sent if it is sensitive. Usually it is better to encrypt it even if the data is not sensitive as it might change later.
- Sanitize any input read from the socket.
- Limit the number of sockets a given user can create. Close the sockets as soon as possible.
Questionable Code Example
function handle_sockets($domain, $type, $protocol, $port, $backlog, $addr, $hostname, $local_socket, $remote_socket, $fd) {
socket_create($domain, $type, $protocol); // Questionable
socket_create_listen($port, $backlog); // Questionable
socket_addrinfo_bind($addr); // Questionable
socket_addrinfo_connect($addr); // Questionable
socket_create_pair($domain, $type, $protocol, $fd);
fsockopen($hostname); // Questionable
pfsockopen($hostname); // Questionable
stream_socket_server($local_socket); // Questionable
stream_socket_client($remote_socket); // Questionable
stream_socket_pair($domain, $type, $protocol); // Questionable
}
See
- MITRE, CWE-20 - Improper Input Validation
- MITRE, CWE-400 - Uncontrolled Resource Consumption ('Resource Exhaustion')
- MITRE, CWE-200 - Information Exposure
- OWASP Top 10 2017 Category A1 - Injection
- OWASP Top 10 2017 Category A3 - Sensitive Data Exposure
- SANS Top 25 - Risky Resource Management
- SANS Top 25 - Porous Defenses