/usr/bin/sshfp is in hash-slinger 2.7-1.
This file is owned by root:root, with mode 0o755.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 | #!/usr/bin/python
#
# Generate SSHFP DNS records (RFC4255) from knownhosts files or ssh-keyscan
#
# Copyright 2010 by Xelerance http://www.xelerance.com/ (Paul Wouters)
# Copyright 2012 Paul Wouters <pwouters@redhat.com>
# Copyright 2014 Gerald Turner <gturner@unzane.com>
# Copyright 2015 Jean-Michel Nirgal Vourgere <jmv_deb@nirgal.com>
# Copyright 2015 Dirk Stoecker <github@dstoecker.de>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
VERSION = "2.7"
import os
import sys
import subprocess
import optparse
import base64
import time
import hashlib
import hmac
import re
# www.dnspython.org
try:
import dns.resolver
import dns.query
import dns.zone
except ImportError:
print >> sys.stderr, "sshfp requires the python-dns package from http://www.pythondns.org/"
print >> sys.stderr, "Fedora: yum install python-dns"
print >> sys.stderr, "Debian: apt-get install python-dnspython (NOT python-dns!)"
print >> sys.stderr, "openSUSE: zypper in python-dnspython"
sys.exit(1)
global all_hosts
global khfile
global hostnames
global trailing
global quiet
global port
global timeout
global algo
DEFAULT_KNOWN_HOSTS_FILE = "~/.ssh/known_hosts"
def show_version():
print >> sys.stderr, "sshfp version: " + VERSION
def create_sshfp(hostname, keytype, keyblob, digesttype):
"""Creates an SSH fingerprint"""
if keytype == "ssh-rsa":
keytype = "1"
elif keytype == "ssh-dss":
keytype = "2"
elif "ecdsa" in keytype:
keytype = "3"
elif keytype == "ssh-ed25519":
# TBD http://tools.ietf.org/html/draft-moonesamy-sshfp-ed25519-01
keytype = "4"
else:
return ""
if digesttype == "sha1":
digest = hashlib.sha1
digesttype = "1"
elif digesttype == "sha256":
digest = hashlib.sha256
digesttype = "2"
else:
return ""
try:
rawkey = base64.b64decode(keyblob)
except TypeError:
print >> sys.stderr, "FAILED on hostname "+hostname+" with keyblob "+keyblob
return "ERROR"
fp = digest(rawkey).hexdigest().upper()
# check for Reverse entries
reverse = 1
parts = hostname.split(".", 3)
if parts[0] != hostname:
for octet in parts:
if not octet.isdigit():
reverse = 0
if reverse:
hostname = parts[3] + "." + parts[2] + "." + parts[1] + "." + parts[0] + ".in-addr.arpa."
# we don't know wether we need a trailing dot :(
# eg if someone did "ssh ns.foo" we don't know if this really is "ns.foo." or "ns.foo" plus resolv.conf domainname
if trailing and not reverse:
if hostname[-1:] != ".":
hostname = hostname + "."
return hostname + " IN SSHFP " + keytype + " " + digesttype + " " + fp
def get_known_host_entry(known_hosts, host):
"""Get a single entry out of a known_hosts file
Uses the ssh-keygen utility."""
cmd = ["ssh-keygen", "-f", known_hosts, "-F", host]
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = process.communicate()
if not quiet and stderr:
print >> sys.stderr, stderr
outputl = []
for e in stdout.split("\n"):
if not e.startswith("#"):
outputl.append(e)
return "\n".join(outputl)
def sshfp_from_file(khfile, wantedHosts):
global all_hosts
global algo
# ok, let's do it
known_hosts = os.path.expanduser(khfile)
try:
khfp = open(known_hosts)
except IOError:
print >> sys.stderr, "ERROR: failed to open file "+ known_hosts
sys.exit(1)
hashed_known_hosts = False
if khfp.readline().startswith("|1|"):
hashed_known_hosts = True
khfp.close()
fingerprints = []
if hashed_known_hosts and all_hosts:
print >> sys.stderr, "ERROR: %s is hashed, cannot use with -a" % known_hosts
sys.exit(1)
elif hashed_known_hosts: #only looking for some known hosts
for host in wantedHosts:
fingerprints.append(process_records(get_known_host_entry(known_hosts, host), (host,)))
else:
try:
khfp = open(known_hosts)
except IOError:
print >> sys.stderr, "ERROR: failed to open file "+ known_hosts
sys.exit(1)
data = khfp.read()
khfp.close()
fingerprints.append(process_records(data, wantedHosts))
return "\n".join(fingerprints)
def check_keytype(keytype, hostname):
global algos
for algo in algos:
if algo == "dsa": # different name in user interface and files
algo = "dss"
if algo in keytype:
return True
if not quiet:
print >> sys.stderr, "Could only find key type %s for %s" % (keytype, hostname)
return False
def check_hashed(entry, hostnames):
(hashtype, salt64, hash64) = entry[1:].split("|")
if hashtype == "1":
salt = base64.b64decode(salt64)
hash = base64.b64decode(hash64)
for host in hostnames:
if hash == hmac.new(salt, host, hashlib.sha1).digest():
return host
return ""
def process_records(data, hostnames):
"""Process all records in a string.
If the global "all_hosts" is True, then return SSHFP entries
for all records with the allowed key types.
If "all_hosts is False and hostnames is non-empty, return
only the items in hostnames
"""
global digests
all_records = []
for record in data.split("\n"):
if record.startswith("#") or record.startswith("@") or not record:
continue
try:
# Ignore optionnal 4th column "root@localhost"
(host, keytype, key) = record.split(" ")[:3]
except ValueError:
if not quiet:
print >> sys.stdout, "Print unable to read record '%s'" % record
continue
if "," in host:
host = host.split(",")[0]
elif host[0] == '|':
host = check_hashed(host, hostnames)
if (all_hosts and host) or host in hostnames:
if not check_keytype(keytype, host):
continue
for digesttype in digests:
value = create_sshfp(host, keytype, key, digesttype)
if not value in all_records:
all_records.append(value)
if all_records:
all_records.sort()
return "\n".join(all_records)
else:
return ""
def get_record(domain, qtype):
try:
answers = dns.resolver.query(domain, qtype)
except dns.resolver.NXDOMAIN:
#print "NXdomain: "+domain
return 0
except dns.resolver.NoAnswer:
#print "NoAnswer: "+domain
return 0
for rdata in answers:
# just return first entry we got, answers[0].target does not work
if qtype == "A":
return rdata
if qtype == "NS":
return str(rdata.target)
else:
print >> sys.stderr, "ERROR: error in get_record, unknown type " + qtype
sys.exit(1)
def get_axfr_record(domain, nameserver):
try:
zone = dns.zone.from_xfr(dns.query.xfr(nameserver, domain, rdtype=dns.rdatatype.AXFR))
except dns.exception.FormError:
raise dns.exception.FormError, domain
else:
return zone
def sshfp_from_axfr(domain, nameserver):
if " " in domain:
print >> sys.stderr, "ERROR: space in domain '"+domain+"' can't be right, aborted"
sys.exit(1)
if not nameserver:
nameserver = get_record(domain, "NS")
if not nameserver:
print >> sys.stderr, "WARNING: no NS record found for domain "+domain+". trying as host record instead"
# better then nothing
return sshfp_from_dns([domain])
hosts = []
#print "nameserver:" + str(ns)
try:
# print "trying axfr for "+domain+"@"+nameserver
axfr = get_axfr_record(domain, nameserver)
except dns.exception.FormError, badDomain:
print >> sys.stderr, "AXFR error: %s - No permission or not authorative for %s; aborting" % (nameserver, badDomain)
sys.exit(1)
for (name, ttl, rdata) in axfr.iterate_rdatas('A'):
#print "name:" +str(name) +", ttl:"+ str(ttl)+ ", rdata:"+str(rdata)
if "@" in str(name):
hosts.append(domain + ".")
else:
if not str(name) == "localhost":
hosts.append("%s.%s." % (name, domain))
return sshfp_from_dns(hosts)
def sshfp_from_dns(hosts):
global quiet
global port
global timeout
global algos
if "dsa" in algos:
print >> sys.stderr, "WARNING: openssh has obsoleted dsa/dss keys"
cmd = ["ssh-keyscan", "-p", str(port), "-T", str(timeout), "-t", ",".join(algos)] + hosts
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = process.communicate()
stderr = re.sub("#.*\n", "", stderr) # strip scan comments
if not quiet:
print >> sys.stderr, stderr
khdns = stdout
return process_records(khdns, hosts)
def main():
global all_hosts
global trailing
global quiet
global port
global timeout
global algos
global digests
parser = optparse.OptionParser()
parser.add_option("-k", "--knownhosts", "--known-hosts",
action="store",
dest="known_hosts",
metavar="KNOWN_HOSTS_FILE",
default=DEFAULT_KNOWN_HOSTS_FILE,
help="obtain public ssh keys from the known_hosts file KNOWN_HOSTS_FILE")
parser.add_option("-s", "--scan",
action="store_true",
default=False,
dest="scan",
help="scan the listed hosts for public keys using ssh-keyscan")
parser.add_option("-a", "--all",
action="store_true",
dest="all_hosts",
help="scan all hosts in the known_hosts file when used with -k. When used with -s, attempt a zone transfer to obtain all A records in the domain provided")
parser.add_option("-d", "--trailing-dot",
action="store_true",
dest="trailing_dot",
help="add a trailing dot to the hostname in the SSHFP records")
parser.add_option("-o", "--output",
action="store",
metavar="FILENAME",
default=None,
help="write to FILENAME instead of stdout")
parser.add_option("-p", "--port",
action="store",
metavar="PORT",
type="int",
default=22,
help="use PORT for scanning")
parser.add_option("-v", "--version",
action="store_true",
dest="version",
help="print version information and exit")
parser.add_option("-q", "--quiet",
action="store_true",
dest="quiet")
parser.add_option("-T", "--timeout",
action="store",
type="int",
dest="timeout",
default=5,
help="scanning timeout (default %default)")
parser.add_option("-t", "--type",
action="append",
type="choice",
dest="algo",
choices=["rsa", "ecdsa", "ed25519", "dsa"],
default=[],
help="key type to fetch (may be specified more than once, default rsa,ecdsa,ed25519,dsa)")
parser.add_option("--digest",
action="append",
type="choice",
dest="digest",
choices=["sha1", "sha256"],
default=[],
help="fingerprint hash function (may be specified more than once, default sha1,sha256)")
parser.add_option("-n", "--nameserver",
action="store",
type="string",
dest="nameserver",
default="",
help="nameserver to use for AXFR (only valid with -s -a)")
(options, args) = parser.parse_args()
# parse options
khfile = options.known_hosts
dodns = options.scan
nameserver = ""
domain = ""
output = options.output
quiet = options.quiet
data = ""
trailing = options.trailing_dot
timeout = options.timeout
algos = options.algo or ["rsa", "ecdsa", "ed25519"]
digests = options.digest or ["sha256"]
all_hosts = options.all_hosts
port = options.port
hostnames = ()
if options.version:
show_version()
sys.exit(0)
if not quiet and port != 22:
print >> sys.stderr, "WARNING: non-standard port numbers are not designated in SSHFP records"
if not quiet and options.known_hosts and options.scan:
print >> sys.stderr, "WARNING: Ignoring known hosts option -k , -s was passed"
if options.nameserver and not options.scan and not options.all_hosts:
print >> sys.stderr, "ERROR: Cannot specify -n without -s and -a"
sys.exit(1)
if not options.scan and options.all_hosts and args:
print >> sys.stderr, "WARNING: -a and hosts both passed, ignoring manual host list"
if not args and (not all_hosts):
print >> sys.stderr, "WARNING: Assuming -a"
all_hosts = True
if options.scan and options.all_hosts:
datal = []
for arg in args:
datal.append(sshfp_from_axfr(arg, options.nameserver))
if not quiet:
datal.insert(0, ";")
datal.insert(0, "; Generated by sshfp %s from %s at %s" % (VERSION, nameserver, time.ctime()))
datal.insert(0, ";")
data = "\n".join(datal)
elif options.scan: # Scan specified hosts
if not args:
print >> sys.stderr, "ERROR: You asked me to scan, but didn't give any hosts to scan"
sys.exit(1)
data = sshfp_from_dns(args)
else: # known_hosts
data = sshfp_from_file(khfile, args)
if output:
try:
fp = open(output, "w")
except IOError:
print >> sys.stderr, "ERROR: can't open '%s'' for writing" % output
sys.exit(1)
else:
fp.write(data)
fp.close()
else:
print data
if __name__ == "__main__":
main()
|