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.7 2001/01/08 22:03:23 markus Exp $");
13 #if defined(HAVE_SYS_QUEUE_H) && !defined(HAVE_BOGUS_SYS_QUEUE_H)
14 #include <sys/queue.h>
16 #include "bsd-queue.h"
20 #include <openssl/bn.h>
21 #include <openssl/rsa.h>
22 #include <openssl/dsa.h>
30 static int argno = 1; /* Number of argument currently being parsed */
32 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);
128 Linebuf_free(Linebuf * lb)
136 Linebuf_restart(Linebuf * lb)
138 clearerr(lb->stream);
144 Linebuf_lineno(Linebuf * lb)
150 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, strerror(errno));
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", lb->filename);
174 /* Double the buffer if we need more space */
175 if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
177 (*lb->errfun) ("linebuf (%s): realloc failed\n", lb->filename);
186 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
188 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
190 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
193 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
194 #elif defined (HAVE_SYSCONF)
195 return sysconf (_SC_OPEN_MAX);
204 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
209 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
210 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
213 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
215 #elif defined (HAVE_SETDTABLESIZE)
222 * This is an strsep function that returns a null field for adjacent
223 * separators. This is the same as the 4.4BSD strsep, but different from the
224 * one in the GNU libc.
227 xstrsep(char **str, const char *delim)
235 e = s + strcspn(s, delim);
245 * Get the next non-null token (like GNU strsep). Strsep() will return a
246 * null token for two adjacent separators, so we may have to loop.
249 strnnsep(char **stringp, char *delim)
254 tok = xstrsep(stringp, delim);
255 } while (tok && *tok == '\0');
260 keyprint(char *host, char *output_name, char *kd, int len)
267 rsa = key_new(KEY_RSA1);
269 buffer_append(&msg, kd, len);
270 buffer_consume(&msg, 8 - (len & 7)); /* padding */
271 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
272 error("%s: invalid packet type", host);
276 buffer_consume(&msg, 8); /* cookie */
279 (void) buffer_get_int(&msg);
280 buffer_get_bignum(&msg, rsa->rsa->e);
281 buffer_get_bignum(&msg, rsa->rsa->n);
284 (void) buffer_get_int(&msg);
285 buffer_get_bignum(&msg, rsa->rsa->e);
286 buffer_get_bignum(&msg, rsa->rsa->n);
289 fprintf(stdout, "%s ", output_name ? output_name : host);
290 key_write(rsa, stdout);
295 tcpconnect(char *host)
297 struct addrinfo hints, *ai, *aitop;
298 char strport[NI_MAXSERV];
301 snprintf(strport, sizeof strport, "%d", PORT);
302 memset(&hints, 0, sizeof(hints));
303 hints.ai_family = family;
304 hints.ai_socktype = SOCK_STREAM;
305 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
306 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
307 for (ai = aitop; ai; ai = ai->ai_next) {
308 s = socket(ai->ai_family, SOCK_STREAM, 0);
310 error("socket: %s", strerror(errno));
313 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
314 fatal("F_SETFL: %s", strerror(errno));
315 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
316 errno != EINPROGRESS)
317 error("connect (`%s'): %s", host, strerror(errno));
328 conalloc(char *iname, char *oname)
331 char *namebase, *name, *namelist;
333 namebase = namelist = xstrdup(iname);
336 name = xstrsep(&namelist, ",");
341 } while ((s = tcpconnect(name)) < 0);
344 fatal("conalloc: fdno %d too high", s);
345 if (fdcon[s].c_status)
346 fatal("conalloc: attempt to reuse fdno %d", s);
349 fdcon[s].c_status = CS_CON;
350 fdcon[s].c_namebase = namebase;
351 fdcon[s].c_name = name;
352 fdcon[s].c_namelist = namelist;
353 fdcon[s].c_output_name = xstrdup(oname);
354 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
357 gettimeofday(&fdcon[s].c_tv, NULL);
358 fdcon[s].c_tv.tv_sec += timeout;
359 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
360 FD_SET(s, &read_wait);
369 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
370 fatal("confree: attempt to free bad fdno %d", s);
371 free(fdcon[s].c_namebase);
372 free(fdcon[s].c_output_name);
373 if (fdcon[s].c_status == CS_KEYS)
374 free(fdcon[s].c_data);
375 fdcon[s].c_status = CS_UNUSED;
376 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
377 FD_CLR(s, &read_wait);
384 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
385 gettimeofday(&fdcon[s].c_tv, NULL);
386 fdcon[s].c_tv.tv_sec += timeout;
387 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
397 iname = xstrdup(c->c_namelist);
398 oname = c->c_output_name;
399 c->c_output_name = NULL;/* prevent it from being freed */
401 ret = conalloc(iname, oname);
413 n = read(s, buf, sizeof(buf));
415 if (errno != ECONNREFUSED)
416 error("read (%s): %s", c->c_name, strerror(errno));
420 if (buf[n - 1] != '\n') {
421 error("%s: bad greeting", c->c_name);
426 fprintf(stderr, "# %s %s\n", c->c_name, buf);
427 n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
428 if (write(s, buf, n) != n) {
429 error("write (%s): %s", c->c_name, strerror(errno));
433 c->c_status = CS_SIZE;
443 if (c->c_status == CS_CON) {
447 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
449 error("read (%s): %s", c->c_name, strerror(errno));
455 if (c->c_off == c->c_len)
456 switch (c->c_status) {
458 c->c_plen = htonl(c->c_plen);
459 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
461 c->c_data = xmalloc(c->c_len);
462 c->c_status = CS_KEYS;
465 keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
470 fatal("conread: invalid status %d", c->c_status);
481 struct timeval seltime, now;
485 gettimeofday(&now, NULL);
489 (c->c_tv.tv_sec > now.tv_sec ||
490 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
492 seltime.tv_sec -= now.tv_sec;
493 seltime.tv_usec -= now.tv_usec;
494 if ((int) seltime.tv_usec < 0) {
495 seltime.tv_usec += 1000000;
499 seltime.tv_sec = seltime.tv_usec = 0;
502 select(maxfd, &r, NULL, &e, &seltime);
503 for (i = 0; i < maxfd; i++)
504 if (FD_ISSET(i, &e)) {
505 error("%s: exception!", fdcon[i].c_name);
507 } else if (FD_ISSET(i, &r))
512 (c->c_tv.tv_sec < now.tv_sec ||
513 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
515 c = c->c_link.tqe_next;
521 nexthost(int argc, char **argv)
529 if (argv[argno][0] != '-')
530 return (argv[argno++]);
531 if (!strcmp(argv[argno], "--")) {
534 return (argv[argno++]);
535 } else if (!strncmp(argv[argno], "-f", 2)) {
538 fname = &argv[argno++][2];
539 else if (++argno >= argc) {
540 error("missing filename for `-f'");
543 fname = argv[argno++];
544 if (!strcmp(fname, "-"))
546 lb = Linebuf_alloc(fname, error);
548 error("ignoring invalid/misplaced option `%s'", argv[argno++]);
563 fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
568 main(int argc, char **argv)
572 __progname = get_progname(argv[0]);
578 if (argv[1][0] == '-' && argv[1][1] == 't') {
581 timeout = atoi(&argv[1][2]);
585 timeout = atoi(argv[argno++]);
593 maxfd = fdlim_get(1);
595 fatal("%s: fdlim_get: bad value", __progname);
596 if (maxfd > MAXMAXFD)
599 fatal("%s: not enough file descriptors", __progname);
600 if (maxfd > fdlim_get(0))
602 fdcon = xmalloc(maxfd * sizeof(con));
605 while (ncon < maxcon) {
608 host = nexthost(argc, argv);
611 name = strnnsep(&host, " \t\n");
612 conalloc(name, *host ? host : name);