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 by leaving this copyright notice intact.
10 RCSID("$OpenBSD: ssh-keyscan.c,v 1.47 2004/03/08 09:38:05 djm Exp $");
12 #include "openbsd-compat/sys-queue.h"
14 #include <openssl/bn.h>
23 #include "myproposal.h"
31 #include "pathnames.h"
33 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
34 Default value is AF_UNSPEC means both IPv4 and IPv6. */
35 int IPv4or6 = AF_UNSPEC;
37 int ssh_port = SSH_DEFAULT_PORT;
43 int get_keytypes = KT_RSA1; /* Get only RSA1 keys by default */
47 /* The number of seconds after which to give up on a TCP connection */
51 #define MAXCON (maxfd - 10)
53 #ifdef HAVE___PROGNAME
54 extern char *__progname;
59 size_t read_wait_size;
61 int nonfatal_fatal = 0;
66 * Keep a connection structure for each file descriptor. The state
67 * associated with file descriptor n is held in fdcon[n].
69 typedef struct Connection {
70 u_char c_status; /* State of connection on this file desc. */
71 #define CS_UNUSED 0 /* File descriptor unused */
72 #define CS_CON 1 /* Waiting to connect/read greeting */
73 #define CS_SIZE 2 /* Waiting to read initial packet size */
74 #define CS_KEYS 3 /* Waiting to read public key packet */
75 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
76 int c_plen; /* Packet length field for ssh packet */
77 int c_len; /* Total bytes which must be read. */
78 int c_off; /* Length of data read so far. */
79 int c_keytype; /* Only one of KT_RSA1, KT_DSA, or KT_RSA */
80 char *c_namebase; /* Address to free for c_name and c_namelist */
81 char *c_name; /* Hostname of connection for errors */
82 char *c_namelist; /* Pointer to other possible addresses */
83 char *c_output_name; /* Hostname of connection for output */
84 char *c_data; /* Data read from this fd */
85 Kex *c_kex; /* The key-exchange struct for ssh2 */
86 struct timeval c_tv; /* Time at which connection gets aborted */
87 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
90 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
94 * This is just a wrapper around fgets() to make it usable.
97 /* Stress-test. Increase this later. */
98 #define LINEBUF_SIZE 16
104 const char *filename;
106 void (*errfun) (const char *,...);
110 Linebuf_alloc(const char *filename, void (*errfun) (const char *,...))
114 if (!(lb = malloc(sizeof(*lb)))) {
116 (*errfun) ("linebuf (%s): malloc failed\n",
117 filename ? filename : "(stdin)");
121 lb->filename = filename;
122 if (!(lb->stream = fopen(filename, "r"))) {
125 (*errfun) ("%s: %s\n", filename, strerror(errno));
129 lb->filename = "(stdin)";
133 if (!(lb->buf = malloc(lb->size = LINEBUF_SIZE))) {
135 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
145 Linebuf_free(Linebuf * lb)
154 Linebuf_restart(Linebuf * lb)
156 clearerr(lb->stream);
162 Linebuf_lineno(Linebuf * lb)
169 Linebuf_getline(Linebuf * lb)
177 if (!fgets(&lb->buf[n], lb->size - n, lb->stream)) {
178 if (ferror(lb->stream) && lb->errfun)
179 (*lb->errfun)("%s: %s\n", lb->filename,
185 /* Return it or an error if it fits */
186 if (n > 0 && lb->buf[n - 1] == '\n') {
187 lb->buf[n - 1] = '\0';
190 if (n != lb->size - 1) {
192 (*lb->errfun)("%s: skipping incomplete last line\n",
196 /* Double the buffer if we need more space */
198 if ((p = realloc(lb->buf, lb->size)) == NULL) {
201 (*lb->errfun)("linebuf (%s): realloc failed\n",
212 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
215 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
217 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
220 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
229 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
235 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
236 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
239 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
241 #elif defined (HAVE_SETDTABLESIZE)
248 * This is an strsep function that returns a null field for adjacent
249 * separators. This is the same as the 4.4BSD strsep, but different from the
250 * one in the GNU libc.
253 xstrsep(char **str, const char *delim)
261 e = s + strcspn(s, delim);
271 * Get the next non-null token (like GNU strsep). Strsep() will return a
272 * null token for two adjacent separators, so we may have to loop.
275 strnnsep(char **stringp, char *delim)
280 tok = xstrsep(stringp, delim);
281 } while (tok && *tok == '\0');
293 rsa = key_new(KEY_RSA1);
295 buffer_append(&msg, c->c_data, c->c_plen);
296 buffer_consume(&msg, 8 - (c->c_plen & 7)); /* padding */
297 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
298 error("%s: invalid packet type", c->c_name);
302 buffer_consume(&msg, 8); /* cookie */
305 (void) buffer_get_int(&msg);
306 buffer_get_bignum(&msg, rsa->rsa->e);
307 buffer_get_bignum(&msg, rsa->rsa->n);
310 (void) buffer_get_int(&msg);
311 buffer_get_bignum(&msg, rsa->rsa->e);
312 buffer_get_bignum(&msg, rsa->rsa->n);
320 hostjump(Key *hostkey)
322 kexjmp_key = hostkey;
327 ssh2_capable(int remote_major, int remote_minor)
329 switch (remote_major) {
331 if (remote_minor == 99)
347 packet_set_connection(c->c_fd, c->c_fd);
349 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = c->c_keytype == KT_DSA?
350 "ssh-dss": "ssh-rsa";
351 c->c_kex = kex_setup(myproposal);
352 c->c_kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
353 c->c_kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
354 c->c_kex->verify_host_key = hostjump;
356 if (!(j = setjmp(kexjmp))) {
358 dispatch_run(DISPATCH_BLOCK, &c->c_kex->done, c->c_kex);
359 fprintf(stderr, "Impossible! dispatch_run() returned!\n");
367 return j < 0? NULL : kexjmp_key;
371 keyprint(con *c, Key *key)
376 fprintf(stdout, "%s ", c->c_output_name ? c->c_output_name : c->c_name);
377 key_write(key, stdout);
382 tcpconnect(char *host)
384 struct addrinfo hints, *ai, *aitop;
385 char strport[NI_MAXSERV];
388 snprintf(strport, sizeof strport, "%d", ssh_port);
389 memset(&hints, 0, sizeof(hints));
390 hints.ai_family = IPv4or6;
391 hints.ai_socktype = SOCK_STREAM;
392 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
393 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
394 for (ai = aitop; ai; ai = ai->ai_next) {
395 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
397 error("socket: %s", strerror(errno));
400 if (fcntl(s, F_SETFL, O_NONBLOCK) < 0)
401 fatal("F_SETFL: %s", strerror(errno));
402 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
403 errno != EINPROGRESS)
404 error("connect (`%s'): %s", host, strerror(errno));
415 conalloc(char *iname, char *oname, int keytype)
417 char *namebase, *name, *namelist;
420 namebase = namelist = xstrdup(iname);
423 name = xstrsep(&namelist, ",");
428 } while ((s = tcpconnect(name)) < 0);
431 fatal("conalloc: fdno %d too high", s);
432 if (fdcon[s].c_status)
433 fatal("conalloc: attempt to reuse fdno %d", s);
436 fdcon[s].c_status = CS_CON;
437 fdcon[s].c_namebase = namebase;
438 fdcon[s].c_name = name;
439 fdcon[s].c_namelist = namelist;
440 fdcon[s].c_output_name = xstrdup(oname);
441 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
444 fdcon[s].c_keytype = keytype;
445 gettimeofday(&fdcon[s].c_tv, NULL);
446 fdcon[s].c_tv.tv_sec += timeout;
447 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
448 FD_SET(s, read_wait);
456 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
457 fatal("confree: attempt to free bad fdno %d", s);
459 xfree(fdcon[s].c_namebase);
460 xfree(fdcon[s].c_output_name);
461 if (fdcon[s].c_status == CS_KEYS)
462 xfree(fdcon[s].c_data);
463 fdcon[s].c_status = CS_UNUSED;
464 fdcon[s].c_keytype = 0;
465 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
466 FD_CLR(s, read_wait);
473 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
474 gettimeofday(&fdcon[s].c_tv, NULL);
475 fdcon[s].c_tv.tv_sec += timeout;
476 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
485 ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
493 int remote_major = 0, remote_minor = 0, n = 0;
495 char remote_version[sizeof buf];
499 bufsiz = sizeof(buf);
501 while (bufsiz-- && (n = read(s, cp, 1)) == 1 && *cp != '\n') {
507 if (errno != ECONNREFUSED)
508 error("read (%s): %s", c->c_name, strerror(errno));
513 error("%s: Connection closed by remote host", c->c_name);
517 if (*cp != '\n' && *cp != '\r') {
518 error("%s: bad greeting", c->c_name);
523 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
524 &remote_major, &remote_minor, remote_version) == 3)
525 compat_datafellows(remote_version);
528 if (c->c_keytype != KT_RSA1) {
529 if (!ssh2_capable(remote_major, remote_minor)) {
530 debug("%s doesn't support ssh2", c->c_name);
534 } else if (remote_major != 1) {
535 debug("%s doesn't support ssh1", c->c_name);
539 fprintf(stderr, "# %s %s\n", c->c_name, chop(buf));
540 n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
541 c->c_keytype == KT_RSA1? PROTOCOL_MAJOR_1 : PROTOCOL_MAJOR_2,
542 c->c_keytype == KT_RSA1? PROTOCOL_MINOR_1 : PROTOCOL_MINOR_2);
543 if (atomicio(vwrite, s, buf, n) != n) {
544 error("write (%s): %s", c->c_name, strerror(errno));
548 if (c->c_keytype != KT_RSA1) {
549 keyprint(c, keygrab_ssh2(c));
553 c->c_status = CS_SIZE;
563 if (c->c_status == CS_CON) {
567 n = read(s, c->c_data + c->c_off, c->c_len - c->c_off);
569 error("read (%s): %s", c->c_name, strerror(errno));
575 if (c->c_off == c->c_len)
576 switch (c->c_status) {
578 c->c_plen = htonl(c->c_plen);
579 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
581 c->c_data = xmalloc(c->c_len);
582 c->c_status = CS_KEYS;
585 keyprint(c, keygrab_ssh1(c));
590 fatal("conread: invalid status %d", c->c_status);
600 struct timeval seltime, now;
605 gettimeofday(&now, NULL);
606 c = TAILQ_FIRST(&tq);
608 if (c && (c->c_tv.tv_sec > now.tv_sec ||
609 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
611 seltime.tv_sec -= now.tv_sec;
612 seltime.tv_usec -= now.tv_usec;
613 if (seltime.tv_usec < 0) {
614 seltime.tv_usec += 1000000;
618 seltime.tv_sec = seltime.tv_usec = 0;
620 r = xmalloc(read_wait_size);
621 memcpy(r, read_wait, read_wait_size);
622 e = xmalloc(read_wait_size);
623 memcpy(e, read_wait, read_wait_size);
625 while (select(maxfd, r, NULL, e, &seltime) == -1 &&
626 (errno == EAGAIN || errno == EINTR))
629 for (i = 0; i < maxfd; i++) {
630 if (FD_ISSET(i, e)) {
631 error("%s: exception!", fdcon[i].c_name);
633 } else if (FD_ISSET(i, r))
639 c = TAILQ_FIRST(&tq);
640 while (c && (c->c_tv.tv_sec < now.tv_sec ||
641 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
644 c = TAILQ_NEXT(c, c_link);
652 char *name = strnnsep(&host, " \t\n");
657 for (j = KT_RSA1; j <= KT_RSA; j *= 2) {
658 if (get_keytypes & j) {
659 while (ncon >= MAXCON)
661 conalloc(name, *host ? host : name, j);
667 fatal(const char *fmt,...)
672 do_log(SYSLOG_LEVEL_FATAL, fmt, args);
683 fprintf(stderr, "usage: %s [-v46] [-p port] [-T timeout] [-t type] [-f file]\n"
684 "\t\t [host | addrlist namelist] [...]\n",
690 main(int argc, char **argv)
692 int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
693 int opt, fopt_count = 0;
699 __progname = ssh_get_progname(argv[0]);
708 while ((opt = getopt(argc, argv, "v46p:T:t:f:")) != -1) {
711 ssh_port = a2port(optarg);
713 fprintf(stderr, "Bad port '%s'\n", optarg);
718 timeout = convtime(optarg);
719 if (timeout == -1 || timeout == 0) {
720 fprintf(stderr, "Bad timeout '%s'\n", optarg);
727 log_level = SYSLOG_LEVEL_DEBUG1;
729 else if (log_level < SYSLOG_LEVEL_DEBUG3)
732 fatal("Too high debugging level.");
735 if (strcmp(optarg, "-") == 0)
737 argv[fopt_count++] = optarg;
741 tname = strtok(optarg, ",");
743 int type = key_type_from_name(tname);
746 get_keytypes |= KT_RSA1;
749 get_keytypes |= KT_DSA;
752 get_keytypes |= KT_RSA;
755 fatal("unknown key type %s", tname);
757 tname = strtok(NULL, ",");
771 if (optind == argc && !fopt_count)
774 log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
776 maxfd = fdlim_get(1);
778 fatal("%s: fdlim_get: bad value", __progname);
779 if (maxfd > MAXMAXFD)
782 fatal("%s: not enough file descriptors", __progname);
783 if (maxfd > fdlim_get(0))
785 fdcon = xmalloc(maxfd * sizeof(con));
786 memset(fdcon, 0, maxfd * sizeof(con));
788 read_wait_size = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
789 read_wait = xmalloc(read_wait_size);
790 memset(read_wait, 0, read_wait_size);
797 for (j = 0; j < fopt_count; j++) {
798 lb = Linebuf_alloc(argv[j], error);
801 while ((line = Linebuf_getline(lb)) != NULL)
807 while (optind < argc)
808 do_host(argv[optind++]);