Skip to content

[BUG] - Issue with auth to a specific device using auth_strategy #2294

Open

Description

@avatarofhope2

Are you using paramiko as a client or server?

Client

What feature(s) aren't working right?

SSH, Keys/auth

What version(s) of paramiko are you using?

3.3.1

What version(s) of Python are you using?

3.9.6

What operating system and version are you using?

CentOS Linux release 7.2.1511 (Core)

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

Vecima Entra Access Controller

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

No response

Expected/desired behavior

I have implemented an auth strategy which uses the following as the first source, and uses plain old Password as the second source.

This appeared to test well for all platforms I use, but later I encountered an Entra Access Controller (in this case the ssh server), which used to work, but no longer does with the auth strategy. My expectation is that if the transport.auth_none(self.username) fails with "Bad authentication type; allowed types: ['publickey', 'password']", that it can continue on to try the next auth source, for Password.

Actual behavior

What instead happens, but only for this device, is that after AdvaAuth fails, Password authentication fails with "Authentication failed: transport shut down or saw EOF". If the auth strategy includes ONLY the Password source, it succeeds.

It kind of seems like the auth strategy is not properly handling the BadAuthenticationType, and/or isn't resetting or clearing state properly to prepare for further attempts.

How to reproduce

Here is the auth source I use first:

class AdvaAuth(Password):
    def __init__(self, username, password_getter, device):
        super().__init__(username, password_getter)
        self.device = device

    def authenticate(self, transport):
        next_auth_types = transport.auth_none(self.username)
        # should raise an exception for all non-Adva devices
        # do some extra stuff, if is succeeds
        return next_auth_types

Where device is an instance of a class which provides a unique interface for our framework, and holds the channel created here for later use.

Anything else?

Unfortunately, I think it may be possible that this device merely ends the connection after the first failed auth source, and I haven't been able to determine if this is a configuration related issue. My hope is to try to fill in the gaps.

Maybe this is caused because none isn't part of the "Authentications that can continue:"? if so it is maybe strange that this is the only platform with this issue. is there a way to have the auth strategy filter out methods that aren't allowed? I would know how to code it in the AuthStrategy, but I'm not sure how to fetch that list in paramiko from the get_sources method. can I get it from the transport?

