Skip to content

New to Python and Paramiko. Getting ValueError("q must be exactly 160, 224, or 256 bits long") #2048

Open

Description

@JakobRottenbucher

Hello, so I'm trying to ssh into my work server, and I keep getting the above error.

File "C:\Users\Me\AppData\Local\Programs\Python\Python310\lib\site-packages\cryptography\hazmat\primitives\asymmetric\dsa.py", line 287, in _check_dsa_parameters 
    raise ValueError("q must be exactly 160, 224, or 256 bits long")

I am using the following code:

import paramiko
paramiko.util.log_to_file('ssh.log') # sets up logging
client = paramiko.SSHClient()
client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
client.connect("server", username="myusername", key_filename="/Users/me/.ssh/pk")

Again, I'm very new to Python and especially Paramiko, so any assistance is greatly appreciated. I "think" the issue is that there is something wrong the OpenSSH key, so it's going down the list of keys and getting to DSA where the length of the RSA key is of course not matching the DSA key.

Activity

  1. Schwaneberg commented on Jun 28, 2022

    @Schwaneberg

    I got the same issue. The problem is an outdated RSA algorithm at the Open SSH Server. Access using the ssh command id possible, if PubkeyAcceptedKeyTypes +ssh-rsa is set in .ssh/config.
    I think this requires a new parameter like enabled_algorithms to white list additional options in the transport API (the opposite of the disabled_algorithms parameter).

  2. bskinn commented on Jun 29, 2022

    @bskinn
    Contributor

    @Schwaneberg:

    I think this requires a new parameter like enabled_algorithms to white list additional options in the transport API (the opposite of the disabled_algorithms parameter).

    Flagging for @bitprophet's attention in case this should be considered in the course of #387. Thanks for this info!

  3. jun66j5 commented on Jun 29, 2022

    @jun66j5
    Contributor

    SSHClient tries to load and authenticate with the given private key file using each RSAKey, DSSKey, ECDSAKey and Ed25519Key until the authentication passes.

    Typically, when the given private key is a RSA key and publickey authentication passes, the issue doesn't occur. However, when the publickey authentication fails using RSAKey, SSHClient is trying to load and authenticate using DSSKey. As the result, the issue occurs.

    $ ssh-keygen -f /tmp/test-rsa
    Generating public/private rsa key pair.
    Enter passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved in /tmp/test-rsa
    Your public key has been saved in /tmp/test-rsa.pub
    The key fingerprint is:
    SHA256:imIkU/P0DhkeA3sOA11rai+o3XHc4rBU2wA9S0sIE2I jun66j5@localhost
    
    $ head -3 /dev/shm/test-rsa
    -----BEGIN OPENSSH PRIVATE KEY-----
    b3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAABlwAAAAdzc2gtcn
    NhAAAAAwEAAQAAAYEAwsw533cX19z5d8HErEY/3M9+OSlQN+XApZIbZ3rxdEcrRGC2JUXH
    
    >>> import paramiko
    >>> key = paramiko.DSSKey.from_private_key_file('/tmp/test-rsa')
    >>> key.sign_ssh_data(b'test')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "paramiko/dsskey.py", line 109, in sign_ssh_data
        key = dsa.DSAPrivateNumbers(
      File ".venv/lib/python3.9/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py", line 242, in private_key
        return ossl.load_dsa_private_numbers(self)
      File ".venv/lib/python3.9/site-packages/cryptography/hazmat/backends/openssl/backend.py", line 822, in load_dsa_private_numbers
        dsa._check_dsa_private_numbers(numbers)
      File ".venv/lib/python3.9/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py", line 283, in _check_dsa_private_numbers
        _check_dsa_parameters(parameters)
      File ".venv/lib/python3.9/site-packages/cryptography/hazmat/primitives/asymmetric/dsa.py", line 275, in _check_dsa_parameters
        raise ValueError("q must be exactly 160, 224, or 256 bits long")
    ValueError: q must be exactly 160, 224, or 256 bits long

    Work around is to pass loaded private key to pkey parameter instead of using key_filename. Also, I suggest to disable look_for_keys feature because of the same reason.

    pkey = paramiko.RSAKey.from_private_key_file("/Users/me/.ssh/pk")
    client.connect("server", username="myusername", pkey=pkey, look_for_keys=False)

    We might (ad hoc) fix SSHClient by attempting to invoke PKey.sign_ssh_data() after loading the private key:

    diff --git a/paramiko/client.py b/paramiko/client.py
    index 92feaa1fb..4cec61a22 100644
    --- a/paramiko/client.py
    +++ b/paramiko/client.py
    @@ -597,6 +597,11 @@ class SSHClient(ClosingContextManager):
                 hexlify(key.get_fingerprint()), key_path
             )
             self._log(DEBUG, msg)
    +        # Attempt to sign data in order to validate the private key
    +        try:
    +            key.sign_ssh_data(b'test')
    +        except Exception as e:
    +            raise SSHException(e)
             # Attempt to load cert if it exists.
             if os.path.isfile(cert_path):
                 key.load_certificate(cert_path)
  4. jun66j5 commented on Jun 29, 2022

    @jun66j5
    Contributor

    Ideally, we should verify keytype in openssh private key format at the following:

    paramiko/paramiko/pkey.py

    Lines 486 to 488 in 50d3322

    # Unpack private key and verify checkints
    cstruct = self._uint32_cstruct_unpack(decrypted_privkey, "uusr")
    checkint1, checkint2, keytype, keydata = cstruct

  5. OneTouchOfME commented on Dec 7, 2022

    @OneTouchOfME

    I had same issue with paramiko=2.12.0

    Unknown exception: q must be exactly 160, 224, or 256 bits long
    Traceback (most recent call last):
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\transport.py", line 2164, in run
        handler(self.auth_handler, m)
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\auth_handler.py", line 395, in _parse_service_accept
        sig = self.private_key.sign_ssh_data(blob, algorithm)
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\dsskey.py", line 109, in sign_ssh_data
        key = dsa.DSAPrivateNumbers(
      File "C:\Users\test\Envs\eps\lib\site-packages\cryptography\hazmat\primitives\asymmetric\dsa.py", line 251, in private_key
        return ossl.load_dsa_private_numbers(self)
      File "C:\Users\test\Envs\eps\lib\site-packages\cryptography\hazmat\backends\openssl\backend.py", line 753, in load_dsa_private_numbers
        dsa._check_dsa_private_numbers(numbers)
      File "C:\Users\test\Envs\eps\lib\site-packages\cryptography\hazmat\primitives\asymmetric\dsa.py", line 295, in _check_dsa_private_numbers
        _check_dsa_parameters(parameters)
      File "C:\Users\test\Envs\eps\lib\site-packages\cryptography\hazmat\primitives\asymmetric\dsa.py", line 287, in _check_dsa_parameters
        raise ValueError("q must be exactly 160, 224, or 256 bits long")
    ValueError: q must be exactly 160, 224, or 256 bits long
    
    Authentication failed due to Invalid Private Key C:\Users\test\.ssh\id_rsa: q must be exactly 160, 224, or 256 bits long
    Traceback (most recent call last):
      File "ssh_older_test.py", line 279, in <module>
        ssh_obj.connect()
      File "ssh_older_test.py", line 132, in connect
        raise e
      File "ssh_older_test.py", line 118, in connect
        self._ssh.connect(
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\client.py", line 450, in connect
        self._auth(
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\client.py", line 697, in _auth
        self._transport.auth_publickey(username, key)
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\transport.py", line 1635, in auth_publickey
        return self.auth_handler.wait_for_response(my_event)
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\auth_handler.py", line 245, in wait_for_response
        raise e
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\transport.py", line 2164, in run
        handler(self.auth_handler, m)
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\auth_handler.py", line 395, in _parse_service_accept
        sig = self.private_key.sign_ssh_data(blob, algorithm)
      File "C:\Users\test\Envs\eps\lib\site-packages\paramiko\dsskey.py", line 109, in sign_ssh_data
        key = dsa.DSAPrivateNumbers(
      File "C:\Users\test\Envs\eps\lib\site-packages\cryptography\hazmat\primitives\asymmetric\dsa.py", line 251, in private_key
        return ossl.load_dsa_private_numbers(self)
      File "C:\Users\test\Envs\eps\lib\site-packages\cryptography\hazmat\backends\openssl\backend.py", line 753, in load_dsa_private_numbers
        dsa._check_dsa_private_numbers(numbers)
      File "C:\Users\test\Envs\eps\lib\site-packages\cryptography\hazmat\primitives\asymmetric\dsa.py", line 295, in _check_dsa_private_numbers
        _check_dsa_parameters(parameters)
      File "C:\Users\test\Envs\eps\lib\site-packages\cryptography\hazmat\primitives\asymmetric\dsa.py", line 287, in _check_dsa_parameters
        raise ValueError("q must be exactly 160, 224, or 256 bits long")
    ValueError: q must be exactly 160, 224, or 256 bits long
    
  6. OneTouchOfME commented on Dec 7, 2022

    @OneTouchOfME

    If there any quick solution of this issue. @jun66j5 in which file and what need to be change so I don't have to wait for next version?

  7. added a commit that references this issue on Jan 12, 2023
  8. khoatrandata commented on Apr 20, 2023

    @khoatrandata

    We are with paramiko version 3.1.0 and have the same issue

    client.connect(
                hostname=sftp_host,
                username=sftp_user,
                key_filename='/my_key_path',
            )
    Unknown exception: q must be exactly 160, 224, or 256 bits long
    ...
    

    the private key works with FileZilla or CyberDuck etc...

  9. jun66j5 commented on Apr 20, 2023

    @jun66j5
    Contributor

    @khoatrandata

    Work around is to pass loaded private key to pkey parameter instead of using key_filename because private key handling of SSHClient is poor.

    pkey = paramiko.RSAKey.from_private_key_file("/path/to/private.key")
    client.connect(hostname=sftp_host, username=sftp_user, pkey=pkey, look_for_keys=False, allow_agent=False)

    (If the private key is not RSA, modify RSAKey with key class which matches the private key.)

    See #2048 (comment)

  10. ssclift commented on Feb 21, 2024

    @ssclift

    My fix has been to create an ~/.ssh/config file and explicitly list an

    IdentityFile /home/fu/.ssh/id_rsa_local_key_of_some_sort

    and make sure the public key is in the .ssh/authorized_keys at the destination.

    Regular ssh, in my case, is using ssh-agent to push through where Paramiko doesn't.

  11. added a commit that references this issue on Jun 16, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions