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.6 2000/12/19 23:17:58 markus Exp $");
13 #ifdef HAVE_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);
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;
201 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
204 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
210 * This is an strsep function that returns a null field for adjacent
211 * separators. This is the same as the 4.4BSD strsep, but different from the
212 * one in the GNU libc.
215 xstrsep(char **str, const char *delim)
223 e = s + strcspn(s, delim);
233 * Get the next non-null token (like GNU strsep). Strsep() will return a
234 * null token for two adjacent separators, so we may have to loop.
237 strnnsep(char **stringp, char *delim)
242 tok = xstrsep(stringp, delim);
243 } while (tok && *tok == '\0');
248 keyprint(char *host, char *output_name, char *kd, int len)
255 rsa = key_new(KEY_RSA1);
257 buffer_append(&msg, kd, len);
258 buffer_consume(&msg, 8 - (len & 7)); /* padding */
259 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
260 error("%s: invalid packet type", host);
264 buffer_consume(&msg, 8); /* cookie */
267 (void) buffer_get_int(&msg);
268 buffer_get_bignum(&msg, rsa->rsa->e);
269 buffer_get_bignum(&msg, rsa->rsa->n);
272 (void) buffer_get_int(&msg);
273 buffer_get_bignum(&msg, rsa->rsa->e);
274 buffer_get_bignum(&msg, rsa->rsa->n);
277 fprintf(stdout, "%s ", output_name ? output_name : host);
278 key_write(rsa, stdout);
283 tcpconnect(char *host)
285 struct addrinfo hints, *ai, *aitop;
286 char strport[NI_MAXSERV];
289 snprintf(strport, sizeof strport, "%d", PORT);
290 memset(&hints, 0, sizeof(hints));
291 hints.ai_family = family;
292 hints.ai_socktype = SOCK_STREAM;
293 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
294 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
295 for (ai = aitop; ai; ai = ai->ai_next) {
296 s = socket(ai->ai_family, SOCK_STREAM, 0);
298 error("socket: %s", strerror(errno));
301 if (fcntl(s, F_SETFL, O_NDELAY) < 0)
302 fatal("F_SETFL: %s", strerror(errno));
303 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
304 errno != EINPROGRESS)
305 error("connect (`%s'): %s", host, strerror(errno));
316 conalloc(char *iname, char *oname)
319 char *namebase, *name, *namelist;
321 namebase = namelist = xstrdup(iname);
324 name = xstrsep(&namelist, ",");
329 } while ((s = tcpconnect(name)) < 0);
332 fatal("conalloc: fdno %d too high", s);
333 if (fdcon[s].c_status)
334 fatal("conalloc: attempt to reuse fdno %d", s);
337 fdcon[s].c_status = CS_CON;
338 fdcon[s].c_namebase = namebase;
339 fdcon[s].c_name = name;
340 fdcon[s].c_namelist = namelist;
341 fdcon[s].c_output_name = xstrdup(oname);
342 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
345 gettimeofday(&fdcon[s].c_tv, NULL);
346 fdcon[s].c_tv.tv_sec += timeout;
347 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
348 FD_SET(s, &read_wait);
357 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
358 fatal("confree: attempt to free bad fdno %d", s);
359 free(fdcon[s].c_namebase);
360 free(fdcon[s].c_output_name);
361 if (fdcon[s].c_status == CS_KEYS)
362 free(fdcon[s].c_data);
363 fdcon[s].c_status = CS_UNUSED;
364 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
365 FD_CLR(s, &read_wait);
372 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
373 gettimeofday(&fdcon[s].c_tv, NULL);
374 fdcon[s].c_tv.tv_sec += timeout;
375 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
385 iname = xstrdup(c->c_namelist);
386 oname = c->c_output_name;
387 c->c_output_name = NULL;/* prevent it from being freed */
389 ret = conalloc(iname, oname);
401 n = read(s, buf, sizeof(buf));
403 if (errno != ECONNREFUSED)
404 error("read (%s): %s", c->c_name, strerror(errno));
408 if (buf[n - 1] != '\n') {
409 error("%s: bad greeting", c->c_name);
414 fprintf(stderr, "# %s %s\n", c->c_name, buf);
415 n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
416 if (write(s, buf, n) != n) {
417 error("write (%s): %s", c->c_name, strerror(errno));
421 c->c_status = CS_SIZE;
431 if (c->c_status == CS_CON) {
435 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
437 error("read (%s): %s", c->c_name, strerror(errno));
443 if (c->c_off == c->c_len)
444 switch (c->c_status) {
446 c->c_plen = htonl(c->c_plen);
447 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
449 c->c_data = xmalloc(c->c_len);
450 c->c_status = CS_KEYS;
453 keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
458 fatal("conread: invalid status %d", c->c_status);
469 struct timeval seltime, now;
473 gettimeofday(&now, NULL);
477 (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 ((int) seltime.tv_usec < 0) {
483 seltime.tv_usec += 1000000;
487 seltime.tv_sec = seltime.tv_usec = 0;
490 select(maxfd, &r, NULL, &e, &seltime);
491 for (i = 0; i < maxfd; i++)
492 if (FD_ISSET(i, &e)) {
493 error("%s: exception!", fdcon[i].c_name);
495 } else if (FD_ISSET(i, &r))
500 (c->c_tv.tv_sec < now.tv_sec ||
501 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
503 c = c->c_link.tqe_next;
509 nexthost(int argc, char **argv)
517 if (argv[argno][0] != '-')
518 return (argv[argno++]);
519 if (!strcmp(argv[argno], "--")) {
522 return (argv[argno++]);
523 } else if (!strncmp(argv[argno], "-f", 2)) {
526 fname = &argv[argno++][2];
527 else if (++argno >= argc) {
528 error("missing filename for `-f'");
531 fname = argv[argno++];
532 if (!strcmp(fname, "-"))
534 lb = Linebuf_alloc(fname, error);
536 error("ignoring invalid/misplaced option `%s'", argv[argno++]);
551 fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
556 main(int argc, char **argv)
560 __progname = get_progname(argv[0]);
566 if (argv[1][0] == '-' && argv[1][1] == 't') {
569 timeout = atoi(&argv[1][2]);
573 timeout = atoi(argv[argno++]);
581 maxfd = fdlim_get(1);
583 fatal("%s: fdlim_get: bad value", __progname);
584 if (maxfd > MAXMAXFD)
587 fatal("%s: not enough file descriptors", __progname);
588 if (maxfd > fdlim_get(0))
590 fdcon = xmalloc(maxfd * sizeof(con));
593 while (ncon < maxcon) {
596 host = nexthost(argc, argv);
599 name = strnnsep(&host, " \t\n");
600 conalloc(name, *host ? host : name);