1 /* $OpenBSD: ssh-keyscan.c,v 1.66 2006/07/10 16:37:36 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>
16 #include <openssl/bn.h>
25 #include "myproposal.h"
35 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
36 Default value is AF_UNSPEC means both IPv4 and IPv6. */
37 int IPv4or6 = AF_UNSPEC;
39 int ssh_port = SSH_DEFAULT_PORT;
45 int get_keytypes = KT_RSA1; /* Get only RSA1 keys by default */
47 int hash_hosts = 0; /* Hash hostname on output */
51 /* The number of seconds after which to give up on a TCP connection */
55 #define MAXCON (maxfd - 10)
57 extern char *__progname;
59 size_t read_wait_nfdset;
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_GRP14_SHA1] = kexdh_client;
354 c->c_kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
355 c->c_kex->kex[KEX_DH_GEX_SHA256] = kexgex_client;
356 c->c_kex->verify_host_key = hostjump;
358 if (!(j = setjmp(kexjmp))) {
360 dispatch_run(DISPATCH_BLOCK, &c->c_kex->done, c->c_kex);
361 fprintf(stderr, "Impossible! dispatch_run() returned!\n");
369 return j < 0? NULL : kexjmp_key;
373 keyprint(con *c, Key *key)
375 char *host = c->c_output_name ? c->c_output_name : c->c_name;
379 if (hash_hosts && (host = host_hash(host, NULL, 0)) == NULL)
380 fatal("host_hash failed");
382 fprintf(stdout, "%s ", host);
383 key_write(key, stdout);
388 tcpconnect(char *host)
390 struct addrinfo hints, *ai, *aitop;
391 char strport[NI_MAXSERV];
394 snprintf(strport, sizeof strport, "%d", ssh_port);
395 memset(&hints, 0, sizeof(hints));
396 hints.ai_family = IPv4or6;
397 hints.ai_socktype = SOCK_STREAM;
398 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
399 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
400 for (ai = aitop; ai; ai = ai->ai_next) {
401 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
403 error("socket: %s", strerror(errno));
406 if (set_nonblock(s) == -1)
407 fatal("%s: set_nonblock(%d)", __func__, s);
408 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
409 errno != EINPROGRESS)
410 error("connect (`%s'): %s", host, strerror(errno));
421 conalloc(char *iname, char *oname, int keytype)
423 char *namebase, *name, *namelist;
426 namebase = namelist = xstrdup(iname);
429 name = xstrsep(&namelist, ",");
434 } while ((s = tcpconnect(name)) < 0);
437 fatal("conalloc: fdno %d too high", s);
438 if (fdcon[s].c_status)
439 fatal("conalloc: attempt to reuse fdno %d", s);
442 fdcon[s].c_status = CS_CON;
443 fdcon[s].c_namebase = namebase;
444 fdcon[s].c_name = name;
445 fdcon[s].c_namelist = namelist;
446 fdcon[s].c_output_name = xstrdup(oname);
447 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
450 fdcon[s].c_keytype = keytype;
451 gettimeofday(&fdcon[s].c_tv, NULL);
452 fdcon[s].c_tv.tv_sec += timeout;
453 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
454 FD_SET(s, read_wait);
462 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
463 fatal("confree: attempt to free bad fdno %d", s);
465 xfree(fdcon[s].c_namebase);
466 xfree(fdcon[s].c_output_name);
467 if (fdcon[s].c_status == CS_KEYS)
468 xfree(fdcon[s].c_data);
469 fdcon[s].c_status = CS_UNUSED;
470 fdcon[s].c_keytype = 0;
471 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
472 FD_CLR(s, read_wait);
479 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
480 gettimeofday(&fdcon[s].c_tv, NULL);
481 fdcon[s].c_tv.tv_sec += timeout;
482 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
491 ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
499 int n = 0, remote_major = 0, remote_minor = 0;
501 char remote_version[sizeof buf];
506 memset(buf, '\0', sizeof(buf));
507 bufsiz = sizeof(buf);
510 (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
515 if (n != 1 || strncmp(buf, "SSH-", 4) == 0)
521 error("%s: Connection closed by remote host", c->c_name);
526 error("read (%s): %s", c->c_name, strerror(errno));
532 if (*cp != '\n' && *cp != '\r') {
533 error("%s: bad greeting", c->c_name);
538 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
539 &remote_major, &remote_minor, remote_version) == 3)
540 compat_datafellows(remote_version);
543 if (c->c_keytype != KT_RSA1) {
544 if (!ssh2_capable(remote_major, remote_minor)) {
545 debug("%s doesn't support ssh2", c->c_name);
549 } else if (remote_major != 1) {
550 debug("%s doesn't support ssh1", c->c_name);
554 fprintf(stderr, "# %s %s\n", c->c_name, chop(buf));
555 n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
556 c->c_keytype == KT_RSA1? PROTOCOL_MAJOR_1 : PROTOCOL_MAJOR_2,
557 c->c_keytype == KT_RSA1? PROTOCOL_MINOR_1 : PROTOCOL_MINOR_2);
558 if (n < 0 || (size_t)n >= sizeof(buf)) {
559 error("snprintf: buffer too small");
563 if (atomicio(vwrite, s, buf, n) != (size_t)n) {
564 error("write (%s): %s", c->c_name, strerror(errno));
568 if (c->c_keytype != KT_RSA1) {
569 keyprint(c, keygrab_ssh2(c));
573 c->c_status = CS_SIZE;
583 if (c->c_status == CS_CON) {
587 n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
589 error("read (%s): %s", c->c_name, strerror(errno));
595 if (c->c_off == c->c_len)
596 switch (c->c_status) {
598 c->c_plen = htonl(c->c_plen);
599 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
601 c->c_data = xmalloc(c->c_len);
602 c->c_status = CS_KEYS;
605 keyprint(c, keygrab_ssh1(c));
609 fatal("conread: invalid status %d", c->c_status);
619 struct timeval seltime, now;
624 gettimeofday(&now, NULL);
625 c = TAILQ_FIRST(&tq);
627 if (c && (c->c_tv.tv_sec > now.tv_sec ||
628 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
630 seltime.tv_sec -= now.tv_sec;
631 seltime.tv_usec -= now.tv_usec;
632 if (seltime.tv_usec < 0) {
633 seltime.tv_usec += 1000000;
637 seltime.tv_sec = seltime.tv_usec = 0;
639 r = xcalloc(read_wait_nfdset, sizeof(fd_mask));
640 e = xcalloc(read_wait_nfdset, sizeof(fd_mask));
641 memcpy(r, read_wait, read_wait_nfdset * sizeof(fd_mask));
642 memcpy(e, read_wait, read_wait_nfdset * sizeof(fd_mask));
644 while (select(maxfd, r, NULL, e, &seltime) == -1 &&
645 (errno == EAGAIN || errno == EINTR))
648 for (i = 0; i < maxfd; i++) {
649 if (FD_ISSET(i, e)) {
650 error("%s: exception!", fdcon[i].c_name);
652 } else if (FD_ISSET(i, r))
658 c = TAILQ_FIRST(&tq);
659 while (c && (c->c_tv.tv_sec < now.tv_sec ||
660 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
663 c = TAILQ_NEXT(c, c_link);
671 char *name = strnnsep(&host, " \t\n");
676 for (j = KT_RSA1; j <= KT_RSA; j *= 2) {
677 if (get_keytypes & j) {
678 while (ncon >= MAXCON)
680 conalloc(name, *host ? host : name, j);
686 fatal(const char *fmt,...)
691 do_log(SYSLOG_LEVEL_FATAL, fmt, args);
702 fprintf(stderr, "usage: %s [-46Hv] [-f file] [-p port] [-T timeout] [-t type]\n"
703 "\t\t [host | addrlist namelist] [...]\n",
709 main(int argc, char **argv)
711 int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
712 int opt, fopt_count = 0;
718 __progname = ssh_get_progname(argv[0]);
723 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */
729 while ((opt = getopt(argc, argv, "Hv46p:T:t:f:")) != -1) {
735 ssh_port = a2port(optarg);
737 fprintf(stderr, "Bad port '%s'\n", optarg);
742 timeout = convtime(optarg);
743 if (timeout == -1 || timeout == 0) {
744 fprintf(stderr, "Bad timeout '%s'\n", optarg);
751 log_level = SYSLOG_LEVEL_DEBUG1;
753 else if (log_level < SYSLOG_LEVEL_DEBUG3)
756 fatal("Too high debugging level.");
759 if (strcmp(optarg, "-") == 0)
761 argv[fopt_count++] = optarg;
765 tname = strtok(optarg, ",");
767 int type = key_type_from_name(tname);
770 get_keytypes |= KT_RSA1;
773 get_keytypes |= KT_DSA;
776 get_keytypes |= KT_RSA;
779 fatal("unknown key type %s", tname);
781 tname = strtok(NULL, ",");
795 if (optind == argc && !fopt_count)
798 log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
800 maxfd = fdlim_get(1);
802 fatal("%s: fdlim_get: bad value", __progname);
803 if (maxfd > MAXMAXFD)
806 fatal("%s: not enough file descriptors", __progname);
807 if (maxfd > fdlim_get(0))
809 fdcon = xcalloc(maxfd, sizeof(con));
811 read_wait_nfdset = howmany(maxfd, NFDBITS);
812 read_wait = xcalloc(read_wait_nfdset, sizeof(fd_mask));
819 for (j = 0; j < fopt_count; j++) {
820 lb = Linebuf_alloc(argv[j], error);
823 while ((line = Linebuf_getline(lb)) != NULL)
829 while (optind < argc)
830 do_host(argv[optind++]);