2 * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>.
4 * Modification and redistribution in source and binary forms is
5 * permitted provided that due credit is given to the author and the
6 * OpenBSD project by leaving this copyright notice intact.
10 RCSID("$OpenBSD: ssh-keyscan.c,v 1.24 2001/06/23 15:12:20 itojun Exp $");
12 #if defined(HAVE_SYS_QUEUE_H) && !defined(HAVE_BOGUS_SYS_QUEUE_H)
13 #include <sys/queue.h>
15 #include "openbsd-compat/fake-queue.h"
19 #include <openssl/bn.h>
30 static int argno = 1; /* Number of argument currently being parsed */
32 int family = AF_UNSPEC; /* IPv4, IPv6 or both */
36 /* The number of seconds after which to give up on a TCP connection */
40 #define MAXCON (maxfd - 10)
42 #ifdef HAVE___PROGNAME
43 extern char *__progname;
48 size_t read_wait_size;
52 * Keep a connection structure for each file descriptor. The state
53 * associated with file descriptor n is held in fdcon[n].
55 typedef struct Connection {
56 u_char c_status; /* State of connection on this file desc. */
57 #define CS_UNUSED 0 /* File descriptor unused */
58 #define CS_CON 1 /* Waiting to connect/read greeting */
59 #define CS_SIZE 2 /* Waiting to read initial packet size */
60 #define CS_KEYS 3 /* Waiting to read public key packet */
61 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
62 int c_plen; /* Packet length field for ssh packet */
63 int c_len; /* Total bytes which must be read. */
64 int c_off; /* Length of data read so far. */
65 char *c_namebase; /* Address to free for c_name and c_namelist */
66 char *c_name; /* Hostname of connection for errors */
67 char *c_namelist; /* Pointer to other possible addresses */
68 char *c_output_name; /* Hostname of connection for output */
69 char *c_data; /* Data read from this fd */
70 struct timeval c_tv; /* Time at which connection gets aborted */
71 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
74 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
78 * This is just a wrapper around fgets() to make it usable.
81 /* Stress-test. Increase this later. */
82 #define LINEBUF_SIZE 16
90 void (*errfun) (const char *,...);
94 Linebuf_alloc(const char *filename, void (*errfun) (const char *,...))
98 if (!(lb = malloc(sizeof(*lb)))) {
100 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
104 lb->filename = filename;
105 if (!(lb->stream = fopen(filename, "r"))) {
108 (*errfun) ("%s: %s\n", filename, strerror(errno));
112 lb->filename = "(stdin)";
116 if (!(lb->buf = malloc(lb->size = LINEBUF_SIZE))) {
118 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
128 Linebuf_free(Linebuf * lb)
137 Linebuf_restart(Linebuf * lb)
139 clearerr(lb->stream);
145 Linebuf_lineno(Linebuf * lb)
152 Linebuf_getline(Linebuf * lb)
159 if (!fgets(&lb->buf[n], lb->size - n, lb->stream)) {
160 if (ferror(lb->stream) && lb->errfun)
161 (*lb->errfun) ("%s: %s\n", lb->filename,
167 /* Return it or an error if it fits */
168 if (n > 0 && lb->buf[n - 1] == '\n') {
169 lb->buf[n - 1] = '\0';
172 if (n != lb->size - 1) {
174 (*lb->errfun) ("%s: skipping incomplete last line\n",
178 /* Double the buffer if we need more space */
179 if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
181 (*lb->errfun) ("linebuf (%s): realloc failed\n",
191 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
194 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
196 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
199 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
200 #elif defined (HAVE_SYSCONF)
201 return sysconf (_SC_OPEN_MAX);
210 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
215 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
216 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
219 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
221 #elif defined (HAVE_SETDTABLESIZE)
228 * This is an strsep function that returns a null field for adjacent
229 * separators. This is the same as the 4.4BSD strsep, but different from the
230 * one in the GNU libc.
233 xstrsep(char **str, const char *delim)
241 e = s + strcspn(s, delim);
251 * Get the next non-null token (like GNU strsep). Strsep() will return a
252 * null token for two adjacent separators, so we may have to loop.
255 strnnsep(char **stringp, char *delim)
260 tok = xstrsep(stringp, delim);
261 } while (tok && *tok == '\0');
266 keyprint(char *host, char *output_name, char *kd, int len)
273 rsa = key_new(KEY_RSA1);
275 buffer_append(&msg, kd, len);
276 buffer_consume(&msg, 8 - (len & 7)); /* padding */
277 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
278 error("%s: invalid packet type", host);
282 buffer_consume(&msg, 8); /* cookie */
285 (void) buffer_get_int(&msg);
286 buffer_get_bignum(&msg, rsa->rsa->e);
287 buffer_get_bignum(&msg, rsa->rsa->n);
290 (void) buffer_get_int(&msg);
291 buffer_get_bignum(&msg, rsa->rsa->e);
292 buffer_get_bignum(&msg, rsa->rsa->n);
295 fprintf(stdout, "%s ", output_name ? output_name : host);
296 key_write(rsa, stdout);
301 tcpconnect(char *host)
303 struct addrinfo hints, *ai, *aitop;
304 char strport[NI_MAXSERV];
307 snprintf(strport, sizeof strport, "%d", SSH_DEFAULT_PORT);
308 memset(&hints, 0, sizeof(hints));
309 hints.ai_family = family;
310 hints.ai_socktype = SOCK_STREAM;
311 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
312 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
313 for (ai = aitop; ai; ai = ai->ai_next) {
314 s = socket(ai->ai_family, SOCK_STREAM, 0);
316 error("socket: %s", strerror(errno));
319 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
320 fatal("F_SETFL: %s", strerror(errno));
321 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
322 errno != EINPROGRESS)
323 error("connect (`%s'): %s", host, strerror(errno));
334 conalloc(char *iname, char *oname)
337 char *namebase, *name, *namelist;
339 namebase = namelist = xstrdup(iname);
342 name = xstrsep(&namelist, ",");
347 } while ((s = tcpconnect(name)) < 0);
350 fatal("conalloc: fdno %d too high", s);
351 if (fdcon[s].c_status)
352 fatal("conalloc: attempt to reuse fdno %d", s);
355 fdcon[s].c_status = CS_CON;
356 fdcon[s].c_namebase = namebase;
357 fdcon[s].c_name = name;
358 fdcon[s].c_namelist = namelist;
359 fdcon[s].c_output_name = xstrdup(oname);
360 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
363 gettimeofday(&fdcon[s].c_tv, NULL);
364 fdcon[s].c_tv.tv_sec += timeout;
365 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
366 FD_SET(s, read_wait);
374 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
375 fatal("confree: attempt to free bad fdno %d", s);
377 xfree(fdcon[s].c_namebase);
378 xfree(fdcon[s].c_output_name);
379 if (fdcon[s].c_status == CS_KEYS)
380 xfree(fdcon[s].c_data);
381 fdcon[s].c_status = CS_UNUSED;
382 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
383 FD_CLR(s, read_wait);
390 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
391 gettimeofday(&fdcon[s].c_tv, NULL);
392 fdcon[s].c_tv.tv_sec += timeout;
393 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
403 iname = xstrdup(c->c_namelist);
404 oname = xstrdup(c->c_output_name);
406 ret = conalloc(iname, oname);
420 bufsiz = sizeof(buf);
422 while (bufsiz-- && (n = read(s, cp, 1)) == 1 && *cp != '\n' && *cp != '\r')
425 if (errno != ECONNREFUSED)
426 error("read (%s): %s", c->c_name, strerror(errno));
430 if (*cp != '\n' && *cp != '\r') {
431 error("%s: bad greeting", c->c_name);
436 fprintf(stderr, "# %s %s\n", c->c_name, buf);
437 n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
438 if (atomicio(write, s, buf, n) != n) {
439 error("write (%s): %s", c->c_name, strerror(errno));
443 c->c_status = CS_SIZE;
453 if (c->c_status == CS_CON) {
457 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
459 error("read (%s): %s", c->c_name, strerror(errno));
465 if (c->c_off == c->c_len)
466 switch (c->c_status) {
468 c->c_plen = htonl(c->c_plen);
469 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
471 c->c_data = xmalloc(c->c_len);
472 c->c_status = CS_KEYS;
475 keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
480 fatal("conread: invalid status %d", c->c_status);
491 struct timeval seltime, now;
495 gettimeofday(&now, NULL);
498 if (c && (c->c_tv.tv_sec > now.tv_sec ||
499 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
501 seltime.tv_sec -= now.tv_sec;
502 seltime.tv_usec -= now.tv_usec;
503 if (seltime.tv_usec < 0) {
504 seltime.tv_usec += 1000000;
508 seltime.tv_sec = seltime.tv_usec = 0;
510 r = xmalloc(read_wait_size);
511 memcpy(r, read_wait, read_wait_size);
512 e = xmalloc(read_wait_size);
513 memcpy(e, read_wait, read_wait_size);
515 while (select(maxfd, r, NULL, e, &seltime) == -1 &&
516 (errno == EAGAIN || errno == EINTR))
519 for (i = 0; i < maxfd; i++) {
520 if (FD_ISSET(i, e)) {
521 error("%s: exception!", fdcon[i].c_name);
523 } else if (FD_ISSET(i, r))
530 while (c && (c->c_tv.tv_sec < now.tv_sec ||
531 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
534 c = c->c_link.tqe_next;
540 nexthost(int argc, char **argv)
548 if (argv[argno][0] != '-')
549 return (argv[argno++]);
550 if (!strcmp(argv[argno], "--")) {
553 return (argv[argno++]);
554 } else if (!strncmp(argv[argno], "-f", 2)) {
558 fname = &argv[argno++][2];
559 else if (++argno >= argc) {
560 error("missing filename for `-f'");
563 fname = argv[argno++];
564 if (!strcmp(fname, "-"))
566 lb = Linebuf_alloc(fname, error);
568 error("ignoring invalid/misplaced option `%s'",
573 line = Linebuf_getline(lb);
585 fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
590 main(int argc, char **argv)
594 __progname = get_progname(argv[0]);
600 if (argv[1][0] == '-' && argv[1][1] == 't') {
603 timeout = atoi(&argv[1][2]);
607 timeout = atoi(argv[argno++]);
615 maxfd = fdlim_get(1);
617 fatal("%s: fdlim_get: bad value", __progname);
618 if (maxfd > MAXMAXFD)
621 fatal("%s: not enough file descriptors", __progname);
622 if (maxfd > fdlim_get(0))
624 fdcon = xmalloc(maxfd * sizeof(con));
625 memset(fdcon, 0, maxfd * sizeof(con));
627 read_wait_size = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
628 read_wait = xmalloc(read_wait_size);
629 memset(read_wait, 0, read_wait_size);
632 while (ncon < MAXCON) {
635 host = nexthost(argc, argv);
638 name = strnnsep(&host, " \t\n");
639 conalloc(name, *host ? host : name);