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