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