xref: /freebsd/crypto/openssh/ssh-keyscan.c (revision 3d9fd9fcb432750f3716b28f6ccb0104cd9d351a)
1 /* $OpenBSD: ssh-keyscan.c,v 1.161 2024/09/09 02:39:57 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
fdlim_get(int hard)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
fdlim_set(int lim)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 *
xstrsep(char ** str,const char * delim)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 *
strnnsep(char ** stringp,char * delim)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
key_print_wrapper(struct sshkey * hostkey,struct ssh * ssh)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
ssh2_capable(int remote_major,int remote_minor)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
keygrab_ssh2(con * c)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 	c->c_ssh->kex->kex[KEX_KEM_MLKEM768X25519_SHA256] = kex_gen_client;
307 	ssh_set_verify_host_key_callback(c->c_ssh, key_print_wrapper);
308 	/*
309 	 * do the key-exchange until an error occurs or until
310 	 * the key_print_wrapper() callback sets c_done.
311 	 */
312 	ssh_dispatch_run(c->c_ssh, DISPATCH_BLOCK, &c->c_done);
313 }
314 
315 static void
keyprint_one(const char * host,struct sshkey * key)316 keyprint_one(const char *host, struct sshkey *key)
317 {
318 	char *hostport = NULL, *hashed = NULL;
319 	const char *known_host;
320 	int r = 0;
321 
322 	found_one = 1;
323 
324 	if (print_sshfp) {
325 		export_dns_rr(host, key, stdout, 0, hashalg);
326 		return;
327 	}
328 
329 	hostport = put_host_port(host, ssh_port);
330 	lowercase(hostport);
331 	if (hash_hosts && (hashed = host_hash(hostport, NULL, 0)) == NULL)
332 		fatal("host_hash failed");
333 	known_host = hash_hosts ? hashed : hostport;
334 	if (!get_cert)
335 		r = fprintf(stdout, "%s ", known_host);
336 	if (r >= 0 && sshkey_write(key, stdout) == 0)
337 		(void)fputs("\n", stdout);
338 	free(hashed);
339 	free(hostport);
340 }
341 
342 static void
keyprint(con * c,struct sshkey * key)343 keyprint(con *c, struct sshkey *key)
344 {
345 	char *hosts = c->c_output_name ? c->c_output_name : c->c_name;
346 	char *host, *ohosts;
347 
348 	if (key == NULL)
349 		return;
350 	if (get_cert || (!hash_hosts && ssh_port == SSH_DEFAULT_PORT)) {
351 		keyprint_one(hosts, key);
352 		return;
353 	}
354 	ohosts = hosts = xstrdup(hosts);
355 	while ((host = strsep(&hosts, ",")) != NULL)
356 		keyprint_one(host, key);
357 	free(ohosts);
358 }
359 
360 static int
tcpconnect(char * host)361 tcpconnect(char *host)
362 {
363 	struct addrinfo hints, *ai, *aitop;
364 	char strport[NI_MAXSERV];
365 	int gaierr, s = -1;
366 
367 	snprintf(strport, sizeof strport, "%d", ssh_port);
368 	memset(&hints, 0, sizeof(hints));
369 	hints.ai_family = IPv4or6;
370 	hints.ai_socktype = SOCK_STREAM;
371 	if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) {
372 		error("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr));
373 		return -1;
374 	}
375 	for (ai = aitop; ai; ai = ai->ai_next) {
376 		s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
377 		if (s == -1) {
378 			error("socket: %s", strerror(errno));
379 			continue;
380 		}
381 		if (set_nonblock(s) == -1)
382 			fatal_f("set_nonblock(%d)", s);
383 		if (connect(s, ai->ai_addr, ai->ai_addrlen) == -1 &&
384 		    errno != EINPROGRESS)
385 			error("connect (`%s'): %s", host, strerror(errno));
386 		else
387 			break;
388 		close(s);
389 		s = -1;
390 	}
391 	freeaddrinfo(aitop);
392 	return s;
393 }
394 
395 static int
conalloc(const char * iname,const char * oname,int keytype)396 conalloc(const char *iname, const char *oname, int keytype)
397 {
398 	char *namebase, *name, *namelist;
399 	int s;
400 
401 	namebase = namelist = xstrdup(iname);
402 
403 	do {
404 		name = xstrsep(&namelist, ",");
405 		if (!name) {
406 			free(namebase);
407 			return (-1);
408 		}
409 	} while ((s = tcpconnect(name)) < 0);
410 
411 	if (s >= maxfd)
412 		fatal("conalloc: fdno %d too high", s);
413 	if (fdcon[s].c_status)
414 		fatal("conalloc: attempt to reuse fdno %d", s);
415 
416 	debug3_f("oname %s kt %d", oname, keytype);
417 	fdcon[s].c_fd = s;
418 	fdcon[s].c_status = CS_CON;
419 	fdcon[s].c_namebase = namebase;
420 	fdcon[s].c_name = name;
421 	fdcon[s].c_namelist = namelist;
422 	fdcon[s].c_output_name = xstrdup(oname);
423 	fdcon[s].c_keytype = keytype;
424 	monotime_ts(&fdcon[s].c_ts);
425 	fdcon[s].c_ts.tv_sec += timeout;
426 	TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
427 	read_wait[s].fd = s;
428 	read_wait[s].events = POLLIN;
429 	ncon++;
430 	return (s);
431 }
432 
433 static void
confree(int s)434 confree(int s)
435 {
436 	if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
437 		fatal("confree: attempt to free bad fdno %d", s);
438 	free(fdcon[s].c_namebase);
439 	free(fdcon[s].c_output_name);
440 	fdcon[s].c_status = CS_UNUSED;
441 	fdcon[s].c_keytype = 0;
442 	if (fdcon[s].c_ssh) {
443 		ssh_packet_close(fdcon[s].c_ssh);
444 		free(fdcon[s].c_ssh);
445 		fdcon[s].c_ssh = NULL;
446 	} else
447 		close(s);
448 	TAILQ_REMOVE(&tq, &fdcon[s], c_link);
449 	read_wait[s].fd = -1;
450 	read_wait[s].events = 0;
451 	ncon--;
452 }
453 
454 static int
conrecycle(int s)455 conrecycle(int s)
456 {
457 	con *c = &fdcon[s];
458 	int ret;
459 
460 	ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
461 	confree(s);
462 	return (ret);
463 }
464 
465 static void
congreet(int s)466 congreet(int s)
467 {
468 	int n = 0, remote_major = 0, remote_minor = 0;
469 	char buf[256], *cp;
470 	char remote_version[sizeof buf];
471 	size_t bufsiz;
472 	con *c = &fdcon[s];
473 
474 	/* send client banner */
475 	n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
476 	    PROTOCOL_MAJOR_2, PROTOCOL_MINOR_2);
477 	if (n < 0 || (size_t)n >= sizeof(buf)) {
478 		error("snprintf: buffer too small");
479 		confree(s);
480 		return;
481 	}
482 	if (atomicio(vwrite, s, buf, n) != (size_t)n) {
483 		error("write (%s): %s", c->c_name, strerror(errno));
484 		confree(s);
485 		return;
486 	}
487 
488 	/*
489 	 * Read the server banner as per RFC4253 section 4.2.  The "SSH-"
490 	 * protocol identification string may be preceded by an arbitrarily
491 	 * large banner which we must read and ignore.  Loop while reading
492 	 * newline-terminated lines until we have one starting with "SSH-".
493 	 * The ID string cannot be longer than 255 characters although the
494 	 * preceding banner lines may (in which case they'll be discarded
495 	 * in multiple iterations of the outer loop).
496 	 */
497 	for (;;) {
498 		memset(buf, '\0', sizeof(buf));
499 		bufsiz = sizeof(buf);
500 		cp = buf;
501 		while (bufsiz-- &&
502 		    (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
503 			if (*cp == '\r')
504 				*cp = '\n';
505 			cp++;
506 		}
507 		if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
508 			break;
509 	}
510 	if (n == 0) {
511 		switch (errno) {
512 		case EPIPE:
513 			error("%s: Connection closed by remote host", c->c_name);
514 			break;
515 		case ECONNREFUSED:
516 			break;
517 		default:
518 			error("read (%s): %s", c->c_name, strerror(errno));
519 			break;
520 		}
521 		conrecycle(s);
522 		return;
523 	}
524 	if (cp >= buf + sizeof(buf)) {
525 		error("%s: greeting exceeds allowable length", c->c_name);
526 		confree(s);
527 		return;
528 	}
529 	if (*cp != '\n' && *cp != '\r') {
530 		error("%s: bad greeting", c->c_name);
531 		confree(s);
532 		return;
533 	}
534 	*cp = '\0';
535 	if ((c->c_ssh = ssh_packet_set_connection(NULL, s, s)) == NULL)
536 		fatal("ssh_packet_set_connection failed");
537 	ssh_packet_set_timeout(c->c_ssh, timeout, 1);
538 	ssh_set_app_data(c->c_ssh, c);	/* back link */
539 	c->c_ssh->compat = 0;
540 	if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
541 	    &remote_major, &remote_minor, remote_version) == 3)
542 		compat_banner(c->c_ssh, remote_version);
543 	if (!ssh2_capable(remote_major, remote_minor)) {
544 		debug("%s doesn't support ssh2", c->c_name);
545 		confree(s);
546 		return;
547 	}
548 	if (!quiet) {
549 		fprintf(stdout, "%c %s:%d %s\n", print_sshfp ? ';' : '#',
550 		    c->c_name, ssh_port, chop(buf));
551 	}
552 	keygrab_ssh2(c);
553 	confree(s);
554 }
555 
556 static void
conread(int s)557 conread(int s)
558 {
559 	con *c = &fdcon[s];
560 
561 	if (c->c_status != CS_CON)
562 		fatal("conread: invalid status %d", c->c_status);
563 
564 	congreet(s);
565 }
566 
567 static void
conloop(void)568 conloop(void)
569 {
570 	struct timespec seltime, now;
571 	con *c;
572 	int i;
573 
574 	monotime_ts(&now);
575 	c = TAILQ_FIRST(&tq);
576 
577 	if (c && timespeccmp(&c->c_ts, &now, >))
578 		timespecsub(&c->c_ts, &now, &seltime);
579 	else
580 		timespecclear(&seltime);
581 
582 	while (ppoll(read_wait, maxfd, &seltime, NULL) == -1) {
583 		if (errno == EAGAIN || errno == EINTR || errno == EWOULDBLOCK)
584 			continue;
585 		error("poll error");
586 	}
587 
588 	for (i = 0; i < maxfd; i++) {
589 		if (read_wait[i].revents & (POLLHUP|POLLERR|POLLNVAL))
590 			confree(i);
591 		else if (read_wait[i].revents & (POLLIN|POLLHUP))
592 			conread(i);
593 	}
594 
595 	c = TAILQ_FIRST(&tq);
596 	while (c && timespeccmp(&c->c_ts, &now, <)) {
597 		int s = c->c_fd;
598 
599 		c = TAILQ_NEXT(c, c_link);
600 		conrecycle(s);
601 	}
602 }
603 
604 static void
do_one_host(char * host)605 do_one_host(char *host)
606 {
607 	char *name = strnnsep(&host, " \t\n");
608 	int j;
609 
610 	if (name == NULL)
611 		return;
612 	for (j = KT_MIN; j <= KT_MAX; j *= 2) {
613 		if (get_keytypes & j) {
614 			while (ncon >= MAXCON)
615 				conloop();
616 			conalloc(name, *host ? host : name, j);
617 		}
618 	}
619 }
620 
621 static void
do_host(char * host)622 do_host(char *host)
623 {
624 	char daddr[128];
625 	struct xaddr addr, end_addr;
626 	u_int masklen;
627 
628 	if (host == NULL)
629 		return;
630 	if (addr_pton_cidr(host, &addr, &masklen) != 0) {
631 		/* Assume argument is a hostname */
632 		do_one_host(host);
633 	} else {
634 		/* Argument is a CIDR range */
635 		debug("CIDR range %s", host);
636 		end_addr = addr;
637 		if (addr_host_to_all1s(&end_addr, masklen) != 0)
638 			goto badaddr;
639 		/*
640 		 * Note: we deliberately include the all-zero/ones addresses.
641 		 */
642 		for (;;) {
643 			if (addr_ntop(&addr, daddr, sizeof(daddr)) != 0) {
644  badaddr:
645 				error("Invalid address %s", host);
646 				return;
647 			}
648 			debug("CIDR expand: address %s", daddr);
649 			do_one_host(daddr);
650 			if (addr_cmp(&addr, &end_addr) == 0)
651 				break;
652 			addr_increment(&addr);
653 		};
654 	}
655 }
656 
657 void
sshfatal(const char * file,const char * func,int line,int showfunc,LogLevel level,const char * suffix,const char * fmt,...)658 sshfatal(const char *file, const char *func, int line, int showfunc,
659     LogLevel level, const char *suffix, const char *fmt, ...)
660 {
661 	va_list args;
662 
663 	va_start(args, fmt);
664 	sshlogv(file, func, line, showfunc, level, suffix, fmt, args);
665 	va_end(args);
666 	cleanup_exit(255);
667 }
668 
669 static void
usage(void)670 usage(void)
671 {
672 	fprintf(stderr,
673 	    "usage: ssh-keyscan [-46cDHqv] [-f file] [-O option] [-p port] [-T timeout]\n"
674 	    "                   [-t type] [host | addrlist namelist]\n");
675 	exit(1);
676 }
677 
678 int
main(int argc,char ** argv)679 main(int argc, char **argv)
680 {
681 	int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
682 	int opt, fopt_count = 0, j;
683 	char *tname, *cp, *line = NULL;
684 	size_t linesize = 0;
685 	FILE *fp;
686 
687 	extern int optind;
688 	extern char *optarg;
689 
690 	__progname = ssh_get_progname(argv[0]);
691 	seed_rng();
692 	TAILQ_INIT(&tq);
693 
694 	/* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
695 	sanitise_stdfd();
696 
697 	if (argc <= 1)
698 		usage();
699 
700 	while ((opt = getopt(argc, argv, "cDHqv46O:p:T:t:f:")) != -1) {
701 		switch (opt) {
702 		case 'H':
703 			hash_hosts = 1;
704 			break;
705 		case 'c':
706 			get_cert = 1;
707 			break;
708 		case 'D':
709 			print_sshfp = 1;
710 			break;
711 		case 'p':
712 			ssh_port = a2port(optarg);
713 			if (ssh_port <= 0) {
714 				fprintf(stderr, "Bad port '%s'\n", optarg);
715 				exit(1);
716 			}
717 			break;
718 		case 'T':
719 			timeout = convtime(optarg);
720 			if (timeout == -1 || timeout == 0) {
721 				fprintf(stderr, "Bad timeout '%s'\n", optarg);
722 				usage();
723 			}
724 			break;
725 		case 'v':
726 			if (!debug_flag) {
727 				debug_flag = 1;
728 				log_level = SYSLOG_LEVEL_DEBUG1;
729 			}
730 			else if (log_level < SYSLOG_LEVEL_DEBUG3)
731 				log_level++;
732 			else
733 				fatal("Too high debugging level.");
734 			break;
735 		case 'q':
736 			quiet = 1;
737 			break;
738 		case 'f':
739 			if (strcmp(optarg, "-") == 0)
740 				optarg = NULL;
741 			argv[fopt_count++] = optarg;
742 			break;
743 		case 'O':
744 			/* Maybe other misc options in the future too */
745 			if (strncmp(optarg, "hashalg=", 8) != 0)
746 				fatal("Unsupported -O option");
747 			if ((hashalg = ssh_digest_alg_by_name(
748 			    optarg + 8)) == -1)
749 				fatal("Unsupported hash algorithm");
750 			break;
751 		case 't':
752 			get_keytypes = 0;
753 			tname = strtok(optarg, ",");
754 			while (tname) {
755 				int type = sshkey_type_from_shortname(tname);
756 
757 				switch (type) {
758 #ifdef WITH_DSA
759 				case KEY_DSA:
760 					get_keytypes |= KT_DSA;
761 					break;
762 #endif
763 				case KEY_ECDSA:
764 					get_keytypes |= KT_ECDSA;
765 					break;
766 				case KEY_RSA:
767 					get_keytypes |= KT_RSA;
768 					break;
769 				case KEY_ED25519:
770 					get_keytypes |= KT_ED25519;
771 					break;
772 				case KEY_XMSS:
773 					get_keytypes |= KT_XMSS;
774 					break;
775 				case KEY_ED25519_SK:
776 					get_keytypes |= KT_ED25519_SK;
777 					break;
778 				case KEY_ECDSA_SK:
779 					get_keytypes |= KT_ECDSA_SK;
780 					break;
781 				case KEY_UNSPEC:
782 				default:
783 					fatal("Unknown key type \"%s\"", tname);
784 				}
785 				tname = strtok(NULL, ",");
786 			}
787 			break;
788 		case '4':
789 			IPv4or6 = AF_INET;
790 			break;
791 		case '6':
792 			IPv4or6 = AF_INET6;
793 			break;
794 		default:
795 			usage();
796 		}
797 	}
798 	if (optind == argc && !fopt_count)
799 		usage();
800 
801 	log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
802 
803 	maxfd = fdlim_get(1);
804 	if (maxfd < 0)
805 		fatal("%s: fdlim_get: bad value", __progname);
806 	if (maxfd > MAXMAXFD)
807 		maxfd = MAXMAXFD;
808 	if (MAXCON <= 0)
809 		fatal("%s: not enough file descriptors", __progname);
810 	if (maxfd > fdlim_get(0))
811 		fdlim_set(maxfd);
812 	fdcon = xcalloc(maxfd, sizeof(con));
813 	read_wait = xcalloc(maxfd, sizeof(struct pollfd));
814 	for (j = 0; j < maxfd; j++)
815 		read_wait[j].fd = -1;
816 
817 	for (j = 0; j < fopt_count; j++) {
818 		if (argv[j] == NULL)
819 			fp = stdin;
820 		else if ((fp = fopen(argv[j], "r")) == NULL)
821 			fatal("%s: %s: %s", __progname,
822 			    fp == stdin ? "<stdin>" : argv[j], strerror(errno));
823 
824 		while (getline(&line, &linesize, fp) != -1) {
825 			/* Chomp off trailing whitespace and comments */
826 			if ((cp = strchr(line, '#')) == NULL)
827 				cp = line + strlen(line) - 1;
828 			while (cp >= line) {
829 				if (*cp == ' ' || *cp == '\t' ||
830 				    *cp == '\n' || *cp == '#')
831 					*cp-- = '\0';
832 				else
833 					break;
834 			}
835 
836 			/* Skip empty lines */
837 			if (*line == '\0')
838 				continue;
839 
840 			do_host(line);
841 		}
842 
843 		if (ferror(fp))
844 			fatal("%s: %s: %s", __progname,
845 			    fp == stdin ? "<stdin>" : argv[j], strerror(errno));
846 
847 		if (fp != stdin)
848 			fclose(fp);
849 	}
850 	free(line);
851 
852 	while (optind < argc)
853 		do_host(argv[optind++]);
854 
855 	while (ncon > 0)
856 		conloop();
857 
858 	return found_one ? 0 : 1;
859 }
860