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