]> andersk Git - openssh.git/blob - ssh-keyscan.c
- deraadt@cvs.openbsd.org 2001/02/21 07:37:04
[openssh.git] / ssh-keyscan.c
1 /*
2  * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>.
3  *
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
7  * intact).
8  */
9
10 #include "includes.h"
11 RCSID("$OpenBSD: ssh-keyscan.c,v 1.17 2001/02/21 07:37:04 deraadt Exp $");
12
13 #if defined(HAVE_SYS_QUEUE_H) && !defined(HAVE_BOGUS_SYS_QUEUE_H)
14 #include <sys/queue.h>
15 #else
16 #include "fake-queue.h"
17 #endif
18 #include <errno.h>
19
20 #include <openssl/bn.h>
21
22 #include "xmalloc.h"
23 #include "ssh.h"
24 #include "ssh1.h"
25 #include "key.h"
26 #include "buffer.h"
27 #include "bufaux.h"
28 #include "log.h"
29
30 static int argno = 1;           /* Number of argument currently being parsed */
31
32 int family = AF_UNSPEC;         /* IPv4, IPv6 or both */
33
34 #define MAXMAXFD 256
35
36 /* The number of seconds after which to give up on a TCP connection */
37 int timeout = 5;
38
39 int maxfd;
40 #define maxcon (maxfd - 10)
41
42 #ifdef HAVE___PROGNAME
43 extern char *__progname;
44 #else
45 char *__progname;
46 #endif
47 fd_set read_wait;
48 int ncon;
49
50 /*
51  * Keep a connection structure for each file descriptor.  The state
52  * associated with file descriptor n is held in fdcon[n].
53  */
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. */
71 } con;
72
73 TAILQ_HEAD(conlist, Connection) tq;     /* Timeout Queue */
74 con *fdcon;
75
76 /*
77  *  This is just a wrapper around fgets() to make it usable.
78  */
79
80 /* Stress-test.  Increase this later. */
81 #define LINEBUF_SIZE 16
82
83 typedef struct {
84         char *buf;
85         u_int size;
86         int lineno;
87         const char *filename;
88         FILE *stream;
89         void (*errfun) (const char *,...);
90 } Linebuf;
91
92 static __inline__ Linebuf *
93 Linebuf_alloc(const char *filename, void (*errfun) (const char *,...))
94 {
95         Linebuf *lb;
96
97         if (!(lb = malloc(sizeof(*lb)))) {
98                 if (errfun)
99                         (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
100                 return (NULL);
101         }
102         if (filename) {
103                 lb->filename = filename;
104                 if (!(lb->stream = fopen(filename, "r"))) {
105                         xfree(lb);
106                         if (errfun)
107                                 (*errfun) ("%s: %s\n", filename, strerror(errno));
108                         return (NULL);
109                 }
110         } else {
111                 lb->filename = "(stdin)";
112                 lb->stream = stdin;
113         }
114
115         if (!(lb->buf = malloc(lb->size = LINEBUF_SIZE))) {
116                 if (errfun)
117                         (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
118                 xfree(lb);
119                 return (NULL);
120         }
121         lb->errfun = errfun;
122         lb->lineno = 0;
123         return (lb);
124 }
125
126 static __inline__ void
127 Linebuf_free(Linebuf * lb)
128 {
129         fclose(lb->stream);
130         xfree(lb->buf);
131         xfree(lb);
132 }
133
134 static __inline__ void
135 Linebuf_restart(Linebuf * lb)
136 {
137         clearerr(lb->stream);
138         rewind(lb->stream);
139         lb->lineno = 0;
140 }
141
142 static __inline__ int
143 Linebuf_lineno(Linebuf * lb)
144 {
145         return (lb->lineno);
146 }
147
148 static __inline__ char *
149 Linebuf_getline(Linebuf * lb)
150 {
151         int n = 0;
152
153         lb->lineno++;
154         for (;;) {
155                 /* Read a line */
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,
159                                     strerror(errno));
160                         return (NULL);
161                 }
162                 n = strlen(lb->buf);
163
164                 /* Return it or an error if it fits */
165                 if (n > 0 && lb->buf[n - 1] == '\n') {
166                         lb->buf[n - 1] = '\0';
167                         return (lb->buf);
168                 }
169                 if (n != lb->size - 1) {
170                         if (lb->errfun)
171                                 (*lb->errfun) ("%s: skipping incomplete last line\n",
172                                     lb->filename);
173                         return (NULL);
174                 }
175                 /* Double the buffer if we need more space */
176                 if (!(lb->buf = realloc(lb->buf, (lb->size *= 2)))) {
177                         if (lb->errfun)
178                                 (*lb->errfun) ("linebuf (%s): realloc failed\n",
179                                     lb->filename);
180                         return (NULL);
181                 }
182         }
183 }
184
185 static int
186 fdlim_get(int hard)
187 {
188 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
189         struct rlimit rlfd;
190
191         if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
192                 return (-1);
193         if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
194                 return 10000;
195         else
196                 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
197 #elif defined (HAVE_SYSCONF)
198         return sysconf (_SC_OPEN_MAX);
199 #else
200         return 10000;
201 #endif
202 }
203
204 static int
205 fdlim_set(int lim)
206 {
207 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
208         struct rlimit rlfd;
209 #endif
210         if (lim <= 0)
211                 return (-1);
212 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
213         if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
214                 return (-1);
215         rlfd.rlim_cur = lim;
216         if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
217                 return (-1);
218 #elif defined (HAVE_SETDTABLESIZE)
219         setdtablesize(lim);
220 #endif
221         return (0);
222 }
223
224 /*
225  * This is an strsep function that returns a null field for adjacent
226  * separators.  This is the same as the 4.4BSD strsep, but different from the
227  * one in the GNU libc.
228  */
229 static __inline__ char *
230 xstrsep(char **str, const char *delim)
231 {
232         char *s, *e;
233
234         if (!**str)
235                 return (NULL);
236
237         s = *str;
238         e = s + strcspn(s, delim);
239
240         if (*e != '\0')
241                 *e++ = '\0';
242         *str = e;
243
244         return (s);
245 }
246
247 /*
248  * Get the next non-null token (like GNU strsep).  Strsep() will return a
249  * null token for two adjacent separators, so we may have to loop.
250  */
251 char *
252 strnnsep(char **stringp, char *delim)
253 {
254         char *tok;
255
256         do {
257                 tok = xstrsep(stringp, delim);
258         } while (tok && *tok == '\0');
259         return (tok);
260 }
261
262 void
263 keyprint(char *host, char *output_name, char *kd, int len)
264 {
265         static Key *rsa;
266         static Buffer msg;
267
268         if (rsa == NULL) {
269                 buffer_init(&msg);
270                 rsa = key_new(KEY_RSA1);
271         }
272         buffer_append(&msg, kd, len);
273         buffer_consume(&msg, 8 - (len & 7));    /* padding */
274         if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
275                 error("%s: invalid packet type", host);
276                 buffer_clear(&msg);
277                 return;
278         }
279         buffer_consume(&msg, 8);                /* cookie */
280
281         /* server key */
282         (void) buffer_get_int(&msg);
283         buffer_get_bignum(&msg, rsa->rsa->e);
284         buffer_get_bignum(&msg, rsa->rsa->n);
285
286         /* host key */
287         (void) buffer_get_int(&msg);
288         buffer_get_bignum(&msg, rsa->rsa->e);
289         buffer_get_bignum(&msg, rsa->rsa->n);
290         buffer_clear(&msg);
291
292         fprintf(stdout, "%s ", output_name ? output_name : host);
293         key_write(rsa, stdout);
294         fputs("\n", stdout);
295 }
296
297 int
298 tcpconnect(char *host)
299 {
300         struct addrinfo hints, *ai, *aitop;
301         char strport[NI_MAXSERV];
302         int gaierr, s = -1;
303
304         snprintf(strport, sizeof strport, "%d", SSH_DEFAULT_PORT);
305         memset(&hints, 0, sizeof(hints));
306         hints.ai_family = family;
307         hints.ai_socktype = SOCK_STREAM;
308         if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
309                 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
310         for (ai = aitop; ai; ai = ai->ai_next) {
311                 s = socket(ai->ai_family, SOCK_STREAM, 0);
312                 if (s < 0) {
313                         error("socket: %s", strerror(errno));
314                         continue;
315                 }
316                 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
317                         fatal("F_SETFL: %s", strerror(errno));
318                 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
319                     errno != EINPROGRESS)
320                         error("connect (`%s'): %s", host, strerror(errno));
321                 else
322                         break;
323                 close(s);
324                 s = -1;
325         }
326         freeaddrinfo(aitop);
327         return s;
328 }
329
330 int
331 conalloc(char *iname, char *oname)
332 {
333         int s;
334         char *namebase, *name, *namelist;
335
336         namebase = namelist = xstrdup(iname);
337
338         do {
339                 name = xstrsep(&namelist, ",");
340                 if (!name) {
341                         xfree(namebase);
342                         return (-1);
343                 }
344         } while ((s = tcpconnect(name)) < 0);
345
346         if (s >= maxfd)
347                 fatal("conalloc: fdno %d too high", s);
348         if (fdcon[s].c_status)
349                 fatal("conalloc: attempt to reuse fdno %d", s);
350
351         fdcon[s].c_fd = s;
352         fdcon[s].c_status = CS_CON;
353         fdcon[s].c_namebase = namebase;
354         fdcon[s].c_name = name;
355         fdcon[s].c_namelist = namelist;
356         fdcon[s].c_output_name = xstrdup(oname);
357         fdcon[s].c_data = (char *) &fdcon[s].c_plen;
358         fdcon[s].c_len = 4;
359         fdcon[s].c_off = 0;
360         gettimeofday(&fdcon[s].c_tv, NULL);
361         fdcon[s].c_tv.tv_sec += timeout;
362         TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
363         FD_SET(s, &read_wait);
364         ncon++;
365         return (s);
366 }
367
368 void
369 confree(int s)
370 {
371         close(s);
372         if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
373                 fatal("confree: attempt to free bad fdno %d", s);
374         xfree(fdcon[s].c_namebase);
375         xfree(fdcon[s].c_output_name);
376         if (fdcon[s].c_status == CS_KEYS)
377                 xfree(fdcon[s].c_data);
378         fdcon[s].c_status = CS_UNUSED;
379         TAILQ_REMOVE(&tq, &fdcon[s], c_link);
380         FD_CLR(s, &read_wait);
381         ncon--;
382 }
383
384 void
385 contouch(int s)
386 {
387         TAILQ_REMOVE(&tq, &fdcon[s], c_link);
388         gettimeofday(&fdcon[s].c_tv, NULL);
389         fdcon[s].c_tv.tv_sec += timeout;
390         TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
391 }
392
393 int
394 conrecycle(int s)
395 {
396         int ret;
397         con *c = &fdcon[s];
398         char *iname, *oname;
399
400         iname = xstrdup(c->c_namelist);
401         oname = xstrdup(c->c_output_name);
402         confree(s);
403         ret = conalloc(iname, oname);
404         xfree(iname);
405         xfree(oname);
406         return (ret);
407 }
408
409 void
410 congreet(int s)
411 {
412         char buf[80];
413         int n;
414         con *c = &fdcon[s];
415
416         n = read(s, buf, sizeof(buf));
417         if (n < 0) {
418                 if (errno != ECONNREFUSED)
419                         error("read (%s): %s", c->c_name, strerror(errno));
420                 conrecycle(s);
421                 return;
422         }
423         if (buf[n - 1] != '\n') {
424                 error("%s: bad greeting", c->c_name);
425                 confree(s);
426                 return;
427         }
428         buf[n - 1] = '\0';
429         fprintf(stderr, "# %s %s\n", c->c_name, buf);
430         n = snprintf(buf, sizeof buf, "SSH-1.5-OpenSSH-keyscan\r\n");
431         if (write(s, buf, n) != n) {
432                 error("write (%s): %s", c->c_name, strerror(errno));
433                 confree(s);
434                 return;
435         }
436         c->c_status = CS_SIZE;
437         contouch(s);
438 }
439
440 void
441 conread(int s)
442 {
443         int n;
444         con *c = &fdcon[s];
445
446         if (c->c_status == CS_CON) {
447                 congreet(s);
448                 return;
449         }
450         n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
451         if (n < 0) {
452                 error("read (%s): %s", c->c_name, strerror(errno));
453                 confree(s);
454                 return;
455         }
456         c->c_off += n;
457
458         if (c->c_off == c->c_len)
459                 switch (c->c_status) {
460                 case CS_SIZE:
461                         c->c_plen = htonl(c->c_plen);
462                         c->c_len = c->c_plen + 8 - (c->c_plen & 7);
463                         c->c_off = 0;
464                         c->c_data = xmalloc(c->c_len);
465                         c->c_status = CS_KEYS;
466                         break;
467                 case CS_KEYS:
468                         keyprint(c->c_name, c->c_output_name, c->c_data, c->c_plen);
469                         confree(s);
470                         return;
471                         break;
472                 default:
473                         fatal("conread: invalid status %d", c->c_status);
474                         break;
475                 }
476
477         contouch(s);
478 }
479
480 void
481 conloop(void)
482 {
483         fd_set r, e;
484         struct timeval seltime, now;
485         int i;
486         con *c;
487
488         gettimeofday(&now, NULL);
489         c = tq.tqh_first;
490
491         if (c &&
492             (c->c_tv.tv_sec > now.tv_sec ||
493              (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
494                 seltime = c->c_tv;
495                 seltime.tv_sec -= now.tv_sec;
496                 seltime.tv_usec -= now.tv_usec;
497                 if (seltime.tv_usec < 0) {
498                         seltime.tv_usec += 1000000;
499                         seltime.tv_sec--;
500                 }
501         } else
502                 seltime.tv_sec = seltime.tv_usec = 0;
503
504         r = e = read_wait;
505         while (select(maxfd, &r, NULL, &e, &seltime) == -1 &&
506             (errno == EAGAIN || errno == EINTR))
507                 ;
508
509         for (i = 0; i < maxfd; i++)
510                 if (FD_ISSET(i, &e)) {
511                         error("%s: exception!", fdcon[i].c_name);
512                         confree(i);
513                 } else if (FD_ISSET(i, &r))
514                         conread(i);
515
516         c = tq.tqh_first;
517         while (c &&
518                (c->c_tv.tv_sec < now.tv_sec ||
519                 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
520                 int s = c->c_fd;
521                 c = c->c_link.tqe_next;
522                 conrecycle(s);
523         }
524 }
525
526 char *
527 nexthost(int argc, char **argv)
528 {
529         static Linebuf *lb;
530
531         for (;;) {
532                 if (!lb) {
533                         if (argno >= argc)
534                                 return (NULL);
535                         if (argv[argno][0] != '-')
536                                 return (argv[argno++]);
537                         if (!strcmp(argv[argno], "--")) {
538                                 if (++argno >= argc)
539                                         return (NULL);
540                                 return (argv[argno++]);
541                         } else if (!strncmp(argv[argno], "-f", 2)) {
542                                 char *fname;
543                                 if (argv[argno][2])
544                                         fname = &argv[argno++][2];
545                                 else if (++argno >= argc) {
546                                         error("missing filename for `-f'");
547                                         return (NULL);
548                                 } else
549                                         fname = argv[argno++];
550                                 if (!strcmp(fname, "-"))
551                                         fname = NULL;
552                                 lb = Linebuf_alloc(fname, error);
553                         } else
554                                 error("ignoring invalid/misplaced option `%s'", argv[argno++]);
555                 } else {
556                         char *line;
557                         line = Linebuf_getline(lb);
558                         if (line)
559                                 return (line);
560                         Linebuf_free(lb);
561                         lb = NULL;
562                 }
563         }
564 }
565
566 static void
567 usage(void)
568 {
569         fatal("usage: %s [-t timeout] { [--] host | -f file } ...", __progname);
570         return;
571 }
572
573 int
574 main(int argc, char **argv)
575 {
576         char *host = NULL;
577
578         __progname = get_progname(argv[0]);
579         TAILQ_INIT(&tq);
580
581         if (argc <= argno)
582                 usage();
583
584         if (argv[1][0] == '-' && argv[1][1] == 't') {
585                 argno++;
586                 if (argv[1][2])
587                         timeout = atoi(&argv[1][2]);
588                 else {
589                         if (argno >= argc)
590                                 usage();
591                         timeout = atoi(argv[argno++]);
592                 }
593                 if (timeout <= 0)
594                         usage();
595         }
596         if (argc <= argno)
597                 usage();
598
599         maxfd = fdlim_get(1);
600         if (maxfd < 0)
601                 fatal("%s: fdlim_get: bad value", __progname);
602         if (maxfd > MAXMAXFD)
603                 maxfd = MAXMAXFD;
604         if (maxcon <= 0)
605                 fatal("%s: not enough file descriptors", __progname);
606         if (maxfd > fdlim_get(0))
607                 fdlim_set(maxfd);
608         fdcon = xmalloc(maxfd * sizeof(con));
609         memset(fdcon, 0, maxfd * sizeof(con));
610
611         do {
612                 while (ncon < maxcon) {
613                         char *name;
614
615                         host = nexthost(argc, argv);
616                         if (host == NULL)
617                                 break;
618                         name = strnnsep(&host, " \t\n");
619                         conalloc(name, *host ? host : name);
620                 }
621                 conloop();
622         } while (host);
623         while (ncon > 0)
624                 conloop();
625
626         return (0);
627 }
This page took 0.089707 seconds and 5 git commands to generate.