xref: /openssh-portable/ssh-keyscan.c (revision 2c71cec0)
1 /* $OpenBSD: ssh-keyscan.c,v 1.138 2020/12/29 00:59:15 djm Exp $ */
2 /*
3  * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>.
4  *
5  * Modification and redistribution in source and binary forms is
6  * permitted provided that due credit is given to the author and the
7  * OpenBSD project by leaving this copyright notice intact.
8  */
9 
10 #include "includes.h"
11 
12 #include <sys/types.h>
13 #include "openbsd-compat/sys-queue.h"
14 #include <sys/resource.h>
15 #ifdef HAVE_SYS_TIME_H
16 # include <sys/time.h>
17 #endif
18 
19 #include <netinet/in.h>
20 #include <arpa/inet.h>
21 
22 #ifdef WITH_OPENSSL
23 #include <openssl/bn.h>
24 #endif
25 
26 #include <netdb.h>
27 #include <errno.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <signal.h>
32 #include <string.h>
33 #include <unistd.h>
34 
35 #include "xmalloc.h"
36 #include "ssh.h"
37 #include "sshbuf.h"
38 #include "sshkey.h"
39 #include "cipher.h"
40 #include "kex.h"
41 #include "compat.h"
42 #include "myproposal.h"
43 #include "packet.h"
44 #include "dispatch.h"
45 #include "log.h"
46 #include "atomicio.h"
47 #include "misc.h"
48 #include "hostfile.h"
49 #include "ssherr.h"
50 #include "ssh_api.h"
51 #include "dns.h"
52 
53 /* Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
54    Default value is AF_UNSPEC means both IPv4 and IPv6. */
55 int IPv4or6 = AF_UNSPEC;
56 
57 int ssh_port = SSH_DEFAULT_PORT;
58 
59 #define KT_DSA		(1)
60 #define KT_RSA		(1<<1)
61 #define KT_ECDSA	(1<<2)
62 #define KT_ED25519	(1<<3)
63 #define KT_XMSS		(1<<4)
64 #define KT_ECDSA_SK	(1<<5)
65 #define KT_ED25519_SK	(1<<6)
66 
67 #define KT_MIN		KT_DSA
68 #define KT_MAX		KT_ED25519_SK
69 
70 int get_cert = 0;
71 int get_keytypes = KT_RSA|KT_ECDSA|KT_ED25519|KT_ECDSA_SK|KT_ED25519_SK;
72 
73 int hash_hosts = 0;		/* Hash hostname on output */
74 
75 int print_sshfp = 0;		/* Print SSHFP records instead of known_hosts */
76 
77 int found_one = 0;		/* Successfully found a key */
78 
79 #define MAXMAXFD 256
80 
81 /* The number of seconds after which to give up on a TCP connection */
82 int timeout = 5;
83 
84 int maxfd;
85 #define MAXCON (maxfd - 10)
86 
87 extern char *__progname;
88 fd_set *read_wait;
89 size_t read_wait_nfdset;
90 int ncon;
91 
92 /*
93  * Keep a connection structure for each file descriptor.  The state
94  * associated with file descriptor n is held in fdcon[n].
95  */
96 typedef struct Connection {
97 	u_char c_status;	/* State of connection on this file desc. */
98 #define CS_UNUSED 0		/* File descriptor unused */
99 #define CS_CON 1		/* Waiting to connect/read greeting */
100 #define CS_SIZE 2		/* Waiting to read initial packet size */
101 #define CS_KEYS 3		/* Waiting to read public key packet */
102 	int c_fd;		/* Quick lookup: c->c_fd == c - fdcon */
103 	int c_plen;		/* Packet length field for ssh packet */
104 	int c_len;		/* Total bytes which must be read. */
105 	int c_off;		/* Length of data read so far. */
106 	int c_keytype;		/* Only one of KT_* */
107 	sig_atomic_t c_done;	/* SSH2 done */
108 	char *c_namebase;	/* Address to free for c_name and c_namelist */
109 	char *c_name;		/* Hostname of connection for errors */
110 	char *c_namelist;	/* Pointer to other possible addresses */
111 	char *c_output_name;	/* Hostname of connection for output */
112 	char *c_data;		/* Data read from this fd */
113 	struct ssh *c_ssh;	/* SSH-connection */
114 	struct timeval c_tv;	/* Time at which connection gets aborted */
115 	TAILQ_ENTRY(Connection) c_link;	/* List of connections in timeout order. */
116 } con;
117 
118 TAILQ_HEAD(conlist, Connection) tq;	/* Timeout Queue */
119 con *fdcon;
120 
121 static void keyprint(con *c, struct sshkey *key);
122 
123 static int
124 fdlim_get(int hard)
125 {
126 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
127 	struct rlimit rlfd;
128 
129 	if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
130 		return (-1);
131 	if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
132 		return SSH_SYSFDMAX;
133 	else
134 		return hard ? rlfd.rlim_max : rlfd.rlim_cur;
135 #else
136 	return SSH_SYSFDMAX;
137 #endif
138 }
139 
140 static int
141 fdlim_set(int lim)
142 {
143 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
144 	struct rlimit rlfd;
145 #endif
146 
147 	if (lim <= 0)
148 		return (-1);
149 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
150 	if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
151 		return (-1);
152 	rlfd.rlim_cur = lim;
153 	if (setrlimit(RLIMIT_NOFILE, &rlfd) == -1)
154 		return (-1);
155 #elif defined (HAVE_SETDTABLESIZE)
156 	setdtablesize(lim);
157 #endif
158 	return (0);
159 }
160 
161 /*
162  * This is an strsep function that returns a null field for adjacent
163  * separators.  This is the same as the 4.4BSD strsep, but different from the
164  * one in the GNU libc.
165  */
166 static char *
167 xstrsep(char **str, const char *delim)
168 {
169 	char *s, *e;
170 
171 	if (!**str)
172 		return (NULL);
173 
174 	s = *str;
175 	e = s + strcspn(s, delim);
176 
177 	if (*e != '\0')
178 		*e++ = '\0';
179 	*str = e;
180 
181 	return (s);
182 }
183 
184 /*
185  * Get the next non-null token (like GNU strsep).  Strsep() will return a
186  * null token for two adjacent separators, so we may have to loop.
187  */
188 static char *
189 strnnsep(char **stringp, char *delim)
190 {
191 	char *tok;
192 
193 	do {
194 		tok = xstrsep(stringp, delim);
195 	} while (tok && *tok == '\0');
196 	return (tok);
197 }
198 
199 
200 static int
201 key_print_wrapper(struct sshkey *hostkey, struct ssh *ssh)
202 {
203 	con *c;
204 
205 	if ((c = ssh_get_app_data(ssh)) != NULL)
206 		keyprint(c, hostkey);
207 	/* always abort key exchange */
208 	return -1;
209 }
210 
211 static int
212 ssh2_capable(int remote_major, int remote_minor)
213 {
214 	switch (remote_major) {
215 	case 1:
216 		if (remote_minor == 99)
217 			return 1;
218 		break;
219 	case 2:
220 		return 1;
221 	default:
222 		break;
223 	}
224 	return 0;
225 }
226 
227 static void
228 keygrab_ssh2(con *c)
229 {
230 	char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
231 	int r;
232 
233 	switch (c->c_keytype) {
234 	case KT_DSA:
235 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
236 		    "ssh-dss-cert-v01@openssh.com" : "ssh-dss";
237 		break;
238 	case KT_RSA:
239 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
240 		    "rsa-sha2-512-cert-v01@openssh.com,"
241 		    "rsa-sha2-256-cert-v01@openssh.com,"
242 		    "ssh-rsa-cert-v01@openssh.com" :
243 		    "rsa-sha2-512,"
244 		    "rsa-sha2-256,"
245 		    "ssh-rsa";
246 		break;
247 	case KT_ED25519:
248 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
249 		    "ssh-ed25519-cert-v01@openssh.com" : "ssh-ed25519";
250 		break;
251 	case KT_XMSS:
252 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
253 		    "ssh-xmss-cert-v01@openssh.com" : "ssh-xmss@openssh.com";
254 		break;
255 	case KT_ECDSA:
256 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
257 		    "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
258 		    "ecdsa-sha2-nistp384-cert-v01@openssh.com,"
259 		    "ecdsa-sha2-nistp521-cert-v01@openssh.com" :
260 		    "ecdsa-sha2-nistp256,"
261 		    "ecdsa-sha2-nistp384,"
262 		    "ecdsa-sha2-nistp521";
263 		break;
264 	case KT_ECDSA_SK:
265 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
266 		    "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com" :
267 		    "sk-ecdsa-sha2-nistp256@openssh.com";
268 		break;
269 	case KT_ED25519_SK:
270 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
271 		    "sk-ssh-ed25519-cert-v01@openssh.com" :
272 		    "sk-ssh-ed25519@openssh.com";
273 		break;
274 	default:
275 		fatal("unknown key type %d", c->c_keytype);
276 		break;
277 	}
278 	if ((r = kex_setup(c->c_ssh, myproposal)) != 0) {
279 		free(c->c_ssh);
280 		fprintf(stderr, "kex_setup: %s\n", ssh_err(r));
281 		exit(1);
282 	}
283 #ifdef WITH_OPENSSL
284 	c->c_ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
285 	c->c_ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
286 	c->c_ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
287 	c->c_ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
288 	c->c_ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
289 	c->c_ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
290 	c->c_ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
291 # ifdef OPENSSL_HAS_ECC
292 	c->c_ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
293 # endif
294 #endif
295 	c->c_ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
296 	c->c_ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
297 	ssh_set_verify_host_key_callback(c->c_ssh, key_print_wrapper);
298 	/*
299 	 * do the key-exchange until an error occurs or until
300 	 * the key_print_wrapper() callback sets c_done.
301 	 */
302 	ssh_dispatch_run(c->c_ssh, DISPATCH_BLOCK, &c->c_done);
303 }
304 
305 static void
306 keyprint_one(const char *host, struct sshkey *key)
307 {
308 	char *hostport;
309 	const char *known_host, *hashed;
310 
311 	found_one = 1;
312 
313 	if (print_sshfp) {
314 		export_dns_rr(host, key, stdout, 0);
315 		return;
316 	}
317 
318 	hostport = put_host_port(host, ssh_port);
319 	lowercase(hostport);
320 	if (hash_hosts && (hashed = host_hash(host, NULL, 0)) == NULL)
321 		fatal("host_hash failed");
322 	known_host = hash_hosts ? hashed : hostport;
323 	if (!get_cert)
324 		fprintf(stdout, "%s ", known_host);
325 	sshkey_write(key, stdout);
326 	fputs("\n", stdout);
327 	free(hostport);
328 }
329 
330 static void
331 keyprint(con *c, struct sshkey *key)
332 {
333 	char *hosts = c->c_output_name ? c->c_output_name : c->c_name;
334 	char *host, *ohosts;
335 
336 	if (key == NULL)
337 		return;
338 	if (get_cert || (!hash_hosts && ssh_port == SSH_DEFAULT_PORT)) {
339 		keyprint_one(hosts, key);
340 		return;
341 	}
342 	ohosts = hosts = xstrdup(hosts);
343 	while ((host = strsep(&hosts, ",")) != NULL)
344 		keyprint_one(host, key);
345 	free(ohosts);
346 }
347 
348 static int
349 tcpconnect(char *host)
350 {
351 	struct addrinfo hints, *ai, *aitop;
352 	char strport[NI_MAXSERV];
353 	int gaierr, s = -1;
354 
355 	snprintf(strport, sizeof strport, "%d", ssh_port);
356 	memset(&hints, 0, sizeof(hints));
357 	hints.ai_family = IPv4or6;
358 	hints.ai_socktype = SOCK_STREAM;
359 	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
360 		error("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
361 		return -1;
362 	}
363 	for (ai = aitop; ai; ai = ai->ai_next) {
364 		s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
365 		if (s == -1) {
366 			error("socket: %s", strerror(errno));
367 			continue;
368 		}
369 		if (set_nonblock(s) == -1)
370 			fatal_f("set_nonblock(%d)", s);
371 		if (connect(s, ai->ai_addr, ai->ai_addrlen) == -1 &&
372 		    errno != EINPROGRESS)
373 			error("connect (`%s'): %s", host, strerror(errno));
374 		else
375 			break;
376 		close(s);
377 		s = -1;
378 	}
379 	freeaddrinfo(aitop);
380 	return s;
381 }
382 
383 static int
384 conalloc(char *iname, char *oname, int keytype)
385 {
386 	char *namebase, *name, *namelist;
387 	int s;
388 
389 	namebase = namelist = xstrdup(iname);
390 
391 	do {
392 		name = xstrsep(&namelist, ",");
393 		if (!name) {
394 			free(namebase);
395 			return (-1);
396 		}
397 	} while ((s = tcpconnect(name)) < 0);
398 
399 	if (s >= maxfd)
400 		fatal("conalloc: fdno %d too high", s);
401 	if (fdcon[s].c_status)
402 		fatal("conalloc: attempt to reuse fdno %d", s);
403 
404 	debug3_f("oname %s kt %d", oname, keytype);
405 	fdcon[s].c_fd = s;
406 	fdcon[s].c_status = CS_CON;
407 	fdcon[s].c_namebase = namebase;
408 	fdcon[s].c_name = name;
409 	fdcon[s].c_namelist = namelist;
410 	fdcon[s].c_output_name = xstrdup(oname);
411 	fdcon[s].c_data = (char *) &fdcon[s].c_plen;
412 	fdcon[s].c_len = 4;
413 	fdcon[s].c_off = 0;
414 	fdcon[s].c_keytype = keytype;
415 	monotime_tv(&fdcon[s].c_tv);
416 	fdcon[s].c_tv.tv_sec += timeout;
417 	TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
418 	FD_SET(s, read_wait);
419 	ncon++;
420 	return (s);
421 }
422 
423 static void
424 confree(int s)
425 {
426 	if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
427 		fatal("confree: attempt to free bad fdno %d", s);
428 	free(fdcon[s].c_namebase);
429 	free(fdcon[s].c_output_name);
430 	if (fdcon[s].c_status == CS_KEYS)
431 		free(fdcon[s].c_data);
432 	fdcon[s].c_status = CS_UNUSED;
433 	fdcon[s].c_keytype = 0;
434 	if (fdcon[s].c_ssh) {
435 		ssh_packet_close(fdcon[s].c_ssh);
436 		free(fdcon[s].c_ssh);
437 		fdcon[s].c_ssh = NULL;
438 	} else
439 		close(s);
440 	TAILQ_REMOVE(&tq, &fdcon[s], c_link);
441 	FD_CLR(s, read_wait);
442 	ncon--;
443 }
444 
445 static void
446 contouch(int s)
447 {
448 	TAILQ_REMOVE(&tq, &fdcon[s], c_link);
449 	monotime_tv(&fdcon[s].c_tv);
450 	fdcon[s].c_tv.tv_sec += timeout;
451 	TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
452 }
453 
454 static int
455 conrecycle(int s)
456 {
457 	con *c = &fdcon[s];
458 	int ret;
459 
460 	ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
461 	confree(s);
462 	return (ret);
463 }
464 
465 static void
466 congreet(int s)
467 {
468 	int n = 0, remote_major = 0, remote_minor = 0;
469 	char buf[256], *cp;
470 	char remote_version[sizeof buf];
471 	size_t bufsiz;
472 	con *c = &fdcon[s];
473 
474 	/* send client banner */
475 	n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
476 	    PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
477 	if (n < 0 || (size_t)n >= sizeof(buf)) {
478 		error("snprintf: buffer too small");
479 		confree(s);
480 		return;
481 	}
482 	if (atomicio(vwrite, s, buf, n) != (size_t)n) {
483 		error("write (%s): %s", c->c_name, strerror(errno));
484 		confree(s);
485 		return;
486 	}
487 
488 	for (;;) {
489 		memset(buf, '\0', sizeof(buf));
490 		bufsiz = sizeof(buf);
491 		cp = buf;
492 		while (bufsiz-- &&
493 		    (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
494 			if (*cp == '\r')
495 				*cp = '\n';
496 			cp++;
497 		}
498 		if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
499 			break;
500 	}
501 	if (n == 0) {
502 		switch (errno) {
503 		case EPIPE:
504 			error("%s: Connection closed by remote host", c->c_name);
505 			break;
506 		case ECONNREFUSED:
507 			break;
508 		default:
509 			error("read (%s): %s", c->c_name, strerror(errno));
510 			break;
511 		}
512 		conrecycle(s);
513 		return;
514 	}
515 	if (*cp != '\n' && *cp != '\r') {
516 		error("%s: bad greeting", c->c_name);
517 		confree(s);
518 		return;
519 	}
520 	*cp = '\0';
521 	if ((c->c_ssh = ssh_packet_set_connection(NULL, s, s)) == NULL)
522 		fatal("ssh_packet_set_connection failed");
523 	ssh_packet_set_timeout(c->c_ssh, timeout, 1);
524 	ssh_set_app_data(c->c_ssh, c);	/* back link */
525 	if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
526 	    &remote_major, &remote_minor, remote_version) == 3)
527 		c->c_ssh->compat = compat_datafellows(remote_version);
528 	else
529 		c->c_ssh->compat = 0;
530 	if (!ssh2_capable(remote_major, remote_minor)) {
531 		debug("%s doesn't support ssh2", c->c_name);
532 		confree(s);
533 		return;
534 	}
535 	fprintf(stderr, "%c %s:%d %s\n", print_sshfp ? ';' : '#',
536 	    c->c_name, ssh_port, chop(buf));
537 	keygrab_ssh2(c);
538 	confree(s);
539 }
540 
541 static void
542 conread(int s)
543 {
544 	con *c = &fdcon[s];
545 	size_t n;
546 
547 	if (c->c_status == CS_CON) {
548 		congreet(s);
549 		return;
550 	}
551 	n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
552 	if (n == 0) {
553 		error("read (%s): %s", c->c_name, strerror(errno));
554 		confree(s);
555 		return;
556 	}
557 	c->c_off += n;
558 
559 	if (c->c_off == c->c_len)
560 		switch (c->c_status) {
561 		case CS_SIZE:
562 			c->c_plen = htonl(c->c_plen);
563 			c->c_len = c->c_plen + 8 - (c->c_plen & 7);
564 			c->c_off = 0;
565 			c->c_data = xmalloc(c->c_len);
566 			c->c_status = CS_KEYS;
567 			break;
568 		default:
569 			fatal("conread: invalid status %d", c->c_status);
570 			break;
571 		}
572 
573 	contouch(s);
574 }
575 
576 static void
577 conloop(void)
578 {
579 	struct timeval seltime, now;
580 	fd_set *r, *e;
581 	con *c;
582 	int i;
583 
584 	monotime_tv(&now);
585 	c = TAILQ_FIRST(&tq);
586 
587 	if (c && timercmp(&c->c_tv, &now, >))
588 		timersub(&c->c_tv, &now, &seltime);
589 	else
590 		timerclear(&seltime);
591 
592 	r = xcalloc(read_wait_nfdset, sizeof(fd_mask));
593 	e = xcalloc(read_wait_nfdset, sizeof(fd_mask));
594 	memcpy(r, read_wait, read_wait_nfdset * sizeof(fd_mask));
595 	memcpy(e, read_wait, read_wait_nfdset * sizeof(fd_mask));
596 
597 	while (select(maxfd, r, NULL, e, &seltime) == -1 &&
598 	    (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK))
599 		;
600 
601 	for (i = 0; i < maxfd; i++) {
602 		if (FD_ISSET(i, e)) {
603 			error("%s: exception!", fdcon[i].c_name);
604 			confree(i);
605 		} else if (FD_ISSET(i, r))
606 			conread(i);
607 	}
608 	free(r);
609 	free(e);
610 
611 	c = TAILQ_FIRST(&tq);
612 	while (c && timercmp(&c->c_tv, &now, <)) {
613 		int s = c->c_fd;
614 
615 		c = TAILQ_NEXT(c, c_link);
616 		conrecycle(s);
617 	}
618 }
619 
620 static void
621 do_host(char *host)
622 {
623 	char *name = strnnsep(&host, " \t\n");
624 	int j;
625 
626 	if (name == NULL)
627 		return;
628 	for (j = KT_MIN; j <= KT_MAX; j *= 2) {
629 		if (get_keytypes & j) {
630 			while (ncon >= MAXCON)
631 				conloop();
632 			conalloc(name, *host ? host : name, j);
633 		}
634 	}
635 }
636 
637 void
638 sshfatal(const char *file, const char *func, int line, int showfunc,
639     LogLevel level, const char *suffix, const char *fmt, ...)
640 {
641 	va_list args;
642 
643 	va_start(args, fmt);
644 	sshlogv(file, func, line, showfunc, level, suffix, fmt, args);
645 	va_end(args);
646 	cleanup_exit(255);
647 }
648 
649 static void
650 usage(void)
651 {
652 	fprintf(stderr,
653 	    "usage: %s [-46cDHv] [-f file] [-p port] [-T timeout] [-t type]\n"
654 	    "\t\t   [host | addrlist namelist]\n",
655 	    __progname);
656 	exit(1);
657 }
658 
659 int
660 main(int argc, char **argv)
661 {
662 	int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
663 	int opt, fopt_count = 0, j;
664 	char *tname, *cp, *line = NULL;
665 	size_t linesize = 0;
666 	FILE *fp;
667 
668 	extern int optind;
669 	extern char *optarg;
670 
671 	__progname = ssh_get_progname(argv[0]);
672 	seed_rng();
673 	TAILQ_INIT(&tq);
674 
675 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
676 	sanitise_stdfd();
677 
678 	if (argc <= 1)
679 		usage();
680 
681 	while ((opt = getopt(argc, argv, "cDHv46p:T:t:f:")) != -1) {
682 		switch (opt) {
683 		case 'H':
684 			hash_hosts = 1;
685 			break;
686 		case 'c':
687 			get_cert = 1;
688 			break;
689 		case 'D':
690 			print_sshfp = 1;
691 			break;
692 		case 'p':
693 			ssh_port = a2port(optarg);
694 			if (ssh_port <= 0) {
695 				fprintf(stderr, "Bad port '%s'\n", optarg);
696 				exit(1);
697 			}
698 			break;
699 		case 'T':
700 			timeout = convtime(optarg);
701 			if (timeout == -1 || timeout == 0) {
702 				fprintf(stderr, "Bad timeout '%s'\n", optarg);
703 				usage();
704 			}
705 			break;
706 		case 'v':
707 			if (!debug_flag) {
708 				debug_flag = 1;
709 				log_level = SYSLOG_LEVEL_DEBUG1;
710 			}
711 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
712 				log_level++;
713 			else
714 				fatal("Too high debugging level.");
715 			break;
716 		case 'f':
717 			if (strcmp(optarg, "-") == 0)
718 				optarg = NULL;
719 			argv[fopt_count++] = optarg;
720 			break;
721 		case 't':
722 			get_keytypes = 0;
723 			tname = strtok(optarg, ",");
724 			while (tname) {
725 				int type = sshkey_type_from_name(tname);
726 
727 				switch (type) {
728 				case KEY_DSA:
729 					get_keytypes |= KT_DSA;
730 					break;
731 				case KEY_ECDSA:
732 					get_keytypes |= KT_ECDSA;
733 					break;
734 				case KEY_RSA:
735 					get_keytypes |= KT_RSA;
736 					break;
737 				case KEY_ED25519:
738 					get_keytypes |= KT_ED25519;
739 					break;
740 				case KEY_XMSS:
741 					get_keytypes |= KT_XMSS;
742 					break;
743 				case KEY_ED25519_SK:
744 					get_keytypes |= KT_ED25519_SK;
745 					break;
746 				case KEY_ECDSA_SK:
747 					get_keytypes |= KT_ECDSA_SK;
748 					break;
749 				case KEY_UNSPEC:
750 				default:
751 					fatal("Unknown key type \"%s\"", tname);
752 				}
753 				tname = strtok(NULL, ",");
754 			}
755 			break;
756 		case '4':
757 			IPv4or6 = AF_INET;
758 			break;
759 		case '6':
760 			IPv4or6 = AF_INET6;
761 			break;
762 		case '?':
763 		default:
764 			usage();
765 		}
766 	}
767 	if (optind == argc && !fopt_count)
768 		usage();
769 
770 	log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
771 
772 	maxfd = fdlim_get(1);
773 	if (maxfd < 0)
774 		fatal("%s: fdlim_get: bad value", __progname);
775 	if (maxfd > MAXMAXFD)
776 		maxfd = MAXMAXFD;
777 	if (MAXCON <= 0)
778 		fatal("%s: not enough file descriptors", __progname);
779 	if (maxfd > fdlim_get(0))
780 		fdlim_set(maxfd);
781 	fdcon = xcalloc(maxfd, sizeof(con));
782 
783 	read_wait_nfdset = howmany(maxfd, NFDBITS);
784 	read_wait = xcalloc(read_wait_nfdset, sizeof(fd_mask));
785 
786 	for (j = 0; j < fopt_count; j++) {
787 		if (argv[j] == NULL)
788 			fp = stdin;
789 		else if ((fp = fopen(argv[j], "r")) == NULL)
790 			fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
791 
792 		while (getline(&line, &linesize, fp) != -1) {
793 			/* Chomp off trailing whitespace and comments */
794 			if ((cp = strchr(line, '#')) == NULL)
795 				cp = line + strlen(line) - 1;
796 			while (cp >= line) {
797 				if (*cp == ' ' || *cp == '\t' ||
798 				    *cp == '\n' || *cp == '#')
799 					*cp-- = '\0';
800 				else
801 					break;
802 			}
803 
804 			/* Skip empty lines */
805 			if (*line == '\0')
806 				continue;
807 
808 			do_host(line);
809 		}
810 
811 		if (ferror(fp))
812 			fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
813 
814 		fclose(fp);
815 	}
816 	free(line);
817 
818 	while (optind < argc)
819 		do_host(argv[optind++]);
820 
821 	while (ncon > 0)
822 		conloop();
823 
824 	return found_one ? 0 : 1;
825 }
826