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