xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-keyscan.c (revision ccd9df534e375a4366c5b55f23782053c7a98d82)
1 /*	$NetBSD: ssh-keyscan.c,v 1.34 2024/07/08 22:33:44 christos Exp $	*/
2 /* $OpenBSD: ssh-keyscan.c,v 1.158 2024/06/14 00:25:25 djm Exp $ */
3 
4 /*
5  * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>.
6  *
7  * Modification and redistribution in source and binary forms is
8  * permitted provided that due credit is given to the author and the
9  * OpenBSD project by leaving this copyright notice intact.
10  */
11 
12 #include "includes.h"
13 __RCSID("$NetBSD: ssh-keyscan.c,v 1.34 2024/07/08 22:33:44 christos Exp $");
14 
15 #include <sys/param.h>
16 #include <sys/types.h>
17 #include <sys/socket.h>
18 #include <sys/queue.h>
19 #include <sys/time.h>
20 #include <sys/resource.h>
21 
22 #ifdef WITH_OPENSSL
23 #include <openssl/bn.h>
24 #endif
25 
26 #include <errno.h>
27 #include <limits.h>
28 #include <netdb.h>
29 #include <stdarg.h>
30 #include <stdio.h>
31 #include <stdlib.h>
32 #include <poll.h>
33 #include <signal.h>
34 #include <string.h>
35 #include <unistd.h>
36 
37 #include "xmalloc.h"
38 #include "ssh.h"
39 #include "sshbuf.h"
40 #include "sshkey.h"
41 #include "cipher.h"
42 #include "digest.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 #include "addr.h"
56 #include "fmt_scaled.h"
57 
58 /* Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
59    Default value is AF_UNSPEC means both IPv4 and IPv6. */
60 int IPv4or6 = AF_UNSPEC;
61 
62 int ssh_port = SSH_DEFAULT_PORT;
63 
64 #define KT_DSA		(1)
65 #define KT_RSA		(1<<1)
66 #define KT_ECDSA	(1<<2)
67 #define KT_ED25519	(1<<3)
68 #define KT_XMSS		(1<<4)
69 #define KT_ECDSA_SK	(1<<5)
70 #define KT_ED25519_SK	(1<<6)
71 
72 #define KT_MIN		KT_DSA
73 #define KT_MAX		KT_ED25519_SK
74 
75 int get_cert = 0;
76 int get_keytypes = KT_RSA|KT_ECDSA|KT_ED25519|KT_ECDSA_SK|KT_ED25519_SK;
77 
78 int hash_hosts = 0;		/* Hash hostname on output */
79 
80 int print_sshfp = 0;		/* Print SSHFP records instead of known_hosts */
81 
82 int found_one = 0;		/* Successfully found a key */
83 
84 int hashalg = -1;		/* Hash for SSHFP records or -1 for all */
85 
86 int quiet = 0;			/* Don't print key comment lines */
87 
88 #define MAXMAXFD 256
89 
90 /* The number of seconds after which to give up on a TCP connection */
91 int timeout = 5;
92 
93 int maxfd;
94 #define MAXCON (maxfd - 10)
95 
96 extern char *__progname;
97 struct pollfd *read_wait;
98 int ncon;
99 
100 /*
101  * Keep a connection structure for each file descriptor.  The state
102  * associated with file descriptor n is held in fdcon[n].
103  */
104 typedef struct Connection {
105 	u_char c_status;	/* State of connection on this file desc. */
106 #define CS_UNUSED 0		/* File descriptor unused */
107 #define CS_CON 1		/* Waiting to connect/read greeting */
108 	int c_fd;		/* Quick lookup: c->c_fd == c - fdcon */
109 	int c_keytype;		/* Only one of KT_* */
110 	sig_atomic_t c_done;	/* SSH2 done */
111 	char *c_namebase;	/* Address to free for c_name and c_namelist */
112 	char *c_name;		/* Hostname of connection for errors */
113 	char *c_namelist;	/* Pointer to other possible addresses */
114 	char *c_output_name;	/* Hostname of connection for output */
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 	struct rlimit rlfd;
129 
130 	if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
131 		return (-1);
132 	if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY ||
133 	    (hard ? rlfd.rlim_max : rlfd.rlim_cur) > INT_MAX)
134 		return sysconf(_SC_OPEN_MAX);
135 	return hard ? rlfd.rlim_max : rlfd.rlim_cur;
136 }
137 
138 static int
139 fdlim_set(int lim)
140 {
141 	struct rlimit rlfd;
142 
143 	if (lim <= 0)
144 		return (-1);
145 	if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
146 		return (-1);
147 	rlfd.rlim_cur = lim;
148 	if (setrlimit(RLIMIT_NOFILE, &rlfd) == -1)
149 		return (-1);
150 	return (0);
151 }
152 
153 /*
154  * This is an strsep function that returns a null field for adjacent
155  * separators.  This is the same as the 4.4BSD strsep, but different from the
156  * one in the GNU libc.
157  */
158 static char *
159 xstrsep(char **str, const char *delim)
160 {
161 	char *s, *e;
162 
163 	if (!**str)
164 		return (NULL);
165 
166 	s = *str;
167 	e = s + strcspn(s, delim);
168 
169 	if (*e != '\0')
170 		*e++ = '\0';
171 	*str = e;
172 
173 	return (s);
174 }
175 
176 /*
177  * Get the next non-null token (like GNU strsep).  Strsep() will return a
178  * null token for two adjacent separators, so we may have to loop.
179  */
180 static char *
181 strnnsep(char **stringp, const char *delim)
182 {
183 	char *tok;
184 
185 	do {
186 		tok = xstrsep(stringp, delim);
187 	} while (tok && *tok == '\0');
188 	return (tok);
189 }
190 
191 
192 static int
193 key_print_wrapper(struct sshkey *hostkey, struct ssh *ssh)
194 {
195 	con *c;
196 
197 	if ((c = ssh_get_app_data(ssh)) != NULL)
198 		keyprint(c, hostkey);
199 	/* always abort key exchange */
200 	return -1;
201 }
202 
203 static int
204 ssh2_capable(int remote_major, int remote_minor)
205 {
206 	switch (remote_major) {
207 	case 1:
208 		if (remote_minor == 99)
209 			return 1;
210 		break;
211 	case 2:
212 		return 1;
213 	default:
214 		break;
215 	}
216 	return 0;
217 }
218 
219 static void
220 keygrab_ssh2(con *c)
221 {
222 	const char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
223 	int r;
224 
225 	switch (c->c_keytype) {
226 	case KT_DSA:
227 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
228 		    "ssh-dss-cert-v01@openssh.com" : "ssh-dss";
229 		break;
230 	case KT_RSA:
231 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
232 		    "rsa-sha2-512-cert-v01@openssh.com,"
233 		    "rsa-sha2-256-cert-v01@openssh.com,"
234 		    "ssh-rsa-cert-v01@openssh.com" :
235 		    "rsa-sha2-512,"
236 		    "rsa-sha2-256,"
237 		    "ssh-rsa";
238 		break;
239 	case KT_ED25519:
240 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
241 		    "ssh-ed25519-cert-v01@openssh.com" : "ssh-ed25519";
242 		break;
243 	case KT_XMSS:
244 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
245 		    "ssh-xmss-cert-v01@openssh.com" : "ssh-xmss@openssh.com";
246 		break;
247 	case KT_ECDSA:
248 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
249 		    "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
250 		    "ecdsa-sha2-nistp384-cert-v01@openssh.com,"
251 		    "ecdsa-sha2-nistp521-cert-v01@openssh.com" :
252 		    "ecdsa-sha2-nistp256,"
253 		    "ecdsa-sha2-nistp384,"
254 		    "ecdsa-sha2-nistp521";
255 		break;
256 	case KT_ECDSA_SK:
257 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
258 		    "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com" :
259 		    "sk-ecdsa-sha2-nistp256@openssh.com";
260 		break;
261 	case KT_ED25519_SK:
262 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
263 		    "sk-ssh-ed25519-cert-v01@openssh.com" :
264 		    "sk-ssh-ed25519@openssh.com";
265 		break;
266 	default:
267 		fatal("unknown key type %d", c->c_keytype);
268 		break;
269 	}
270 	if ((r = kex_setup(c->c_ssh, __UNCONST(myproposal))) != 0) {
271 		free(c->c_ssh);
272 		fprintf(stderr, "kex_setup: %s\n", ssh_err(r));
273 		exit(1);
274 	}
275 #ifdef WITH_OPENSSL
276 	c->c_ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
277 	c->c_ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
278 	c->c_ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
279 	c->c_ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
280 	c->c_ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
281 	c->c_ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
282 	c->c_ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
283 	c->c_ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
284 #endif
285 	c->c_ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
286 	c->c_ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
287 	ssh_set_verify_host_key_callback(c->c_ssh, key_print_wrapper);
288 	/*
289 	 * do the key-exchange until an error occurs or until
290 	 * the key_print_wrapper() callback sets c_done.
291 	 */
292 	ssh_dispatch_run(c->c_ssh, DISPATCH_BLOCK, &c->c_done);
293 }
294 
295 static void
296 keyprint_one(const char *host, struct sshkey *key)
297 {
298 	char *hostport = NULL, *hashed = NULL;
299 	const char *known_host;
300 	int r = 0;
301 
302 	found_one = 1;
303 
304 	if (print_sshfp) {
305 		export_dns_rr(host, key, stdout, 0, hashalg);
306 		return;
307 	}
308 
309 	hostport = put_host_port(host, ssh_port);
310 	lowercase(hostport);
311 	if (hash_hosts && (hashed = host_hash(hostport, NULL, 0)) == NULL)
312 		fatal("host_hash failed");
313 	known_host = hash_hosts ? hashed : hostport;
314 	if (!get_cert)
315 		r = fprintf(stdout, "%s ", known_host);
316 	if (r >= 0 && sshkey_write(key, stdout) == 0)
317 		(void)fputs("\n", stdout);
318 	free(hashed);
319 	free(hostport);
320 }
321 
322 static void
323 keyprint(con *c, struct sshkey *key)
324 {
325 	char *hosts = c->c_output_name ? c->c_output_name : c->c_name;
326 	char *host, *ohosts;
327 
328 	if (key == NULL)
329 		return;
330 	if (get_cert || (!hash_hosts && ssh_port == SSH_DEFAULT_PORT)) {
331 		keyprint_one(hosts, key);
332 		return;
333 	}
334 	ohosts = hosts = xstrdup(hosts);
335 	while ((host = strsep(&hosts, ",")) != NULL)
336 		keyprint_one(host, key);
337 	free(ohosts);
338 }
339 
340 static int
341 tcpconnect(char *host)
342 {
343 	struct addrinfo hints, *ai, *aitop;
344 	char strport[NI_MAXSERV];
345 	int gaierr, s = -1;
346 
347 	snprintf(strport, sizeof strport, "%d", ssh_port);
348 	memset(&hints, 0, sizeof(hints));
349 	hints.ai_family = IPv4or6;
350 	hints.ai_socktype = SOCK_STREAM;
351 	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
352 		error("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
353 		return -1;
354 	}
355 	for (ai = aitop; ai; ai = ai->ai_next) {
356 		s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
357 		if (s == -1) {
358 			error("socket: %s", strerror(errno));
359 			continue;
360 		}
361 		if (set_nonblock(s) == -1)
362 			fatal_f("set_nonblock(%d)", s);
363 		if (connect(s, ai->ai_addr, ai->ai_addrlen) == -1 &&
364 		    errno != EINPROGRESS)
365 			error("connect (`%s'): %s", host, strerror(errno));
366 		else
367 			break;
368 		close(s);
369 		s = -1;
370 	}
371 	freeaddrinfo(aitop);
372 	return s;
373 }
374 
375 static int
376 conalloc(const char *iname, const char *oname, int keytype)
377 {
378 	char *namebase, *name, *namelist;
379 	int s;
380 
381 	namebase = namelist = xstrdup(iname);
382 
383 	do {
384 		name = xstrsep(&namelist, ",");
385 		if (!name) {
386 			free(namebase);
387 			return (-1);
388 		}
389 	} while ((s = tcpconnect(name)) < 0);
390 
391 	if (s >= maxfd)
392 		fatal("conalloc: fdno %d too high", s);
393 	if (fdcon[s].c_status)
394 		fatal("conalloc: attempt to reuse fdno %d", s);
395 
396 	debug3_f("oname %s kt %d", oname, keytype);
397 	fdcon[s].c_fd = s;
398 	fdcon[s].c_status = CS_CON;
399 	fdcon[s].c_namebase = namebase;
400 	fdcon[s].c_name = name;
401 	fdcon[s].c_namelist = namelist;
402 	fdcon[s].c_output_name = xstrdup(oname);
403 	fdcon[s].c_keytype = keytype;
404 	monotime_ts(&fdcon[s].c_ts);
405 	fdcon[s].c_ts.tv_sec += timeout;
406 	TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
407 	read_wait[s].fd = s;
408 	read_wait[s].events = POLLIN;
409 	ncon++;
410 	return (s);
411 }
412 
413 static void
414 confree(int s)
415 {
416 	if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
417 		fatal("confree: attempt to free bad fdno %d", s);
418 	free(fdcon[s].c_namebase);
419 	free(fdcon[s].c_output_name);
420 	fdcon[s].c_status = CS_UNUSED;
421 	fdcon[s].c_keytype = 0;
422 	if (fdcon[s].c_ssh) {
423 		ssh_packet_close(fdcon[s].c_ssh);
424 		free(fdcon[s].c_ssh);
425 		fdcon[s].c_ssh = NULL;
426 	} else
427 		close(s);
428 	TAILQ_REMOVE(&tq, &fdcon[s], c_link);
429 	read_wait[s].fd = -1;
430 	read_wait[s].events = 0;
431 	ncon--;
432 }
433 
434 static int
435 conrecycle(int s)
436 {
437 	con *c = &fdcon[s];
438 	int ret;
439 
440 	ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
441 	confree(s);
442 	return (ret);
443 }
444 
445 static void
446 congreet(int s)
447 {
448 	int n = 0, remote_major = 0, remote_minor = 0;
449 	char buf[256], *cp;
450 	char remote_version[sizeof buf];
451 	size_t bufsiz;
452 	con *c = &fdcon[s];
453 
454 	/* send client banner */
455 	n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
456 	    PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
457 	if (n < 0 || (size_t)n >= sizeof(buf)) {
458 		error("snprintf: buffer too small");
459 		confree(s);
460 		return;
461 	}
462 	if (atomicio(vwrite, s, buf, n) != (size_t)n) {
463 		error("write (%s): %s", c->c_name, strerror(errno));
464 		confree(s);
465 		return;
466 	}
467 
468 	/*
469 	 * Read the server banner as per RFC4253 section 4.2.  The "SSH-"
470 	 * protocol identification string may be preceded by an arbitrarily
471 	 * large banner which we must read and ignore.  Loop while reading
472 	 * newline-terminated lines until we have one starting with "SSH-".
473 	 * The ID string cannot be longer than 255 characters although the
474 	 * preceding banner lines may (in which case they'll be discarded
475 	 * in multiple iterations of the outer loop).
476 	 */
477 	for (;;) {
478 		memset(buf, '\0', sizeof(buf));
479 		bufsiz = sizeof(buf);
480 		cp = buf;
481 		while (bufsiz-- &&
482 		    (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
483 			if (*cp == '\r')
484 				*cp = '\n';
485 			cp++;
486 		}
487 		if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
488 			break;
489 	}
490 	if (n == 0) {
491 		switch (errno) {
492 		case EPIPE:
493 			error("%s: Connection closed by remote host", c->c_name);
494 			break;
495 		case ECONNREFUSED:
496 			break;
497 		default:
498 			error("read (%s): %s", c->c_name, strerror(errno));
499 			break;
500 		}
501 		conrecycle(s);
502 		return;
503 	}
504 	if (cp >= buf + sizeof(buf)) {
505 		error("%s: greeting exceeds allowable length", c->c_name);
506 		confree(s);
507 		return;
508 	}
509 	if (*cp != '\n' && *cp != '\r') {
510 		error("%s: bad greeting", c->c_name);
511 		confree(s);
512 		return;
513 	}
514 	*cp = '\0';
515 	if ((c->c_ssh = ssh_packet_set_connection(NULL, s, s)) == NULL)
516 		fatal("ssh_packet_set_connection failed");
517 	ssh_packet_set_timeout(c->c_ssh, timeout, 1);
518 	ssh_set_app_data(c->c_ssh, c);	/* back link */
519 	c->c_ssh->compat = 0;
520 	if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
521 	    &remote_major, &remote_minor, remote_version) == 3)
522 		compat_banner(c->c_ssh, remote_version);
523 	if (!ssh2_capable(remote_major, remote_minor)) {
524 		debug("%s doesn't support ssh2", c->c_name);
525 		confree(s);
526 		return;
527 	}
528 	if (!quiet) {
529 		fprintf(stdout, "%c %s:%d %s\n", print_sshfp ? ';' : '#',
530 		    c->c_name, ssh_port, chop(buf));
531 	}
532 	keygrab_ssh2(c);
533 	confree(s);
534 }
535 
536 static void
537 conread(int s)
538 {
539 	con *c = &fdcon[s];
540 
541 	if (c->c_status != CS_CON)
542 		fatal("conread: invalid status %d", c->c_status);
543 
544 	congreet(s);
545 }
546 
547 static void
548 conloop(void)
549 {
550 	struct timespec seltime, now;
551 	con *c;
552 	int i;
553 
554 	monotime_ts(&now);
555 	c = TAILQ_FIRST(&tq);
556 
557 	if (c && timespeccmp(&c->c_ts, &now, >))
558 		timespecsub(&c->c_ts, &now, &seltime);
559 	else
560 		timespecclear(&seltime);
561 
562 	while (ppoll(read_wait, maxfd, &seltime, NULL) == -1) {
563 		if (errno == EAGAIN || errno == EINTR)
564 			continue;
565 		error("poll error");
566 	}
567 
568 	for (i = 0; i < maxfd; i++) {
569 		if (read_wait[i].revents & (POLLHUP|POLLERR|POLLNVAL))
570 			confree(i);
571 		else if (read_wait[i].revents & (POLLIN|POLLHUP))
572 			conread(i);
573 	}
574 
575 	c = TAILQ_FIRST(&tq);
576 	while (c && timespeccmp(&c->c_ts, &now, <)) {
577 		int s = c->c_fd;
578 
579 		c = TAILQ_NEXT(c, c_link);
580 		conrecycle(s);
581 	}
582 }
583 
584 static void
585 do_one_host(char *host)
586 {
587 	char *name = strnnsep(&host, " \t\n");
588 	int j;
589 
590 	if (name == NULL)
591 		return;
592 	for (j = KT_MIN; j <= KT_MAX; j *= 2) {
593 		if (get_keytypes & j) {
594 			while (ncon >= MAXCON)
595 				conloop();
596 			conalloc(name, *host ? host : name, j);
597 		}
598 	}
599 }
600 
601 static void
602 do_host(char *host)
603 {
604 	char daddr[128];
605 	struct xaddr addr, end_addr;
606 	u_int masklen;
607 
608 	if (host == NULL)
609 		return;
610 	if (addr_pton_cidr(host, &addr, &masklen) != 0) {
611 		/* Assume argument is a hostname */
612 		do_one_host(host);
613 	} else {
614 		/* Argument is a CIDR range */
615 		debug("CIDR range %s", host);
616 		end_addr = addr;
617 		if (addr_host_to_all1s(&end_addr, masklen) != 0)
618 			goto badaddr;
619 		/*
620 		 * Note: we deliberately include the all-zero/ones addresses.
621 		 */
622 		for (;;) {
623 			if (addr_ntop(&addr, daddr, sizeof(daddr)) != 0) {
624  badaddr:
625 				error("Invalid address %s", host);
626 				return;
627 			}
628 			debug("CIDR expand: address %s", daddr);
629 			do_one_host(daddr);
630 			if (addr_cmp(&addr, &end_addr) == 0)
631 				break;
632 			addr_increment(&addr);
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 __dead static void
650 usage(void)
651 {
652 	fprintf(stderr,
653 	    "usage: ssh-keyscan [-46cDHqv] [-f file] [-O option] [-p port] [-T timeout]\n"
654 	    "                   [-t type] [host | addrlist namelist]\n");
655 	exit(1);
656 }
657 
658 int
659 main(int argc, char **argv)
660 {
661 	int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
662 	int opt, fopt_count = 0, j;
663 	char *tname, *cp, *line = NULL;
664 	size_t linesize = 0;
665 	FILE *fp;
666 
667 	extern int optind;
668 	extern char *optarg;
669 
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, "cDHqv46O:p: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 'q':
714 			quiet = 1;
715 			break;
716 		case 'f':
717 			if (strcmp(optarg, "-") == 0)
718 				optarg = NULL;
719 			argv[fopt_count++] = optarg;
720 			break;
721 		case 'O':
722 			/* Maybe other misc options in the future too */
723 			if (strncmp(optarg, "hashalg=", 8) != 0)
724 				fatal("Unsupported -O option");
725 			if ((hashalg = ssh_digest_alg_by_name(
726 			    optarg + 8)) == -1)
727 				fatal("Unsupported hash algorithm");
728 			break;
729 		case 't':
730 			get_keytypes = 0;
731 			tname = strtok(optarg, ",");
732 			while (tname) {
733 				int type = sshkey_type_from_name(tname);
734 
735 				switch (type) {
736 #ifdef WITH_DSA
737 				case KEY_DSA:
738 					get_keytypes |= KT_DSA;
739 					break;
740 #endif
741 				case KEY_ECDSA:
742 					get_keytypes |= KT_ECDSA;
743 					break;
744 				case KEY_RSA:
745 					get_keytypes |= KT_RSA;
746 					break;
747 				case KEY_ED25519:
748 					get_keytypes |= KT_ED25519;
749 					break;
750 				case KEY_XMSS:
751 					get_keytypes |= KT_XMSS;
752 					break;
753 				case KEY_ED25519_SK:
754 					get_keytypes |= KT_ED25519_SK;
755 					break;
756 				case KEY_ECDSA_SK:
757 					get_keytypes |= KT_ECDSA_SK;
758 					break;
759 				case KEY_UNSPEC:
760 				default:
761 					fatal("Unknown key type \"%s\"", tname);
762 				}
763 				tname = strtok(NULL, ",");
764 			}
765 			break;
766 		case '4':
767 			IPv4or6 = AF_INET;
768 			break;
769 		case '6':
770 			IPv4or6 = AF_INET6;
771 			break;
772 		default:
773 			usage();
774 		}
775 	}
776 	if (optind == argc && !fopt_count)
777 		usage();
778 
779 	log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
780 
781 	maxfd = fdlim_get(1);
782 	if (maxfd < 0)
783 		fatal("%s: fdlim_get: bad value", __progname);
784 	if (maxfd > MAXMAXFD)
785 		maxfd = MAXMAXFD;
786 	if (MAXCON <= 0)
787 		fatal("%s: not enough file descriptors", __progname);
788 	if (maxfd > fdlim_get(0))
789 		fdlim_set(maxfd);
790 	fdcon = xcalloc(maxfd, sizeof(con));
791 	read_wait = xcalloc(maxfd, sizeof(struct pollfd));
792 	for (j = 0; j < maxfd; j++)
793 		read_wait[j].fd = -1;
794 
795 	for (j = 0; j < fopt_count; j++) {
796 		if (argv[j] == NULL)
797 			fp = stdin;
798 		else if ((fp = fopen(argv[j], "r")) == NULL)
799 			fatal("%s: %s: %s", __progname,
800 			    fp == stdin ? "<stdin>" : argv[j], strerror(errno));
801 
802 		while (getline(&line, &linesize, fp) != -1) {
803 			/* Chomp off trailing whitespace and comments */
804 			if ((cp = strchr(line, '#')) == NULL)
805 				cp = line + strlen(line) - 1;
806 			while (cp >= line) {
807 				if (*cp == ' ' || *cp == '\t' ||
808 				    *cp == '\n' || *cp == '#')
809 					*cp-- = '\0';
810 				else
811 					break;
812 			}
813 
814 			/* Skip empty lines */
815 			if (*line == '\0')
816 				continue;
817 
818 			do_host(line);
819 		}
820 
821 		if (ferror(fp))
822 			fatal("%s: %s: %s", __progname,
823 			    fp == stdin ? "<stdin>" : argv[j], strerror(errno));
824 
825 		if (fp != stdin)
826 			fclose(fp);
827 	}
828 	free(line);
829 
830 	while (optind < argc)
831 		do_host(argv[optind++]);
832 
833 	while (ncon > 0)
834 		conloop();
835 
836 	return found_one ? 0 : 1;
837 }
838