edit: I found this link which shows how I might fetch that list, but... it involves running auth_none first, so that would defeat the purpose, if that is what is causing the connection to be terminated. (https://stackoverflow.com/questions/1253870/get-allowed-auths-in-paramiko-for-authentication-types)

I read that the openssh client always tries none auth first. If true, my hope would be to utilize that, but maybe I'm misunderstanding.

I appreciate your time and hope I've done my due diligence to your expectations.

here is the ssh -v output for the device.

OpenSSH_7.4p1, OpenSSL 1.0.2k-fips  26 Jan 2017
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 58: Applying options for *
debug1: Connecting to test_host [<ip>] port 22.
debug1: Connection established.
debug1: identity file /home/test_user_/.ssh/id_rsa type 1
debug1: key_load_public: No such file or directory
debug1: identity file /home/test_user_/.ssh/id_rsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/test_user_/.ssh/id_dsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/test_user_/.ssh/id_dsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/test_user_/.ssh/id_ecdsa type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/test_user_/.ssh/id_ecdsa-cert type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/test_user_/.ssh/id_ed25519 type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/test_user_/.ssh/id_ed25519-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4
debug1: Remote protocol version 2.0, remote software version NCS-4.7.7.4
debug1: no match: NCS-4.7.7.4
debug1: Authenticating to test_host:22 as 'test_user'
debug1: SSH2_MSG_KEXINIT sent
debug1: SSH2_MSG_KEXINIT received
debug1: kex: algorithm: diffie-hellman-group-exchange-sha256
debug1: kex: host key algorithm: ssh-rsa
debug1: kex: server->client cipher: aes128-ctr MAC: hmac-sha2-256 compression: none
debug1: kex: client->server cipher: aes128-ctr MAC: hmac-sha2-256 compression: none
debug1: kex: diffie-hellman-group-exchange-sha256 need=32 dh_need=32
debug1: kex: diffie-hellman-group-exchange-sha256 need=32 dh_need=32
debug1: SSH2_MSG_KEX_DH_GEX_REQUEST(1024<8192<8192) sent
debug1: got SSH2_MSG_KEX_DH_GEX_GROUP
debug1: SSH2_MSG_KEX_DH_GEX_INIT sent
debug1: got SSH2_MSG_KEX_DH_GEX_REPLY
debug1: Server host key: ssh-rsa SHA256:p6NcG+zMUSdNwzXFWXxQGcdnI1jAN1gHlQhAEF3KScw
debug1: Host 'test_host' is known and matches the RSA host key.
debug1: Found key in /home/test_user_/.ssh/known_hosts:27
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug1: SSH2_MSG_NEWKEYS received
debug1: rekey after 4294967296 blocks
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug1: Authentications that can continue: publickey,password
debug1: Next authentication method: publickey
debug1: Offering RSA public key: /home/test_user_/.ssh/id_rsa
debug1: Server accepts key: pkalg ssh-rsa blen 535
debug1: Authentications that can continue: publickey,password
debug1: Trying private key: /home/test_user_/.ssh/id_dsa
debug1: Trying private key: /home/test_user_/.ssh/id_ecdsa
debug1: Trying private key: /home/test_user_/.ssh/id_ed25519
debug1: Next authentication method: password
test_user@test_host's password: 
debug1: Authentication succeeded (password).
Authenticated to test_host ([<ip>]:22).
debug1: channel 0: new [client-session]
debug1: Entering interactive session.
debug1: pledge: network
debug1: Sending environment.
debug1: Sending env LANG = en_US.UTF-8

Activity

  1. bskinn commented on Sep 27, 2023

    @bskinn
    Contributor

    Yes, this is a great ticket, thanks for all the detail, @avatarofhope2!

    Switching the label here to Support since it appears to be particular to the hardware.

    Calling out this question in particular; @jun66j5, do you know?

    is there a way to have the auth strategy filter out methods that aren't allowed? I would know how to code it in the AuthStrategy, but I'm not sure how to fetch that list in paramiko from the get_sources method. can I get it from the transport?

  2. jun66j5 commented on Sep 30, 2023

    @jun66j5
    Contributor

    I read that the openssh client always tries none auth first. If true, my hope would be to utilize that, but maybe I'm misunderstanding.

    That's right. The openssh client tries only allowed authentication requests after none authentication request. Sadly, paramiko doesn't send the none authentication request. OpenSSHAuthStrategy in fabric doesn't send also. See
    https://github.com/fabric/fabric/blob/3.2.2/fabric/auth.py#L184-L188 .

    I tried to implement it to respect allowed authentication requests.

    Try to save the following script as paramiko-client.py and run python paramiko-client.py HOSTNAME USERNAME PASSWORD.

    import os
    import sys
    
    import paramiko
    from paramiko import DSSKey, RSAKey, ECDSAKey, Ed25519Key
    from paramiko.auth_strategy import (
        AuthStrategy, InMemoryPrivateKey, OnDiskPrivateKey, NoneAuth, Password,
    )
    from paramiko.agent import Agent
    
    class Baton(object):
    
        allowed_types = ()
        hostname = None
        username = None
        password = None
    
    class CustomNoneAuth(NoneAuth):
    
        def __init__(self, username, baton):
            super().__init__(username)
            self.baton = baton
    
        def authenticate(self, transport):
            try:
                return super().authenticate(transport)
            except paramiko.BadAuthenticationType as e:
                self.baton.allowed_types = e.allowed_types
                raise
    
    class CustomAuthStrategy(AuthStrategy):
    
        def __init__(self, baton, ssh_config):
            self.baton = baton
            super().__init__(ssh_config)
    
        def get_sources(self):
            baton = self.baton
            yield CustomNoneAuth(baton.username, baton)
            for type_ in baton.allowed_types:
                if type_ == 'publickey':
                    yield from self._agent_keys()
                    yield from self._home_keys()
                    continue
                if type_ == 'password':
                    yield Password(baton.username, lambda: baton.password)
                    continue
    
        def _agent_keys(self):
            username = self.baton.username
            agent = Agent()
            try:
                for pkey in agent.get_keys():
                    yield InMemoryPrivateKey(username, pkey)
            finally:
                agent.close()
    
        def _home_keys(self):
            username = self.baton.username
            dir_ = os.path.expanduser('~/.ssh')
            for klass, filename in (
                (Ed25519Key, 'id_ed25519'),
                (ECDSAKey, 'id_ecdsa'),
                (RSAKey, 'id_rsa'),
                (DSSKey, 'id_dsa'),
            ):
                path = os.path.join(dir_, filename)
                try:
                    pkey = klass.from_private_key_file(path)
                except:
                    continue
                else:
                    yield OnDiskPrivateKey(username, 'implicit-home', path, pkey)
    
    def main():
        baton = Baton()
        baton.hostname, baton.username, baton.password = sys.argv[1:]
        paramiko.util.log_to_file('/dev/stderr')
        config = paramiko.SSHConfig()
        auth_strategy = CustomAuthStrategy(baton, config)
        with paramiko.SSHClient() as cli:
            cli.set_missing_host_key_policy(paramiko.AutoAddPolicy)
            cli.connect(baton.hostname, auth_strategy=auth_strategy)
            print(cli.get_transport())
    
    if __name__ == '__main__':
        main()
  3. somurzakov commented on Oct 5, 2023

    @somurzakov

    thank you @jun66j5 - this is fantastic workaround.

    I had similar issue, but just wanted to auth using None auth strategy.
    if anyone is using HashiCorp Boundary to connect to ssh target with credential injection, you can use this workaround with None auth strategy to connect:

    1. create boundary tunnel: boundary connect -target-id tssh_CavbartZqMNi -listen-port 10000
    2. use this python sample:
    import paramiko
    from paramiko.auth_strategy import NoneAuth
    
    client = paramiko.SSHClient()
    client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
    client.connect('localhost', port=10000, auth_strategy=NoneAuth(''))
    
    stdin, stdout, stderr = client.exec_command("whoami")
    print("".join(stdout.readlines()))
    
  4. jun66j5 commented on Oct 6, 2023

    @jun66j5
    Contributor

    @bskinn I'd suggest closing this support issue because of no response from the issuer.

  5. avatarofhope2 commented on Oct 6, 2023

    @avatarofhope2
    Author

    nothing here that has resolved my issue. just confirmations of what I've already stated. if auth none doesn't succeed, and i can't follow up with anything because of the transport, this doesn't meet my requirements.

  6. OakyNam commented on Jul 13, 2024

    @OakyNam

    any progress being made on this? in my application we have begun using expect as an alternative.

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