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