Skip to content

Poor performance loading known hosts #437

Open

Description

@candlerb

Platform: OSX 10.9.5, Macbook Air 2011 (dual-core i7 1.8GHz), python 2.7.8 from homebrew, paramiko (1.15.1) from pip install.

Summary: it takes over 20 seconds just to read my known_hosts file, which has 1158 entries of which 556 are hashed. This causes applications like ansible to appear to hang

Brians-MacBook-Air:~ $ wc -l .ssh/known_hosts
    1158 .ssh/known_hosts
Brians-MacBook-Air:~ $ grep '^|1|' .ssh/known_hosts | wc -l
     556
Brians-MacBook-Air:~ $ python
Python 2.7.8 (default, Oct 19 2014, 16:03:53)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.51)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import sys
>>> import time
>>> from paramiko.hostkeys import HostKeys
>>> sys.version
'2.7.8 (default, Oct 19 2014, 16:03:53) \n[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.51)]'
>>> t1 = time.time(); hk = HostKeys("/Users/brian/.ssh/known_hosts"); t2 = time.time()
>>> t2 - t1
23.82344102859497
>>>

Putting this in a script and running with -m cProfile -s tottime:

$ python -m cProfile -s tottime testkeys.py
41.5394990444
         72687186 function calls (72687138 primitive calls) in 41.726 seconds

   Ordered by: internal time

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
   398944   12.977    0.000   17.103    0.000 util.py:315(constant_time_bytes_eq)
   398944    4.441    0.000   21.948    0.000 hostkeys.py:258(hash_host)
 47877081    3.949    0.000    3.949    0.000 {ord}
   398944    2.993    0.000    5.586    0.000 hmac.py:30(__init__)
   797888    2.063    0.000    3.809    0.000 base64.py:310(encodestring)
     1296    1.531    0.001   41.216    0.032 hostkeys.py:127(lookup)
  1595776    1.459    0.000    1.459    0.000 {method 'update' of '_hashlib.HASH' objects}
   799038    1.079    0.000    1.079    0.000 {_codecs.utf_8_decode}
   799038    0.928    0.000    2.476    0.000 {method 'decode' of 'str' objects}
   797888    0.788    0.000    0.788    0.000 {binascii.b2a_base64}
   799038    0.701    0.000    3.349    0.000 py3compat.py:48(u)
  1196833    0.696    0.000    0.696    0.000 {_hashlib.openssl_sha1}
   797888    0.689    0.000    0.689    0.000 {method 'digest' of '_hashlib.HASH' objects}
  1786782    0.644    0.000    0.644    0.000 {method 'startswith' of 'str' objects}
   400094    0.555    0.000    0.555    0.000 {binascii.a2b_base64}
   398944    0.545    0.000    1.457    0.000 hmac.py:100(_current)
   800537    0.522    0.000    0.522    0.000 {range}
3215514/3215506    0.515    0.000    0.515    0.000 {len}
   799038    0.469    0.000    1.548    0.000 utf_8.py:15(decode)
   799046    0.433    0.000    0.599    0.000 py3compat.py:36(b)
   398944    0.404    0.000    2.189    0.000 hmac.py:109(digest)

I am having difficulty understanding why so much work is required when simply reading the known_hosts file.

It's not possible to compare one hashed entry against another hashed entry, so at best you could check a non-hashed entry against all the other hashed entries - but why would you want to do so? I think this only matters when you lookup a hostname, in which case you can compare it against both the hashed and non-hashed entries. And in any case there's no benefit using a constant-time match!

Therefore I would suggest that the merging logic which replaces one key with another should just match on the raw key (hashed or unhashed) rather than calling the expensive 'lookup' function.

