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.18 2001/03/03 06:53:12 deraadt Exp $");
13 #if defined(HAVE_SYS_QUEUE_H) && !defined(HAVE_BOGUS_SYS_QUEUE_H)
14 #include <sys/queue.h>
16 #include "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;
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 *,...);
93 static __inline__ Linebuf *
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);
127 static __inline__ void
128 Linebuf_free(Linebuf * lb)
135 static __inline__ void
136 Linebuf_restart(Linebuf * lb)
138 clearerr(lb->stream);
143 static __inline__ int
144 Linebuf_lineno(Linebuf * lb)
149 static __inline__ char *
150 Linebuf_getline(Linebuf * lb)
157 if (!fgets(&lb->buf[n], lb->size - n, lb->stream)) {
158 if (ferror(lb->stream) && lb->errfun)
159 (*lb->errfun) ("%s: %s\n", lb->filename,
165 /* Return it or an error if it fits */
166 if (n > 0 && lb->buf[n - 1] == '\n') {
167 lb->buf[n - 1] = '\0';
170 if (n != lb->size - 1) {
172 (*lb->errfun) ("%s: skipping incomplete last line\n",
176 /* Double the buffer if we need more space */
177 if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
179 (*lb->errfun) ("linebuf (%s): realloc failed\n",
189 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
192 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
194 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
197 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
198 #elif defined (HAVE_SYSCONF)
199 return sysconf (_SC_OPEN_MAX);
208 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
213 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
214 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
217 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
219 #elif defined (HAVE_SETDTABLESIZE)
226 * This is an strsep function that returns a null field for adjacent
227 * separators. This is the same as the 4.4BSD strsep, but different from the
228 * one in the GNU libc.
230 static __inline__ char *
231 xstrsep(char **str, const char *delim)
239 e = s + strcspn(s, delim);
249 * Get the next non-null token (like GNU strsep). Strsep() will return a
250 * null token for two adjacent separators, so we may have to loop.
253 strnnsep(char **stringp, char *delim)
258 tok = xstrsep(stringp, delim);
259 } while (tok && *tok == '\0');
264 keyprint(char *host, char *output_name, char *kd, int len)
271 rsa = key_new(KEY_RSA1);
273 buffer_append(&msg, kd, len);
274 buffer_consume(&msg, 8 - (len & 7)); /* padding */
275 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
276 error("%s: invalid packet type", host);
280 buffer_consume(&msg, 8); /* cookie */
283 (void) buffer_get_int(&msg);
284 buffer_get_bignum(&msg, rsa->rsa->e);
285 buffer_get_bignum(&msg, rsa->rsa->n);
288 (void) buffer_get_int(&msg);
289 buffer_get_bignum(&msg, rsa->rsa->e);
290 buffer_get_bignum(&msg, rsa->rsa->n);
293 fprintf(stdout, "%s ", output_name ? output_name : host);
294 key_write(rsa, stdout);
299 tcpconnect(char *host)
301 struct addrinfo hints, *ai, *aitop;
302 char strport[NI_MAXSERV];
305 snprintf(strport, sizeof strport, "%d", SSH_DEFAULT_PORT);
306 memset(&hints, 0, sizeof(hints));
307 hints.ai_family = family;
308 hints.ai_socktype = SOCK_STREAM;
309 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
310 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
311 for (ai = aitop; ai; ai = ai->ai_next) {
312 s = socket(ai->ai_family, SOCK_STREAM, 0);
314 error("socket: %s", strerror(errno));
317 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
318 fatal("F_SETFL: %s", strerror(errno));
319 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
320 errno != EINPROGRESS)
321 error("connect (`%s'): %s", host, strerror(errno));
332 conalloc(char *iname, char *oname)
335 char *namebase, *name, *namelist;
337 namebase = namelist = xstrdup(iname);
340 name = xstrsep(&namelist, ",");
345 } while ((s = tcpconnect(name)) < 0);
348 fatal("conalloc: fdno %d too high", s);
349 if (fdcon[s].c_status)
350 fatal("conalloc: attempt to reuse fdno %d", s);
353 fdcon[s].c_status = CS_CON;
354 fdcon[s].c_namebase = namebase;
355 fdcon[s].c_name = name;
356 fdcon[s].c_namelist = namelist;
357 fdcon[s].c_output_name = xstrdup(oname);
358 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
361 gettimeofday(&fdcon[s].c_tv, NULL);
362 fdcon[s].c_tv.tv_sec += timeout;
363 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
364 FD_SET(s, &read_wait);
372 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
373 fatal("confree: attempt to free bad fdno %d", s);
375 xfree(fdcon[s].c_namebase);
376 xfree(fdcon[s].c_output_name);
377 if (fdcon[s].c_status == CS_KEYS)
378 xfree(fdcon[s].c_data);
379 fdcon[s].c_status = CS_UNUSED;
380 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
381 FD_CLR(s, &read_wait);
388 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
389 gettimeofday(&fdcon[s].c_tv, NULL);
390 fdcon[s].c_tv.tv_sec += timeout;
391 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
401 iname = xstrdup(c->c_namelist);
402 oname = xstrdup(c->c_output_name);
404 ret = conalloc(iname, oname);
417 n = read(s, buf, sizeof(buf));
419 if (errno != ECONNREFUSED)
420 error("read (%s): %s", c->c_name, strerror(errno));
424 if (buf[n - 1] != '\n') {
425 error("%s: bad greeting", c->c_name);
430 fprintf(stderr, "# %s %s\n", c->c_name, buf);
431 n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
432 if (atomicio(write, s, buf, n) != n) {
433 error("write (%s): %s", c->c_name, strerror(errno));
437 c->c_status = CS_SIZE;
447 if (c->c_status == CS_CON) {
451 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
453 error("read (%s): %s", c->c_name, strerror(errno));
459 if (c->c_off == c->c_len)
460 switch (c->c_status) {
462 c->c_plen = htonl(c->c_plen);
463 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
465 c->c_data = xmalloc(c->c_len);
466 c->c_status = CS_KEYS;
469 keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
474 fatal("conread: invalid status %d", c->c_status);
485 struct timeval seltime, now;
489 gettimeofday(&now, NULL);
492 if (c && (c->c_tv.tv_sec > now.tv_sec ||
493 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
495 seltime.tv_sec -= now.tv_sec;
496 seltime.tv_usec -= now.tv_usec;
497 if (seltime.tv_usec < 0) {
498 seltime.tv_usec += 1000000;
502 seltime.tv_sec = seltime.tv_usec = 0;
505 while (select(maxfd, &r, NULL, &e, &seltime) == -1 &&
506 (errno == EAGAIN || errno == EINTR))
509 for (i = 0; i < maxfd; i++) {
510 if (FD_ISSET(i, &e)) {
511 error("%s: exception!", fdcon[i].c_name);
513 } else if (FD_ISSET(i, &r))
518 while (c && (c->c_tv.tv_sec < now.tv_sec ||
519 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
522 c = c->c_link.tqe_next;
528 nexthost(int argc, char **argv)
536 if (argv[argno][0] != '-')
537 return (argv[argno++]);
538 if (!strcmp(argv[argno], "--")) {
541 return (argv[argno++]);
542 } else if (!strncmp(argv[argno], "-f", 2)) {
546 fname = &argv[argno++][2];
547 else if (++argno >= argc) {
548 error("missing filename for `-f'");
551 fname = argv[argno++];
552 if (!strcmp(fname, "-"))
554 lb = Linebuf_alloc(fname, error);
556 error("ignoring invalid/misplaced option `%s'",
561 line = Linebuf_getline(lb);
573 fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
578 main(int argc, char **argv)
582 __progname = get_progname(argv[0]);
588 if (argv[1][0] == '-' && argv[1][1] == 't') {
591 timeout = atoi(&argv[1][2]);
595 timeout = atoi(argv[argno++]);
603 maxfd = fdlim_get(1);
605 fatal("%s: fdlim_get: bad value", __progname);
606 if (maxfd > MAXMAXFD)
609 fatal("%s: not enough file descriptors", __progname);
610 if (maxfd > fdlim_get(0))
612 fdcon = xmalloc(maxfd * sizeof(con));
613 memset(fdcon, 0, maxfd * sizeof(con));
616 while (ncon < MAXCON) {
619 host = nexthost(argc, argv);
622 name = strnnsep(&host, " \t\n");
623 conalloc(name, *host ? host : name);