CodeQL documentation

Accepting unknown SSH host keys when using Paramiko

ID: py/paramiko-missing-host-key-validation
Kind: problem
Severity: error
Precision: high
   - security
   - external/cwe/cwe-295
Query suites:
   - python-code-scanning.qls
   - python-security-extended.qls
   - python-security-and-quality.qls

Click to see the query in the CodeQL repository

In the Secure Shell (SSH) protocol, host keys are used to verify the identity of remote hosts. Accepting unknown host keys may leave the connection open to man-in-the-middle attacks.


Do not accept unknown host keys. In particular, do not set the default missing host key policy for the Paramiko library to either AutoAddPolicy or WarningPolicy. Both of these policies continue even when the host key is unknown. The default setting of RejectPolicy is secure because it throws an exception when it encounters an unknown host key.


The following example shows two ways of opening an SSH connection to The first function sets the missing host key policy to AutoAddPolicy. If the host key verification fails, the client will continue to interact with the server, even though the connection may be compromised. The second function sets the host key policy to RejectPolicy, and will throw an exception if the host key verification fails.

from paramiko.client import SSHClient, AutoAddPolicy, RejectPolicy

def unsafe_connect():
    client = SSHClient()

    # ... interaction with server


def safe_connect():
    client = SSHClient()

    # ... interaction with server