Skip to content

Key handling is terribad #387

Open
Open

Description

@bitprophet

There are a number of issues stemming from what feels like a simply too-naïve implementation of key handling in SSHClient and PKey.

I am making a single ticket for this because most of the existing PRs poking at it are too limited in scope; this sort of change has a high chance for bugs and breaking backwards compatibility (intentionally or no) and I feel it needs a broadly considered update.

[EDIT: See this comment for an update on the intent/scope of this issue!]


The high level details:

  • First off, SSHClient._auth uses a multi-exit strategy combined with storing a single exception to raise at the end of the process. This frequently means the raised exception at auth time is flat out incorrect as to the true cause of the inability to authenticate.
    • For example, early on it attempts to check over all explicitly given key_filename values...and since it can't reliably know offhand which key types they are, it tries all known key types. In order. This will always generate/store errors unless one happens to have only one key and it's of the arbitrarily-first-in-the-list key type.
    • Thus even if all keys given were valid keys of their intended type, and they also all happened to be invalid from the target server's perspective (i.e. the user doesn't actually have an accepted key) we raise to them a nice helpful "Hey your key is fucked up" error instead of "None of your keys were accepted by the server".
  • Furthermore, PKey._read_private_key - used frequently within the above, indirectly - is similarly messy, and many, many types of key loading/reading problems end up raising an error about how Private key file is encrypted - on unencrypted files.
    • Why? Simply because the logic assumes if it gets to the end of the function, and the password kwarg is blank, that a password was required and not given.
    • While I haven't debugged this as deeply as I'd like yet, it comes up frequently when trying to deal with ECDSA keys, and/or when lower level key handling (or key related crap in the test suite) is presently botched.

A number of tickets have sprung up on this, I'm sure I haven't gotten all of them, but they include #358 and #224.

Strongly related are a bevvy of tickets concerned with exception handling & exception types/subclasses, such as Fabric #85 and our own #351 and #293.

Activity

  1. bitprophet commented on Sep 6, 2014

    @bitprophet
    MemberAuthor

    Another good example of this hilarity is a recent test I added that attempts to prove a negative case of multiple key handling; when the test server is configured to only accept ECDSA, and only an RSA key is given to connect(), it (on my Mac localhost) raises a PasswordRequiredException (odd, but a known thing). So far so good, self.testRaises(PasswordRequiredException, ...), done. Right?

    Except on Travis-CI's VMs, it raises SSHException straight up, which fails the test. And on a random Ubuntu 13.10 VM I had lying around, the same test raises AuthenticationException! This sort of system-sensitive bullshit is probably one reason why we get so many related looking but different-traceback reports :(

  2. bitprophet commented on Sep 10, 2014

    @bitprophet
    MemberAuthor

    I started prep work for this while dealing with #243, insofar as I added a bunch more log output (DEBUG) to _auth so at least it's easier to trace how a given auth process worked, what errors got raised where, etc.

    I also started factoring out some common patterns (nearly every step has the same try/except, auth, check for two-factor, return-or-keep-going, process) though sadly the heavy reliance on variables "falling through" requires some real dumb argument passing & return value stuff. Should hopefully still be worthwhile when done.

    However this is turning into a morass so I am punting for now. Left the work in a branch named for #243.

  3. Russell-Jones commented on May 9, 2015

    @Russell-Jones

    One approach to starting to debug it:

    1. change saved_exceptions to an array, i.e.
    saved_exceptions = []
    ...
    saved_exceptions.append(e)
    
    1. Do something like this so you get tracebacks for all exceptions.

    2. replace "except Exception" with lists of explicit exception types (maybe by concatenating lists of common ones)

    Any thoughts before I give this a go?

  4. Russell-Jones commented on May 9, 2015

    @Russell-Jones

    So something like this

    import traceback
    import sys
    
    saved_exceptions = []
    
    for c in "hello":
        try:
            int(c) # obviously fails
        except ValueError: 
            saved_exceptions.append(sys.exc_info())
    
    if saved_exceptions is not None:
       raise Exception("\n\n".join(
              ''.join(traceback.format_exception(t, e, tb))
              for t, e, tb in saved_exceptions) )
    

    I'd use SSHException instead of Exception.

  5. added this to the 2.0 milestone on Nov 2, 2015
  6. redbearder commented on Nov 19, 2015

    @redbearder

    I face this issue yesterday and find a workaround solution with another script
    expect -c "set timeout -1;
    spawn -noecho ssh -o StrictHostKeyChecking=no $2 ${@:3} exit;
    expect assword:;
    send -- $1\r;
    interact;";
    the parameter StrictHostKeyChecking=no is the key arg

    hope author can combine this solution to paramiko new release

    thx

  7. 48 remaining items

  8. bitprophet commented on Apr 3, 2023

    @bitprophet
    MemberAuthor

    @anarcat Yea, that sort of added visibility is absolutely going to be part of the new exception type/s I'm envisioning.

    Still figuring out the details, but at the absolute worst, a caller would be trivially able to get the list of key paths attempted (and how each failed), from introspecting the top level exception in a try/except block.

    And offhand I assume the cleanest way to do it is to implement a variant on your PR, that raises more-detailed subclass exceptions which the top-level/aggregate one literally just sticks in a list. This way, lower-level users of Paramiko still benefit, and the higher-level code there or in Fabric doesn't have to do as much work either. 🤔

  9. anarcat commented on Apr 3, 2023

    @anarcat
  10. radssh commented on Apr 3, 2023

    @radssh
    Contributor

    @bitprophet -

    I have been tinkering with the concept of wrapping the entire authentication process within a separate class, primarily driven by a SSHConfig object, which should a) avoid a bunch of the **kwargs and b) keep things friendly for embedding configs in ~/.ssh/config-like style. Keeping a default IdentityFile value like OpenSSH and support for IdentitiesOnly gives the level of control that OpenSSH provides, with least surprise in behavior.

    There are also some conditional handling things, like shifting to rsa-sha2-256/512 instead of ssh-rsa when client and server support/prefer/require. Again, the leveraging of SSHConfig helps a great deal with the client-side configuration for this. I did have to retain some session info in the Transport to pull this off, specifically capturing the server-sig-algs message that may be passed during the connection setup.

    That being said, I've only focused on the client side of things for authentication (and key handling), the server side I have had the luxury of ignoring for my needs.

  11. bitprophet commented on Apr 3, 2023

    @bitprophet
    MemberAuthor

    There are also some conditional handling things, like shifting to rsa-sha2-256/512 instead of ssh-rsa when client and server support/prefer/require

    Weird, how recent is the branch you're working off for this? As of a few revisions ago we should be dealing with server-sig-algs mostly-correctly & in fact most users that run into SHA2 issues are the ones who have to disable it when their targets aren't correctly indicating the lack.

    the server side I have had the luxury of ignoring for my needs.

    Honestly, same for now. I do want the server to get more compatible sometime too, but it's always a vanishingly smaller userbase vs client so difficult to justify the time until it becomes a self-itch-scratch (eg if/when I need the test harness server to act more OpenSSH-like...).


    I'm still kicking this around but I am continuing to think that doing this at the Fabric level makes the most sense. Fabric already autoloads ssh_config, for example, so it just needs additional tweaks to be more OpenSSH-compatible. Doing it there also makes ignoring the server side slightly more understandable as Fabric has no server component 😇

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

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions