1 /* $OpenBSD: ssh-keyscan.c,v 1.72 2006/08/01 23:22:47 stevesk Exp $ */
3 * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>.
5 * Modification and redistribution in source and binary forms is
6 * permitted provided that due credit is given to the author and the
7 * OpenBSD project by leaving this copyright notice intact.
12 #include "openbsd-compat/sys-queue.h"
13 #include <sys/resource.h>
14 #ifdef HAVE_SYS_TIME_H
15 # include <sys/time.h>
18 #include <openssl/bn.h>
35 #include "myproposal.h"
45 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
46 Default value is AF_UNSPEC means both IPv4 and IPv6. */
47 int IPv4or6 = AF_UNSPEC;
49 int ssh_port = SSH_DEFAULT_PORT;
55 int get_keytypes = KT_RSA1; /* Get only RSA1 keys by default */
57 int hash_hosts = 0; /* Hash hostname on output */
61 /* The number of seconds after which to give up on a TCP connection */
65 #define MAXCON (maxfd - 10)
67 extern char *__progname;
69 size_t read_wait_nfdset;
71 int nonfatal_fatal = 0;
76 * Keep a connection structure for each file descriptor. The state
77 * associated with file descriptor n is held in fdcon[n].
79 typedef struct Connection {
80 u_char c_status; /* State of connection on this file desc. */
81 #define CS_UNUSED 0 /* File descriptor unused */
82 #define CS_CON 1 /* Waiting to connect/read greeting */
83 #define CS_SIZE 2 /* Waiting to read initial packet size */
84 #define CS_KEYS 3 /* Waiting to read public key packet */
85 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
86 int c_plen; /* Packet length field for ssh packet */
87 int c_len; /* Total bytes which must be read. */
88 int c_off; /* Length of data read so far. */
89 int c_keytype; /* Only one of KT_RSA1, KT_DSA, or KT_RSA */
90 char *c_namebase; /* Address to free for c_name and c_namelist */
91 char *c_name; /* Hostname of connection for errors */
92 char *c_namelist; /* Pointer to other possible addresses */
93 char *c_output_name; /* Hostname of connection for output */
94 char *c_data; /* Data read from this fd */
95 Kex *c_kex; /* The key-exchange struct for ssh2 */
96 struct timeval c_tv; /* Time at which connection gets aborted */
97 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
100 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
104 * This is just a wrapper around fgets() to make it usable.
107 /* Stress-test. Increase this later. */
108 #define LINEBUF_SIZE 16
114 const char *filename;
116 void (*errfun) (const char *,...);
120 Linebuf_alloc(const char *filename, void (*errfun) (const char *,...))
124 if (!(lb = malloc(sizeof(*lb)))) {
126 (*errfun) ("linebuf (%s): malloc failed\n",
127 filename ? filename : "(stdin)");
131 lb->filename = filename;
132 if (!(lb->stream = fopen(filename, "r"))) {
135 (*errfun) ("%s: %s\n", filename, strerror(errno));
139 lb->filename = "(stdin)";
143 if (!(lb->buf = malloc((lb->size = LINEBUF_SIZE)))) {
145 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
155 Linebuf_free(Linebuf * lb)
164 Linebuf_restart(Linebuf * lb)
166 clearerr(lb->stream);
172 Linebuf_lineno(Linebuf * lb)
179 Linebuf_getline(Linebuf * lb)
187 if (!fgets(&lb->buf[n], lb->size - n, lb->stream)) {
188 if (ferror(lb->stream) && lb->errfun)
189 (*lb->errfun)("%s: %s\n", lb->filename,
195 /* Return it or an error if it fits */
196 if (n > 0 && lb->buf[n - 1] == '\n') {
197 lb->buf[n - 1] = '\0';
200 if (n != lb->size - 1) {
202 (*lb->errfun)("%s: skipping incomplete last line\n",
206 /* Double the buffer if we need more space */
208 if ((p = realloc(lb->buf, lb->size)) == NULL) {
211 (*lb->errfun)("linebuf (%s): realloc failed\n",
222 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
225 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
227 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
230 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
239 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
245 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
246 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
249 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
251 #elif defined (HAVE_SETDTABLESIZE)
258 * This is an strsep function that returns a null field for adjacent
259 * separators. This is the same as the 4.4BSD strsep, but different from the
260 * one in the GNU libc.
263 xstrsep(char **str, const char *delim)
271 e = s + strcspn(s, delim);
281 * Get the next non-null token (like GNU strsep). Strsep() will return a
282 * null token for two adjacent separators, so we may have to loop.
285 strnnsep(char **stringp, char *delim)
290 tok = xstrsep(stringp, delim);
291 } while (tok && *tok == '\0');
303 rsa = key_new(KEY_RSA1);
305 buffer_append(&msg, c->c_data, c->c_plen);
306 buffer_consume(&msg, 8 - (c->c_plen & 7)); /* padding */
307 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
308 error("%s: invalid packet type", c->c_name);
312 buffer_consume(&msg, 8); /* cookie */
315 (void) buffer_get_int(&msg);
316 buffer_get_bignum(&msg, rsa->rsa->e);
317 buffer_get_bignum(&msg, rsa->rsa->n);
320 (void) buffer_get_int(&msg);
321 buffer_get_bignum(&msg, rsa->rsa->e);
322 buffer_get_bignum(&msg, rsa->rsa->n);
330 hostjump(Key *hostkey)
332 kexjmp_key = hostkey;
337 ssh2_capable(int remote_major, int remote_minor)
339 switch (remote_major) {
341 if (remote_minor == 99)
357 packet_set_connection(c->c_fd, c->c_fd);
359 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = c->c_keytype == KT_DSA?
360 "ssh-dss": "ssh-rsa";
361 c->c_kex = kex_setup(myproposal);
362 c->c_kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
363 c->c_kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
364 c->c_kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
365 c->c_kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
366 c->c_kex->verify_host_key = hostjump;
368 if (!(j = setjmp(kexjmp))) {
370 dispatch_run(DISPATCH_BLOCK, &c->c_kex->done, c->c_kex);
371 fprintf(stderr, "Impossible! dispatch_run() returned!\n");
379 return j < 0? NULL : kexjmp_key;
383 keyprint(con *c, Key *key)
385 char *host = c->c_output_name ? c->c_output_name : c->c_name;
389 if (hash_hosts && (host = host_hash(host, NULL, 0)) == NULL)
390 fatal("host_hash failed");
392 fprintf(stdout, "%s ", host);
393 key_write(key, stdout);
398 tcpconnect(char *host)
400 struct addrinfo hints, *ai, *aitop;
401 char strport[NI_MAXSERV];
404 snprintf(strport, sizeof strport, "%d", ssh_port);
405 memset(&hints, 0, sizeof(hints));
406 hints.ai_family = IPv4or6;
407 hints.ai_socktype = SOCK_STREAM;
408 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
409 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
410 for (ai = aitop; ai; ai = ai->ai_next) {
411 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
413 error("socket: %s", strerror(errno));
416 if (set_nonblock(s) == -1)
417 fatal("%s: set_nonblock(%d)", __func__, s);
418 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
419 errno != EINPROGRESS)
420 error("connect (`%s'): %s", host, strerror(errno));
431 conalloc(char *iname, char *oname, int keytype)
433 char *namebase, *name, *namelist;
436 namebase = namelist = xstrdup(iname);
439 name = xstrsep(&namelist, ",");
444 } while ((s = tcpconnect(name)) < 0);
447 fatal("conalloc: fdno %d too high", s);
448 if (fdcon[s].c_status)
449 fatal("conalloc: attempt to reuse fdno %d", s);
452 fdcon[s].c_status = CS_CON;
453 fdcon[s].c_namebase = namebase;
454 fdcon[s].c_name = name;
455 fdcon[s].c_namelist = namelist;
456 fdcon[s].c_output_name = xstrdup(oname);
457 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
460 fdcon[s].c_keytype = keytype;
461 gettimeofday(&fdcon[s].c_tv, NULL);
462 fdcon[s].c_tv.tv_sec += timeout;
463 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
464 FD_SET(s, read_wait);
472 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
473 fatal("confree: attempt to free bad fdno %d", s);
475 xfree(fdcon[s].c_namebase);
476 xfree(fdcon[s].c_output_name);
477 if (fdcon[s].c_status == CS_KEYS)
478 xfree(fdcon[s].c_data);
479 fdcon[s].c_status = CS_UNUSED;
480 fdcon[s].c_keytype = 0;
481 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
482 FD_CLR(s, read_wait);
489 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
490 gettimeofday(&fdcon[s].c_tv, NULL);
491 fdcon[s].c_tv.tv_sec += timeout;
492 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
501 ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
509 int n = 0, remote_major = 0, remote_minor = 0;
511 char remote_version[sizeof buf];
516 memset(buf, '\0', sizeof(buf));
517 bufsiz = sizeof(buf);
520 (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
525 if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
531 error("%s: Connection closed by remote host", c->c_name);
536 error("read (%s): %s", c->c_name, strerror(errno));
542 if (*cp != '\n' && *cp != '\r') {
543 error("%s: bad greeting", c->c_name);
548 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
549 &remote_major, &remote_minor, remote_version) == 3)
550 compat_datafellows(remote_version);
553 if (c->c_keytype != KT_RSA1) {
554 if (!ssh2_capable(remote_major, remote_minor)) {
555 debug("%s doesn't support ssh2", c->c_name);
559 } else if (remote_major != 1) {
560 debug("%s doesn't support ssh1", c->c_name);
564 fprintf(stderr, "# %s %s\n", c->c_name, chop(buf));
565 n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
566 c->c_keytype == KT_RSA1? PROTOCOL_MAJOR_1 : PROTOCOL_MAJOR_2,
567 c->c_keytype == KT_RSA1? PROTOCOL_MINOR_1 : PROTOCOL_MINOR_2);
568 if (n < 0 || (size_t)n >= sizeof(buf)) {
569 error("snprintf: buffer too small");
573 if (atomicio(vwrite, s, buf, n) != (size_t)n) {
574 error("write (%s): %s", c->c_name, strerror(errno));
578 if (c->c_keytype != KT_RSA1) {
579 keyprint(c, keygrab_ssh2(c));
583 c->c_status = CS_SIZE;
593 if (c->c_status == CS_CON) {
597 n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
599 error("read (%s): %s", c->c_name, strerror(errno));
605 if (c->c_off == c->c_len)
606 switch (c->c_status) {
608 c->c_plen = htonl(c->c_plen);
609 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
611 c->c_data = xmalloc(c->c_len);
612 c->c_status = CS_KEYS;
615 keyprint(c, keygrab_ssh1(c));
619 fatal("conread: invalid status %d", c->c_status);
629 struct timeval seltime, now;
634 gettimeofday(&now, NULL);
635 c = TAILQ_FIRST(&tq);
637 if (c && (c->c_tv.tv_sec > now.tv_sec ||
638 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
640 seltime.tv_sec -= now.tv_sec;
641 seltime.tv_usec -= now.tv_usec;
642 if (seltime.tv_usec < 0) {
643 seltime.tv_usec += 1000000;
647 seltime.tv_sec = seltime.tv_usec = 0;
649 r = xcalloc(read_wait_nfdset, sizeof(fd_mask));
650 e = xcalloc(read_wait_nfdset, sizeof(fd_mask));
651 memcpy(r, read_wait, read_wait_nfdset * sizeof(fd_mask));
652 memcpy(e, read_wait, read_wait_nfdset * sizeof(fd_mask));
654 while (select(maxfd, r, NULL, e, &seltime) == -1 &&
655 (errno == EAGAIN || errno == EINTR))
658 for (i = 0; i < maxfd; i++) {
659 if (FD_ISSET(i, e)) {
660 error("%s: exception!", fdcon[i].c_name);
662 } else if (FD_ISSET(i, r))
668 c = TAILQ_FIRST(&tq);
669 while (c && (c->c_tv.tv_sec < now.tv_sec ||
670 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
673 c = TAILQ_NEXT(c, c_link);
681 char *name = strnnsep(&host, " \t\n");
686 for (j = KT_RSA1; j <= KT_RSA; j *= 2) {
687 if (get_keytypes & j) {
688 while (ncon >= MAXCON)
690 conalloc(name, *host ? host : name, j);
696 fatal(const char *fmt,...)
701 do_log(SYSLOG_LEVEL_FATAL, fmt, args);
712 fprintf(stderr, "usage: %s [-46Hv] [-f file] [-p port] [-T timeout] [-t type]\n"
713 "\t\t [host | addrlist namelist] [...]\n",
719 main(int argc, char **argv)
721 int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
722 int opt, fopt_count = 0;
728 __progname = ssh_get_progname(argv[0]);
733 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
739 while ((opt = getopt(argc, argv, "Hv46p:T:t:f:")) != -1) {
745 ssh_port = a2port(optarg);
747 fprintf(stderr, "Bad port '%s'\n", optarg);
752 timeout = convtime(optarg);
753 if (timeout == -1 || timeout == 0) {
754 fprintf(stderr, "Bad timeout '%s'\n", optarg);
761 log_level = SYSLOG_LEVEL_DEBUG1;
763 else if (log_level < SYSLOG_LEVEL_DEBUG3)
766 fatal("Too high debugging level.");
769 if (strcmp(optarg, "-") == 0)
771 argv[fopt_count++] = optarg;
775 tname = strtok(optarg, ",");
777 int type = key_type_from_name(tname);
780 get_keytypes |= KT_RSA1;
783 get_keytypes |= KT_DSA;
786 get_keytypes |= KT_RSA;
789 fatal("unknown key type %s", tname);
791 tname = strtok(NULL, ",");
805 if (optind == argc && !fopt_count)
808 log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
810 maxfd = fdlim_get(1);
812 fatal("%s: fdlim_get: bad value", __progname);
813 if (maxfd > MAXMAXFD)
816 fatal("%s: not enough file descriptors", __progname);
817 if (maxfd > fdlim_get(0))
819 fdcon = xcalloc(maxfd, sizeof(con));
821 read_wait_nfdset = howmany(maxfd, NFDBITS);
822 read_wait = xcalloc(read_wait_nfdset, sizeof(fd_mask));
829 for (j = 0; j < fopt_count; j++) {
830 lb = Linebuf_alloc(argv[j], error);
833 while ((line = Linebuf_getline(lb)) != NULL)
839 while (optind < argc)
840 do_host(argv[optind++]);