xref: /netbsd-src/crypto/external/bsd/openssh/dist/ssh-keyscan.c (revision afab4e300d3a9fb07dd8c80daf53d0feb3345706)
1 /*	$NetBSD: ssh-keyscan.c,v 1.30 2022/10/05 22:39:36 christos Exp $	*/
2 /* $OpenBSD: ssh-keyscan.c,v 1.146 2022/08/19 04:02:46 dtucker 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.30 2022/10/05 22:39:36 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 <netdb.h>
28 #include <stdarg.h>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <poll.h>
32 #include <signal.h>
33 #include <string.h>
34 #include <unistd.h>
35 
36 #include "xmalloc.h"
37 #include "ssh.h"
38 #include "sshbuf.h"
39 #include "sshkey.h"
40 #include "cipher.h"
41 #include "kex.h"
42 #include "compat.h"
43 #include "myproposal.h"
44 #include "packet.h"
45 #include "dispatch.h"
46 #include "log.h"
47 #include "atomicio.h"
48 #include "misc.h"
49 #include "hostfile.h"
50 #include "ssherr.h"
51 #include "ssh_api.h"
52 #include "dns.h"
53 
54 /* Flag indicating whether IPv4 or IPv6.  This can be set on the command line.
55    Default value is AF_UNSPEC means both IPv4 and IPv6. */
56 int IPv4or6 = AF_UNSPEC;
57 
58 int ssh_port = SSH_DEFAULT_PORT;
59 
60 #define KT_DSA		(1)
61 #define KT_RSA		(1<<1)
62 #define KT_ECDSA	(1<<2)
63 #define KT_ED25519	(1<<3)
64 #define KT_XMSS		(1<<4)
65 #define KT_ECDSA_SK	(1<<5)
66 #define KT_ED25519_SK	(1<<6)
67 
68 #define KT_MIN		KT_DSA
69 #define KT_MAX		KT_ED25519_SK
70 
71 int get_cert = 0;
72 int get_keytypes = KT_RSA|KT_ECDSA|KT_ED25519|KT_ECDSA_SK|KT_ED25519_SK;
73 
74 int hash_hosts = 0;		/* Hash hostname on output */
75 
76 int print_sshfp = 0;		/* Print SSHFP records instead of known_hosts */
77 
78 int found_one = 0;		/* Successfully found a key */
79 
80 #define MAXMAXFD 256
81 
82 /* The number of seconds after which to give up on a TCP connection */
83 int timeout = 5;
84 
85 int maxfd;
86 #define MAXCON (maxfd - 10)
87 
88 extern char *__progname;
89 struct pollfd *read_wait;
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 timespec c_ts;	/* 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 	struct rlimit rlfd;
127 
128 	if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
129 		return (-1);
130 	if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
131 		return sysconf(_SC_OPEN_MAX);
132 	else
133 		return hard ? rlfd.rlim_max : rlfd.rlim_cur;
134 }
135 
136 static int
137 fdlim_set(int lim)
138 {
139 	struct rlimit rlfd;
140 
141 	if (lim <= 0)
142 		return (-1);
143 	if (getrlimit(RLIMIT_NOFILE, &rlfd) == -1)
144 		return (-1);
145 	rlfd.rlim_cur = lim;
146 	if (setrlimit(RLIMIT_NOFILE, &rlfd) == -1)
147 		return (-1);
148 	return (0);
149 }
150 
151 /*
152  * This is an strsep function that returns a null field for adjacent
153  * separators.  This is the same as the 4.4BSD strsep, but different from the
154  * one in the GNU libc.
155  */
156 static char *
157 xstrsep(char **str, const char *delim)
158 {
159 	char *s, *e;
160 
161 	if (!**str)
162 		return (NULL);
163 
164 	s = *str;
165 	e = s + strcspn(s, delim);
166 
167 	if (*e != '\0')
168 		*e++ = '\0';
169 	*str = e;
170 
171 	return (s);
172 }
173 
174 /*
175  * Get the next non-null token (like GNU strsep).  Strsep() will return a
176  * null token for two adjacent separators, so we may have to loop.
177  */
178 static char *
179 strnnsep(char **stringp, const char *delim)
180 {
181 	char *tok;
182 
183 	do {
184 		tok = xstrsep(stringp, delim);
185 	} while (tok && *tok == '\0');
186 	return (tok);
187 }
188 
189 
190 static int
191 key_print_wrapper(struct sshkey *hostkey, struct ssh *ssh)
192 {
193 	con *c;
194 
195 	if ((c = ssh_get_app_data(ssh)) != NULL)
196 		keyprint(c, hostkey);
197 	/* always abort key exchange */
198 	return -1;
199 }
200 
201 static int
202 ssh2_capable(int remote_major, int remote_minor)
203 {
204 	switch (remote_major) {
205 	case 1:
206 		if (remote_minor == 99)
207 			return 1;
208 		break;
209 	case 2:
210 		return 1;
211 	default:
212 		break;
213 	}
214 	return 0;
215 }
216 
217 static void
218 keygrab_ssh2(con *c)
219 {
220 	const char *myproposal[PROPOSAL_MAX] = { KEX_CLIENT };
221 	int r;
222 
223 	switch (c->c_keytype) {
224 	case KT_DSA:
225 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
226 		    "ssh-dss-cert-v01@openssh.com" : "ssh-dss";
227 		break;
228 	case KT_RSA:
229 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
230 		    "rsa-sha2-512-cert-v01@openssh.com,"
231 		    "rsa-sha2-256-cert-v01@openssh.com,"
232 		    "ssh-rsa-cert-v01@openssh.com" :
233 		    "rsa-sha2-512,"
234 		    "rsa-sha2-256,"
235 		    "ssh-rsa";
236 		break;
237 	case KT_ED25519:
238 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
239 		    "ssh-ed25519-cert-v01@openssh.com" : "ssh-ed25519";
240 		break;
241 	case KT_XMSS:
242 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
243 		    "ssh-xmss-cert-v01@openssh.com" : "ssh-xmss@openssh.com";
244 		break;
245 	case KT_ECDSA:
246 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
247 		    "ecdsa-sha2-nistp256-cert-v01@openssh.com,"
248 		    "ecdsa-sha2-nistp384-cert-v01@openssh.com,"
249 		    "ecdsa-sha2-nistp521-cert-v01@openssh.com" :
250 		    "ecdsa-sha2-nistp256,"
251 		    "ecdsa-sha2-nistp384,"
252 		    "ecdsa-sha2-nistp521";
253 		break;
254 	case KT_ECDSA_SK:
255 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
256 		    "sk-ecdsa-sha2-nistp256-cert-v01@openssh.com" :
257 		    "sk-ecdsa-sha2-nistp256@openssh.com";
258 		break;
259 	case KT_ED25519_SK:
260 		myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = get_cert ?
261 		    "sk-ssh-ed25519-cert-v01@openssh.com" :
262 		    "sk-ssh-ed25519@openssh.com";
263 		break;
264 	default:
265 		fatal("unknown key type %d", c->c_keytype);
266 		break;
267 	}
268 	if ((r = kex_setup(c->c_ssh, myproposal)) != 0) {
269 		free(c->c_ssh);
270 		fprintf(stderr, "kex_setup: %s\n", ssh_err(r));
271 		exit(1);
272 	}
273 #ifdef WITH_OPENSSL
274 	c->c_ssh->kex->kex[KEX_DH_GRP1_SHA1] = kex_gen_client;
275 	c->c_ssh->kex->kex[KEX_DH_GRP14_SHA1] = kex_gen_client;
276 	c->c_ssh->kex->kex[KEX_DH_GRP14_SHA256] = kex_gen_client;
277 	c->c_ssh->kex->kex[KEX_DH_GRP16_SHA512] = kex_gen_client;
278 	c->c_ssh->kex->kex[KEX_DH_GRP18_SHA512] = kex_gen_client;
279 	c->c_ssh->kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
280 	c->c_ssh->kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
281 	c->c_ssh->kex->kex[KEX_ECDH_SHA2] = kex_gen_client;
282 #endif
283 	c->c_ssh->kex->kex[KEX_C25519_SHA256] = kex_gen_client;
284 	c->c_ssh->kex->kex[KEX_KEM_SNTRUP761X25519_SHA512] = kex_gen_client;
285 	ssh_set_verify_host_key_callback(c->c_ssh, key_print_wrapper);
286 	/*
287 	 * do the key-exchange until an error occurs or until
288 	 * the key_print_wrapper() callback sets c_done.
289 	 */
290 	ssh_dispatch_run(c->c_ssh, DISPATCH_BLOCK, &c->c_done);
291 }
292 
293 static void
294 keyprint_one(const char *host, struct sshkey *key)
295 {
296 	char *hostport = NULL, *hashed = NULL;
297 	const char *known_host;
298 
299 	found_one = 1;
300 
301 	if (print_sshfp) {
302 		export_dns_rr(host, key, stdout, 0);
303 		return;
304 	}
305 
306 	hostport = put_host_port(host, ssh_port);
307 	lowercase(hostport);
308 	if (hash_hosts && (hashed = host_hash(hostport, NULL, 0)) == NULL)
309 		fatal("host_hash failed");
310 	known_host = hash_hosts ? hashed : hostport;
311 	if (!get_cert)
312 		fprintf(stdout, "%s ", known_host);
313 	sshkey_write(key, stdout);
314 	fputs("\n", stdout);
315 	free(hashed);
316 	free(hostport);
317 }
318 
319 static void
320 keyprint(con *c, struct sshkey *key)
321 {
322 	char *hosts = c->c_output_name ? c->c_output_name : c->c_name;
323 	char *host, *ohosts;
324 
325 	if (key == NULL)
326 		return;
327 	if (get_cert || (!hash_hosts && ssh_port == SSH_DEFAULT_PORT)) {
328 		keyprint_one(hosts, key);
329 		return;
330 	}
331 	ohosts = hosts = xstrdup(hosts);
332 	while ((host = strsep(&hosts, ",")) != NULL)
333 		keyprint_one(host, key);
334 	free(ohosts);
335 }
336 
337 static int
338 tcpconnect(char *host)
339 {
340 	struct addrinfo hints, *ai, *aitop;
341 	char strport[NI_MAXSERV];
342 	int gaierr, s = -1;
343 
344 	snprintf(strport, sizeof strport, "%d", ssh_port);
345 	memset(&hints, 0, sizeof(hints));
346 	hints.ai_family = IPv4or6;
347 	hints.ai_socktype = SOCK_STREAM;
348 	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
349 		error("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
350 		return -1;
351 	}
352 	for (ai = aitop; ai; ai = ai->ai_next) {
353 		s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
354 		if (s == -1) {
355 			error("socket: %s", strerror(errno));
356 			continue;
357 		}
358 		if (set_nonblock(s) == -1)
359 			fatal_f("set_nonblock(%d)", s);
360 		if (connect(s, ai->ai_addr, ai->ai_addrlen) == -1 &&
361 		    errno != EINPROGRESS)
362 			error("connect (`%s'): %s", host, strerror(errno));
363 		else
364 			break;
365 		close(s);
366 		s = -1;
367 	}
368 	freeaddrinfo(aitop);
369 	return s;
370 }
371 
372 static int
373 conalloc(char *iname, char *oname, int keytype)
374 {
375 	char *namebase, *name, *namelist;
376 	int s;
377 
378 	namebase = namelist = xstrdup(iname);
379 
380 	do {
381 		name = xstrsep(&namelist, ",");
382 		if (!name) {
383 			free(namebase);
384 			return (-1);
385 		}
386 	} while ((s = tcpconnect(name)) < 0);
387 
388 	if (s >= maxfd)
389 		fatal("conalloc: fdno %d too high", s);
390 	if (fdcon[s].c_status)
391 		fatal("conalloc: attempt to reuse fdno %d", s);
392 
393 	debug3_f("oname %s kt %d", oname, keytype);
394 	fdcon[s].c_fd = s;
395 	fdcon[s].c_status = CS_CON;
396 	fdcon[s].c_namebase = namebase;
397 	fdcon[s].c_name = name;
398 	fdcon[s].c_namelist = namelist;
399 	fdcon[s].c_output_name = xstrdup(oname);
400 	fdcon[s].c_data = (char *) &fdcon[s].c_plen;
401 	fdcon[s].c_len = 4;
402 	fdcon[s].c_off = 0;
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 	if (fdcon[s].c_status == CS_KEYS)
421 		free(fdcon[s].c_data);
422 	fdcon[s].c_status = CS_UNUSED;
423 	fdcon[s].c_keytype = 0;
424 	if (fdcon[s].c_ssh) {
425 		ssh_packet_close(fdcon[s].c_ssh);
426 		free(fdcon[s].c_ssh);
427 		fdcon[s].c_ssh = NULL;
428 	} else
429 		close(s);
430 	TAILQ_REMOVE(&tq, &fdcon[s], c_link);
431 	read_wait[s].fd = -1;
432 	read_wait[s].events = 0;
433 	ncon--;
434 }
435 
436 static void
437 contouch(int s)
438 {
439 	TAILQ_REMOVE(&tq, &fdcon[s], c_link);
440 	monotime_ts(&fdcon[s].c_ts);
441 	fdcon[s].c_ts.tv_sec += timeout;
442 	TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
443 }
444 
445 static int
446 conrecycle(int s)
447 {
448 	con *c = &fdcon[s];
449 	int ret;
450 
451 	ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
452 	confree(s);
453 	return (ret);
454 }
455 
456 static void
457 congreet(int s)
458 {
459 	int n = 0, remote_major = 0, remote_minor = 0;
460 	char buf[256], *cp;
461 	char remote_version[sizeof buf];
462 	size_t bufsiz;
463 	con *c = &fdcon[s];
464 
465 	/* send client banner */
466 	n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
467 	    PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
468 	if (n < 0 || (size_t)n >= sizeof(buf)) {
469 		error("snprintf: buffer too small");
470 		confree(s);
471 		return;
472 	}
473 	if (atomicio(vwrite, s, buf, n) != (size_t)n) {
474 		error("write (%s): %s", c->c_name, strerror(errno));
475 		confree(s);
476 		return;
477 	}
478 
479 	/*
480 	 * Read the server banner as per RFC4253 section 4.2.  The "SSH-"
481 	 * protocol identification string may be preceeded by an arbitarily
482 	 * large banner which we must read and ignore.  Loop while reading
483 	 * newline-terminated lines until we have one starting with "SSH-".
484 	 * The ID string cannot be longer than 255 characters although the
485 	 * preceeding banner lines may (in which case they'll be discarded
486 	 * in multiple iterations of the outer loop).
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 >= buf + sizeof(buf)) {
516 		error("%s: greeting exceeds allowable length", c->c_name);
517 		confree(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)
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 __dead 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 	TAILQ_INIT(&tq);
669 
670 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
671 	sanitise_stdfd();
672 
673 	if (argc <= 1)
674 		usage();
675 
676 	while ((opt = getopt(argc, argv, "cDHv46p:T:t:f:")) != -1) {
677 		switch (opt) {
678 		case 'H':
679 			hash_hosts = 1;
680 			break;
681 		case 'c':
682 			get_cert = 1;
683 			break;
684 		case 'D':
685 			print_sshfp = 1;
686 			break;
687 		case 'p':
688 			ssh_port = a2port(optarg);
689 			if (ssh_port <= 0) {
690 				fprintf(stderr, "Bad port '%s'\n", optarg);
691 				exit(1);
692 			}
693 			break;
694 		case 'T':
695 			timeout = convtime(optarg);
696 			if (timeout == -1 || timeout == 0) {
697 				fprintf(stderr, "Bad timeout '%s'\n", optarg);
698 				usage();
699 			}
700 			break;
701 		case 'v':
702 			if (!debug_flag) {
703 				debug_flag = 1;
704 				log_level = SYSLOG_LEVEL_DEBUG1;
705 			}
706 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
707 				log_level++;
708 			else
709 				fatal("Too high debugging level.");
710 			break;
711 		case 'f':
712 			if (strcmp(optarg, "-") == 0)
713 				optarg = NULL;
714 			argv[fopt_count++] = optarg;
715 			break;
716 		case 't':
717 			get_keytypes = 0;
718 			tname = strtok(optarg, ",");
719 			while (tname) {
720 				int type = sshkey_type_from_name(tname);
721 
722 				switch (type) {
723 				case KEY_DSA:
724 					get_keytypes |= KT_DSA;
725 					break;
726 				case KEY_ECDSA:
727 					get_keytypes |= KT_ECDSA;
728 					break;
729 				case KEY_RSA:
730 					get_keytypes |= KT_RSA;
731 					break;
732 				case KEY_ED25519:
733 					get_keytypes |= KT_ED25519;
734 					break;
735 				case KEY_XMSS:
736 					get_keytypes |= KT_XMSS;
737 					break;
738 				case KEY_ED25519_SK:
739 					get_keytypes |= KT_ED25519_SK;
740 					break;
741 				case KEY_ECDSA_SK:
742 					get_keytypes |= KT_ECDSA_SK;
743 					break;
744 				case KEY_UNSPEC:
745 				default:
746 					fatal("Unknown key type \"%s\"", tname);
747 				}
748 				tname = strtok(NULL, ",");
749 			}
750 			break;
751 		case '4':
752 			IPv4or6 = AF_INET;
753 			break;
754 		case '6':
755 			IPv4or6 = AF_INET6;
756 			break;
757 		case '?':
758 		default:
759 			usage();
760 		}
761 	}
762 	if (optind == argc && !fopt_count)
763 		usage();
764 
765 	log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
766 
767 	maxfd = fdlim_get(1);
768 	if (maxfd < 0)
769 		fatal("%s: fdlim_get: bad value", __progname);
770 	if (maxfd > MAXMAXFD)
771 		maxfd = MAXMAXFD;
772 	if (MAXCON <= 0)
773 		fatal("%s: not enough file descriptors", __progname);
774 	if (maxfd > fdlim_get(0))
775 		fdlim_set(maxfd);
776 	fdcon = xcalloc(maxfd, sizeof(con));
777 	read_wait = xcalloc(maxfd, sizeof(struct pollfd));
778 	for (j = 0; j < maxfd; j++)
779 		read_wait[j].fd = -1;
780 
781 	for (j = 0; j < fopt_count; j++) {
782 		if (argv[j] == NULL)
783 			fp = stdin;
784 		else if ((fp = fopen(argv[j], "r")) == NULL)
785 			fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
786 
787 		while (getline(&line, &linesize, fp) != -1) {
788 			/* Chomp off trailing whitespace and comments */
789 			if ((cp = strchr(line, '#')) == NULL)
790 				cp = line + strlen(line) - 1;
791 			while (cp >= line) {
792 				if (*cp == ' ' || *cp == '\t' ||
793 				    *cp == '\n' || *cp == '#')
794 					*cp-- = '\0';
795 				else
796 					break;
797 			}
798 
799 			/* Skip empty lines */
800 			if (*line == '\0')
801 				continue;
802 
803 			do_host(line);
804 		}
805 
806 		if (ferror(fp))
807 			fatal("%s: %s: %s", __progname, argv[j], strerror(errno));
808 
809 		fclose(fp);
810 	}
811 	free(line);
812 
813 	while (optind < argc)
814 		do_host(argv[optind++]);
815 
816 	while (ncon > 0)
817 		conloop();
818 
819 	return found_one ? 0 : 1;
820 }
821