Activity

  1. candlerb commented on Nov 14, 2014

    @candlerb
    Author

    Here is a rough patch. It reduces the load time in this case from ~23 seconds to 0.3 seconds. It needs reviewing to check I've understood the required merging logic (i.e. ignore entries where both the hostname and the key are identical; retain entries where either the hostname or the key are different)

    --- paramiko/hostkeys.py.orig   2014-11-06 13:58:33.000000000 +0000
    +++ paramiko/hostkeys.py    2014-11-14 10:10:27.000000000 +0000
    @@ -100,7 +100,9 @@
                     if e is not None:
                         _hostnames = e.hostnames
                         for h in _hostnames:
    -                        if self.check(h, e.key):
    +                        matches = [True for se in self._entries
    +                                   if h in se.hostnames and e.key == se.key]
    +                        if matches:
                                 e.hostnames.remove(h)
                         if len(e.hostnames):
                             self._entries.append(e)
    

    Note: this is still an O(n2) algorithm. It could probably be faster if _entries were a dict or OrderedDict, but that would be a more intrusive change.

  2. added this to the 1.15.2 et al milestone on Nov 14, 2014
  3. bitprophet commented on Nov 24, 2014

    @bitprophet
    Member

    The offending code seems to have been added in 080bece which was from #87.

    There's actually an open related ticket from the same author (#166) that tries to enforce a "hash all hostnames by default" behavior (which I assume OpenSSH doesn't do, though c36e3d1 implies it does. Hrm.) This might potentially help us move towards a random-access lookup pattern, but also requires solving the "write-out" problem because it would mutate everybody's known_hosts files and that feels real gross.

    That's just me checking up on the background, though - I agree that use of HostKeys.check here looks inappropriate/expensive and also that it'd be rad for us to have a direct lookup approach. I think I'm going to look for other related tickets, read up on the OpenSSH spec for known_hosts files, and try overhauling this a bit more if nobody else already has. (This is in part because I don't know for sure if your suggested "are these two things the same host entry?" logic is in fact 100% correct, so I want to find out.)

  4. bitprophet commented on Nov 24, 2014

    @bitprophet
    Member

    #435 is another ticket which really wants a cleaner separation of in-memory storage and file writeback data.

  5. candlerb commented on Nov 24, 2014

    @candlerb
    Author

    Regarding OpenSSH default behaviour:

    The vendor default is not to hash known_hosts (and I confirm for example that CentOS doesn't). But of course Debian Knowns Better [TM].

    The Debian wheezy ssh_config(5) manpage says:

         Note that the Debian openssh-client package sets several options as stan‐
         dard in /etc/ssh/ssh_config which are not the default in ssh(1):
    
               ·   SendEnv LANG LC_*
               ·   HashKnownHosts yes
               ·   GSSAPIAuthentication yes
    
  6. bitprophet commented on Nov 25, 2014

    @bitprophet
    Member

    After reading the sshd manpage section (specifically SSH_KNOWN_HOSTS FILE FORMAT):

    • Yes, the default is to not hash hostnames. Whee.
    • Lines technically consist of optional markers, hostname/pattern, bits (key), key-related metadata (exponent, modulus), and a final comment field.
      • However it goes on to say that RSA keys pull their exponent and modulus from the key itself, and this matches the live known_hosts files I've seen which always look like <hostname> <key type, eg 'ssh-rsa'> <key bits> <comment>.
      • Paramiko has never supported the explicit expontent/modulus fields, nor have I heard much clamor asking for them, so we'll continue ignoring them for now.
    • Lines may have >1 host pattern on them (i.e. aliasing the key on that line to >1 potential lookup match) split by commas.
      • Paramiko supports the comma splitting, it's what ends up in HostKey.hostnames.
      • However I don't see the code supporting any of the pattern stuff at this point in time. Would be nice to add at some point if anybody asks, so probably a good idea to leave a hook in.
    • There may be >1 line in a file with the same exact hostname/pattern field but differing key data (e.g. two entries for foo with different keys), in which case any successful match is considered 'good'.
  7. bitprophet commented on Nov 25, 2014

    @bitprophet
    Member

    The above suggests the following to me offhand:

    • Minimum-effort way to support constant time lookup is to use something like AliasDict with the existing support for comma-split hostname fields, and use that structure as a reference.
      • Main wrinkle is how to support writing the file back out in as unchanged a manner as possible. Requires more thought.
      • Suspect just keeping a separate line-entry-based structure that is only updated on load and save (and which has a well defined transition into the dict format on load) might be best.
      • Also not a terrible thing for us to do some mutation as long as it's "nice" (e.g. if we ended up collapsing aliases into single entries, it's still valid and probably wouldn't make anybody too angry?)
    • Since supporting server host key lookup fails if a server has multiple keys #138 would be nice, could simply have the values be iterables of keys.
    • Supporting pattern matching eventually, would be more complex, but theoretically no more complex than the very similar code over in the ssh_config handling module. As above, though, I think this can be punted on since I never see anybody using it.
  8. candlerb commented on Nov 25, 2014

    @candlerb
    Author

    8 entries (out of 1159) in my known_hosts file have explicit key-length and modulus, which paramiko ignores: e.g.

    |1|zI2VuNxyeFCAbrUA9lYCMOoG4Cw=|VmF9aZYBs3P4CqISBNLq0L3RRrY= 1024 35 160466827611973637632025731570155272213198006712606173732650051767043998749523599128191419105052967810888240810575827035714773293163926255923350058778229984473532660980168422909846988151318070216960638018439232142397454614522837722125493540859271211459549452563832071508532523834857264020888602781004904770031
    

    I imagine this may date from hosts using RSA1 keys? (Since the hostname is annoyingly hashed, I can't be sure)

    It doesn't worry me that paramiko doesn't support this, but I thought you might like an example.

  9. bitprophet commented on Nov 25, 2014

    @bitprophet
    Member

    Yea, the current code wouldn't outright break just by loading those, but if you tried actually talking to those hosts I expect it would not function.

  10. modified the milestones: 2.0, 1.15.2 et al on Nov 26, 2014
  11. modified the milestones: 2.0, on Apr 24, 2016
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