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