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.17 2001/02/21 07:37:04 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>
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;
51 * Keep a connection structure for each file descriptor. The state
52 * associated with file descriptor n is held in fdcon[n].
54 typedef struct Connection {
55 u_char c_status; /* State of connection on this file desc. */
56 #define CS_UNUSED 0 /* File descriptor unused */
57 #define CS_CON 1 /* Waiting to connect/read greeting */
58 #define CS_SIZE 2 /* Waiting to read initial packet size */
59 #define CS_KEYS 3 /* Waiting to read public key packet */
60 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
61 int c_plen; /* Packet length field for ssh packet */
62 int c_len; /* Total bytes which must be read. */
63 int c_off; /* Length of data read so far. */
64 char *c_namebase; /* Address to free for c_name and c_namelist */
65 char *c_name; /* Hostname of connection for errors */
66 char *c_namelist; /* Pointer to other possible addresses */
67 char *c_output_name; /* Hostname of connection for output */
68 char *c_data; /* Data read from this fd */
69 struct timeval c_tv; /* Time at which connection gets aborted */
70 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
73 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
77 * This is just a wrapper around fgets() to make it usable.
80 /* Stress-test. Increase this later. */
81 #define LINEBUF_SIZE 16
89 void (*errfun) (const char *,...);
92 static __inline__ Linebuf *
93 Linebuf_alloc(const char *filename, void (*errfun) (const char *,...))
97 if (!(lb = malloc(sizeof(*lb)))) {
99 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
103 lb->filename = filename;
104 if (!(lb->stream = fopen(filename, "r"))) {
107 (*errfun) ("%s: %s\n", filename, strerror(errno));
111 lb->filename = "(stdin)";
115 if (!(lb->buf = malloc(lb->size = LINEBUF_SIZE))) {
117 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
126 static __inline__ void
127 Linebuf_free(Linebuf * lb)
134 static __inline__ void
135 Linebuf_restart(Linebuf * lb)
137 clearerr(lb->stream);
142 static __inline__ int
143 Linebuf_lineno(Linebuf * lb)
148 static __inline__ char *
149 Linebuf_getline(Linebuf * lb)
156 if (!fgets(&lb->buf[n], lb->size - n, lb->stream)) {
157 if (ferror(lb->stream) && lb->errfun)
158 (*lb->errfun) ("%s: %s\n", lb->filename,
164 /* Return it or an error if it fits */
165 if (n > 0 && lb->buf[n - 1] == '\n') {
166 lb->buf[n - 1] = '\0';
169 if (n != lb->size - 1) {
171 (*lb->errfun) ("%s: skipping incomplete last line\n",
175 /* Double the buffer if we need more space */
176 if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
178 (*lb->errfun) ("linebuf (%s): realloc failed\n",
188 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
191 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
193 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
196 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
197 #elif defined (HAVE_SYSCONF)
198 return sysconf (_SC_OPEN_MAX);
207 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
212 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
213 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
216 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
218 #elif defined (HAVE_SETDTABLESIZE)
225 * This is an strsep function that returns a null field for adjacent
226 * separators. This is the same as the 4.4BSD strsep, but different from the
227 * one in the GNU libc.
229 static __inline__ char *
230 xstrsep(char **str, const char *delim)
238 e = s + strcspn(s, delim);
248 * Get the next non-null token (like GNU strsep). Strsep() will return a
249 * null token for two adjacent separators, so we may have to loop.
252 strnnsep(char **stringp, char *delim)
257 tok = xstrsep(stringp, delim);
258 } while (tok && *tok == '\0');
263 keyprint(char *host, char *output_name, char *kd, int len)
270 rsa = key_new(KEY_RSA1);
272 buffer_append(&msg, kd, len);
273 buffer_consume(&msg, 8 - (len & 7)); /* padding */
274 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
275 error("%s: invalid packet type", host);
279 buffer_consume(&msg, 8); /* cookie */
282 (void) buffer_get_int(&msg);
283 buffer_get_bignum(&msg, rsa->rsa->e);
284 buffer_get_bignum(&msg, rsa->rsa->n);
287 (void) buffer_get_int(&msg);
288 buffer_get_bignum(&msg, rsa->rsa->e);
289 buffer_get_bignum(&msg, rsa->rsa->n);
292 fprintf(stdout, "%s ", output_name ? output_name : host);
293 key_write(rsa, stdout);
298 tcpconnect(char *host)
300 struct addrinfo hints, *ai, *aitop;
301 char strport[NI_MAXSERV];
304 snprintf(strport, sizeof strport, "%d", SSH_DEFAULT_PORT);
305 memset(&hints, 0, sizeof(hints));
306 hints.ai_family = family;
307 hints.ai_socktype = SOCK_STREAM;
308 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
309 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
310 for (ai = aitop; ai; ai = ai->ai_next) {
311 s = socket(ai->ai_family, SOCK_STREAM, 0);
313 error("socket: %s", strerror(errno));
316 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
317 fatal("F_SETFL: %s", strerror(errno));
318 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
319 errno != EINPROGRESS)
320 error("connect (`%s'): %s", host, strerror(errno));
331 conalloc(char *iname, char *oname)
334 char *namebase, *name, *namelist;
336 namebase = namelist = xstrdup(iname);
339 name = xstrsep(&namelist, ",");
344 } while ((s = tcpconnect(name)) < 0);
347 fatal("conalloc: fdno %d too high", s);
348 if (fdcon[s].c_status)
349 fatal("conalloc: attempt to reuse fdno %d", s);
352 fdcon[s].c_status = CS_CON;
353 fdcon[s].c_namebase = namebase;
354 fdcon[s].c_name = name;
355 fdcon[s].c_namelist = namelist;
356 fdcon[s].c_output_name = xstrdup(oname);
357 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
360 gettimeofday(&fdcon[s].c_tv, NULL);
361 fdcon[s].c_tv.tv_sec += timeout;
362 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
363 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);
374 xfree(fdcon[s].c_namebase);
375 xfree(fdcon[s].c_output_name);
376 if (fdcon[s].c_status == CS_KEYS)
377 xfree(fdcon[s].c_data);
378 fdcon[s].c_status = CS_UNUSED;
379 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
380 FD_CLR(s, &read_wait);
387 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
388 gettimeofday(&fdcon[s].c_tv, NULL);
389 fdcon[s].c_tv.tv_sec += timeout;
390 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
400 iname = xstrdup(c->c_namelist);
401 oname = xstrdup(c->c_output_name);
403 ret = conalloc(iname, oname);
416 n = read(s, buf, sizeof(buf));
418 if (errno != ECONNREFUSED)
419 error("read (%s): %s", c->c_name, strerror(errno));
423 if (buf[n - 1] != '\n') {
424 error("%s: bad greeting", c->c_name);
429 fprintf(stderr, "# %s %s\n", c->c_name, buf);
430 n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
431 if (write(s, buf, n) != n) {
432 error("write (%s): %s", c->c_name, strerror(errno));
436 c->c_status = CS_SIZE;
446 if (c->c_status == CS_CON) {
450 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
452 error("read (%s): %s", c->c_name, strerror(errno));
458 if (c->c_off == c->c_len)
459 switch (c->c_status) {
461 c->c_plen = htonl(c->c_plen);
462 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
464 c->c_data = xmalloc(c->c_len);
465 c->c_status = CS_KEYS;
468 keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
473 fatal("conread: invalid status %d", c->c_status);
484 struct timeval seltime, now;
488 gettimeofday(&now, NULL);
492 (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 (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))) {
521 c = c->c_link.tqe_next;
527 nexthost(int argc, char **argv)
535 if (argv[argno][0] != '-')
536 return (argv[argno++]);
537 if (!strcmp(argv[argno], "--")) {
540 return (argv[argno++]);
541 } else if (!strncmp(argv[argno], "-f", 2)) {
544 fname = &argv[argno++][2];
545 else if (++argno >= argc) {
546 error("missing filename for `-f'");
549 fname = argv[argno++];
550 if (!strcmp(fname, "-"))
552 lb = Linebuf_alloc(fname, error);
554 error("ignoring invalid/misplaced option `%s'", argv[argno++]);
557 line = Linebuf_getline(lb);
569 fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
574 main(int argc, char **argv)
578 __progname = get_progname(argv[0]);
584 if (argv[1][0] == '-' && argv[1][1] == 't') {
587 timeout = atoi(&argv[1][2]);
591 timeout = atoi(argv[argno++]);
599 maxfd = fdlim_get(1);
601 fatal("%s: fdlim_get: bad value", __progname);
602 if (maxfd > MAXMAXFD)
605 fatal("%s: not enough file descriptors", __progname);
606 if (maxfd > fdlim_get(0))
608 fdcon = xmalloc(maxfd * sizeof(con));
609 memset(fdcon, 0, maxfd * sizeof(con));
612 while (ncon < maxcon) {
615 host = nexthost(argc, argv);
618 name = strnnsep(&host, " \t\n");
619 conalloc(name, *host ? host : name);