Skip to content

Commit

Permalink
Merge pull request #153 from glasserc/log_bad_hostkeys
Browse files Browse the repository at this point in the history
Warn on parse failure when reading known_hosts
  • Loading branch information
bitprophet committed Apr 29, 2013
2 parents a1fa1ba + aee2355 commit 675d79d
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 3 deletions.
2 changes: 2 additions & 0 deletions NEWS
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,8 @@ v1.11.0 (DD MM YYYY)
v1.10.2 (DD MM 2013)
--------------------

* #153, #67: Warn on parse failure when reading known_hosts
file. Thanks to `@glasserc` for patch.
* #146: Indentation fixes for readability. Thanks to Abhinav Upadhyay for catch
& patch.

Expand Down
11 changes: 8 additions & 3 deletions paramiko/hostkeys.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
from paramiko.common import *
from paramiko.dsskey import DSSKey
from paramiko.rsakey import RSAKey
from paramiko.util import get_logger


class InvalidHostKey(Exception):
Expand All @@ -48,7 +49,7 @@ def __init__(self, hostnames=None, key=None):
self.hostnames = hostnames
self.key = key

def from_line(cls, line):
def from_line(cls, line, lineno=None):
"""
Parses the given line of text to find the names for the host,
the type of key, and the key data. The line is expected to be in the
Expand All @@ -61,9 +62,12 @@ def from_line(cls, line):
@param line: a line from an OpenSSH known_hosts file
@type line: str
"""
log = get_logger('paramiko.hostkeys')
fields = line.split(' ')
if len(fields) < 3:
# Bad number of fields
log.warn("Not enough fields found in known_hosts in line %s (%r)" %
(lineno, line))
return None
fields = fields[:3]

Expand All @@ -78,6 +82,7 @@ def from_line(cls, line):
elif keytype == 'ssh-dss':
key = DSSKey(data=base64.decodestring(key))
else:
log.warn("Unable to handle key of type %s" % (keytype,))
return None
except binascii.Error, e:
raise InvalidHostKey(line, e)
Expand Down Expand Up @@ -160,11 +165,11 @@ def load(self, filename):
@raise IOError: if there was an error reading the file
"""
f = open(filename, 'r')
for line in f:
for lineno, line in enumerate(f):
line = line.strip()
if (len(line) == 0) or (line[0] == '#'):
continue
e = HostKeyEntry.from_line(line)
e = HostKeyEntry.from_line(line, lineno)
if e is not None:
_hostnames = e.hostnames
for h in _hostnames:
Expand Down

0 comments on commit 675d79d

Please sign in to comment.