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