Skip to content

[BUG] - Authentication issue with rsa key #2268

Open

Description

@TabsB

Are you using paramiko as a client or server?

Client

What feature(s) aren't working right?

SFTP, Keys/auth

What version(s) of paramiko are you using?

3.2.0

What version(s) of Python are you using?

3.7.v27

What operating system and version are you using?

not sure, running from aws lambda function

If you're connecting as a client, which SSH server are you connecting to?

No response

If you're using paramiko as part of another tool, which tool/version?

No response

Expected/desired behavior

I'm using paramiko to connect to an sftp, with public/private key pair. The implementation is done in a lambda function, in aws. Paramiko is added as a layer to the lambda. My implementation for the authentication part:

transport = paramiko.Transport((host, port))
if self.password is not None:
transport.connect(username=username, password=password)
else:
rsa_private_key = paramiko.RSAKey.from_private_key(io.StringIO(private_key), passphrase)
transport.connect(username=self.username, pkey=rsa_private_key)

if transport is not None:
sftp_client = paramiko.SFTPClient.from_transport(transport)

The private_key holds an rsa private key witch starts with
-----BEGIN RSA PRIVATE KEY-----
......
-----END RSA PRIVATE KEY-----
The passphrase is None.

The authentication should pass at this point.
I already tested the key auth with another software, FileZilla and it works.

Actual behavior

Instead of connecting to the sftp server, I'm getting authentication failed.

"message": "AuthenticationException('Authentication failed.')",
"traceback": "Traceback (most recent call last):\n File "/var/task/upload.py", line 49, in main\n transport.connect(username=client_auth_data["username"], pkey=rsa_private_key)\n File "/opt/python/paramiko/transport.py", line 1411, in connect\n self.auth_publickey(username, pkey)\n File "/opt/python/paramiko/transport.py", line 1658, in auth_publickey\n return self.auth_handler.wait_for_response(my_event)\n File "/opt/python/paramiko/auth_handler.py", line 263, in wait_for_response\n raise e\nparamiko.ssh_exception.AuthenticationException: Authentication failed.\n"

I get no other specific error.

How to reproduce

sftp_client = None
transport = None
port = int(client_auth_data["port"]) if "port" in client_auth_data else 22 #default port is 22
try:
transport = paramiko.Transport((client_auth_data["host"], port))
if 'password' in client_auth_data:
transport.connect(username=client_auth_data["username"], password=client_auth_data["password"])
else:
passphrase = client_auth_data["passphrase"] if "passphrase" in client_auth_data else None
rsa_private_key = paramiko.RSAKey.from_private_key(io.StringIO((client_auth_data["private_key"])), passphrase)
transport.connect(username=client_auth_data["username"], pkey=rsa_private_key)

if transport is not None:
    sftp_client = paramiko.SFTPClient.from_transport(transport)

except Exception as e:
log.exception({"message": repr(e), "traceback":traceback.format_exc()})

Anything else?

No response

