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 #include <sys/queue.h>
16 #include <openssl/bn.h>
27 static int argno = 1; /* Number of argument currently being parsed */
29 int family = AF_UNSPEC; /* IPv4, IPv6 or both */
33 /* The number of seconds after which to give up on a TCP connection */
37 #define MAXCON (maxfd - 10)
39 extern char *__progname;
41 size_t read_wait_size;
45 * Keep a connection structure for each file descriptor. The state
46 * associated with file descriptor n is held in fdcon[n].
48 typedef struct Connection {
49 u_char c_status; /* State of connection on this file desc. */
50 #define CS_UNUSED 0 /* File descriptor unused */
51 #define CS_CON 1 /* Waiting to connect/read greeting */
52 #define CS_SIZE 2 /* Waiting to read initial packet size */
53 #define CS_KEYS 3 /* Waiting to read public key packet */
54 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
55 int c_plen; /* Packet length field for ssh packet */
56 int c_len; /* Total bytes which must be read. */
57 int c_off; /* Length of data read so far. */
58 char *c_namebase; /* Address to free for c_name and c_namelist */
59 char *c_name; /* Hostname of connection for errors */
60 char *c_namelist; /* Pointer to other possible addresses */
61 char *c_output_name; /* Hostname of connection for output */
62 char *c_data; /* Data read from this fd */
63 struct timeval c_tv; /* Time at which connection gets aborted */
64 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
67 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
71 * This is just a wrapper around fgets() to make it usable.
74 /* Stress-test. Increase this later. */
75 #define LINEBUF_SIZE 16
83 void (*errfun) (const char *,...);
87 Linebuf_alloc(const char *filename, void (*errfun) (const char *,...))
91 if (!(lb = malloc(sizeof(*lb)))) {
93 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
97 lb->filename = filename;
98 if (!(lb->stream = fopen(filename, "r"))) {
101 (*errfun) ("%s: %s\n", filename, strerror(errno));
105 lb->filename = "(stdin)";
109 if (!(lb->buf = malloc(lb->size = LINEBUF_SIZE))) {
111 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
121 Linebuf_free(Linebuf * lb)
129 Linebuf_restart(Linebuf * lb)
131 clearerr(lb->stream);
137 Linebuf_lineno(Linebuf * lb)
143 Linebuf_getline(Linebuf * lb)
150 if (!fgets(&lb->buf[n], lb->size - n, lb->stream)) {
151 if (ferror(lb->stream) && lb->errfun)
152 (*lb->errfun) ("%s: %s\n", lb->filename,
158 /* Return it or an error if it fits */
159 if (n > 0 && lb->buf[n - 1] == '\n') {
160 lb->buf[n - 1] = '\0';
163 if (n != lb->size - 1) {
165 (*lb->errfun) ("%s: skipping incomplete last line\n",
169 /* Double the buffer if we need more space */
170 if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
172 (*lb->errfun) ("linebuf (%s): realloc failed\n",
184 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
186 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
189 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
198 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
201 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
207 * This is an strsep function that returns a null field for adjacent
208 * separators. This is the same as the 4.4BSD strsep, but different from the
209 * one in the GNU libc.
212 xstrsep(char **str, const char *delim)
220 e = s + strcspn(s, delim);
230 * Get the next non-null token (like GNU strsep). Strsep() will return a
231 * null token for two adjacent separators, so we may have to loop.
234 strnnsep(char **stringp, char *delim)
239 tok = xstrsep(stringp, delim);
240 } while (tok && *tok == '\0');
245 keyprint(char *host, char *output_name, char *kd, int len)
252 rsa = key_new(KEY_RSA1);
254 buffer_append(&msg, kd, len);
255 buffer_consume(&msg, 8 - (len & 7)); /* padding */
256 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
257 error("%s: invalid packet type", host);
261 buffer_consume(&msg, 8); /* cookie */
264 (void) buffer_get_int(&msg);
265 buffer_get_bignum(&msg, rsa->rsa->e);
266 buffer_get_bignum(&msg, rsa->rsa->n);
269 (void) buffer_get_int(&msg);
270 buffer_get_bignum(&msg, rsa->rsa->e);
271 buffer_get_bignum(&msg, rsa->rsa->n);
274 fprintf(stdout, "%s ", output_name ? output_name : host);
275 key_write(rsa, stdout);
280 tcpconnect(char *host)
282 struct addrinfo hints, *ai, *aitop;
283 char strport[NI_MAXSERV];
286 snprintf(strport, sizeof strport, "%d", SSH_DEFAULT_PORT);
287 memset(&hints, 0, sizeof(hints));
288 hints.ai_family = family;
289 hints.ai_socktype = SOCK_STREAM;
290 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
291 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
292 for (ai = aitop; ai; ai = ai->ai_next) {
293 s = socket(ai->ai_family, SOCK_STREAM, 0);
295 error("socket: %s", strerror(errno));
298 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
299 fatal("F_SETFL: %s", strerror(errno));
300 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
301 errno != EINPROGRESS)
302 error("connect (`%s'): %s", host, strerror(errno));
313 conalloc(char *iname, char *oname)
316 char *namebase, *name, *namelist;
318 namebase = namelist = xstrdup(iname);
321 name = xstrsep(&namelist, ",");
326 } while ((s = tcpconnect(name)) < 0);
329 fatal("conalloc: fdno %d too high", s);
330 if (fdcon[s].c_status)
331 fatal("conalloc: attempt to reuse fdno %d", s);
334 fdcon[s].c_status = CS_CON;
335 fdcon[s].c_namebase = namebase;
336 fdcon[s].c_name = name;
337 fdcon[s].c_namelist = namelist;
338 fdcon[s].c_output_name = xstrdup(oname);
339 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
342 gettimeofday(&fdcon[s].c_tv, NULL);
343 fdcon[s].c_tv.tv_sec += timeout;
344 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
345 FD_SET(s, read_wait);
353 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
354 fatal("confree: attempt to free bad fdno %d", s);
356 xfree(fdcon[s].c_namebase);
357 xfree(fdcon[s].c_output_name);
358 if (fdcon[s].c_status == CS_KEYS)
359 xfree(fdcon[s].c_data);
360 fdcon[s].c_status = CS_UNUSED;
361 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
362 FD_CLR(s, read_wait);
369 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
370 gettimeofday(&fdcon[s].c_tv, NULL);
371 fdcon[s].c_tv.tv_sec += timeout;
372 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
382 iname = xstrdup(c->c_namelist);
383 oname = xstrdup(c->c_output_name);
385 ret = conalloc(iname, oname);
399 bufsiz = sizeof(buf);
401 while (bufsiz-- && (n = read(s, cp, 1)) == 1 && *cp != '\n' && *cp != '\r')
404 if (errno != ECONNREFUSED)
405 error("read (%s): %s", c->c_name, strerror(errno));
409 if (*cp != '\n' && *cp != '\r') {
410 error("%s: bad greeting", c->c_name);
415 fprintf(stderr, "# %s %s\n", c->c_name, buf);
416 n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
417 if (atomicio(write, s, buf, n) != n) {
418 error("write (%s): %s", c->c_name, strerror(errno));
422 c->c_status = CS_SIZE;
432 if (c->c_status == CS_CON) {
436 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
438 error("read (%s): %s", c->c_name, strerror(errno));
444 if (c->c_off == c->c_len)
445 switch (c->c_status) {
447 c->c_plen = htonl(c->c_plen);
448 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
450 c->c_data = xmalloc(c->c_len);
451 c->c_status = CS_KEYS;
454 keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
459 fatal("conread: invalid status %d", c->c_status);
470 struct timeval seltime, now;
474 gettimeofday(&now, NULL);
477 if (c && (c->c_tv.tv_sec > now.tv_sec ||
478 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
480 seltime.tv_sec -= now.tv_sec;
481 seltime.tv_usec -= now.tv_usec;
482 if (seltime.tv_usec < 0) {
483 seltime.tv_usec += 1000000;
487 seltime.tv_sec = seltime.tv_usec = 0;
489 r = xmalloc(read_wait_size);
490 memcpy(r, read_wait, read_wait_size);
491 e = xmalloc(read_wait_size);
492 memcpy(e, read_wait, read_wait_size);
494 while (select(maxfd, r, NULL, e, &seltime) == -1 &&
495 (errno == EAGAIN || errno == EINTR))
498 for (i = 0; i < maxfd; i++) {
499 if (FD_ISSET(i, e)) {
500 error("%s: exception!", fdcon[i].c_name);
502 } else if (FD_ISSET(i, r))
509 while (c && (c->c_tv.tv_sec < now.tv_sec ||
510 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
513 c = c->c_link.tqe_next;
519 nexthost(int argc, char **argv)
527 if (argv[argno][0] != '-')
528 return (argv[argno++]);
529 if (!strcmp(argv[argno], "--")) {
532 return (argv[argno++]);
533 } 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'",
552 line = Linebuf_getline(lb);
564 fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
569 main(int argc, char **argv)
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));
603 memset(fdcon, 0, maxfd * sizeof(con));
605 read_wait_size = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
606 read_wait = xmalloc(read_wait_size);
607 memset(read_wait, 0, read_wait_size);
610 while (ncon < MAXCON) {
613 host = nexthost(argc, argv);
616 name = strnnsep(&host, " \t\n");
617 conalloc(name, *host ? host : name);