forked from xelerance/sshfp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
sshfp
executable file
·458 lines (410 loc) · 12.6 KB
/
sshfp
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
#!/usr/bin/python
# Generate SSHFP DNS records (RFC4255) from knownhosts files or ssh-keyscan
# Copyright by Xelerance http://www.xelerance.com/
# Paul Wouters <[email protected]>
# License: GNU GENERAL PUBLIC LICENSE Version 2 or later
# vim:set ts=4 sw=4 sts=4 noexpandtab
import os
import sys
import subprocess
import optparse
import base64
import time
import re
# www.dnspython.org
try:
import dns.resolver
import dns.query
import dns.zone
except ImportError:
print("sshfp requires the python-dns package from http://www.pythondns.org/", file=sys.stderr)
print("Fedora: yum install python-dns", file=sys.stderr)
print("Debian: apt-get install python-dnspython (NOT python-dns!)", file=sys.stderr)
print("openSUSE: zypper in python-dnspython", file=sys.stderr)
print("OSX: pip install dnspython", file=sys.stderr)
sys.exit(1)
ishashlib = False
try:
import hashlib
ishashlib = True
except ImportError:
import sha
global all_hosts
global khfile
global hostnames
global trailing
global quiet
global port
global timeout
global algo
global fphashes
VERSION = "1.3.0"
DEFAULT_KNOWN_HOSTS_FILE = "~/.ssh/known_hosts"
def show_version():
print("sshfp version: " + VERSION, file=sys.stderr)
print("Source : http://www.xelerance.com/software/sshfp/", file=sys.stderr)
print("Author:\n Paul Wouters <[email protected]>", file=sys.stderr)
print(" James Brown <[email protected]>", file=sys.stderr)
def create_sshfp(hostname, keytype, keyblob, fphash):
"""Creates an SSH fingerprint"""
if keytype == "ssh-rsa":
keytype = "1"
elif keytype == "ssh-dss":
keytype = "2"
elif keytype == "ecdsa-sha2-nistp256":
keytype = "3"
elif keytype == "ssh-ed25519":
keytype = "4"
else:
return ""
try:
rawkey = base64.b64decode(keyblob)
except TypeError:
print("FAILED on hostname "+hostname+" with keyblob "+keyblob, file=sys.stderr)
return "ERROR"
hashcode = "1"
if ishashlib:
if fphash == "sha2":
digest = hashlib.sha256
hashcode = "2"
else:
digest = hashlib.sha1
else:
digest = sha.new
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 + " " + hashcode + " " + 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(stderr, file=sys.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("ERROR: failed to open file "+ known_hosts, file=sys.stderr)
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("ERROR: %s is hashed, cannot use with -a" % known_hosts, file=sys.stderr)
sys.exit(1)
elif hashed_known_hosts: #only looking for some known hosts
for host in wantedHosts:
fingerprints.append(process_record(get_known_host_entry(known_hosts, host), host))
else:
try:
khfp = open(known_hosts)
except IOError:
print("ERROR: failed to open file "+ known_hosts, file=sys.stderr)
sys.exit(1)
data = khfp.read()
khfp.close()
fingerprints.append(process_records(data, wantedHosts))
return "\n".join(fingerprints)
def check_keytype(keytype):
global algos
for algo in algos:
if "ssh-%s" % algo[:-1] == keytype[:-1]:
return True
if "ecdsa" == algo and "ecdsa-sha2-nistp256" == keytype:
return True
return False
def process_record(record, hostname):
global fphashes
all_records = []
(host, keytype, key) = record.split(" ")
key = key.rstrip()
if check_keytype(keytype):
for fphash in fphashes:
all_records.append(create_sshfp(host, keytype, key, fphash))
if all_records:
all_records.sort()
return "\n".join(all_records)
else:
return ""
def process_records(data, hostnames):
global fphashes
"""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
"""
all_records = []
for record in data.split("\n"):
if record.startswith("#") or not record:
continue
try:
(host, keytype, key) = record.split(" ")
except ValueError:
if not quiet:
print("Unable to read record '%s'" % record, file=sys.stdout)
continue
if "," in host:
host = host.split(",")[0]
if all_hosts or host in hostnames or host == hostnames:
if not check_keytype(keytype):
continue
if regexfilter:
if regexfilter.search(str(host)):
for fphash in fphashes:
all_records.append(create_sshfp(host, keytype, key, fphash))
else:
print("- Host excluded by regex pattern: {}".format(host), file=sys.stderr)
else:
for fphash in fphashes:
all_records.append(create_sshfp(host, keytype, key, fphash))
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("ERROR: error in get_record, unknown type " + qtype, file=sys.stderr)
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("ERROR: space in domain '"+domain+"' can't be right, aborted", file=sys.stderr)
sys.exit(1)
if not nameserver:
nameserver = get_record(domain, "NS")
if not nameserver:
print("WARNING: no NS record found for domain "+domain+". trying as host record instead", file=sys.stderr)
# 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 as badDomain:
print("AXFR error: %s - No permission or not authorative for %s; aborting" % (nameserver, badDomain), file=sys.stderr)
sys.exit(1)
for rdatas in ('A', 'AAAA'):
for (name, ttl, rdata) in axfr.iterate_rdatas(rdatas):
#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
hosts = sort_uniq(hosts)
khdns = ''
for p in port:
cmd = ["ssh-keyscan", "-p", str(p), "-T", str(timeout), "-t", ",".join(algos)] + hosts
#pp.pprint(cmd)
process = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(stdout, stderr) = process.communicate()
if not quiet:
print(stderr, file=sys.stderr)
sys.stderr.flush()
khdns = khdns + stdout
return process_records(khdns, hosts)
def sort_uniq(dlist):
a = []
for l in dlist:
for q in l.split('\n'):
if not str(q) in a:
a.append(str(q))
return sorted(a)
def main():
global all_hosts
global trailing
global quiet
global port
global timeout
global algos
global regexfilter
global fphashes
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="append",
metavar="PORT",
type="int",
dest="port",
default=[22],
help="use PORT for scanning. Can be used multiple times to scan more ports.")
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", "dsa", "ecdsa", "ed25519"],
default=[],
help="key type to fetch (may be specified more than once, default dsa,rsa,ecdsa,ed25519)")
parser.add_option("-n", "--nameserver",
action="store",
type="string",
dest="nameserver",
default="",
help="nameserver to use for AXFR (only valid with -s -a)")
parser.add_option("-r", "--regex",
action="store",
type="string",
dest="regex",
default=None,
help="Regex of hosts to be included. E.g. -r '^(ht|aws).*'")
parser.add_option("-H", "--hashfunction",
action="append",
type="choice",
dest="fphashes",
choices=["sha1", "sha2"],
default=[],
help="Hash function to use, default sha1,sha2")
(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
if options.regex: regexfilter = re.compile(options.regex, re.IGNORECASE)
else: regexfilter = None
fphashes = options.fphashes or ["sha1", "sha2"]
hostnames = ()
if options.version:
show_version()
sys.exit(0)
if not quiet and 22 not in port:
print("WARNING: non-standard port numbers are not designated in SSHFP records", file=sys.stderr)
if not quiet and options.known_hosts and options.scan:
print("WARNING: Ignoring -k option, -s was passed", file=sys.stderr)
if options.nameserver and not options.scan and not options.all_hosts:
print("ERROR: Cannot specify -n without -s and -a", file=sys.stderr)
sys.exit(1)
if not options.scan and options.all_hosts and args:
print("WARNING: -a and hosts both passed, ignoring manual host list", file=sys.stderr)
if not args and (not all_hosts):
print("WARNING: Assuming -a", file=sys.stderr)
all_hosts = True
if not ishashlib and "sha2" in options.fphashes:
print("WARNING: Hashlib not supported, ignoring -H sha2", file=sys.stderr)
fphashes = ["sha1"]
if options.scan and options.all_hosts:
datal = []
for arg in args:
datal.append(sshfp_from_axfr(arg, options.nameserver))
datal = sort_uniq(datal)
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("ERROR: You asked me to scan, but didn't give any hosts to scan", file=sys.stderr)
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("ERROR: can't open '%s'' for writing" % output, file=sys.stderr)
sys.exit(1)
else:
fp.write(data)
fp.close()
else:
print(data)
if __name__ == "__main__":
main()