Activity

  1. bskinn commented on Jul 25, 2023

    @bskinn
    Contributor

    Hi @TabsB, thanks for the report.

    Can you reformat your code snippets and errors and such using code blocks? It's really hard to read without fixed-width code formatting. Thanks!

  2. TabsB commented on Jul 27, 2023

    @TabsB
    Author

    Sure!

    The code:

    sftp_client = None
    transport = None
    try:
         transport = paramiko.Transport((client_auth_data["host"], port))
         if 'password' in client_auth_data:
              transport.connect(username=client_auth_data["username"], password=client_auth_data["password"])
         else:
              passphrase = client_auth_data["passphrase"] if "passphrase" in client_auth_data else None
              rsa_private_key = paramiko.RSAKey.from_private_key(io.StringIO(client_auth_data["private_key"]), passphrase)
              transport.connect(username=client_auth_data["username"], pkey=rsa_private_key)
                    
         if transport is not None:
              sftp_client = paramiko.SFTPClient.from_transport(transport)
    except Exception as e:
         log.exception({"message": repr(e), "traceback":traceback.format_exc()})
    

    where client_auth_data is a json containg authentication data.

    The error:

    "message": "AuthenticationException('Authentication failed.')",
    "traceback": "Traceback (most recent call last):\n File "/var/task/upload.py", line 49, in main\n transport.connect(username=client_auth_data["username"], pkey=rsa_private_key)\n File "/opt/python/paramiko/transport.py", line 1411, in connect\n self.auth_publickey(username, pkey)\n File "/opt/python/paramiko/transport.py", line 1658, in auth_publickey\n return self.auth_handler.wait_for_response(my_event)\n File "/opt/python/paramiko/auth_handler.py", line 263, in wait_for_response\n raise e\nparamiko.ssh_exception.AuthenticationException: Authentication failed.\n"
    
  3. masashiozakirivf commented on Aug 2, 2023

    @masashiozakirivf

    In my environment, transport.connect() without password results to "AuthenticationException('Authentication failed.')"
    I set up password on PC I want to connect to.

    If you want to know how to connect to non password PC, this information is not useful....

  4. TabsB commented on Aug 10, 2023

    @TabsB
    Author

    Hello @bskinn,

    I was wondering if there are any updates or if you need any additional information from me to proceed.
    Thanks!

  5. Tobotimus commented on Sep 13, 2023

    @Tobotimus

    Hi, I'm experiencing the same issue after upgrading from v2.7.2 to v3.3.1, including the context of using paramiko to connect to an SFTP server, with the client running on AWS Lambda.

    After inspecting the DEBUG logs, I can see that my issue is due to the server not supporting either RSA2 key verification or the server-sig-algs extension.

    I also found a relevant (and very helpful) warning in the changelog entry for 2.9.0, which even suggests a workaround!

    Specifically, you need to specify disabled_algorithms={'keys': ['rsa-sha2-256', 'rsa-sha2-512']} in either SSHClient or Transport.

    Though note that for me, I actually had to specify disabled_algorithms={'pubkeys': ['rsa-sha2-256', 'rsa-sha2-512']}, note the difference keys -> pubkeys.

    So, my issue had nothing to do with AWS Lambda, and @TabsB your issue might not either. I can't say whether your issue is the same as mine, but it seems likely.

    FYI if you want to check the debug logs, you need to do this by configuring the paramiko.transport logger using the Python logging module, e.g. this will cause log messages to be printed to sys.stderr:

    import logging
    
    logging.basicConfig(format="[{levelname}] {message}", style="{")
    logging.getLogger("paramiko.transport").setLevel(logging.DEBUG)

    So @TabsB perhaps you can try the following on line 4 of your code:

        transport = paramiko.Transport((client_auth_data["host"], port), disabled_algorithms={"pubkeys": ["rsa-sha2-256", "rsa-sha2-512"]})

    P.S. Thanks paramiko team for the amazingly helpful and detailed documentation <3

  6. TabsB commented on Oct 30, 2023

    @TabsB
    Author

    Thanks @Tobotimus for the tips, I will try to use the paramiko debug logs. I think you might be right about the server not supporting the authentication, but I'll dig into that using the debug logs. I did have another sftp server these past days, for which the authentication with public/private key worked smoothly. So, you might be right about the whole thing ;)

  7. babaMar commented on Dec 8, 2023

    @babaMar

    Experiencing something similar:

    [2023-12-08, 12:49:01 UTC] {transport.py:1893} DEBUG - starting thread (client mode): 0x15644cd0
    [2023-12-08, 12:49:01 UTC] {transport.py:1893} DEBUG - Local version/idstring: SSH-2.0-paramiko_3.3.1
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - Remote version/idstring: SSH-2.0-mod_sftp
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} INFO - Connected (version 2.0, client mod_sftp)
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - === Key exchange possibilities ===
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - kex algos: [email protected], ecdh-sha2-nistp521, ecdh-sha2-nistp384, ecdh-sha2-nistp256, diffie-hellman-group-exchange-sha256
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - server key: ecdsa-sha2-nistp256, ssh-rsa
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - client encrypt: aes256-ctr, aes192-ctr, aes128-ctr
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - server encrypt: aes256-ctr, aes192-ctr, aes128-ctr
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - client mac: hmac-sha2-256, hmac-sha2-512
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - server mac: hmac-sha2-256, hmac-sha2-512
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - client compress: [email protected], zlib, none
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - server compress: [email protected], zlib, none
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - client lang: <none>
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - server lang: <none>
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - kex follows: False
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - === Key exchange agreements ===
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - Kex: [email protected]
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - HostKey: ecdsa-sha2-nistp256
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - Cipher: aes128-ctr
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - MAC: hmac-sha2-256
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - Compression: none
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - === End of kex handshake ===
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - kex engine KexCurve25519 specified hash_algo <built-in function openssl_sha256>
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - Switch to new keys ...
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - Trying SSH key b'348f3627d8ef87349ace2ba94df42fff'
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - userauth is OK
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - Finalizing pubkey algorithm for key of type 'ssh-rsa'
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - Our pubkey algorithm list: ['rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa']
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - Server did not send a server-sig-algs list; defaulting to our first preferred algo ('rsa-sha2-512')
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} DEBUG - NOTE: you may use the 'disabled_algorithms' SSHClient/Transport init kwarg to disable that or other algorithms if your server does not support them!
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} INFO - Auth banner: b'\r\n\tCisco Systems File Transfer Service.\r\n\r\n  \t\t\t\t\t |        |      Cisco Systems, Inc.\r\n\t\t\t\t\t|||      |||     170 West Tasman Drive\r\n\tPhone: +1.800.553.2447\t     .:|||||:..:|||||:.  San Jose, CA 95134\r\n\r\n\tLocal time is Fri Dec 08 04:49:02 2023.\r\n\r\n\r\n\r\n\tThis system hosts the sftp.cisco.com domain:\r\n\r\n\tsftp.cisco.com domain host the SFTP(SSH File Transfer Protocol) service.\r\n\r\n\tPlease read the following instructions before proceeding.\r\n\r\n\t\t\t1.\tPORT = "22" (port 22 is the SFTP server\'s port.  If you do not specify port 22, the SFTP client/cli may default use port 22.\r\n\t\t\t2.\tPROTOCOL = "SFTP".\r\n\t\t\t3.\tENCRYPTION = "By default encrypted over SSH".\r\n\t\t\t4.\tLOGON TYPE = "Normal" (use normal if you will logon using your cisco.com credentials) OR "Key File"(use keyfile if you want to connect to SFTP server using your public\r\n\t\t\t\tkey without user/password method).\r\n\t\t\t5.\tAnonymous access is blocked due to security reasons.\r\n\r\n\t=======> SFTP.CISCO.COM <========\r\n\r\n\tPublicly distributed software is available on ftp.cisco.com in the /pub directory.\r\n\tAll the other software is available in the Download area on www.cisco.com.\r\n\r\n\tBy downloading Cisco Software using this system you agree to the following:\r\n\r\n\t\t- Cisco products, technology and services are subject to U.S. and local export control laws and regulations.\r\n\r\n\t\t- Customer shall comply with such laws and regulations governing use, export, re-export, and transfer of products, technology and services and will obtain all required U.S. and local aut\t\t    horizations, permits, or licenses.\r\n\r\n\t\t- Customer certifies that they are not on the U.S. Department of Commerce Denied Persons List or affiliated lists, on the U.S. Department of Treasury Specially Designated Nationals List \t\t    or on any U.S. Government export exclusion lists.\r\n\r\n\t\t- The export obligations under this clause shall survive the expiration or termination of this Agreement.\r\n\r\n\t\t- You are bound by the Cisco End User License Agreement ("EULA ") posted at\r\n\t\t  http://cisco.com/go/eula regarding the use of any software you download from this site.\r\n\t\t\t\r\n\t\t- If you are a Cisco customer and encounter any problems using this site, please contact your local Technical Assistance Center (TAC).\r\n\r\n\t\t- If you are a Cisco employee and encounter problems using this site, open a Remedy case using the "FTS Platform (FTP)" link in the "Business Services" section.\r\n\r\n\t\t\t*******FTS team reachable at [email protected]**********\r\n'
    [2023-12-08, 12:49:02 UTC] {transport.py:1893} INFO - Authentication (publickey) failed.
    [2023-12-08, 12:49:02 UTC] {taskinstance.py:1937} ERROR - Task failed with exception
    Traceback (most recent call last):
      File "/usr/local/airflow/plugins/sftp/operator/lp_s3_to_sftp_operator.py", line 74, in execute
        sftp_client = ssh_hook.get_conn().open_sftp()
      File "/usr/local/lib/python3.10/site-packages/airflow/providers/ssh/hooks/ssh.py", line 346, in get_conn
        for attempt in Retrying(
      File "/usr/local/lib/python3.10/site-packages/tenacity/__init__.py", line 347, in __iter__
        do = self.iter(retry_state=retry_state)
      File "/usr/local/lib/python3.10/site-packages/tenacity/__init__.py", line 325, in iter
        raise retry_exc.reraise()
      File "/usr/local/lib/python3.10/site-packages/tenacity/__init__.py", line 158, in reraise
        raise self.last_attempt.result()
      File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 451, in result
        return self.__get_result()
      File "/usr/local/lib/python3.10/concurrent/futures/_base.py", line 403, in __get_result
        raise self._exception
      File "/usr/local/lib/python3.10/site-packages/airflow/providers/ssh/hooks/ssh.py", line 353, in get_conn
        client.connect(**connect_kwargs)
      File "/usr/local/lib/python3.10/site-packages/paramiko/client.py", line 485, in connect
        self._auth(
      File "/usr/local/lib/python3.10/site-packages/paramiko/client.py", line 818, in _auth
        raise saved_exception
      File "/usr/local/lib/python3.10/site-packages/paramiko/client.py", line 716, in _auth
        self._transport.auth_publickey(username, pkey)
      File "/usr/local/lib/python3.10/site-packages/paramiko/transport.py", line 1658, in auth_publickey
        return self.auth_handler.wait_for_response(my_event)
      File "/usr/local/lib/python3.10/site-packages/paramiko/auth_handler.py", line 263, in wait_for_response
        raise e
    paramiko.ssh_exception.AuthenticationException: Authentication failed.
    
  8. babaMar commented on Dec 8, 2023

    @babaMar

    With the same code and paramiko==2.8.1 I have no problems..

    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - starting thread (client mode): 0x263a8e50
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - Local version/idstring: SSH-2.0-paramiko_2.8.1
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - Remote version/idstring: SSH-2.0-mod_sftp
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} INFO - Connected (version 2.0, client mod_sftp)
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - kex algos:['[email protected]', 'ecdh-sha2-nistp521', 'ecdh-sha2-nistp384', 'ecdh-sha2-nistp256', 'diffie-hellman-group-exchange-sha256'] server key:['ecdsa-sha2-nistp256', 'ssh-rsa'] client encrypt:['aes256-ctr', 'aes192-ctr', 'aes128-ctr'] server encrypt:['aes256-ctr', 'aes192-ctr', 'aes128-ctr'] client mac:['hmac-sha2-256', 'hmac-sha2-512'] server mac:['hmac-sha2-256', 'hmac-sha2-512'] client compress:['[email protected]', 'zlib', 'none'] server compress:['[email protected]', 'zlib', 'none'] client lang:[''] server lang:[''] kex follows?False
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - Kex agreed: [email protected]
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - HostKey agreed: ecdsa-sha2-nistp256
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - Cipher agreed: aes128-ctr
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - MAC agreed: hmac-sha2-256
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - Compression agreed: none
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - kex engine KexCurve25519 specified hash_algo <built-in function openssl_sha256>
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - Switch to new keys ...
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - Adding ecdsa-sha2-nistp256 host key for sftp.cisco.com: b'2c1ab74fa975ab38000976d6649fe3bc'
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - Trying SSH key b'348f3627d8ef87349ace2ba94df42fff'
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - userauth is OK
    [2023-12-08, 13:30:24 UTC] {transport.py:1819} INFO - Auth banner: b'\r\n\tCisco Systems File Transfer Service.\r\n\r\n  \t\t\t\t\t |        |      Cisco Systems, Inc.\r\n\t\t\t\t\t|||      |||     170 West Tasman Drive\r\n\tPhone: +1.800.553.2447\t     .:|||||:..:|||||:.  San Jose, CA 95134\r\n\r\n\tLocal time is Fri Dec 08 05:30:23 2023.\r\n\r\n\r\n\r\n\tThis system hosts the sftp.cisco.com domain:\r\n\r\n\tsftp.cisco.com domain host the SFTP(SSH File Transfer Protocol) service.\r\n\r\n\tPlease read the following instructions before proceeding.\r\n\r\n\t\t\t1.\tPORT = "22" (port 22 is the SFTP server\'s port.  If you do not specify port 22, the SFTP client/cli may default use port 22.\r\n\t\t\t2.\tPROTOCOL = "SFTP".\r\n\t\t\t3.\tENCRYPTION = "By default encrypted over SSH".\r\n\t\t\t4.\tLOGON TYPE = "Normal" (use normal if you will logon using your cisco.com credentials) OR "Key File"(use keyfile if you want to connect to SFTP server using your public\r\n\t\t\t\tkey without user/password method).\r\n\t\t\t5.\tAnonymous access is blocked due to security reasons.\r\n\r\n\t=======> SFTP.CISCO.COM <========\r\n\r\n\tPublicly distributed software is available on ftp.cisco.com in the /pub directory.\r\n\tAll the other software is available in the Download area on www.cisco.com.\r\n\r\n\tBy downloading Cisco Software using this system you agree to the following:\r\n\r\n\t\t- Cisco products, technology and services are subject to U.S. and local export control laws and regulations.\r\n\r\n\t\t- Customer shall comply with such laws and regulations governing use, export, re-export, and transfer of products, technology and services and will obtain all required U.S. and local aut\t\t    horizations, permits, or licenses.\r\n\r\n\t\t- Customer certifies that they are not on the U.S. Department of Commerce Denied Persons List or affiliated lists, on the U.S. Department of Treasury Specially Designated Nationals List \t\t    or on any U.S. Government export exclusion lists.\r\n\r\n\t\t- The export obligations under this clause shall survive the expiration or termination of this Agreement.\r\n\r\n\t\t- You are bound by the Cisco End User License Agreement ("EULA ") posted at\r\n\t\t  http://cisco.com/go/eula regarding the use of any software you download from this site.\r\n\t\t\t\r\n\t\t- If you are a Cisco customer and encounter any problems using this site, please contact your local Technical Assistance Center (TAC).\r\n\r\n\t\t- If you are a Cisco employee and encounter problems using this site, open a Remedy case using the "FTS Platform (FTP)" link in the "Business Services" section.\r\n\r\n\t\t\t*******FTS team reachable at [email protected]**********\r\n'
    [2023-12-08, 13:30:24 UTC] {transport.py:1819} INFO - Authentication (publickey) successful!
    
  9. babaMar commented on Dec 8, 2023

    @babaMar

    Looks like this specific line is missing from the logs when it fails:
    [2023-12-08, 13:30:23 UTC] {transport.py:1819} DEBUG - Adding ecdsa-sha2-nistp256 host key for sftp.cisco.com: b'2c1ab74fa975ab38000976d6649fe3bc'

  10. mnhunter commented on Jul 30, 2024

    @mnhunter

    Worked on netmiko script if added parametr - disabled_algorithms={'pubkeys':['rsa-sha2-256', 'rsa-sha2-512']}
    paramiko ver 3.4.0

    example connToSwitch.py

    _#!/bin/python
    from netmiko import ConnectHandler
    import csv
    import os
    import paramiko
    import keyring

    #from getpass import getpass

    key = paramiko.RSAKey.from_private_key_file(filename="/home/user/.ssh/id_rsa", password="passphrase")
    devices = [
    {
    'device_type': 'eltex',
    'host': 'MySwitch', # in /etc/hosts else then ip-addr
    'username': 'user',
    'ssh_config_file': "~/.ssh/config",
    'pkey': key,
    'disabled_algorithms':{'pubkeys': ['rsa-sha2-256', 'rsa-sha2-512']}
    'port': 22,
    }
    ]

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