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.11 2001/01/21 19:05:57 markus 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);
127 Linebuf_free(Linebuf * lb)
135 Linebuf_restart(Linebuf * lb)
137 clearerr(lb->stream);
143 Linebuf_lineno(Linebuf * lb)
149 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, strerror(errno));
163 /* Return it or an error if it fits */
164 if (n > 0 && lb->buf[n - 1] == '\n') {
165 lb->buf[n - 1] = '\0';
168 if (n != lb->size - 1) {
170 (*lb->errfun) ("%s: skipping incomplete last line\n", lb->filename);
173 /* Double the buffer if we need more space */
174 if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
176 (*lb->errfun) ("linebuf (%s): realloc failed\n", lb->filename);
185 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
187 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
189 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
192 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
193 #elif defined (HAVE_SYSCONF)
194 return sysconf (_SC_OPEN_MAX);
203 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
208 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
209 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
212 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
214 #elif defined (HAVE_SETDTABLESIZE)
221 * This is an strsep function that returns a null field for adjacent
222 * separators. This is the same as the 4.4BSD strsep, but different from the
223 * one in the GNU libc.
226 xstrsep(char **str, const char *delim)
234 e = s + strcspn(s, delim);
244 * Get the next non-null token (like GNU strsep). Strsep() will return a
245 * null token for two adjacent separators, so we may have to loop.
248 strnnsep(char **stringp, char *delim)
253 tok = xstrsep(stringp, delim);
254 } while (tok && *tok == '\0');
259 keyprint(char *host, char *output_name, char *kd, int len)
266 rsa = key_new(KEY_RSA1);
268 buffer_append(&msg, kd, len);
269 buffer_consume(&msg, 8 - (len & 7)); /* padding */
270 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
271 error("%s: invalid packet type", host);
275 buffer_consume(&msg, 8); /* cookie */
278 (void) buffer_get_int(&msg);
279 buffer_get_bignum(&msg, rsa->rsa->e);
280 buffer_get_bignum(&msg, rsa->rsa->n);
283 (void) buffer_get_int(&msg);
284 buffer_get_bignum(&msg, rsa->rsa->e);
285 buffer_get_bignum(&msg, rsa->rsa->n);
288 fprintf(stdout, "%s ", output_name ? output_name : host);
289 key_write(rsa, stdout);
294 tcpconnect(char *host)
296 struct addrinfo hints, *ai, *aitop;
297 char strport[NI_MAXSERV];
300 snprintf(strport, sizeof strport, "%d", SSH_DEFAULT_PORT);
301 memset(&hints, 0, sizeof(hints));
302 hints.ai_family = family;
303 hints.ai_socktype = SOCK_STREAM;
304 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
305 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
306 for (ai = aitop; ai; ai = ai->ai_next) {
307 s = socket(ai->ai_family, SOCK_STREAM, 0);
309 error("socket: %s", strerror(errno));
312 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
313 fatal("F_SETFL: %s", strerror(errno));
314 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
315 errno != EINPROGRESS)
316 error("connect (`%s'): %s", host, strerror(errno));
327 conalloc(char *iname, char *oname)
330 char *namebase, *name, *namelist;
332 namebase = namelist = xstrdup(iname);
335 name = xstrsep(&namelist, ",");
340 } while ((s = tcpconnect(name)) < 0);
343 fatal("conalloc: fdno %d too high", s);
344 if (fdcon[s].c_status)
345 fatal("conalloc: attempt to reuse fdno %d", s);
348 fdcon[s].c_status = CS_CON;
349 fdcon[s].c_namebase = namebase;
350 fdcon[s].c_name = name;
351 fdcon[s].c_namelist = namelist;
352 fdcon[s].c_output_name = xstrdup(oname);
353 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
356 gettimeofday(&fdcon[s].c_tv, NULL);
357 fdcon[s].c_tv.tv_sec += timeout;
358 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
359 FD_SET(s, &read_wait);
368 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
369 fatal("confree: attempt to free bad fdno %d", s);
370 xfree(fdcon[s].c_namebase);
371 xfree(fdcon[s].c_output_name);
372 if (fdcon[s].c_status == CS_KEYS)
373 xfree(fdcon[s].c_data);
374 fdcon[s].c_status = CS_UNUSED;
375 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
376 FD_CLR(s, &read_wait);
383 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
384 gettimeofday(&fdcon[s].c_tv, NULL);
385 fdcon[s].c_tv.tv_sec += timeout;
386 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
396 iname = xstrdup(c->c_namelist);
397 oname = xstrdup(c->c_output_name);
399 ret = conalloc(iname, oname);
412 n = read(s, buf, sizeof(buf));
414 if (errno != ECONNREFUSED)
415 error("read (%s): %s", c->c_name, strerror(errno));
419 if (buf[n - 1] != '\n') {
420 error("%s: bad greeting", c->c_name);
425 fprintf(stderr, "# %s %s\n", c->c_name, buf);
426 n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
427 if (write(s, buf, n) != n) {
428 error("write (%s): %s", c->c_name, strerror(errno));
432 c->c_status = CS_SIZE;
442 if (c->c_status == CS_CON) {
446 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
448 error("read (%s): %s", c->c_name, strerror(errno));
454 if (c->c_off == c->c_len)
455 switch (c->c_status) {
457 c->c_plen = htonl(c->c_plen);
458 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
460 c->c_data = xmalloc(c->c_len);
461 c->c_status = CS_KEYS;
464 keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
469 fatal("conread: invalid status %d", c->c_status);
480 struct timeval seltime, now;
484 gettimeofday(&now, NULL);
488 (c->c_tv.tv_sec > now.tv_sec ||
489 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
491 seltime.tv_sec -= now.tv_sec;
492 seltime.tv_usec -= now.tv_usec;
493 if ((int) seltime.tv_usec < 0) {
494 seltime.tv_usec += 1000000;
498 seltime.tv_sec = seltime.tv_usec = 0;
501 select(maxfd, &r, NULL, &e, &seltime);
502 for (i = 0; i < maxfd; i++)
503 if (FD_ISSET(i, &e)) {
504 error("%s: exception!", fdcon[i].c_name);
506 } else if (FD_ISSET(i, &r))
511 (c->c_tv.tv_sec < now.tv_sec ||
512 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
514 c = c->c_link.tqe_next;
520 nexthost(int argc, char **argv)
528 if (argv[argno][0] != '-')
529 return (argv[argno++]);
530 if (!strcmp(argv[argno], "--")) {
533 return (argv[argno++]);
534 } else if (!strncmp(argv[argno], "-f", 2)) {
537 fname = &argv[argno++][2];
538 else if (++argno >= argc) {
539 error("missing filename for `-f'");
542 fname = argv[argno++];
543 if (!strcmp(fname, "-"))
545 lb = Linebuf_alloc(fname, error);
547 error("ignoring invalid/misplaced option `%s'", argv[argno++]);
562 fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
567 main(int argc, char **argv)
571 __progname = get_progname(argv[0]);
577 if (argv[1][0] == '-' && argv[1][1] == 't') {
580 timeout = atoi(&argv[1][2]);
584 timeout = atoi(argv[argno++]);
592 maxfd = fdlim_get(1);
594 fatal("%s: fdlim_get: bad value", __progname);
595 if (maxfd > MAXMAXFD)
598 fatal("%s: not enough file descriptors", __progname);
599 if (maxfd > fdlim_get(0))
601 fdcon = xmalloc(maxfd * sizeof(con));
604 while (ncon < maxcon) {
607 host = nexthost(argc, argv);
610 name = strnnsep(&host, " \t\n");
611 conalloc(name, *host ? host : name);