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.1 2000/12/04 19:24:02 markus Exp $");
13 #include <sys/queue.h>
17 #include <openssl/bn.h>
18 #include <openssl/rsa.h>
19 #include <openssl/dsa.h>
27 static int argno = 1; /* Number of argument currently being parsed */
29 int family = AF_UNSPEC; /* IPv4, IPv6 or both */
34 /* The number of seconds after which to give up on a TCP connection */
38 #define maxcon (maxfd - 10)
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 unsigned 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 *,...);
86 static inline Linebuf *
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 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, strerror(errno));
157 /* Return it or an error if it fits */
158 if (n > 0 && lb->buf[n - 1] == '\n') {
159 lb->buf[n - 1] = '\0';
162 if (n != lb->size - 1) {
164 (*lb->errfun) ("%s: skipping incomplete last line\n", lb->filename);
167 /* Double the buffer if we need more space */
168 if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
170 (*lb->errfun) ("linebuf (%s): realloc failed\n", lb->filename);
180 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
182 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
185 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
194 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
197 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
203 * This is an strsep function that returns a null field for adjacent
204 * separators. This is the same as the 4.4BSD strsep, but different from the
205 * one in the GNU libc.
208 xstrsep(char **str, const char *delim)
216 e = s + strcspn(s, delim);
226 * Get the next non-null token (like GNU strsep). Strsep() will return a
227 * null token for two adjacent separators, so we may have to loop.
230 strnnsep(char **stringp, char *delim)
235 tok = xstrsep(stringp, delim);
236 } while (tok && *tok == '\0');
241 keyprint(char *host, char *output_name, char *kd, int len)
248 rsa = key_new(KEY_RSA1);
250 buffer_append(&msg, kd, len);
251 buffer_consume(&msg, 8 - (len & 7)); /* padding */
252 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
253 error("%s: invalid packet type", host);
257 buffer_consume(&msg, 8); /* cookie */
260 (void) buffer_get_int(&msg);
261 buffer_get_bignum(&msg, rsa->rsa->e);
262 buffer_get_bignum(&msg, rsa->rsa->n);
265 (void) buffer_get_int(&msg);
266 buffer_get_bignum(&msg, rsa->rsa->e);
267 buffer_get_bignum(&msg, rsa->rsa->n);
270 fprintf(stdout, "%s ", output_name ? output_name : host);
271 key_write(rsa, stdout);
276 tcpconnect(char *host)
278 struct addrinfo hints, *ai, *aitop;
279 char strport[NI_MAXSERV];
282 snprintf(strport, sizeof strport, "%d", PORT);
283 memset(&hints, 0, sizeof(hints));
284 hints.ai_family = family;
285 hints.ai_socktype = SOCK_STREAM;
286 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
287 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
288 for (ai = aitop; ai; ai = ai->ai_next) {
289 s = socket(ai->ai_family, SOCK_STREAM, 0);
291 error("socket: %s", strerror(errno));
294 if (fcntl(s, F_SETFL, O_NDELAY) < 0)
295 fatal("F_SETFL: %s", strerror(errno));
296 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
297 errno != EINPROGRESS)
298 error("connect (`%s'): %s", host, strerror(errno));
309 conalloc(char *iname, char *oname)
312 char *namebase, *name, *namelist;
314 namebase = namelist = xstrdup(iname);
317 name = xstrsep(&namelist, ",");
322 } while ((s = tcpconnect(name)) < 0);
325 fatal("conalloc: fdno %d too high\n", s);
326 if (fdcon[s].c_status)
327 fatal("conalloc: attempt to reuse fdno %d\n", s);
330 fdcon[s].c_status = CS_CON;
331 fdcon[s].c_namebase = namebase;
332 fdcon[s].c_name = name;
333 fdcon[s].c_namelist = namelist;
334 fdcon[s].c_output_name = xstrdup(oname);
335 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
338 gettimeofday(&fdcon[s].c_tv, NULL);
339 fdcon[s].c_tv.tv_sec += timeout;
340 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
341 FD_SET(s, &read_wait);
350 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
351 fatal("confree: attempt to free bad fdno %d\n", s);
352 free(fdcon[s].c_namebase);
353 free(fdcon[s].c_output_name);
354 if (fdcon[s].c_status == CS_KEYS)
355 free(fdcon[s].c_data);
356 fdcon[s].c_status = CS_UNUSED;
357 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
358 FD_CLR(s, &read_wait);
365 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
366 gettimeofday(&fdcon[s].c_tv, NULL);
367 fdcon[s].c_tv.tv_sec += timeout;
368 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
378 iname = xstrdup(c->c_namelist);
379 oname = c->c_output_name;
380 c->c_output_name = NULL;/* prevent it from being freed */
382 ret = conalloc(iname, oname);
394 n = read(s, buf, sizeof(buf));
396 if (errno != ECONNREFUSED)
397 error("read (%s): %s", c->c_name, strerror(errno));
401 if (buf[n - 1] != '\n') {
402 error("%s: bad greeting", c->c_name);
407 fprintf(stderr, "# %s %s\n", c->c_name, buf);
408 n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
409 if (write(s, buf, n) != n) {
410 error("write (%s): %s", c->c_name, strerror(errno));
414 c->c_status = CS_SIZE;
424 if (c->c_status == CS_CON) {
428 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
430 error("read (%s): %s", c->c_name, strerror(errno));
436 if (c->c_off == c->c_len)
437 switch (c->c_status) {
439 c->c_plen = htonl(c->c_plen);
440 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
442 c->c_data = xmalloc(c->c_len);
443 c->c_status = CS_KEYS;
446 keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
451 fatal("conread: invalid status %d\n", c->c_status);
462 struct timeval seltime, now;
466 gettimeofday(&now, NULL);
470 (c->c_tv.tv_sec > now.tv_sec ||
471 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
473 seltime.tv_sec -= now.tv_sec;
474 seltime.tv_usec -= now.tv_usec;
475 if ((int) seltime.tv_usec < 0) {
476 seltime.tv_usec += 1000000;
480 seltime.tv_sec = seltime.tv_usec = 0;
483 select(maxfd, &r, NULL, &e, &seltime);
484 for (i = 0; i < maxfd; i++)
485 if (FD_ISSET(i, &e)) {
486 error("%s: exception!", fdcon[i].c_name);
488 } else if (FD_ISSET(i, &r))
493 (c->c_tv.tv_sec < now.tv_sec ||
494 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
496 c = c->c_link.tqe_next;
502 nexthost(int argc, char **argv)
510 if (argv[argno][0] != '-')
511 return (argv[argno++]);
512 if (!strcmp(argv[argno], "--")) {
515 return (argv[argno++]);
516 } else if (!strncmp(argv[argno], "-f", 2)) {
519 fname = &argv[argno++][2];
520 else if (++argno >= argc) {
521 error("missing filename for `-f'");
524 fname = argv[argno++];
525 if (!strcmp(fname, "-"))
527 lb = Linebuf_alloc(fname, warn);
529 error("ignoring invalid/misplaced option `%s'", argv[argno++]);
544 fatal("usage: %s [-t timeout] { [--] host | -f file } ...\n", prog);
549 main(int argc, char **argv)
555 if ((prog = strrchr(argv[0], '/')))
563 if (argv[1][0] == '-' && argv[1][1] == 't') {
566 timeout = atoi(&argv[1][2]);
570 timeout = atoi(argv[argno++]);
578 maxfd = fdlim_get(1);
580 fatal("%s: fdlim_get: bad value\n", prog);
581 if (maxfd > MAXMAXFD)
584 fatal("%s: not enough file descriptors\n", prog);
585 if (maxfd > fdlim_get(0))
587 fdcon = xmalloc(maxfd * sizeof(con));
590 while (ncon < maxcon) {
593 host = nexthost(argc, argv);
596 name = strnnsep(&host, " \t\n");
597 conalloc(name, *host ? host : name);