1 /* $NetBSD: ssh-keyscan.c,v 1.4 2010/11/21 18:29:49 adam Exp $ */ 2 /* $OpenBSD: ssh-keyscan.c,v 1.82 2010/06/22 04:54:30 djm Exp $ */ 3 /* 4 * Copyright 1995, 1996 by David Mazieres <dm@lcs.mit.edu>. 5 * 6 * Modification and redistribution in source and binary forms is 7 * permitted provided that due credit is given to the author and the 8 * OpenBSD project by leaving this copyright notice intact. 9 */ 10 11 #include "includes.h" 12 __RCSID("$NetBSD: ssh-keyscan.c,v 1.4 2010/11/21 18:29:49 adam Exp $"); 13 14 #include <sys/param.h> 15 #include <sys/types.h> 16 #include <sys/socket.h> 17 #include <sys/queue.h> 18 #include <sys/time.h> 19 #include <sys/resource.h> 20 21 #include <openssl/bn.h> 22 23 #include <errno.h> 24 #include <netdb.h> 25 #include <setjmp.h> 26 #include <stdarg.h> 27 #include <stdio.h> 28 #include <stdlib.h> 29 #include <signal.h> 30 #include <string.h> 31 #include <unistd.h> 32 33 #include "xmalloc.h" 34 #include "ssh.h" 35 #include "ssh1.h" 36 #include "buffer.h" 37 #include "key.h" 38 #include "cipher.h" 39 #include "kex.h" 40 #include "compat.h" 41 #include "myproposal.h" 42 #include "packet.h" 43 #include "dispatch.h" 44 #include "log.h" 45 #include "atomicio.h" 46 #include "misc.h" 47 #include "hostfile.h" 48 49 /* Flag indicating whether IPv4 or IPv6. This can be set on the command line. 50 Default value is AF_UNSPEC means both IPv4 and IPv6. */ 51 int IPv4or6 = AF_UNSPEC; 52 53 int ssh_port = SSH_DEFAULT_PORT; 54 55 #define KT_RSA1 1 56 #define KT_DSA 2 57 #define KT_RSA 4 58 59 int get_keytypes = KT_RSA; /* Get only RSA keys by default */ 60 61 int hash_hosts = 0; /* Hash hostname on output */ 62 63 #define MAXMAXFD 256 64 65 /* The number of seconds after which to give up on a TCP connection */ 66 int timeout = 5; 67 68 int maxfd; 69 #define MAXCON (maxfd - 10) 70 71 extern char *__progname; 72 fd_set *read_wait; 73 size_t read_wait_nfdset; 74 int ncon; 75 int nonfatal_fatal = 0; 76 jmp_buf kexjmp; 77 Key *kexjmp_key; 78 79 /* 80 * Keep a connection structure for each file descriptor. The state 81 * associated with file descriptor n is held in fdcon[n]. 82 */ 83 typedef struct Connection { 84 u_char c_status; /* State of connection on this file desc. */ 85 #define CS_UNUSED 0 /* File descriptor unused */ 86 #define CS_CON 1 /* Waiting to connect/read greeting */ 87 #define CS_SIZE 2 /* Waiting to read initial packet size */ 88 #define CS_KEYS 3 /* Waiting to read public key packet */ 89 int c_fd; /* Quick lookup: c->c_fd == c - fdcon */ 90 int c_plen; /* Packet length field for ssh packet */ 91 int c_len; /* Total bytes which must be read. */ 92 int c_off; /* Length of data read so far. */ 93 int c_keytype; /* Only one of KT_RSA1, KT_DSA, or KT_RSA */ 94 char *c_namebase; /* Address to free for c_name and c_namelist */ 95 char *c_name; /* Hostname of connection for errors */ 96 char *c_namelist; /* Pointer to other possible addresses */ 97 char *c_output_name; /* Hostname of connection for output */ 98 char *c_data; /* Data read from this fd */ 99 Kex *c_kex; /* The key-exchange struct for ssh2 */ 100 struct timeval c_tv; /* Time at which connection gets aborted */ 101 TAILQ_ENTRY(Connection) c_link; /* List of connections in timeout order. */ 102 } con; 103 104 TAILQ_HEAD(conlist, Connection) tq; /* Timeout Queue */ 105 con *fdcon; 106 107 static int 108 fdlim_get(int hard) 109 { 110 struct rlimit rlfd; 111 112 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0) 113 return (-1); 114 if ((hard ? rlfd.rlim_max : rlfd.rlim_cur) == RLIM_INFINITY) 115 return sysconf(_SC_OPEN_MAX); 116 else 117 return hard ? rlfd.rlim_max : rlfd.rlim_cur; 118 } 119 120 static int 121 fdlim_set(int lim) 122 { 123 struct rlimit rlfd; 124 125 if (lim <= 0) 126 return (-1); 127 if (getrlimit(RLIMIT_NOFILE, &rlfd) < 0) 128 return (-1); 129 rlfd.rlim_cur = lim; 130 if (setrlimit(RLIMIT_NOFILE, &rlfd) < 0) 131 return (-1); 132 return (0); 133 } 134 135 /* 136 * This is an strsep function that returns a null field for adjacent 137 * separators. This is the same as the 4.4BSD strsep, but different from the 138 * one in the GNU libc. 139 */ 140 static char * 141 xstrsep(char **str, const char *delim) 142 { 143 char *s, *e; 144 145 if (!**str) 146 return (NULL); 147 148 s = *str; 149 e = s + strcspn(s, delim); 150 151 if (*e != '\0') 152 *e++ = '\0'; 153 *str = e; 154 155 return (s); 156 } 157 158 /* 159 * Get the next non-null token (like GNU strsep). Strsep() will return a 160 * null token for two adjacent separators, so we may have to loop. 161 */ 162 static char * 163 strnnsep(char **stringp, char *delim) 164 { 165 char *tok; 166 167 do { 168 tok = xstrsep(stringp, delim); 169 } while (tok && *tok == '\0'); 170 return (tok); 171 } 172 173 static Key * 174 keygrab_ssh1(con *c) 175 { 176 static Key *rsa; 177 static Buffer msg; 178 179 if (rsa == NULL) { 180 buffer_init(&msg); 181 rsa = key_new(KEY_RSA1); 182 } 183 buffer_append(&msg, c->c_data, c->c_plen); 184 buffer_consume(&msg, 8 - (c->c_plen & 7)); /* padding */ 185 if (buffer_get_char(&msg) != (int) SSH_SMSG_PUBLIC_KEY) { 186 error("%s: invalid packet type", c->c_name); 187 buffer_clear(&msg); 188 return NULL; 189 } 190 buffer_consume(&msg, 8); /* cookie */ 191 192 /* server key */ 193 (void) buffer_get_int(&msg); 194 buffer_get_bignum(&msg, rsa->rsa->e); 195 buffer_get_bignum(&msg, rsa->rsa->n); 196 197 /* host key */ 198 (void) buffer_get_int(&msg); 199 buffer_get_bignum(&msg, rsa->rsa->e); 200 buffer_get_bignum(&msg, rsa->rsa->n); 201 202 buffer_clear(&msg); 203 204 return (rsa); 205 } 206 207 static int 208 hostjump(Key *hostkey) 209 { 210 kexjmp_key = hostkey; 211 longjmp(kexjmp, 1); 212 } 213 214 static int 215 ssh2_capable(int remote_major, int remote_minor) 216 { 217 switch (remote_major) { 218 case 1: 219 if (remote_minor == 99) 220 return 1; 221 break; 222 case 2: 223 return 1; 224 default: 225 break; 226 } 227 return 0; 228 } 229 230 static Key * 231 keygrab_ssh2(con *c) 232 { 233 int j; 234 235 packet_set_connection(c->c_fd, c->c_fd); 236 enable_compat20(); 237 myproposal[PROPOSAL_SERVER_HOST_KEY_ALGS] = c->c_keytype == KT_DSA? 238 "ssh-dss": "ssh-rsa"; 239 c->c_kex = kex_setup(myproposal); 240 c->c_kex->kex[KEX_DH_GRP1_SHA1] = kexdh_client; 241 c->c_kex->kex[KEX_DH_GRP14_SHA1] = kexdh_client; 242 c->c_kex->kex[KEX_DH_GEX_SHA1] = kexgex_client; 243 c->c_kex->kex[KEX_DH_GEX_SHA256] = kexgex_client; 244 c->c_kex->verify_host_key = hostjump; 245 246 if (!(j = setjmp(kexjmp))) { 247 nonfatal_fatal = 1; 248 dispatch_run(DISPATCH_BLOCK, &c->c_kex->done, c->c_kex); 249 fprintf(stderr, "Impossible! dispatch_run() returned!\n"); 250 exit(1); 251 } 252 nonfatal_fatal = 0; 253 xfree(c->c_kex); 254 c->c_kex = NULL; 255 packet_close(); 256 257 return j < 0? NULL : kexjmp_key; 258 } 259 260 static void 261 keyprint(con *c, Key *key) 262 { 263 char *host = c->c_output_name ? c->c_output_name : c->c_name; 264 265 if (!key) 266 return; 267 if (hash_hosts && (host = host_hash(host, NULL, 0)) == NULL) 268 fatal("host_hash failed"); 269 270 fprintf(stdout, "%s ", host); 271 key_write(key, stdout); 272 fputs("\n", stdout); 273 } 274 275 static int 276 tcpconnect(char *host) 277 { 278 struct addrinfo hints, *ai, *aitop; 279 char strport[NI_MAXSERV]; 280 int gaierr, s = -1; 281 282 snprintf(strport, sizeof strport, "%d", ssh_port); 283 memset(&hints, 0, sizeof(hints)); 284 hints.ai_family = IPv4or6; 285 hints.ai_socktype = SOCK_STREAM; 286 if ((gaierr = getaddrinfo(host, strport, &hints, &aitop)) != 0) 287 fatal("getaddrinfo %s: %s", host, ssh_gai_strerror(gaierr)); 288 for (ai = aitop; ai; ai = ai->ai_next) { 289 s = socket(ai->ai_family, ai->ai_socktype, ai->ai_protocol); 290 if (s < 0) { 291 error("socket: %s", strerror(errno)); 292 continue; 293 } 294 if (set_nonblock(s) == -1) 295 fatal("%s: set_nonblock(%d)", __func__, s); 296 if (connect(s, ai->ai_addr, ai->ai_addrlen) < 0 && 297 errno != EINPROGRESS) 298 error("connect (`%s'): %s", host, strerror(errno)); 299 else 300 break; 301 close(s); 302 s = -1; 303 } 304 freeaddrinfo(aitop); 305 return s; 306 } 307 308 static int 309 conalloc(char *iname, char *oname, int keytype) 310 { 311 char *namebase, *name, *namelist; 312 int s; 313 314 namebase = namelist = xstrdup(iname); 315 316 do { 317 name = xstrsep(&namelist, ","); 318 if (!name) { 319 xfree(namebase); 320 return (-1); 321 } 322 } while ((s = tcpconnect(name)) < 0); 323 324 if (s >= maxfd) 325 fatal("conalloc: fdno %d too high", s); 326 if (fdcon[s].c_status) 327 fatal("conalloc: attempt to reuse fdno %d", s); 328 329 fdcon[s].c_fd = s; 330 fdcon[s].c_status = CS_CON; 331 fdcon[s].c_namebase = namebase; 332 fdcon[s].c_name = name; 333 fdcon[s].c_namelist = namelist; 334 fdcon[s].c_output_name = xstrdup(oname); 335 fdcon[s].c_data = (char *) &fdcon[s].c_plen; 336 fdcon[s].c_len = 4; 337 fdcon[s].c_off = 0; 338 fdcon[s].c_keytype = keytype; 339 gettimeofday(&fdcon[s].c_tv, NULL); 340 fdcon[s].c_tv.tv_sec += timeout; 341 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link); 342 FD_SET(s, read_wait); 343 ncon++; 344 return (s); 345 } 346 347 static void 348 confree(int s) 349 { 350 if (s >= maxfd || fdcon[s].c_status == CS_UNUSED) 351 fatal("confree: attempt to free bad fdno %d", s); 352 close(s); 353 xfree(fdcon[s].c_namebase); 354 xfree(fdcon[s].c_output_name); 355 if (fdcon[s].c_status == CS_KEYS) 356 xfree(fdcon[s].c_data); 357 fdcon[s].c_status = CS_UNUSED; 358 fdcon[s].c_keytype = 0; 359 TAILQ_REMOVE(&tq, &fdcon[s], c_link); 360 FD_CLR(s, read_wait); 361 ncon--; 362 } 363 364 static void 365 contouch(int s) 366 { 367 TAILQ_REMOVE(&tq, &fdcon[s], c_link); 368 gettimeofday(&fdcon[s].c_tv, NULL); 369 fdcon[s].c_tv.tv_sec += timeout; 370 TAILQ_INSERT_TAIL(&tq, &fdcon[s], c_link); 371 } 372 373 static int 374 conrecycle(int s) 375 { 376 con *c = &fdcon[s]; 377 int ret; 378 379 ret = conalloc(c->c_namelist, c->c_output_name, c->c_keytype); 380 confree(s); 381 return (ret); 382 } 383 384 static void 385 congreet(int s) 386 { 387 int n = 0, remote_major = 0, remote_minor = 0; 388 char buf[256], *cp; 389 char remote_version[sizeof buf]; 390 size_t bufsiz; 391 con *c = &fdcon[s]; 392 393 for (;;) { 394 memset(buf, '\0', sizeof(buf)); 395 bufsiz = sizeof(buf); 396 cp = buf; 397 while (bufsiz-- && 398 (n = atomicio(read, s, cp, 1)) == 1 && *cp != '\n') { 399 if (*cp == '\r') 400 *cp = '\n'; 401 cp++; 402 } 403 if (n != 1 || strncmp(buf, "SSH-", 4) == 0) 404 break; 405 } 406 if (n == 0) { 407 switch (errno) { 408 case EPIPE: 409 error("%s: Connection closed by remote host", c->c_name); 410 break; 411 case ECONNREFUSED: 412 break; 413 default: 414 error("read (%s): %s", c->c_name, strerror(errno)); 415 break; 416 } 417 conrecycle(s); 418 return; 419 } 420 if (*cp != '\n' && *cp != '\r') { 421 error("%s: bad greeting", c->c_name); 422 confree(s); 423 return; 424 } 425 *cp = '\0'; 426 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", 427 &remote_major, &remote_minor, remote_version) == 3) 428 compat_datafellows(remote_version); 429 else 430 datafellows = 0; 431 if (c->c_keytype != KT_RSA1) { 432 if (!ssh2_capable(remote_major, remote_minor)) { 433 debug("%s doesn't support ssh2", c->c_name); 434 confree(s); 435 return; 436 } 437 } else if (remote_major != 1) { 438 debug("%s doesn't support ssh1", c->c_name); 439 confree(s); 440 return; 441 } 442 fprintf(stderr, "# %s %s\n", c->c_name, chop(buf)); 443 n = snprintf(buf, sizeof buf, "SSH-%d.%d-OpenSSH-keyscan\r\n", 444 c->c_keytype == KT_RSA1? PROTOCOL_MAJOR_1 : PROTOCOL_MAJOR_2, 445 c->c_keytype == KT_RSA1? PROTOCOL_MINOR_1 : PROTOCOL_MINOR_2); 446 if (n < 0 || (size_t)n >= sizeof(buf)) { 447 error("snprintf: buffer too small"); 448 confree(s); 449 return; 450 } 451 if (atomicio(vwrite, s, buf, n) != (size_t)n) { 452 error("write (%s): %s", c->c_name, strerror(errno)); 453 confree(s); 454 return; 455 } 456 if (c->c_keytype != KT_RSA1) { 457 keyprint(c, keygrab_ssh2(c)); 458 confree(s); 459 return; 460 } 461 c->c_status = CS_SIZE; 462 contouch(s); 463 } 464 465 static void 466 conread(int s) 467 { 468 con *c = &fdcon[s]; 469 size_t n; 470 471 if (c->c_status == CS_CON) { 472 congreet(s); 473 return; 474 } 475 n = atomicio(read, s, c->c_data + c->c_off, c->c_len - c->c_off); 476 if (n == 0) { 477 error("read (%s): %s", c->c_name, strerror(errno)); 478 confree(s); 479 return; 480 } 481 c->c_off += n; 482 483 if (c->c_off == c->c_len) 484 switch (c->c_status) { 485 case CS_SIZE: 486 c->c_plen = htonl(c->c_plen); 487 c->c_len = c->c_plen + 8 - (c->c_plen & 7); 488 c->c_off = 0; 489 c->c_data = xmalloc(c->c_len); 490 c->c_status = CS_KEYS; 491 break; 492 case CS_KEYS: 493 keyprint(c, keygrab_ssh1(c)); 494 confree(s); 495 return; 496 default: 497 fatal("conread: invalid status %d", c->c_status); 498 break; 499 } 500 501 contouch(s); 502 } 503 504 static void 505 conloop(void) 506 { 507 struct timeval seltime, now; 508 fd_set *r, *e; 509 con *c; 510 int i; 511 512 gettimeofday(&now, NULL); 513 c = TAILQ_FIRST(&tq); 514 515 if (c && (c->c_tv.tv_sec > now.tv_sec || 516 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec > now.tv_usec))) { 517 seltime = c->c_tv; 518 seltime.tv_sec -= now.tv_sec; 519 seltime.tv_usec -= now.tv_usec; 520 if (seltime.tv_usec < 0) { 521 seltime.tv_usec += 1000000; 522 seltime.tv_sec--; 523 } 524 } else 525 seltime.tv_sec = seltime.tv_usec = 0; 526 527 r = xcalloc(read_wait_nfdset, sizeof(fd_mask)); 528 e = xcalloc(read_wait_nfdset, sizeof(fd_mask)); 529 memcpy(r, read_wait, read_wait_nfdset * sizeof(fd_mask)); 530 memcpy(e, read_wait, read_wait_nfdset * sizeof(fd_mask)); 531 532 while (select(maxfd, r, NULL, e, &seltime) == -1 && 533 (errno == EAGAIN || errno == EINTR)) 534 ; 535 536 for (i = 0; i < maxfd; i++) { 537 if (FD_ISSET(i, e)) { 538 error("%s: exception!", fdcon[i].c_name); 539 confree(i); 540 } else if (FD_ISSET(i, r)) 541 conread(i); 542 } 543 xfree(r); 544 xfree(e); 545 546 c = TAILQ_FIRST(&tq); 547 while (c && (c->c_tv.tv_sec < now.tv_sec || 548 (c->c_tv.tv_sec == now.tv_sec && c->c_tv.tv_usec < now.tv_usec))) { 549 int s = c->c_fd; 550 551 c = TAILQ_NEXT(c, c_link); 552 conrecycle(s); 553 } 554 } 555 556 static void 557 do_host(char *host) 558 { 559 char *name = strnnsep(&host, " \t\n"); 560 int j; 561 562 if (name == NULL) 563 return; 564 for (j = KT_RSA1; j <= KT_RSA; j *= 2) { 565 if (get_keytypes & j) { 566 while (ncon >= MAXCON) 567 conloop(); 568 conalloc(name, *host ? host : name, j); 569 } 570 } 571 } 572 573 void 574 fatal(const char *fmt,...) 575 { 576 va_list args; 577 578 va_start(args, fmt); 579 do_log(SYSLOG_LEVEL_FATAL, fmt, args); 580 va_end(args); 581 if (nonfatal_fatal) 582 longjmp(kexjmp, -1); 583 else 584 exit(255); 585 } 586 587 static void 588 usage(void) 589 { 590 fprintf(stderr, 591 "usage: %s [-46Hv] [-f file] [-p port] [-T timeout] [-t type]\n" 592 "\t\t [host | addrlist namelist] ...\n", 593 __progname); 594 exit(1); 595 } 596 597 int 598 main(int argc, char **argv) 599 { 600 int debug_flag = 0, log_level = SYSLOG_LEVEL_INFO; 601 int opt, fopt_count = 0, j; 602 char *tname, *cp, line[NI_MAXHOST]; 603 FILE *fp; 604 u_long linenum; 605 606 extern int optind; 607 extern char *optarg; 608 609 TAILQ_INIT(&tq); 610 611 /* Ensure that fds 0, 1 and 2 are open or directed to /dev/null */ 612 sanitise_stdfd(); 613 614 if (argc <= 1) 615 usage(); 616 617 while ((opt = getopt(argc, argv, "Hv46p:T:t:f:")) != -1) { 618 switch (opt) { 619 case 'H': 620 hash_hosts = 1; 621 break; 622 case 'p': 623 ssh_port = a2port(optarg); 624 if (ssh_port <= 0) { 625 fprintf(stderr, "Bad port '%s'\n", optarg); 626 exit(1); 627 } 628 break; 629 case 'T': 630 timeout = convtime(optarg); 631 if (timeout == -1 || timeout == 0) { 632 fprintf(stderr, "Bad timeout '%s'\n", optarg); 633 usage(); 634 } 635 break; 636 case 'v': 637 if (!debug_flag) { 638 debug_flag = 1; 639 log_level = SYSLOG_LEVEL_DEBUG1; 640 } 641 else if (log_level < SYSLOG_LEVEL_DEBUG3) 642 log_level++; 643 else 644 fatal("Too high debugging level."); 645 break; 646 case 'f': 647 if (strcmp(optarg, "-") == 0) 648 optarg = NULL; 649 argv[fopt_count++] = optarg; 650 break; 651 case 't': 652 get_keytypes = 0; 653 tname = strtok(optarg, ","); 654 while (tname) { 655 int type = key_type_from_name(tname); 656 switch (type) { 657 case KEY_RSA1: 658 get_keytypes |= KT_RSA1; 659 break; 660 case KEY_DSA: 661 get_keytypes |= KT_DSA; 662 break; 663 case KEY_RSA: 664 get_keytypes |= KT_RSA; 665 break; 666 case KEY_UNSPEC: 667 fatal("unknown key type %s", tname); 668 } 669 tname = strtok(NULL, ","); 670 } 671 break; 672 case '4': 673 IPv4or6 = AF_INET; 674 break; 675 case '6': 676 IPv4or6 = AF_INET6; 677 break; 678 case '?': 679 default: 680 usage(); 681 } 682 } 683 if (optind == argc && !fopt_count) 684 usage(); 685 686 log_init("ssh-keyscan", log_level, SYSLOG_FACILITY_USER, 1); 687 688 maxfd = fdlim_get(1); 689 if (maxfd < 0) 690 fatal("%s: fdlim_get: bad value", __progname); 691 if (maxfd > MAXMAXFD) 692 maxfd = MAXMAXFD; 693 if (MAXCON <= 0) 694 fatal("%s: not enough file descriptors", __progname); 695 if (maxfd > fdlim_get(0)) 696 fdlim_set(maxfd); 697 fdcon = xcalloc(maxfd, sizeof(con)); 698 699 read_wait_nfdset = howmany(maxfd, NFDBITS); 700 read_wait = xcalloc(read_wait_nfdset, sizeof(fd_mask)); 701 702 for (j = 0; j < fopt_count; j++) { 703 if (argv[j] == NULL) 704 fp = stdin; 705 else if ((fp = fopen(argv[j], "r")) == NULL) 706 fatal("%s: %s: %s", __progname, argv[j], 707 strerror(errno)); 708 linenum = 0; 709 710 while (read_keyfile_line(fp, 711 argv[j] == NULL ? "(stdin)" : argv[j], line, sizeof(line), 712 &linenum) != -1) { 713 /* Chomp off trailing whitespace and comments */ 714 if ((cp = strchr(line, '#')) == NULL) 715 cp = line + strlen(line) - 1; 716 while (cp >= line) { 717 if (*cp == ' ' || *cp == '\t' || 718 *cp == '\n' || *cp == '#') 719 *cp-- = '\0'; 720 else 721 break; 722 } 723 724 /* Skip empty lines */ 725 if (*line == '\0') 726 continue; 727 728 do_host(line); 729 } 730 731 if (ferror(fp)) 732 fatal("%s: %s: %s", __progname, argv[j], 733 strerror(errno)); 734 735 fclose(fp); 736 } 737 738 while (optind < argc) 739 do_host(argv[optind++]); 740 741 while (ncon > 0) 742 conloop(); 743 744 return (0); 745 } 746