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