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 (for instance by leaving this copyright notice
11 RCSID("$OpenBSD: ssh-keyscan.c,v 1.22 2001/03/06 06:11:18 deraadt Exp $");
13 #if defined(HAVE_SYS_QUEUE_H) && !defined(HAVE_BOGUS_SYS_QUEUE_H)
14 #include <sys/queue.h>
16 #include "openbsd-compat/fake-queue.h"
20 #include <openssl/bn.h>
31 static int argno = 1; /* Number of argument currently being parsed */
33 int family = AF_UNSPEC; /* IPv4, IPv6 or both */
37 /* The number of seconds after which to give up on a TCP connection */
41 #define MAXCON (maxfd - 10)
43 #ifdef HAVE___PROGNAME
44 extern char *__progname;
49 size_t read_wait_size;
53 * Keep a connection structure for each file descriptor. The state
54 * associated with file descriptor n is held in fdcon[n].
56 typedef struct Connection {
57 u_char c_status; /* State of connection on this file desc. */
58 #define CS_UNUSED 0 /* File descriptor unused */
59 #define CS_CON 1 /* Waiting to connect/read greeting */
60 #define CS_SIZE 2 /* Waiting to read initial packet size */
61 #define CS_KEYS 3 /* Waiting to read public key packet */
62 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
63 int c_plen; /* Packet length field for ssh packet */
64 int c_len; /* Total bytes which must be read. */
65 int c_off; /* Length of data read so far. */
66 char *c_namebase; /* Address to free for c_name and c_namelist */
67 char *c_name; /* Hostname of connection for errors */
68 char *c_namelist; /* Pointer to other possible addresses */
69 char *c_output_name; /* Hostname of connection for output */
70 char *c_data; /* Data read from this fd */
71 struct timeval c_tv; /* Time at which connection gets aborted */
72 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
75 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
79 * This is just a wrapper around fgets() to make it usable.
82 /* Stress-test. Increase this later. */
83 #define LINEBUF_SIZE 16
91 void (*errfun) (const char *,...);
95 Linebuf_alloc(const char *filename, void (*errfun) (const char *,...))
99 if (!(lb = malloc(sizeof(*lb)))) {
101 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
105 lb->filename = filename;
106 if (!(lb->stream = fopen(filename, "r"))) {
109 (*errfun) ("%s: %s\n", filename, strerror(errno));
113 lb->filename = "(stdin)";
117 if (!(lb->buf = malloc(lb->size = LINEBUF_SIZE))) {
119 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
129 Linebuf_free(Linebuf * lb)
137 Linebuf_restart(Linebuf * lb)
139 clearerr(lb->stream);
145 Linebuf_lineno(Linebuf * lb)
151 Linebuf_getline(Linebuf * lb)
158 if (!fgets(&lb->buf[n], lb->size - n, lb->stream)) {
159 if (ferror(lb->stream) && lb->errfun)
160 (*lb->errfun) ("%s: %s\n", lb->filename,
166 /* Return it or an error if it fits */
167 if (n > 0 && lb->buf[n - 1] == '\n') {
168 lb->buf[n - 1] = '\0';
171 if (n != lb->size - 1) {
173 (*lb->errfun) ("%s: skipping incomplete last line\n",
177 /* Double the buffer if we need more space */
178 if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
180 (*lb->errfun) ("linebuf (%s): realloc failed\n",
190 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
193 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
195 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
198 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
199 #elif defined (HAVE_SYSCONF)
200 return sysconf (_SC_OPEN_MAX);
209 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
214 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
215 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
218 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
220 #elif defined (HAVE_SETDTABLESIZE)
227 * This is an strsep function that returns a null field for adjacent
228 * separators. This is the same as the 4.4BSD strsep, but different from the
229 * one in the GNU libc.
232 xstrsep(char **str, const char *delim)
240 e = s + strcspn(s, delim);
250 * Get the next non-null token (like GNU strsep). Strsep() will return a
251 * null token for two adjacent separators, so we may have to loop.
254 strnnsep(char **stringp, char *delim)
259 tok = xstrsep(stringp, delim);
260 } while (tok && *tok == '\0');
265 keyprint(char *host, char *output_name, char *kd, int len)
272 rsa = key_new(KEY_RSA1);
274 buffer_append(&msg, kd, len);
275 buffer_consume(&msg, 8 - (len & 7)); /* padding */
276 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
277 error("%s: invalid packet type", host);
281 buffer_consume(&msg, 8); /* cookie */
284 (void) buffer_get_int(&msg);
285 buffer_get_bignum(&msg, rsa->rsa->e);
286 buffer_get_bignum(&msg, rsa->rsa->n);
289 (void) buffer_get_int(&msg);
290 buffer_get_bignum(&msg, rsa->rsa->e);
291 buffer_get_bignum(&msg, rsa->rsa->n);
294 fprintf(stdout, "%s ", output_name ? output_name : host);
295 key_write(rsa, stdout);
300 tcpconnect(char *host)
302 struct addrinfo hints, *ai, *aitop;
303 char strport[NI_MAXSERV];
306 snprintf(strport, sizeof strport, "%d", SSH_DEFAULT_PORT);
307 memset(&hints, 0, sizeof(hints));
308 hints.ai_family = family;
309 hints.ai_socktype = SOCK_STREAM;
310 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
311 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
312 for (ai = aitop; ai; ai = ai->ai_next) {
313 s = socket(ai->ai_family, SOCK_STREAM, 0);
315 error("socket: %s", strerror(errno));
318 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
319 fatal("F_SETFL: %s", strerror(errno));
320 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
321 errno != EINPROGRESS)
322 error("connect (`%s'): %s", host, strerror(errno));
333 conalloc(char *iname, char *oname)
336 char *namebase, *name, *namelist;
338 namebase = namelist = xstrdup(iname);
341 name = xstrsep(&namelist, ",");
346 } while ((s = tcpconnect(name)) < 0);
349 fatal("conalloc: fdno %d too high", s);
350 if (fdcon[s].c_status)
351 fatal("conalloc: attempt to reuse fdno %d", s);
354 fdcon[s].c_status = CS_CON;
355 fdcon[s].c_namebase = namebase;
356 fdcon[s].c_name = name;
357 fdcon[s].c_namelist = namelist;
358 fdcon[s].c_output_name = xstrdup(oname);
359 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
362 gettimeofday(&fdcon[s].c_tv, NULL);
363 fdcon[s].c_tv.tv_sec += timeout;
364 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
365 FD_SET(s, read_wait);
373 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
374 fatal("confree: attempt to free bad fdno %d", s);
376 xfree(fdcon[s].c_namebase);
377 xfree(fdcon[s].c_output_name);
378 if (fdcon[s].c_status == CS_KEYS)
379 xfree(fdcon[s].c_data);
380 fdcon[s].c_status = CS_UNUSED;
381 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
382 FD_CLR(s, read_wait);
389 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
390 gettimeofday(&fdcon[s].c_tv, NULL);
391 fdcon[s].c_tv.tv_sec += timeout;
392 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
402 iname = xstrdup(c->c_namelist);
403 oname = xstrdup(c->c_output_name);
405 ret = conalloc(iname, oname);
419 bufsiz = sizeof(buf);
421 while (bufsiz-- && (n = read(s, cp, 1)) == 1 && *cp != '\n' && *cp != '\r')
424 if (errno != ECONNREFUSED)
425 error("read (%s): %s", c->c_name, strerror(errno));
429 if (*cp != '\n' && *cp != '\r') {
430 error("%s: bad greeting", c->c_name);
435 fprintf(stderr, "# %s %s\n", c->c_name, buf);
436 n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
437 if (atomicio(write, s, buf, n) != n) {
438 error("write (%s): %s", c->c_name, strerror(errno));
442 c->c_status = CS_SIZE;
452 if (c->c_status == CS_CON) {
456 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
458 error("read (%s): %s", c->c_name, strerror(errno));
464 if (c->c_off == c->c_len)
465 switch (c->c_status) {
467 c->c_plen = htonl(c->c_plen);
468 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
470 c->c_data = xmalloc(c->c_len);
471 c->c_status = CS_KEYS;
474 keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
479 fatal("conread: invalid status %d", c->c_status);
490 struct timeval seltime, now;
494 gettimeofday(&now, NULL);
497 if (c && (c->c_tv.tv_sec > now.tv_sec ||
498 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
500 seltime.tv_sec -= now.tv_sec;
501 seltime.tv_usec -= now.tv_usec;
502 if (seltime.tv_usec < 0) {
503 seltime.tv_usec += 1000000;
507 seltime.tv_sec = seltime.tv_usec = 0;
509 r = xmalloc(read_wait_size);
510 memcpy(r, read_wait, read_wait_size);
511 e = xmalloc(read_wait_size);
512 memcpy(e, read_wait, read_wait_size);
514 while (select(maxfd, r, NULL, e, &seltime) == -1 &&
515 (errno == EAGAIN || errno == EINTR))
518 for (i = 0; i < maxfd; i++) {
519 if (FD_ISSET(i, e)) {
520 error("%s: exception!", fdcon[i].c_name);
522 } else if (FD_ISSET(i, r))
529 while (c && (c->c_tv.tv_sec < now.tv_sec ||
530 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
533 c = c->c_link.tqe_next;
539 nexthost(int argc, char **argv)
547 if (argv[argno][0] != '-')
548 return (argv[argno++]);
549 if (!strcmp(argv[argno], "--")) {
552 return (argv[argno++]);
553 } else if (!strncmp(argv[argno], "-f", 2)) {
557 fname = &argv[argno++][2];
558 else if (++argno >= argc) {
559 error("missing filename for `-f'");
562 fname = argv[argno++];
563 if (!strcmp(fname, "-"))
565 lb = Linebuf_alloc(fname, error);
567 error("ignoring invalid/misplaced option `%s'",
572 line = Linebuf_getline(lb);
584 fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
589 main(int argc, char **argv)
593 __progname = get_progname(argv[0]);
599 if (argv[1][0] == '-' && argv[1][1] == 't') {
602 timeout = atoi(&argv[1][2]);
606 timeout = atoi(argv[argno++]);
614 maxfd = fdlim_get(1);
616 fatal("%s: fdlim_get: bad value", __progname);
617 if (maxfd > MAXMAXFD)
620 fatal("%s: not enough file descriptors", __progname);
621 if (maxfd > fdlim_get(0))
623 fdcon = xmalloc(maxfd * sizeof(con));
624 memset(fdcon, 0, maxfd * sizeof(con));
626 read_wait_size = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
627 read_wait = xmalloc(read_wait_size);
628 memset(read_wait, 0, read_wait_size);
631 while (ncon < MAXCON) {
634 host = nexthost(argc, argv);
637 name = strnnsep(&host, " \t\n");
638 conalloc(name, *host ? host : name);