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