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.50 2004/08/11 21:44:32 avsm Exp $");
12 #include "openbsd-compat/sys-queue.h"
14 #include <openssl/bn.h>
23 #include "myproposal.h"
32 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line.
33 Default value is AF_UNSPEC means both IPv4 and IPv6. */
34 int IPv4or6 = AF_UNSPEC;
36 int ssh_port = SSH_DEFAULT_PORT;
42 int get_keytypes = KT_RSA1; /* Get only RSA1 keys by default */
46 /* The number of seconds after which to give up on a TCP connection */
50 #define MAXCON (maxfd - 10)
52 extern char *__progname;
54 size_t read_wait_size;
56 int nonfatal_fatal = 0;
61 * Keep a connection structure for each file descriptor. The state
62 * associated with file descriptor n is held in fdcon[n].
64 typedef struct Connection {
65 u_char c_status; /* State of connection on this file desc. */
66 #define CS_UNUSED 0 /* File descriptor unused */
67 #define CS_CON 1 /* Waiting to connect/read greeting */
68 #define CS_SIZE 2 /* Waiting to read initial packet size */
69 #define CS_KEYS 3 /* Waiting to read public key packet */
70 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */
71 int c_plen; /* Packet length field for ssh packet */
72 int c_len; /* Total bytes which must be read. */
73 int c_off; /* Length of data read so far. */
74 int c_keytype; /* Only one of KT_RSA1, KT_DSA, or KT_RSA */
75 char *c_namebase; /* Address to free for c_name and c_namelist */
76 char *c_name; /* Hostname of connection for errors */
77 char *c_namelist; /* Pointer to other possible addresses */
78 char *c_output_name; /* Hostname of connection for output */
79 char *c_data; /* Data read from this fd */
80 Kex *c_kex; /* The key-exchange struct for ssh2 */
81 struct timeval c_tv; /* Time at which connection gets aborted */
82 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */
85 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */
89 * This is just a wrapper around fgets() to make it usable.
92 /* Stress-test. Increase this later. */
93 #define LINEBUF_SIZE 16
101 void (*errfun) (const char *,...);
105 Linebuf_alloc(const char *filename, void (*errfun) (const char *,...))
109 if (!(lb = malloc(sizeof(*lb)))) {
111 (*errfun) ("linebuf (%s): malloc failed\n",
112 filename ? filename : "(stdin)");
116 lb->filename = filename;
117 if (!(lb->stream = fopen(filename, "r"))) {
120 (*errfun) ("%s: %s\n", filename, strerror(errno));
124 lb->filename = "(stdin)";
128 if (!(lb->buf = malloc(lb->size = LINEBUF_SIZE))) {
130 (*errfun) ("linebuf (%s): malloc failed\n", lb->filename);
140 Linebuf_free(Linebuf * lb)
149 Linebuf_restart(Linebuf * lb)
151 clearerr(lb->stream);
157 Linebuf_lineno(Linebuf * lb)
164 Linebuf_getline(Linebuf * lb)
172 if (!fgets(&lb->buf[n], lb->size - n, lb->stream)) {
173 if (ferror(lb->stream) && lb->errfun)
174 (*lb->errfun)("%s: %s\n", lb->filename,
180 /* Return it or an error if it fits */
181 if (n > 0 && lb->buf[n - 1] == '\n') {
182 lb->buf[n - 1] = '\0';
185 if (n != lb->size - 1) {
187 (*lb->errfun)("%s: skipping incomplete last line\n",
191 /* Double the buffer if we need more space */
193 if ((p = realloc(lb->buf, lb->size)) == NULL) {
196 (*lb->errfun)("linebuf (%s): realloc failed\n",
207 #if defined(HAVE_GETRLIMIT) && defined(RLIMIT_NOFILE)
210 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
212 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY)
215 return hard ? rlfd.rlim_max : rlfd.rlim_cur;
224 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
230 #if defined(HAVE_SETRLIMIT) && defined(RLIMIT_NOFILE)
231 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0)
234 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0)
236 #elif defined (HAVE_SETDTABLESIZE)
243 * This is an strsep function that returns a null field for adjacent
244 * separators. This is the same as the 4.4BSD strsep, but different from the
245 * one in the GNU libc.
248 xstrsep(char **str, const char *delim)
256 e = s + strcspn(s, delim);
266 * Get the next non-null token (like GNU strsep). Strsep() will return a
267 * null token for two adjacent separators, so we may have to loop.
270 strnnsep(char **stringp, char *delim)
275 tok = xstrsep(stringp, delim);
276 } while (tok && *tok == '\0');
288 rsa = key_new(KEY_RSA1);
290 buffer_append(&msg, c->c_data, c->c_plen);
291 buffer_consume(&msg, 8 - (c->c_plen & 7)); /* padding */
292 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) {
293 error("%s: invalid packet type", c->c_name);
297 buffer_consume(&msg, 8); /* cookie */
300 (void) buffer_get_int(&msg);
301 buffer_get_bignum(&msg, rsa->rsa->e);
302 buffer_get_bignum(&msg, rsa->rsa->n);
305 (void) buffer_get_int(&msg);
306 buffer_get_bignum(&msg, rsa->rsa->e);
307 buffer_get_bignum(&msg, rsa->rsa->n);
315 hostjump(Key *hostkey)
317 kexjmp_key = hostkey;
322 ssh2_capable(int remote_major, int remote_minor)
324 switch (remote_major) {
326 if (remote_minor == 99)
342 packet_set_connection(c->c_fd, c->c_fd);
344 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = c->c_keytype == KT_DSA?
345 "ssh-dss": "ssh-rsa";
346 c->c_kex = kex_setup(myproposal);
347 c->c_kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client;
348 c->c_kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client;
349 c->c_kex->kex[KEX_DH_GEX_SHA1] = kexgex_client;
350 c->c_kex->verify_host_key = hostjump;
352 if (!(j = setjmp(kexjmp))) {
354 dispatch_run(DISPATCH_BLOCK, &c->c_kex->done, c->c_kex);
355 fprintf(stderr, "Impossible! dispatch_run() returned!\n");
363 return j < 0? NULL : kexjmp_key;
367 keyprint(con *c, Key *key)
372 fprintf(stdout, "%s ", c->c_output_name ? c->c_output_name : c->c_name);
373 key_write(key, stdout);
378 tcpconnect(char *host)
380 struct addrinfo hints, *ai, *aitop;
381 char strport[NI_MAXSERV];
384 snprintf(strport, sizeof strport, "%d", ssh_port);
385 memset(&hints, 0, sizeof(hints));
386 hints.ai_family = IPv4or6;
387 hints.ai_socktype = SOCK_STREAM;
388 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0)
389 fatal("getaddrinfo %s: %s", host, gai_strerror(gaierr));
390 for (ai = aitop; ai; ai = ai->ai_next) {
391 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol);
393 error("socket: %s", strerror(errno));
396 if (set_nonblock(s) == -1)
397 fatal("%s: set_nonblock(%d)", __func__, s);
398 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 &&
399 errno != EINPROGRESS)
400 error("connect (`%s'): %s", host, strerror(errno));
411 conalloc(char *iname, char *oname, int keytype)
413 char *namebase, *name, *namelist;
416 namebase = namelist = xstrdup(iname);
419 name = xstrsep(&namelist, ",");
424 } while ((s = tcpconnect(name)) < 0);
427 fatal("conalloc: fdno %d too high", s);
428 if (fdcon[s].c_status)
429 fatal("conalloc: attempt to reuse fdno %d", s);
432 fdcon[s].c_status = CS_CON;
433 fdcon[s].c_namebase = namebase;
434 fdcon[s].c_name = name;
435 fdcon[s].c_namelist = namelist;
436 fdcon[s].c_output_name = xstrdup(oname);
437 fdcon[s].c_data = (char *) &fdcon[s].c_plen;
440 fdcon[s].c_keytype = keytype;
441 gettimeofday(&fdcon[s].c_tv, NULL);
442 fdcon[s].c_tv.tv_sec += timeout;
443 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
444 FD_SET(s, read_wait);
452 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED)
453 fatal("confree: attempt to free bad fdno %d", s);
455 xfree(fdcon[s].c_namebase);
456 xfree(fdcon[s].c_output_name);
457 if (fdcon[s].c_status == CS_KEYS)
458 xfree(fdcon[s].c_data);
459 fdcon[s].c_status = CS_UNUSED;
460 fdcon[s].c_keytype = 0;
461 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
462 FD_CLR(s, read_wait);
469 TAILQ_REMOVE(&tq, &fdcon[s], c_link);
470 gettimeofday(&fdcon[s].c_tv, NULL);
471 fdcon[s].c_tv.tv_sec += timeout;
472 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link);
481 ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype);
489 int remote_major = 0, remote_minor = 0, n = 0;
491 char remote_version[sizeof buf];
495 bufsiz = sizeof(buf);
497 while (bufsiz-- && (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') {
503 if (errno != ECONNREFUSED)
504 error("read (%s): %s", c->c_name, strerror(errno));
509 error("%s: Connection closed by remote host", c->c_name);
513 if (*cp != '\n' && *cp != '\r') {
514 error("%s: bad greeting", c->c_name);
519 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n",
520 &remote_major, &remote_minor, remote_version) == 3)
521 compat_datafellows(remote_version);
524 if (c->c_keytype != KT_RSA1) {
525 if (!ssh2_capable(remote_major, remote_minor)) {
526 debug("%s doesn't support ssh2", c->c_name);
530 } else if (remote_major != 1) {
531 debug("%s doesn't support ssh1", c->c_name);
535 fprintf(stderr, "# %s %s\n", c->c_name, chop(buf));
536 n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n",
537 c->c_keytype == KT_RSA1? PROTOCOL_MAJOR_1 : PROTOCOL_MAJOR_2,
538 c->c_keytype == KT_RSA1? PROTOCOL_MINOR_1 : PROTOCOL_MINOR_2);
539 if (atomicio(vwrite, s, buf, n) != n) {
540 error("write (%s): %s", c->c_name, strerror(errno));
544 if (c->c_keytype != KT_RSA1) {
545 keyprint(c, keygrab_ssh2(c));
549 c->c_status = CS_SIZE;
559 if (c->c_status == CS_CON) {
563 n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off);
565 error("read (%s): %s", c->c_name, strerror(errno));
571 if (c->c_off == c->c_len)
572 switch (c->c_status) {
574 c->c_plen = htonl(c->c_plen);
575 c->c_len = c->c_plen + 8 - (c->c_plen & 7);
577 c->c_data = xmalloc(c->c_len);
578 c->c_status = CS_KEYS;
581 keyprint(c, keygrab_ssh1(c));
586 fatal("conread: invalid status %d", c->c_status);
596 struct timeval seltime, now;
601 gettimeofday(&now, NULL);
602 c = TAILQ_FIRST(&tq);
604 if (c && (c->c_tv.tv_sec > now.tv_sec ||
605 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) {
607 seltime.tv_sec -= now.tv_sec;
608 seltime.tv_usec -= now.tv_usec;
609 if (seltime.tv_usec < 0) {
610 seltime.tv_usec += 1000000;
614 seltime.tv_sec = seltime.tv_usec = 0;
616 r = xmalloc(read_wait_size);
617 memcpy(r, read_wait, read_wait_size);
618 e = xmalloc(read_wait_size);
619 memcpy(e, read_wait, read_wait_size);
621 while (select(maxfd, r, NULL, e, &seltime) == -1 &&
622 (errno == EAGAIN || errno == EINTR))
625 for (i = 0; i < maxfd; i++) {
626 if (FD_ISSET(i, e)) {
627 error("%s: exception!", fdcon[i].c_name);
629 } else if (FD_ISSET(i, r))
635 c = TAILQ_FIRST(&tq);
636 while (c && (c->c_tv.tv_sec < now.tv_sec ||
637 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) {
640 c = TAILQ_NEXT(c, c_link);
648 char *name = strnnsep(&host, " \t\n");
653 for (j = KT_RSA1; j <= KT_RSA; j *= 2) {
654 if (get_keytypes & j) {
655 while (ncon >= MAXCON)
657 conalloc(name, *host ? host : name, j);
663 fatal(const char *fmt,...)
668 do_log(SYSLOG_LEVEL_FATAL, fmt, args);
679 fprintf(stderr, "usage: %s [-v46] [-p port] [-T timeout] [-t type] [-f file]\n"
680 "\t\t [host | addrlist namelist] [...]\n",
686 main(int argc, char **argv)
688 int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO;
689 int opt, fopt_count = 0;
695 __progname = ssh_get_progname(argv[0]);
703 while ((opt = getopt(argc, argv, "v46p:T:t:f:")) != -1) {
706 ssh_port = a2port(optarg);
708 fprintf(stderr, "Bad port '%s'\n", optarg);
713 timeout = convtime(optarg);
714 if (timeout == -1 || timeout == 0) {
715 fprintf(stderr, "Bad timeout '%s'\n", optarg);
722 log_level = SYSLOG_LEVEL_DEBUG1;
724 else if (log_level < SYSLOG_LEVEL_DEBUG3)
727 fatal("Too high debugging level.");
730 if (strcmp(optarg, "-") == 0)
732 argv[fopt_count++] = optarg;
736 tname = strtok(optarg, ",");
738 int type = key_type_from_name(tname);
741 get_keytypes |= KT_RSA1;
744 get_keytypes |= KT_DSA;
747 get_keytypes |= KT_RSA;
750 fatal("unknown key type %s", tname);
752 tname = strtok(NULL, ",");
766 if (optind == argc && !fopt_count)
769 log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1);
771 maxfd = fdlim_get(1);
773 fatal("%s: fdlim_get: bad value", __progname);
774 if (maxfd > MAXMAXFD)
777 fatal("%s: not enough file descriptors", __progname);
778 if (maxfd > fdlim_get(0))
780 fdcon = xmalloc(maxfd * sizeof(con));
781 memset(fdcon, 0, maxfd * sizeof(con));
783 read_wait_size = howmany(maxfd, NFDBITS) * sizeof(fd_mask);
784 read_wait = xmalloc(read_wait_size);
785 memset(read_wait, 0, read_wait_size);
792 for (j = 0; j < fopt_count; j++) {
793 lb = Linebuf_alloc(argv[j], error);
796 while ((line = Linebuf_getline(lb)) != NULL)
802 while (optind < argc)
803 do_host(argv[optind++]);