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