sshd.c revision 57430
1/* 2 * Author: Tatu Ylonen <ylo@cs.hut.fi> 3 * Copyright (c) 1995 Tatu Ylonen <ylo@cs.hut.fi>, Espoo, Finland 4 * All rights reserved 5 * Created: Fri Mar 17 17:09:28 1995 ylo 6 * This program is the ssh daemon. It listens for connections from clients, and 7 * performs authentication, executes use commands or shell, and forwards 8 * information to/from the application to the user client over an encrypted 9 * connection. This can also handle forwarding of X11, TCP/IP, and authentication 10 * agent connections. 11 */ 12 13#include "includes.h" 14RCSID("$OpenBSD: sshd.c,v 1.88 2000/02/15 16:52:57 markus Exp $"); 15 16#include "xmalloc.h" 17#include "rsa.h" 18#include "ssh.h" 19#include "pty.h" 20#include "packet.h" 21#include "buffer.h" 22#include "cipher.h" 23#include "mpaux.h" 24#include "servconf.h" 25#include "uidswap.h" 26#include "compat.h" 27 28#ifdef LIBWRAP 29#include <tcpd.h> 30#include <syslog.h> 31int allow_severity = LOG_INFO; 32int deny_severity = LOG_WARNING; 33#endif /* LIBWRAP */ 34 35#ifndef O_NOCTTY 36#define O_NOCTTY 0 37#endif 38 39/* Local Xauthority file. */ 40static char *xauthfile = NULL; 41 42/* Server configuration options. */ 43ServerOptions options; 44 45/* Name of the server configuration file. */ 46char *config_file_name = SERVER_CONFIG_FILE; 47 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 */ 52int IPv4or6 = AF_UNSPEC; 53 54/* 55 * Debug mode flag. This can be set on the command line. If debug 56 * mode is enabled, extra debugging output will be sent to the system 57 * log, the daemon will not go to background, and will exit after processing 58 * the first connection. 59 */ 60int debug_flag = 0; 61 62/* Flag indicating that the daemon is being started from inetd. */ 63int inetd_flag = 0; 64 65/* debug goes to stderr unless inetd_flag is set */ 66int log_stderr = 0; 67 68/* argv[0] without path. */ 69char *av0; 70 71/* Saved arguments to main(). */ 72char **saved_argv; 73 74/* 75 * The sockets that the server is listening; this is used in the SIGHUP 76 * signal handler. 77 */ 78#define MAX_LISTEN_SOCKS 16 79int listen_socks[MAX_LISTEN_SOCKS]; 80int num_listen_socks = 0; 81 82/* 83 * the client's version string, passed by sshd2 in compat mode. if != NULL, 84 * sshd will skip the version-number exchange 85 */ 86char *client_version_string = NULL; 87 88/* Flags set in auth-rsa from authorized_keys flags. These are set in auth-rsa.c. */ 89int no_port_forwarding_flag = 0; 90int no_agent_forwarding_flag = 0; 91int no_x11_forwarding_flag = 0; 92int no_pty_flag = 0; 93 94/* RSA authentication "command=" option. */ 95char *forced_command = NULL; 96 97/* RSA authentication "environment=" options. */ 98struct envstring *custom_environment = NULL; 99 100/* Session id for the current session. */ 101unsigned char session_id[16]; 102 103/* 104 * Any really sensitive data in the application is contained in this 105 * structure. The idea is that this structure could be locked into memory so 106 * that the pages do not get written into swap. However, there are some 107 * problems. The private key contains BIGNUMs, and we do not (in principle) 108 * have access to the internals of them, and locking just the structure is 109 * not very useful. Currently, memory locking is not implemented. 110 */ 111struct { 112 RSA *private_key; /* Private part of server key. */ 113 RSA *host_key; /* Private part of host key. */ 114} sensitive_data; 115 116/* 117 * Flag indicating whether the current session key has been used. This flag 118 * is set whenever the key is used, and cleared when the key is regenerated. 119 */ 120int key_used = 0; 121 122/* This is set to true when SIGHUP is received. */ 123int received_sighup = 0; 124 125/* Public side of the server key. This value is regenerated regularly with 126 the private key. */ 127RSA *public_key; 128 129/* Prototypes for various functions defined later in this file. */ 130void do_ssh_kex(); 131void do_authentication(); 132void do_authloop(struct passwd * pw); 133void do_fake_authloop(char *user); 134void do_authenticated(struct passwd * pw); 135void do_exec_pty(const char *command, int ptyfd, int ttyfd, 136 const char *ttyname, struct passwd * pw, const char *term, 137 const char *display, const char *auth_proto, 138 const char *auth_data); 139void do_exec_no_pty(const char *command, struct passwd * pw, 140 const char *display, const char *auth_proto, 141 const char *auth_data); 142void do_child(const char *command, struct passwd * pw, const char *term, 143 const char *display, const char *auth_proto, 144 const char *auth_data, const char *ttyname); 145 146/* 147 * Remove local Xauthority file. 148 */ 149void 150xauthfile_cleanup_proc(void *ignore) 151{ 152 debug("xauthfile_cleanup_proc called"); 153 154 if (xauthfile != NULL) { 155 char *p; 156 unlink(xauthfile); 157 p = strrchr(xauthfile, '/'); 158 if (p != NULL) { 159 *p = '\0'; 160 rmdir(xauthfile); 161 } 162 xfree(xauthfile); 163 xauthfile = NULL; 164 } 165} 166 167/* 168 * Close all listening sockets 169 */ 170void 171close_listen_socks(void) 172{ 173 int i; 174 for (i = 0; i < num_listen_socks; i++) 175 close(listen_socks[i]); 176 num_listen_socks = -1; 177} 178 179/* 180 * Signal handler for SIGHUP. Sshd execs itself when it receives SIGHUP; 181 * the effect is to reread the configuration file (and to regenerate 182 * the server key). 183 */ 184void 185sighup_handler(int sig) 186{ 187 received_sighup = 1; 188 signal(SIGHUP, sighup_handler); 189} 190 191/* 192 * Called from the main program after receiving SIGHUP. 193 * Restarts the server. 194 */ 195void 196sighup_restart() 197{ 198 log("Received SIGHUP; restarting."); 199 close_listen_socks(); 200 execv(saved_argv[0], saved_argv); 201 log("RESTART FAILED: av0='%s', error: %s.", av0, strerror(errno)); 202 exit(1); 203} 204 205/* 206 * Generic signal handler for terminating signals in the master daemon. 207 * These close the listen socket; not closing it seems to cause "Address 208 * already in use" problems on some machines, which is inconvenient. 209 */ 210void 211sigterm_handler(int sig) 212{ 213 log("Received signal %d; terminating.", sig); 214 close_listen_socks(); 215 exit(255); 216} 217 218/* 219 * SIGCHLD handler. This is called whenever a child dies. This will then 220 * reap any zombies left by exited c. 221 */ 222void 223main_sigchld_handler(int sig) 224{ 225 int save_errno = errno; 226 int status; 227 228 while (waitpid(-1, &status, WNOHANG) > 0) 229 ; 230 231 signal(SIGCHLD, main_sigchld_handler); 232 errno = save_errno; 233} 234 235/* 236 * Signal handler for the alarm after the login grace period has expired. 237 */ 238void 239grace_alarm_handler(int sig) 240{ 241 /* Close the connection. */ 242 packet_close(); 243 244 /* Log error and exit. */ 245 fatal("Timeout before authentication for %s.", get_remote_ipaddr()); 246} 247 248/* 249 * convert ssh auth msg type into description 250 */ 251char * 252get_authname(int type) 253{ 254 static char buf[1024]; 255 switch (type) { 256 case SSH_CMSG_AUTH_PASSWORD: 257 return "password"; 258 case SSH_CMSG_AUTH_RSA: 259 return "rsa"; 260 case SSH_CMSG_AUTH_RHOSTS_RSA: 261 return "rhosts-rsa"; 262 case SSH_CMSG_AUTH_RHOSTS: 263 return "rhosts"; 264#ifdef KRB4 265 case SSH_CMSG_AUTH_KERBEROS: 266 return "kerberos"; 267#endif 268#ifdef SKEY 269 case SSH_CMSG_AUTH_TIS_RESPONSE: 270 return "s/key"; 271#endif 272 } 273 snprintf(buf, sizeof buf, "bad-auth-msg-%d", type); 274 return buf; 275} 276 277/* 278 * Signal handler for the key regeneration alarm. Note that this 279 * alarm only occurs in the daemon waiting for connections, and it does not 280 * do anything with the private key or random state before forking. 281 * Thus there should be no concurrency control/asynchronous execution 282 * problems. 283 */ 284void 285key_regeneration_alarm(int sig) 286{ 287 int save_errno = errno; 288 289 /* Check if we should generate a new key. */ 290 if (key_used) { 291 /* This should really be done in the background. */ 292 log("Generating new %d bit RSA key.", options.server_key_bits); 293 294 if (sensitive_data.private_key != NULL) 295 RSA_free(sensitive_data.private_key); 296 sensitive_data.private_key = RSA_new(); 297 298 if (public_key != NULL) 299 RSA_free(public_key); 300 public_key = RSA_new(); 301 302 rsa_generate_key(sensitive_data.private_key, public_key, 303 options.server_key_bits); 304 arc4random_stir(); 305 key_used = 0; 306 log("RSA key generation complete."); 307 } 308 /* Reschedule the alarm. */ 309 signal(SIGALRM, key_regeneration_alarm); 310 alarm(options.key_regeneration_time); 311 errno = save_errno; 312} 313 314/* 315 * Main program for the daemon. 316 */ 317int 318main(int ac, char **av) 319{ 320 extern char *optarg; 321 extern int optind; 322 int opt, sock_in = 0, sock_out = 0, newsock, i, fdsetsz, pid, on = 1; 323 socklen_t fromlen; 324 int remote_major, remote_minor; 325 int silentrsa = 0; 326 fd_set *fdset; 327 struct sockaddr_storage from; 328 char buf[100]; /* Must not be larger than remote_version. */ 329 char remote_version[100]; /* Must be at least as big as buf. */ 330 const char *remote_ip; 331 int remote_port; 332 char *comment; 333 FILE *f; 334 struct linger linger; 335 struct addrinfo *ai; 336 char ntop[NI_MAXHOST], strport[NI_MAXSERV]; 337 int listen_sock, maxfd; 338 339 /* Save argv[0]. */ 340 saved_argv = av; 341 if (strchr(av[0], '/')) 342 av0 = strrchr(av[0], '/') + 1; 343 else 344 av0 = av[0]; 345 346 /* Initialize configuration options to their default values. */ 347 initialize_server_options(&options); 348 349 /* Parse command-line arguments. */ 350 while ((opt = getopt(ac, av, "f:p:b:k:h:g:V:diqQ46")) != EOF) { 351 switch (opt) { 352 case '4': 353 IPv4or6 = AF_INET; 354 break; 355 case '6': 356 IPv4or6 = AF_INET6; 357 break; 358 case 'f': 359 config_file_name = optarg; 360 break; 361 case 'd': 362 debug_flag = 1; 363 options.log_level = SYSLOG_LEVEL_DEBUG; 364 break; 365 case 'i': 366 inetd_flag = 1; 367 break; 368 case 'Q': 369 silentrsa = 1; 370 break; 371 case 'q': 372 options.log_level = SYSLOG_LEVEL_QUIET; 373 break; 374 case 'b': 375 options.server_key_bits = atoi(optarg); 376 break; 377 case 'p': 378 options.ports_from_cmdline = 1; 379 if (options.num_ports >= MAX_PORTS) 380 fatal("too many ports.\n"); 381 options.ports[options.num_ports++] = atoi(optarg); 382 break; 383 case 'g': 384 options.login_grace_time = atoi(optarg); 385 break; 386 case 'k': 387 options.key_regeneration_time = atoi(optarg); 388 break; 389 case 'h': 390 options.host_key_file = optarg; 391 break; 392 case 'V': 393 client_version_string = optarg; 394 /* only makes sense with inetd_flag, i.e. no listen() */ 395 inetd_flag = 1; 396 break; 397 case '?': 398 default: 399 fprintf(stderr, "sshd version %s\n", SSH_VERSION); 400 fprintf(stderr, "Usage: %s [options]\n", av0); 401 fprintf(stderr, "Options:\n"); 402 fprintf(stderr, " -f file Configuration file (default %s)\n", SERVER_CONFIG_FILE); 403 fprintf(stderr, " -d Debugging mode\n"); 404 fprintf(stderr, " -i Started from inetd\n"); 405 fprintf(stderr, " -q Quiet (no logging)\n"); 406 fprintf(stderr, " -p port Listen on the specified port (default: 22)\n"); 407 fprintf(stderr, " -k seconds Regenerate server key every this many seconds (default: 3600)\n"); 408 fprintf(stderr, " -g seconds Grace period for authentication (default: 300)\n"); 409 fprintf(stderr, " -b bits Size of server RSA key (default: 768 bits)\n"); 410 fprintf(stderr, " -h file File from which to read host key (default: %s)\n", 411 HOST_KEY_FILE); 412 fprintf(stderr, " -4 Use IPv4 only\n"); 413 fprintf(stderr, " -6 Use IPv6 only\n"); 414 exit(1); 415 } 416 } 417 418 /* 419 * Force logging to stderr until we have loaded the private host 420 * key (unless started from inetd) 421 */ 422 log_init(av0, 423 options.log_level == -1 ? SYSLOG_LEVEL_INFO : options.log_level, 424 options.log_facility == -1 ? SYSLOG_FACILITY_AUTH : options.log_facility, 425 !inetd_flag); 426 427 /* check if RSA support exists */ 428 if (rsa_alive() == 0) { 429 if (silentrsa == 0) 430 printf("sshd: no RSA support in libssl and libcrypto -- exiting. See ssl(8)\n"); 431 log("no RSA support in libssl and libcrypto -- exiting. See ssl(8)"); 432 exit(1); 433 } 434 /* Read server configuration options from the configuration file. */ 435 read_server_config(&options, config_file_name); 436 437 /* Fill in default values for those options not explicitly set. */ 438 fill_default_server_options(&options); 439 440 /* Check certain values for sanity. */ 441 if (options.server_key_bits < 512 || 442 options.server_key_bits > 32768) { 443 fprintf(stderr, "Bad server key size.\n"); 444 exit(1); 445 } 446 /* Check that there are no remaining arguments. */ 447 if (optind < ac) { 448 fprintf(stderr, "Extra argument %s.\n", av[optind]); 449 exit(1); 450 } 451 452 debug("sshd version %.100s", SSH_VERSION); 453 454 sensitive_data.host_key = RSA_new(); 455 errno = 0; 456 /* Load the host key. It must have empty passphrase. */ 457 if (!load_private_key(options.host_key_file, "", 458 sensitive_data.host_key, &comment)) { 459 error("Could not load host key: %.200s: %.100s", 460 options.host_key_file, strerror(errno)); 461 exit(1); 462 } 463 xfree(comment); 464 465 /* Initialize the log (it is reinitialized below in case we 466 forked). */ 467 if (debug_flag && !inetd_flag) 468 log_stderr = 1; 469 log_init(av0, options.log_level, options.log_facility, log_stderr); 470 471 /* If not in debugging mode, and not started from inetd, 472 disconnect from the controlling terminal, and fork. The 473 original process exits. */ 474 if (!debug_flag && !inetd_flag) { 475#ifdef TIOCNOTTY 476 int fd; 477#endif /* TIOCNOTTY */ 478 if (daemon(0, 0) < 0) 479 fatal("daemon() failed: %.200s", strerror(errno)); 480 481 /* Disconnect from the controlling tty. */ 482#ifdef TIOCNOTTY 483 fd = open("/dev/tty", O_RDWR | O_NOCTTY); 484 if (fd >= 0) { 485 (void) ioctl(fd, TIOCNOTTY, NULL); 486 close(fd); 487 } 488#endif /* TIOCNOTTY */ 489 } 490 /* Reinitialize the log (because of the fork above). */ 491 log_init(av0, options.log_level, options.log_facility, log_stderr); 492 493 /* Check that server and host key lengths differ sufficiently. 494 This is necessary to make double encryption work with rsaref. 495 Oh, I hate software patents. I dont know if this can go? Niels */ 496 if (options.server_key_bits > 497 BN_num_bits(sensitive_data.host_key->n) - SSH_KEY_BITS_RESERVED && 498 options.server_key_bits < 499 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) { 500 options.server_key_bits = 501 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED; 502 debug("Forcing server key to %d bits to make it differ from host key.", 503 options.server_key_bits); 504 } 505 /* Do not display messages to stdout in RSA code. */ 506 rsa_set_verbose(0); 507 508 /* Initialize the random number generator. */ 509 arc4random_stir(); 510 511 /* Chdir to the root directory so that the current disk can be 512 unmounted if desired. */ 513 chdir("/"); 514 515 /* Close connection cleanly after attack. */ 516 cipher_attack_detected = packet_disconnect; 517 518 /* Start listening for a socket, unless started from inetd. */ 519 if (inetd_flag) { 520 int s1, s2; 521 s1 = dup(0); /* Make sure descriptors 0, 1, and 2 are in use. */ 522 s2 = dup(s1); 523 sock_in = dup(0); 524 sock_out = dup(1); 525 /* We intentionally do not close the descriptors 0, 1, and 2 526 as our code for setting the descriptors won\'t work 527 if ttyfd happens to be one of those. */ 528 debug("inetd sockets after dupping: %d, %d", sock_in, sock_out); 529 530 public_key = RSA_new(); 531 sensitive_data.private_key = RSA_new(); 532 533 log("Generating %d bit RSA key.", options.server_key_bits); 534 rsa_generate_key(sensitive_data.private_key, public_key, 535 options.server_key_bits); 536 arc4random_stir(); 537 log("RSA key generation complete."); 538 } else { 539 for (ai = options.listen_addrs; ai; ai = ai->ai_next) { 540 if (ai->ai_family != AF_INET && ai->ai_family != AF_INET6) 541 continue; 542 if (num_listen_socks >= MAX_LISTEN_SOCKS) 543 fatal("Too many listen sockets. " 544 "Enlarge MAX_LISTEN_SOCKS"); 545 if (getnameinfo(ai->ai_addr, ai->ai_addrlen, 546 ntop, sizeof(ntop), strport, sizeof(strport), 547 NI_NUMERICHOST|NI_NUMERICSERV) != 0) { 548 error("getnameinfo failed"); 549 continue; 550 } 551 /* Create socket for listening. */ 552 listen_sock = socket(ai->ai_family, SOCK_STREAM, 0); 553 if (listen_sock < 0) { 554 /* kernel may not support ipv6 */ 555 verbose("socket: %.100s", strerror(errno)); 556 continue; 557 } 558 if (fcntl(listen_sock, F_SETFL, O_NONBLOCK) < 0) { 559 error("listen_sock O_NONBLOCK: %s", strerror(errno)); 560 close(listen_sock); 561 continue; 562 } 563 /* 564 * Set socket options. We try to make the port 565 * reusable and have it close as fast as possible 566 * without waiting in unnecessary wait states on 567 * close. 568 */ 569 setsockopt(listen_sock, SOL_SOCKET, SO_REUSEADDR, 570 (void *) &on, sizeof(on)); 571 linger.l_onoff = 1; 572 linger.l_linger = 5; 573 setsockopt(listen_sock, SOL_SOCKET, SO_LINGER, 574 (void *) &linger, sizeof(linger)); 575 576 debug("Bind to port %s on %s.", strport, ntop); 577 578 /* Bind the socket to the desired port. */ 579 if (bind(listen_sock, ai->ai_addr, ai->ai_addrlen) < 0) { 580 error("Bind to port %s on %s failed: %.200s.", 581 strport, ntop, strerror(errno)); 582 close(listen_sock); 583 continue; 584 } 585 listen_socks[num_listen_socks] = listen_sock; 586 num_listen_socks++; 587 588 /* Start listening on the port. */ 589 log("Server listening on %s port %s.", ntop, strport); 590 if (listen(listen_sock, 5) < 0) 591 fatal("listen: %.100s", strerror(errno)); 592 593 } 594 freeaddrinfo(options.listen_addrs); 595 596 if (!num_listen_socks) 597 fatal("Cannot bind any address."); 598 599 if (!debug_flag) { 600 /* 601 * Record our pid in /etc/sshd_pid to make it easier 602 * to kill the correct sshd. We don\'t want to do 603 * this before the bind above because the bind will 604 * fail if there already is a daemon, and this will 605 * overwrite any old pid in the file. 606 */ 607 f = fopen(SSH_DAEMON_PID_FILE, "w"); 608 if (f) { 609 fprintf(f, "%u\n", (unsigned int) getpid()); 610 fclose(f); 611 } 612 } 613 614 public_key = RSA_new(); 615 sensitive_data.private_key = RSA_new(); 616 617 log("Generating %d bit RSA key.", options.server_key_bits); 618 rsa_generate_key(sensitive_data.private_key, public_key, 619 options.server_key_bits); 620 arc4random_stir(); 621 log("RSA key generation complete."); 622 623 /* Schedule server key regeneration alarm. */ 624 signal(SIGALRM, key_regeneration_alarm); 625 alarm(options.key_regeneration_time); 626 627 /* Arrange to restart on SIGHUP. The handler needs listen_sock. */ 628 signal(SIGHUP, sighup_handler); 629 signal(SIGTERM, sigterm_handler); 630 signal(SIGQUIT, sigterm_handler); 631 632 /* Arrange SIGCHLD to be caught. */ 633 signal(SIGCHLD, main_sigchld_handler); 634 635 /* setup fd set for listen */ 636 maxfd = 0; 637 for (i = 0; i < num_listen_socks; i++) 638 if (listen_socks[i] > maxfd) 639 maxfd = listen_socks[i]; 640 fdsetsz = howmany(maxfd, NFDBITS) * sizeof(fd_mask); 641 fdset = (fd_set *)xmalloc(fdsetsz); 642 643 /* 644 * Stay listening for connections until the system crashes or 645 * the daemon is killed with a signal. 646 */ 647 for (;;) { 648 if (received_sighup) 649 sighup_restart(); 650 /* Wait in select until there is a connection. */ 651 memset(fdset, 0, fdsetsz); 652 for (i = 0; i < num_listen_socks; i++) 653 FD_SET(listen_socks[i], fdset); 654 if (select(maxfd + 1, fdset, NULL, NULL, NULL) < 0) { 655 if (errno != EINTR) 656 error("select: %.100s", strerror(errno)); 657 continue; 658 } 659 for (i = 0; i < num_listen_socks; i++) { 660 if (!FD_ISSET(listen_socks[i], fdset)) 661 continue; 662 fromlen = sizeof(from); 663 newsock = accept(listen_socks[i], (struct sockaddr *)&from, 664 &fromlen); 665 if (newsock < 0) { 666 if (errno != EINTR && errno != EWOULDBLOCK) 667 error("accept: %.100s", strerror(errno)); 668 continue; 669 } 670 if (fcntl(newsock, F_SETFL, 0) < 0) { 671 error("newsock del O_NONBLOCK: %s", strerror(errno)); 672 continue; 673 } 674 /* 675 * Got connection. Fork a child to handle it, unless 676 * we are in debugging mode. 677 */ 678 if (debug_flag) { 679 /* 680 * In debugging mode. Close the listening 681 * socket, and start processing the 682 * connection without forking. 683 */ 684 debug("Server will not fork when running in debugging mode."); 685 close_listen_socks(); 686 sock_in = newsock; 687 sock_out = newsock; 688 pid = getpid(); 689 break; 690 } else { 691 /* 692 * Normal production daemon. Fork, and have 693 * the child process the connection. The 694 * parent continues listening. 695 */ 696 if ((pid = fork()) == 0) { 697 /* 698 * Child. Close the listening socket, and start using the 699 * accepted socket. Reinitialize logging (since our pid has 700 * changed). We break out of the loop to handle the connection. 701 */ 702 close_listen_socks(); 703 sock_in = newsock; 704 sock_out = newsock; 705 log_init(av0, options.log_level, options.log_facility, log_stderr); 706 break; 707 } 708 } 709 710 /* Parent. Stay in the loop. */ 711 if (pid < 0) 712 error("fork: %.100s", strerror(errno)); 713 else 714 debug("Forked child %d.", pid); 715 716 /* Mark that the key has been used (it was "given" to the child). */ 717 key_used = 1; 718 719 arc4random_stir(); 720 721 /* Close the new socket (the child is now taking care of it). */ 722 close(newsock); 723 } /* for (i = 0; i < num_listen_socks; i++) */ 724 /* child process check (or debug mode) */ 725 if (num_listen_socks < 0) 726 break; 727 } 728 } 729 730 /* This is the child processing a new connection. */ 731 732 /* 733 * Disable the key regeneration alarm. We will not regenerate the 734 * key since we are no longer in a position to give it to anyone. We 735 * will not restart on SIGHUP since it no longer makes sense. 736 */ 737 alarm(0); 738 signal(SIGALRM, SIG_DFL); 739 signal(SIGHUP, SIG_DFL); 740 signal(SIGTERM, SIG_DFL); 741 signal(SIGQUIT, SIG_DFL); 742 signal(SIGCHLD, SIG_DFL); 743 744 /* 745 * Set socket options for the connection. We want the socket to 746 * close as fast as possible without waiting for anything. If the 747 * connection is not a socket, these will do nothing. 748 */ 749 /* setsockopt(sock_in, SOL_SOCKET, SO_REUSEADDR, (void *)&on, sizeof(on)); */ 750 linger.l_onoff = 1; 751 linger.l_linger = 5; 752 setsockopt(sock_in, SOL_SOCKET, SO_LINGER, (void *) &linger, sizeof(linger)); 753 754 /* 755 * Register our connection. This turns encryption off because we do 756 * not have a key. 757 */ 758 packet_set_connection(sock_in, sock_out); 759 760 remote_port = get_remote_port(); 761 remote_ip = get_remote_ipaddr(); 762 763 /* Check whether logins are denied from this host. */ 764#ifdef LIBWRAP 765 /* XXX LIBWRAP noes not know about IPv6 */ 766 { 767 struct request_info req; 768 769 request_init(&req, RQ_DAEMON, av0, RQ_FILE, sock_in, NULL); 770 fromhost(&req); 771 772 if (!hosts_access(&req)) { 773 close(sock_in); 774 close(sock_out); 775 refuse(&req); 776 } 777/*XXX IPv6 verbose("Connection from %.500s port %d", eval_client(&req), remote_port); */ 778 } 779#endif /* LIBWRAP */ 780 /* Log the connection. */ 781 verbose("Connection from %.500s port %d", remote_ip, remote_port); 782 783 /* 784 * We don\'t want to listen forever unless the other side 785 * successfully authenticates itself. So we set up an alarm which is 786 * cleared after successful authentication. A limit of zero 787 * indicates no limit. Note that we don\'t set the alarm in debugging 788 * mode; it is just annoying to have the server exit just when you 789 * are about to discover the bug. 790 */ 791 signal(SIGALRM, grace_alarm_handler); 792 if (!debug_flag) 793 alarm(options.login_grace_time); 794 795 if (client_version_string != NULL) { 796 /* we are exec'ed by sshd2, so skip exchange of protocol version */ 797 strlcpy(buf, client_version_string, sizeof(buf)); 798 } else { 799 /* Send our protocol version identification. */ 800 snprintf(buf, sizeof buf, "SSH-%d.%d-%.100s\n", 801 PROTOCOL_MAJOR, PROTOCOL_MINOR, SSH_VERSION); 802 if (atomicio(write, sock_out, buf, strlen(buf)) != strlen(buf)) { 803 log("Could not write ident string to %s.", remote_ip); 804 fatal_cleanup(); 805 } 806 807 /* Read other side\'s version identification. */ 808 for (i = 0; i < sizeof(buf) - 1; i++) { 809 if (read(sock_in, &buf[i], 1) != 1) { 810 log("Did not receive ident string from %s.", remote_ip); 811 fatal_cleanup(); 812 } 813 if (buf[i] == '\r') { 814 buf[i] = '\n'; 815 buf[i + 1] = 0; 816 break; 817 } 818 if (buf[i] == '\n') { 819 /* buf[i] == '\n' */ 820 buf[i + 1] = 0; 821 break; 822 } 823 } 824 buf[sizeof(buf) - 1] = 0; 825 } 826 827 /* 828 * Check that the versions match. In future this might accept 829 * several versions and set appropriate flags to handle them. 830 */ 831 if (sscanf(buf, "SSH-%d.%d-%[^\n]\n", &remote_major, &remote_minor, 832 remote_version) != 3) { 833 char *s = "Protocol mismatch.\n"; 834 835 (void) atomicio(write, sock_out, s, strlen(s)); 836 close(sock_in); 837 close(sock_out); 838 log("Bad protocol version identification '%.100s' from %s", 839 buf, remote_ip); 840 fatal_cleanup(); 841 } 842 debug("Client protocol version %d.%d; client software version %.100s", 843 remote_major, remote_minor, remote_version); 844 if (remote_major != PROTOCOL_MAJOR) { 845 char *s = "Protocol major versions differ.\n"; 846 847 (void) atomicio(write, sock_out, s, strlen(s)); 848 close(sock_in); 849 close(sock_out); 850 log("Protocol major versions differ for %s: %d vs. %d", 851 remote_ip, PROTOCOL_MAJOR, remote_major); 852 fatal_cleanup(); 853 } 854 /* Check that the client has sufficiently high software version. */ 855 if (remote_major == 1 && remote_minor < 3) 856 packet_disconnect("Your ssh version is too old and is no longer supported. Please install a newer version."); 857 858 if (remote_major == 1 && remote_minor == 3) { 859 /* note that this disables agent-forwarding */ 860 enable_compat13(); 861 } 862 /* 863 * Check that the connection comes from a privileged port. Rhosts- 864 * and Rhosts-RSA-Authentication only make sense from priviledged 865 * programs. Of course, if the intruder has root access on his local 866 * machine, he can connect from any port. So do not use these 867 * authentication methods from machines that you do not trust. 868 */ 869 if (remote_port >= IPPORT_RESERVED || 870 remote_port < IPPORT_RESERVED / 2) { 871 options.rhosts_authentication = 0; 872 options.rhosts_rsa_authentication = 0; 873 } 874#ifdef KRB4 875 if (!packet_connection_is_ipv4() && 876 options.kerberos_authentication) { 877 debug("Kerberos Authentication disabled, only available for IPv4."); 878 options.kerberos_authentication = 0; 879 } 880#endif /* KRB4 */ 881 882 packet_set_nonblocking(); 883 884 /* perform the key exchange */ 885 do_ssh_kex(); 886 887 /* authenticate user and start session */ 888 do_authentication(); 889 890#ifdef KRB4 891 /* Cleanup user's ticket cache file. */ 892 if (options.kerberos_ticket_cleanup) 893 (void) dest_tkt(); 894#endif /* KRB4 */ 895 896 /* Cleanup user's local Xauthority file. */ 897 if (xauthfile) 898 xauthfile_cleanup_proc(NULL); 899 900 /* The connection has been terminated. */ 901 verbose("Closing connection to %.100s", remote_ip); 902 packet_close(); 903 exit(0); 904} 905 906/* 907 * SSH1 key exchange 908 */ 909void 910do_ssh_kex() 911{ 912 int i, len; 913 int plen, slen; 914 BIGNUM *session_key_int; 915 unsigned char session_key[SSH_SESSION_KEY_LENGTH]; 916 unsigned char cookie[8]; 917 unsigned int cipher_type, auth_mask, protocol_flags; 918 u_int32_t rand = 0; 919 920 /* 921 * Generate check bytes that the client must send back in the user 922 * packet in order for it to be accepted; this is used to defy ip 923 * spoofing attacks. Note that this only works against somebody 924 * doing IP spoofing from a remote machine; any machine on the local 925 * network can still see outgoing packets and catch the random 926 * cookie. This only affects rhosts authentication, and this is one 927 * of the reasons why it is inherently insecure. 928 */ 929 for (i = 0; i < 8; i++) { 930 if (i % 4 == 0) 931 rand = arc4random(); 932 cookie[i] = rand & 0xff; 933 rand >>= 8; 934 } 935 936 /* 937 * Send our public key. We include in the packet 64 bits of random 938 * data that must be matched in the reply in order to prevent IP 939 * spoofing. 940 */ 941 packet_start(SSH_SMSG_PUBLIC_KEY); 942 for (i = 0; i < 8; i++) 943 packet_put_char(cookie[i]); 944 945 /* Store our public server RSA key. */ 946 packet_put_int(BN_num_bits(public_key->n)); 947 packet_put_bignum(public_key->e); 948 packet_put_bignum(public_key->n); 949 950 /* Store our public host RSA key. */ 951 packet_put_int(BN_num_bits(sensitive_data.host_key->n)); 952 packet_put_bignum(sensitive_data.host_key->e); 953 packet_put_bignum(sensitive_data.host_key->n); 954 955 /* Put protocol flags. */ 956 packet_put_int(SSH_PROTOFLAG_HOST_IN_FWD_OPEN); 957 958 /* Declare which ciphers we support. */ 959 packet_put_int(cipher_mask()); 960 961 /* Declare supported authentication types. */ 962 auth_mask = 0; 963 if (options.rhosts_authentication) 964 auth_mask |= 1 << SSH_AUTH_RHOSTS; 965 if (options.rhosts_rsa_authentication) 966 auth_mask |= 1 << SSH_AUTH_RHOSTS_RSA; 967 if (options.rsa_authentication) 968 auth_mask |= 1 << SSH_AUTH_RSA; 969#ifdef KRB4 970 if (options.kerberos_authentication) 971 auth_mask |= 1 << SSH_AUTH_KERBEROS; 972#endif 973#ifdef AFS 974 if (options.kerberos_tgt_passing) 975 auth_mask |= 1 << SSH_PASS_KERBEROS_TGT; 976 if (options.afs_token_passing) 977 auth_mask |= 1 << SSH_PASS_AFS_TOKEN; 978#endif 979#ifdef SKEY 980 if (options.skey_authentication == 1) 981 auth_mask |= 1 << SSH_AUTH_TIS; 982#endif 983 if (options.password_authentication) 984 auth_mask |= 1 << SSH_AUTH_PASSWORD; 985 packet_put_int(auth_mask); 986 987 /* Send the packet and wait for it to be sent. */ 988 packet_send(); 989 packet_write_wait(); 990 991 debug("Sent %d bit public key and %d bit host key.", 992 BN_num_bits(public_key->n), BN_num_bits(sensitive_data.host_key->n)); 993 994 /* Read clients reply (cipher type and session key). */ 995 packet_read_expect(&plen, SSH_CMSG_SESSION_KEY); 996 997 /* Get cipher type and check whether we accept this. */ 998 cipher_type = packet_get_char(); 999 1000 if (!(cipher_mask() & (1 << cipher_type))) 1001 packet_disconnect("Warning: client selects unsupported cipher."); 1002 1003 /* Get check bytes from the packet. These must match those we 1004 sent earlier with the public key packet. */ 1005 for (i = 0; i < 8; i++) 1006 if (cookie[i] != packet_get_char()) 1007 packet_disconnect("IP Spoofing check bytes do not match."); 1008 1009 debug("Encryption type: %.200s", cipher_name(cipher_type)); 1010 1011 /* Get the encrypted integer. */ 1012 session_key_int = BN_new(); 1013 packet_get_bignum(session_key_int, &slen); 1014 1015 protocol_flags = packet_get_int(); 1016 packet_set_protocol_flags(protocol_flags); 1017 1018 packet_integrity_check(plen, 1 + 8 + slen + 4, SSH_CMSG_SESSION_KEY); 1019 1020 /* 1021 * Decrypt it using our private server key and private host key (key 1022 * with larger modulus first). 1023 */ 1024 if (BN_cmp(sensitive_data.private_key->n, sensitive_data.host_key->n) > 0) { 1025 /* Private key has bigger modulus. */ 1026 if (BN_num_bits(sensitive_data.private_key->n) < 1027 BN_num_bits(sensitive_data.host_key->n) + SSH_KEY_BITS_RESERVED) { 1028 fatal("do_connection: %s: private_key %d < host_key %d + SSH_KEY_BITS_RESERVED %d", 1029 get_remote_ipaddr(), 1030 BN_num_bits(sensitive_data.private_key->n), 1031 BN_num_bits(sensitive_data.host_key->n), 1032 SSH_KEY_BITS_RESERVED); 1033 } 1034 rsa_private_decrypt(session_key_int, session_key_int, 1035 sensitive_data.private_key); 1036 rsa_private_decrypt(session_key_int, session_key_int, 1037 sensitive_data.host_key); 1038 } else { 1039 /* Host key has bigger modulus (or they are equal). */ 1040 if (BN_num_bits(sensitive_data.host_key->n) < 1041 BN_num_bits(sensitive_data.private_key->n) + SSH_KEY_BITS_RESERVED) { 1042 fatal("do_connection: %s: host_key %d < private_key %d + SSH_KEY_BITS_RESERVED %d", 1043 get_remote_ipaddr(), 1044 BN_num_bits(sensitive_data.host_key->n), 1045 BN_num_bits(sensitive_data.private_key->n), 1046 SSH_KEY_BITS_RESERVED); 1047 } 1048 rsa_private_decrypt(session_key_int, session_key_int, 1049 sensitive_data.host_key); 1050 rsa_private_decrypt(session_key_int, session_key_int, 1051 sensitive_data.private_key); 1052 } 1053 1054 compute_session_id(session_id, cookie, 1055 sensitive_data.host_key->n, 1056 sensitive_data.private_key->n); 1057 1058 /* Destroy the private and public keys. They will no longer be needed. */ 1059 RSA_free(public_key); 1060 RSA_free(sensitive_data.private_key); 1061 RSA_free(sensitive_data.host_key); 1062 1063 /* 1064 * Extract session key from the decrypted integer. The key is in the 1065 * least significant 256 bits of the integer; the first byte of the 1066 * key is in the highest bits. 1067 */ 1068 BN_mask_bits(session_key_int, sizeof(session_key) * 8); 1069 len = BN_num_bytes(session_key_int); 1070 if (len < 0 || len > sizeof(session_key)) 1071 fatal("do_connection: bad len from %s: session_key_int %d > sizeof(session_key) %d", 1072 get_remote_ipaddr(), 1073 len, sizeof(session_key)); 1074 memset(session_key, 0, sizeof(session_key)); 1075 BN_bn2bin(session_key_int, session_key + sizeof(session_key) - len); 1076 1077 /* Destroy the decrypted integer. It is no longer needed. */ 1078 BN_clear_free(session_key_int); 1079 1080 /* Xor the first 16 bytes of the session key with the session id. */ 1081 for (i = 0; i < 16; i++) 1082 session_key[i] ^= session_id[i]; 1083 1084 /* Set the session key. From this on all communications will be encrypted. */ 1085 packet_set_encryption_key(session_key, SSH_SESSION_KEY_LENGTH, cipher_type); 1086 1087 /* Destroy our copy of the session key. It is no longer needed. */ 1088 memset(session_key, 0, sizeof(session_key)); 1089 1090 debug("Received session key; encryption turned on."); 1091 1092 /* Send an acknowledgement packet. Note that this packet is sent encrypted. */ 1093 packet_start(SSH_SMSG_SUCCESS); 1094 packet_send(); 1095 packet_write_wait(); 1096} 1097 1098 1099/* 1100 * Check if the user is allowed to log in via ssh. If user is listed in 1101 * DenyUsers or user's primary group is listed in DenyGroups, false will 1102 * be returned. If AllowUsers isn't empty and user isn't listed there, or 1103 * if AllowGroups isn't empty and user isn't listed there, false will be 1104 * returned. 1105 * If the user's shell is not executable, false will be returned. 1106 * Otherwise true is returned. 1107 */ 1108static int 1109allowed_user(struct passwd * pw) 1110{ 1111 struct stat st; 1112 struct group *grp; 1113 int i; 1114 1115 /* Shouldn't be called if pw is NULL, but better safe than sorry... */ 1116 if (!pw) 1117 return 0; 1118 1119 /* deny if shell does not exists or is not executable */ 1120 if (stat(pw->pw_shell, &st) != 0) 1121 return 0; 1122 if (!((st.st_mode & S_IFREG) && (st.st_mode & (S_IXOTH|S_IXUSR|S_IXGRP)))) 1123 return 0; 1124 1125 /* Return false if user is listed in DenyUsers */ 1126 if (options.num_deny_users > 0) { 1127 if (!pw->pw_name) 1128 return 0; 1129 for (i = 0; i < options.num_deny_users; i++) 1130 if (match_pattern(pw->pw_name, options.deny_users[i])) 1131 return 0; 1132 } 1133 /* Return false if AllowUsers isn't empty and user isn't listed there */ 1134 if (options.num_allow_users > 0) { 1135 if (!pw->pw_name) 1136 return 0; 1137 for (i = 0; i < options.num_allow_users; i++) 1138 if (match_pattern(pw->pw_name, options.allow_users[i])) 1139 break; 1140 /* i < options.num_allow_users iff we break for loop */ 1141 if (i >= options.num_allow_users) 1142 return 0; 1143 } 1144 /* Get the primary group name if we need it. Return false if it fails */ 1145 if (options.num_deny_groups > 0 || options.num_allow_groups > 0) { 1146 grp = getgrgid(pw->pw_gid); 1147 if (!grp) 1148 return 0; 1149 1150 /* Return false if user's group is listed in DenyGroups */ 1151 if (options.num_deny_groups > 0) { 1152 if (!grp->gr_name) 1153 return 0; 1154 for (i = 0; i < options.num_deny_groups; i++) 1155 if (match_pattern(grp->gr_name, options.deny_groups[i])) 1156 return 0; 1157 } 1158 /* 1159 * Return false if AllowGroups isn't empty and user's group 1160 * isn't listed there 1161 */ 1162 if (options.num_allow_groups > 0) { 1163 if (!grp->gr_name) 1164 return 0; 1165 for (i = 0; i < options.num_allow_groups; i++) 1166 if (match_pattern(grp->gr_name, options.allow_groups[i])) 1167 break; 1168 /* i < options.num_allow_groups iff we break for 1169 loop */ 1170 if (i >= options.num_allow_groups) 1171 return 0; 1172 } 1173 } 1174 /* We found no reason not to let this user try to log on... */ 1175 return 1; 1176} 1177 1178/* 1179 * Performs authentication of an incoming connection. Session key has already 1180 * been exchanged and encryption is enabled. 1181 */ 1182void 1183do_authentication() 1184{ 1185 struct passwd *pw, pwcopy; 1186 int plen, ulen; 1187 char *user; 1188 1189 /* Get the name of the user that we wish to log in as. */ 1190 packet_read_expect(&plen, SSH_CMSG_USER); 1191 1192 /* Get the user name. */ 1193 user = packet_get_string(&ulen); 1194 packet_integrity_check(plen, (4 + ulen), SSH_CMSG_USER); 1195 1196 setproctitle("%s", user); 1197 1198#ifdef AFS 1199 /* If machine has AFS, set process authentication group. */ 1200 if (k_hasafs()) { 1201 k_setpag(); 1202 k_unlog(); 1203 } 1204#endif /* AFS */ 1205 1206 /* Verify that the user is a valid user. */ 1207 pw = getpwnam(user); 1208 if (!pw || !allowed_user(pw)) 1209 do_fake_authloop(user); 1210 xfree(user); 1211 1212 /* Take a copy of the returned structure. */ 1213 memset(&pwcopy, 0, sizeof(pwcopy)); 1214 pwcopy.pw_name = xstrdup(pw->pw_name); 1215 pwcopy.pw_passwd = xstrdup(pw->pw_passwd); 1216 pwcopy.pw_uid = pw->pw_uid; 1217 pwcopy.pw_gid = pw->pw_gid; 1218 pwcopy.pw_dir = xstrdup(pw->pw_dir); 1219 pwcopy.pw_shell = xstrdup(pw->pw_shell); 1220 pw = &pwcopy; 1221 1222 /* 1223 * If we are not running as root, the user must have the same uid as 1224 * the server. 1225 */ 1226 if (getuid() != 0 && pw->pw_uid != getuid()) 1227 packet_disconnect("Cannot change user when server not running as root."); 1228 1229 debug("Attempting authentication for %.100s.", pw->pw_name); 1230 1231 /* If the user has no password, accept authentication immediately. */ 1232 if (options.password_authentication && 1233#ifdef KRB4 1234 (!options.kerberos_authentication || options.kerberos_or_local_passwd) && 1235#endif /* KRB4 */ 1236 auth_password(pw, "")) { 1237 /* Authentication with empty password succeeded. */ 1238 log("Login for user %s from %.100s, accepted without authentication.", 1239 pw->pw_name, get_remote_ipaddr()); 1240 } else { 1241 /* Loop until the user has been authenticated or the 1242 connection is closed, do_authloop() returns only if 1243 authentication is successfull */ 1244 do_authloop(pw); 1245 } 1246 1247 /* Check if the user is logging in as root and root logins are disallowed. */ 1248 if (pw->pw_uid == 0 && !options.permit_root_login) { 1249 if (forced_command) 1250 log("Root login accepted for forced command."); 1251 else 1252 packet_disconnect("ROOT LOGIN REFUSED FROM %.200s", 1253 get_canonical_hostname()); 1254 } 1255 /* The user has been authenticated and accepted. */ 1256 packet_start(SSH_SMSG_SUCCESS); 1257 packet_send(); 1258 packet_write_wait(); 1259 1260 /* Perform session preparation. */ 1261 do_authenticated(pw); 1262} 1263 1264#define AUTH_FAIL_MAX 6 1265#define AUTH_FAIL_LOG (AUTH_FAIL_MAX/2) 1266#define AUTH_FAIL_MSG "Too many authentication failures for %.100s" 1267 1268/* 1269 * read packets and try to authenticate local user *pw. 1270 * return if authentication is successfull 1271 */ 1272void 1273do_authloop(struct passwd * pw) 1274{ 1275 int attempt = 0; 1276 unsigned int bits; 1277 BIGNUM *client_host_key_e, *client_host_key_n; 1278 BIGNUM *n; 1279 char *client_user, *password; 1280 char user[1024]; 1281 int plen, dlen, nlen, ulen, elen; 1282 int type = 0; 1283 void (*authlog) (const char *fmt,...) = verbose; 1284 1285 /* Indicate that authentication is needed. */ 1286 packet_start(SSH_SMSG_FAILURE); 1287 packet_send(); 1288 packet_write_wait(); 1289 1290 for (attempt = 1;; attempt++) { 1291 int authenticated = 0; 1292 strlcpy(user, "", sizeof user); 1293 1294 /* Get a packet from the client. */ 1295 type = packet_read(&plen); 1296 1297 /* Process the packet. */ 1298 switch (type) { 1299#ifdef AFS 1300 case SSH_CMSG_HAVE_KERBEROS_TGT: 1301 if (!options.kerberos_tgt_passing) { 1302 /* packet_get_all(); */ 1303 verbose("Kerberos tgt passing disabled."); 1304 break; 1305 } else { 1306 /* Accept Kerberos tgt. */ 1307 char *tgt = packet_get_string(&dlen); 1308 packet_integrity_check(plen, 4 + dlen, type); 1309 if (!auth_kerberos_tgt(pw, tgt)) 1310 verbose("Kerberos tgt REFUSED for %s", pw->pw_name); 1311 xfree(tgt); 1312 } 1313 continue; 1314 1315 case SSH_CMSG_HAVE_AFS_TOKEN: 1316 if (!options.afs_token_passing || !k_hasafs()) { 1317 /* packet_get_all(); */ 1318 verbose("AFS token passing disabled."); 1319 break; 1320 } else { 1321 /* Accept AFS token. */ 1322 char *token_string = packet_get_string(&dlen); 1323 packet_integrity_check(plen, 4 + dlen, type); 1324 if (!auth_afs_token(pw, token_string)) 1325 verbose("AFS token REFUSED for %s", pw->pw_name); 1326 xfree(token_string); 1327 } 1328 continue; 1329#endif /* AFS */ 1330#ifdef KRB4 1331 case SSH_CMSG_AUTH_KERBEROS: 1332 if (!options.kerberos_authentication) { 1333 /* packet_get_all(); */ 1334 verbose("Kerberos authentication disabled."); 1335 break; 1336 } else { 1337 /* Try Kerberos v4 authentication. */ 1338 KTEXT_ST auth; 1339 char *tkt_user = NULL; 1340 char *kdata = packet_get_string((unsigned int *) &auth.length); 1341 packet_integrity_check(plen, 4 + auth.length, type); 1342 1343 if (auth.length < MAX_KTXT_LEN) 1344 memcpy(auth.dat, kdata, auth.length); 1345 xfree(kdata); 1346 1347 authenticated = auth_krb4(pw->pw_name, &auth, &tkt_user); 1348 1349 if (authenticated) { 1350 snprintf(user, sizeof user, " tktuser %s", tkt_user); 1351 xfree(tkt_user); 1352 } 1353 } 1354 break; 1355#endif /* KRB4 */ 1356 1357 case SSH_CMSG_AUTH_RHOSTS: 1358 if (!options.rhosts_authentication) { 1359 verbose("Rhosts authentication disabled."); 1360 break; 1361 } 1362 /* 1363 * Get client user name. Note that we just have to 1364 * trust the client; this is one reason why rhosts 1365 * authentication is insecure. (Another is 1366 * IP-spoofing on a local network.) 1367 */ 1368 client_user = packet_get_string(&ulen); 1369 packet_integrity_check(plen, 4 + ulen, type); 1370 1371 /* Try to authenticate using /etc/hosts.equiv and 1372 .rhosts. */ 1373 authenticated = auth_rhosts(pw, client_user); 1374 1375 snprintf(user, sizeof user, " ruser %s", client_user); 1376 xfree(client_user); 1377 break; 1378 1379 case SSH_CMSG_AUTH_RHOSTS_RSA: 1380 if (!options.rhosts_rsa_authentication) { 1381 verbose("Rhosts with RSA authentication disabled."); 1382 break; 1383 } 1384 /* 1385 * Get client user name. Note that we just have to 1386 * trust the client; root on the client machine can 1387 * claim to be any user. 1388 */ 1389 client_user = packet_get_string(&ulen); 1390 1391 /* Get the client host key. */ 1392 client_host_key_e = BN_new(); 1393 client_host_key_n = BN_new(); 1394 bits = packet_get_int(); 1395 packet_get_bignum(client_host_key_e, &elen); 1396 packet_get_bignum(client_host_key_n, &nlen); 1397 1398 if (bits != BN_num_bits(client_host_key_n)) 1399 error("Warning: keysize mismatch for client_host_key: " 1400 "actual %d, announced %d", BN_num_bits(client_host_key_n), bits); 1401 packet_integrity_check(plen, (4 + ulen) + 4 + elen + nlen, type); 1402 1403 authenticated = auth_rhosts_rsa(pw, client_user, 1404 client_host_key_e, client_host_key_n); 1405 BN_clear_free(client_host_key_e); 1406 BN_clear_free(client_host_key_n); 1407 1408 snprintf(user, sizeof user, " ruser %s", client_user); 1409 xfree(client_user); 1410 break; 1411 1412 case SSH_CMSG_AUTH_RSA: 1413 if (!options.rsa_authentication) { 1414 verbose("RSA authentication disabled."); 1415 break; 1416 } 1417 /* RSA authentication requested. */ 1418 n = BN_new(); 1419 packet_get_bignum(n, &nlen); 1420 packet_integrity_check(plen, nlen, type); 1421 authenticated = auth_rsa(pw, n); 1422 BN_clear_free(n); 1423 break; 1424 1425 case SSH_CMSG_AUTH_PASSWORD: 1426 if (!options.password_authentication) { 1427 verbose("Password authentication disabled."); 1428 break; 1429 } 1430 /* 1431 * Read user password. It is in plain text, but was 1432 * transmitted over the encrypted channel so it is 1433 * not visible to an outside observer. 1434 */ 1435 password = packet_get_string(&dlen); 1436 packet_integrity_check(plen, 4 + dlen, type); 1437 1438 /* Try authentication with the password. */ 1439 authenticated = auth_password(pw, password); 1440 1441 memset(password, 0, strlen(password)); 1442 xfree(password); 1443 break; 1444 1445#ifdef SKEY 1446 case SSH_CMSG_AUTH_TIS: 1447 debug("rcvd SSH_CMSG_AUTH_TIS"); 1448 if (options.skey_authentication == 1) { 1449 char *skeyinfo = skey_keyinfo(pw->pw_name); 1450 if (skeyinfo == NULL) { 1451 debug("generating fake skeyinfo for %.100s.", pw->pw_name); 1452 skeyinfo = skey_fake_keyinfo(pw->pw_name); 1453 } 1454 if (skeyinfo != NULL) { 1455 /* we send our s/key- in tis-challenge messages */ 1456 debug("sending challenge '%s'", skeyinfo); 1457 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE); 1458 packet_put_string(skeyinfo, strlen(skeyinfo)); 1459 packet_send(); 1460 packet_write_wait(); 1461 continue; 1462 } 1463 } 1464 break; 1465 case SSH_CMSG_AUTH_TIS_RESPONSE: 1466 debug("rcvd SSH_CMSG_AUTH_TIS_RESPONSE"); 1467 if (options.skey_authentication == 1) { 1468 char *response = packet_get_string(&dlen); 1469 debug("skey response == '%s'", response); 1470 packet_integrity_check(plen, 4 + dlen, type); 1471 authenticated = (skey_haskey(pw->pw_name) == 0 && 1472 skey_passcheck(pw->pw_name, response) != -1); 1473 xfree(response); 1474 } 1475 break; 1476#else 1477 case SSH_CMSG_AUTH_TIS: 1478 /* TIS Authentication is unsupported */ 1479 log("TIS authentication unsupported."); 1480 break; 1481#endif 1482 1483 default: 1484 /* 1485 * Any unknown messages will be ignored (and failure 1486 * returned) during authentication. 1487 */ 1488 log("Unknown message during authentication: type %d", type); 1489 break; 1490 } 1491 1492 /* Raise logging level */ 1493 if (authenticated || 1494 attempt == AUTH_FAIL_LOG || 1495 type == SSH_CMSG_AUTH_PASSWORD) 1496 authlog = log; 1497 1498 authlog("%s %s for %.200s from %.200s port %d%s", 1499 authenticated ? "Accepted" : "Failed", 1500 get_authname(type), 1501 pw->pw_uid == 0 ? "ROOT" : pw->pw_name, 1502 get_remote_ipaddr(), 1503 get_remote_port(), 1504 user); 1505 1506 if (authenticated) 1507 return; 1508 1509 if (attempt > AUTH_FAIL_MAX) 1510 packet_disconnect(AUTH_FAIL_MSG, pw->pw_name); 1511 1512 /* Send a message indicating that the authentication attempt failed. */ 1513 packet_start(SSH_SMSG_FAILURE); 1514 packet_send(); 1515 packet_write_wait(); 1516 } 1517} 1518 1519/* 1520 * The user does not exist or access is denied, 1521 * but fake indication that authentication is needed. 1522 */ 1523void 1524do_fake_authloop(char *user) 1525{ 1526 int attempt = 0; 1527 1528 log("Faking authloop for illegal user %.200s from %.200s port %d", 1529 user, 1530 get_remote_ipaddr(), 1531 get_remote_port()); 1532 1533 /* Indicate that authentication is needed. */ 1534 packet_start(SSH_SMSG_FAILURE); 1535 packet_send(); 1536 packet_write_wait(); 1537 1538 /* 1539 * Keep reading packets, and always respond with a failure. This is 1540 * to avoid disclosing whether such a user really exists. 1541 */ 1542 for (attempt = 1;; attempt++) { 1543 /* Read a packet. This will not return if the client disconnects. */ 1544 int plen; 1545 int type = packet_read(&plen); 1546#ifdef SKEY 1547 int dlen; 1548 char *password, *skeyinfo; 1549 /* Try to send a fake s/key challenge. */ 1550 if (options.skey_authentication == 1 && 1551 (skeyinfo = skey_fake_keyinfo(user)) != NULL) { 1552 password = NULL; 1553 if (type == SSH_CMSG_AUTH_TIS) { 1554 packet_start(SSH_SMSG_AUTH_TIS_CHALLENGE); 1555 packet_put_string(skeyinfo, strlen(skeyinfo)); 1556 packet_send(); 1557 packet_write_wait(); 1558 continue; 1559 } else if (type == SSH_CMSG_AUTH_PASSWORD && 1560 options.password_authentication && 1561 (password = packet_get_string(&dlen)) != NULL && 1562 dlen == 5 && 1563 strncasecmp(password, "s/key", 5) == 0 ) { 1564 packet_send_debug(skeyinfo); 1565 } 1566 if (password != NULL) 1567 xfree(password); 1568 } 1569#endif 1570 if (attempt > AUTH_FAIL_MAX) 1571 packet_disconnect(AUTH_FAIL_MSG, user); 1572 1573 /* 1574 * Send failure. This should be indistinguishable from a 1575 * failed authentication. 1576 */ 1577 packet_start(SSH_SMSG_FAILURE); 1578 packet_send(); 1579 packet_write_wait(); 1580 } 1581 /* NOTREACHED */ 1582 abort(); 1583} 1584 1585struct pty_cleanup_context { 1586 const char *ttyname; 1587 int pid; 1588}; 1589 1590/* 1591 * Function to perform cleanup if we get aborted abnormally (e.g., due to a 1592 * dropped connection). 1593 */ 1594void 1595pty_cleanup_proc(void *context) 1596{ 1597 struct pty_cleanup_context *cu = context; 1598 1599 debug("pty_cleanup_proc called"); 1600 1601 /* Record that the user has logged out. */ 1602 record_logout(cu->pid, cu->ttyname); 1603 1604 /* Release the pseudo-tty. */ 1605 pty_release(cu->ttyname); 1606} 1607 1608/* simple cleanup: chown tty slave back to root */ 1609static void 1610pty_release_proc(void *tty) 1611{ 1612 char *ttyname = tty; 1613 pty_release(ttyname); 1614} 1615 1616/* 1617 * Prepares for an interactive session. This is called after the user has 1618 * been successfully authenticated. During this message exchange, pseudo 1619 * terminals are allocated, X11, TCP/IP, and authentication agent forwardings 1620 * are requested, etc. 1621 */ 1622void 1623do_authenticated(struct passwd * pw) 1624{ 1625 int type; 1626 int compression_level = 0, enable_compression_after_reply = 0; 1627 int have_pty = 0, ptyfd = -1, ttyfd = -1; 1628 int row, col, xpixel, ypixel, screen; 1629 char ttyname[64]; 1630 char *command, *term = NULL, *display = NULL, *proto = NULL, *data = NULL; 1631 int n_bytes; 1632 1633 /* 1634 * Cancel the alarm we set to limit the time taken for 1635 * authentication. 1636 */ 1637 alarm(0); 1638 1639 /* 1640 * Inform the channel mechanism that we are the server side and that 1641 * the client may request to connect to any port at all. (The user 1642 * could do it anyway, and we wouldn\'t know what is permitted except 1643 * by the client telling us, so we can equally well trust the client 1644 * not to request anything bogus.) 1645 */ 1646 if (!no_port_forwarding_flag) 1647 channel_permit_all_opens(); 1648 1649 /* 1650 * We stay in this loop until the client requests to execute a shell 1651 * or a command. 1652 */ 1653 while (1) { 1654 int plen, dlen; 1655 1656 /* Get a packet from the client. */ 1657 type = packet_read(&plen); 1658 1659 /* Process the packet. */ 1660 switch (type) { 1661 case SSH_CMSG_REQUEST_COMPRESSION: 1662 packet_integrity_check(plen, 4, type); 1663 compression_level = packet_get_int(); 1664 if (compression_level < 1 || compression_level > 9) { 1665 packet_send_debug("Received illegal compression level %d.", 1666 compression_level); 1667 goto fail; 1668 } 1669 /* Enable compression after we have responded with SUCCESS. */ 1670 enable_compression_after_reply = 1; 1671 break; 1672 1673 case SSH_CMSG_REQUEST_PTY: 1674 if (no_pty_flag) { 1675 debug("Allocating a pty not permitted for this authentication."); 1676 goto fail; 1677 } 1678 if (have_pty) 1679 packet_disconnect("Protocol error: you already have a pty."); 1680 1681 debug("Allocating pty."); 1682 1683 /* Allocate a pty and open it. */ 1684 if (!pty_allocate(&ptyfd, &ttyfd, ttyname, 1685 sizeof(ttyname))) { 1686 error("Failed to allocate pty."); 1687 goto fail; 1688 } 1689 fatal_add_cleanup(pty_release_proc, (void *)ttyname); 1690 pty_setowner(pw, ttyname); 1691 1692 /* Get TERM from the packet. Note that the value may be of arbitrary length. */ 1693 term = packet_get_string(&dlen); 1694 packet_integrity_check(dlen, strlen(term), type); 1695 1696 /* Remaining bytes */ 1697 n_bytes = plen - (4 + dlen + 4 * 4); 1698 1699 if (strcmp(term, "") == 0) { 1700 xfree(term); 1701 term = NULL; 1702 } 1703 1704 /* Get window size from the packet. */ 1705 row = packet_get_int(); 1706 col = packet_get_int(); 1707 xpixel = packet_get_int(); 1708 ypixel = packet_get_int(); 1709 pty_change_window_size(ptyfd, row, col, xpixel, ypixel); 1710 1711 /* Get tty modes from the packet. */ 1712 tty_parse_modes(ttyfd, &n_bytes); 1713 packet_integrity_check(plen, 4 + dlen + 4 * 4 + n_bytes, type); 1714 1715 /* Indicate that we now have a pty. */ 1716 have_pty = 1; 1717 break; 1718 1719 case SSH_CMSG_X11_REQUEST_FORWARDING: 1720 if (!options.x11_forwarding) { 1721 packet_send_debug("X11 forwarding disabled in server configuration file."); 1722 goto fail; 1723 } 1724#ifdef XAUTH_PATH 1725 if (no_x11_forwarding_flag) { 1726 packet_send_debug("X11 forwarding not permitted for this authentication."); 1727 goto fail; 1728 } 1729 debug("Received request for X11 forwarding with auth spoofing."); 1730 if (display) 1731 packet_disconnect("Protocol error: X11 display already set."); 1732 { 1733 int proto_len, data_len; 1734 proto = packet_get_string(&proto_len); 1735 data = packet_get_string(&data_len); 1736 packet_integrity_check(plen, 4 + proto_len + 4 + data_len + 4, type); 1737 } 1738 if (packet_get_protocol_flags() & SSH_PROTOFLAG_SCREEN_NUMBER) 1739 screen = packet_get_int(); 1740 else 1741 screen = 0; 1742 display = x11_create_display_inet(screen, options.x11_display_offset); 1743 if (!display) 1744 goto fail; 1745 1746 /* Setup to always have a local .Xauthority. */ 1747 xauthfile = xmalloc(MAXPATHLEN); 1748 strlcpy(xauthfile, "/tmp/ssh-XXXXXXXX", MAXPATHLEN); 1749 temporarily_use_uid(pw->pw_uid); 1750 if (mkdtemp(xauthfile) == NULL) { 1751 restore_uid(); 1752 error("private X11 dir: mkdtemp %s failed: %s", 1753 xauthfile, strerror(errno)); 1754 xfree(xauthfile); 1755 xauthfile = NULL; 1756 goto fail; 1757 } 1758 restore_uid(); 1759 strlcat(xauthfile, "/cookies", MAXPATHLEN); 1760 fatal_add_cleanup(xauthfile_cleanup_proc, NULL); 1761 break; 1762#else /* XAUTH_PATH */ 1763 packet_send_debug("No xauth program; cannot forward with spoofing."); 1764 goto fail; 1765#endif /* XAUTH_PATH */ 1766 1767 case SSH_CMSG_AGENT_REQUEST_FORWARDING: 1768 if (no_agent_forwarding_flag || compat13) { 1769 debug("Authentication agent forwarding not permitted for this authentication."); 1770 goto fail; 1771 } 1772 debug("Received authentication agent forwarding request."); 1773 auth_input_request_forwarding(pw); 1774 break; 1775 1776 case SSH_CMSG_PORT_FORWARD_REQUEST: 1777 if (no_port_forwarding_flag) { 1778 debug("Port forwarding not permitted for this authentication."); 1779 goto fail; 1780 } 1781 debug("Received TCP/IP port forwarding request."); 1782 channel_input_port_forward_request(pw->pw_uid == 0); 1783 break; 1784 1785 case SSH_CMSG_MAX_PACKET_SIZE: 1786 if (packet_set_maxsize(packet_get_int()) < 0) 1787 goto fail; 1788 break; 1789 1790 case SSH_CMSG_EXEC_SHELL: 1791 /* Set interactive/non-interactive mode. */ 1792 packet_set_interactive(have_pty || display != NULL, 1793 options.keepalives); 1794 1795 if (forced_command != NULL) 1796 goto do_forced_command; 1797 debug("Forking shell."); 1798 packet_integrity_check(plen, 0, type); 1799 if (have_pty) 1800 do_exec_pty(NULL, ptyfd, ttyfd, ttyname, pw, term, display, proto, data); 1801 else 1802 do_exec_no_pty(NULL, pw, display, proto, data); 1803 return; 1804 1805 case SSH_CMSG_EXEC_CMD: 1806 /* Set interactive/non-interactive mode. */ 1807 packet_set_interactive(have_pty || display != NULL, 1808 options.keepalives); 1809 1810 if (forced_command != NULL) 1811 goto do_forced_command; 1812 /* Get command from the packet. */ 1813 { 1814 int dlen; 1815 command = packet_get_string(&dlen); 1816 debug("Executing command '%.500s'", command); 1817 packet_integrity_check(plen, 4 + dlen, type); 1818 } 1819 if (have_pty) 1820 do_exec_pty(command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data); 1821 else 1822 do_exec_no_pty(command, pw, display, proto, data); 1823 xfree(command); 1824 return; 1825 1826 default: 1827 /* 1828 * Any unknown messages in this phase are ignored, 1829 * and a failure message is returned. 1830 */ 1831 log("Unknown packet type received after authentication: %d", type); 1832 goto fail; 1833 } 1834 1835 /* The request was successfully processed. */ 1836 packet_start(SSH_SMSG_SUCCESS); 1837 packet_send(); 1838 packet_write_wait(); 1839 1840 /* Enable compression now that we have replied if appropriate. */ 1841 if (enable_compression_after_reply) { 1842 enable_compression_after_reply = 0; 1843 packet_start_compression(compression_level); 1844 } 1845 continue; 1846 1847fail: 1848 /* The request failed. */ 1849 packet_start(SSH_SMSG_FAILURE); 1850 packet_send(); 1851 packet_write_wait(); 1852 continue; 1853 1854do_forced_command: 1855 /* 1856 * There is a forced command specified for this login. 1857 * Execute it. 1858 */ 1859 debug("Executing forced command: %.900s", forced_command); 1860 if (have_pty) 1861 do_exec_pty(forced_command, ptyfd, ttyfd, ttyname, pw, term, display, proto, data); 1862 else 1863 do_exec_no_pty(forced_command, pw, display, proto, data); 1864 return; 1865 } 1866} 1867 1868/* 1869 * This is called to fork and execute a command when we have no tty. This 1870 * will call do_child from the child, and server_loop from the parent after 1871 * setting up file descriptors and such. 1872 */ 1873void 1874do_exec_no_pty(const char *command, struct passwd * pw, 1875 const char *display, const char *auth_proto, 1876 const char *auth_data) 1877{ 1878 int pid; 1879 1880#ifdef USE_PIPES 1881 int pin[2], pout[2], perr[2]; 1882 /* Allocate pipes for communicating with the program. */ 1883 if (pipe(pin) < 0 || pipe(pout) < 0 || pipe(perr) < 0) 1884 packet_disconnect("Could not create pipes: %.100s", 1885 strerror(errno)); 1886#else /* USE_PIPES */ 1887 int inout[2], err[2]; 1888 /* Uses socket pairs to communicate with the program. */ 1889 if (socketpair(AF_UNIX, SOCK_STREAM, 0, inout) < 0 || 1890 socketpair(AF_UNIX, SOCK_STREAM, 0, err) < 0) 1891 packet_disconnect("Could not create socket pairs: %.100s", 1892 strerror(errno)); 1893#endif /* USE_PIPES */ 1894 1895 setproctitle("%s@notty", pw->pw_name); 1896 1897 /* Fork the child. */ 1898 if ((pid = fork()) == 0) { 1899 /* Child. Reinitialize the log since the pid has changed. */ 1900 log_init(av0, options.log_level, options.log_facility, log_stderr); 1901 1902 /* 1903 * Create a new session and process group since the 4.4BSD 1904 * setlogin() affects the entire process group. 1905 */ 1906 if (setsid() < 0) 1907 error("setsid failed: %.100s", strerror(errno)); 1908 1909#ifdef USE_PIPES 1910 /* 1911 * Redirect stdin. We close the parent side of the socket 1912 * pair, and make the child side the standard input. 1913 */ 1914 close(pin[1]); 1915 if (dup2(pin[0], 0) < 0) 1916 perror("dup2 stdin"); 1917 close(pin[0]); 1918 1919 /* Redirect stdout. */ 1920 close(pout[0]); 1921 if (dup2(pout[1], 1) < 0) 1922 perror("dup2 stdout"); 1923 close(pout[1]); 1924 1925 /* Redirect stderr. */ 1926 close(perr[0]); 1927 if (dup2(perr[1], 2) < 0) 1928 perror("dup2 stderr"); 1929 close(perr[1]); 1930#else /* USE_PIPES */ 1931 /* 1932 * Redirect stdin, stdout, and stderr. Stdin and stdout will 1933 * use the same socket, as some programs (particularly rdist) 1934 * seem to depend on it. 1935 */ 1936 close(inout[1]); 1937 close(err[1]); 1938 if (dup2(inout[0], 0) < 0) /* stdin */ 1939 perror("dup2 stdin"); 1940 if (dup2(inout[0], 1) < 0) /* stdout. Note: same socket as stdin. */ 1941 perror("dup2 stdout"); 1942 if (dup2(err[0], 2) < 0) /* stderr */ 1943 perror("dup2 stderr"); 1944#endif /* USE_PIPES */ 1945 1946 /* Do processing for the child (exec command etc). */ 1947 do_child(command, pw, NULL, display, auth_proto, auth_data, NULL); 1948 /* NOTREACHED */ 1949 } 1950 if (pid < 0) 1951 packet_disconnect("fork failed: %.100s", strerror(errno)); 1952#ifdef USE_PIPES 1953 /* We are the parent. Close the child sides of the pipes. */ 1954 close(pin[0]); 1955 close(pout[1]); 1956 close(perr[1]); 1957 1958 /* Enter the interactive session. */ 1959 server_loop(pid, pin[1], pout[0], perr[0]); 1960 /* server_loop has closed pin[1], pout[1], and perr[1]. */ 1961#else /* USE_PIPES */ 1962 /* We are the parent. Close the child sides of the socket pairs. */ 1963 close(inout[0]); 1964 close(err[0]); 1965 1966 /* 1967 * Enter the interactive session. Note: server_loop must be able to 1968 * handle the case that fdin and fdout are the same. 1969 */ 1970 server_loop(pid, inout[1], inout[1], err[1]); 1971 /* server_loop has closed inout[1] and err[1]. */ 1972#endif /* USE_PIPES */ 1973} 1974 1975/* 1976 * This is called to fork and execute a command when we have a tty. This 1977 * will call do_child from the child, and server_loop from the parent after 1978 * setting up file descriptors, controlling tty, updating wtmp, utmp, 1979 * lastlog, and other such operations. 1980 */ 1981void 1982do_exec_pty(const char *command, int ptyfd, int ttyfd, 1983 const char *ttyname, struct passwd * pw, const char *term, 1984 const char *display, const char *auth_proto, 1985 const char *auth_data) 1986{ 1987 int pid, fdout; 1988 int ptymaster; 1989 const char *hostname; 1990 time_t last_login_time; 1991 char buf[100], *time_string; 1992 FILE *f; 1993 char line[256]; 1994 struct stat st; 1995 int quiet_login; 1996 struct sockaddr_storage from; 1997 socklen_t fromlen; 1998 struct pty_cleanup_context cleanup_context; 1999 2000 /* Get remote host name. */ 2001 hostname = get_canonical_hostname(); 2002 2003 /* 2004 * Get the time when the user last logged in. Buf will be set to 2005 * contain the hostname the last login was from. 2006 */ 2007 if (!options.use_login) { 2008 last_login_time = get_last_login_time(pw->pw_uid, pw->pw_name, 2009 buf, sizeof(buf)); 2010 } 2011 setproctitle("%s@%s", pw->pw_name, strrchr(ttyname, '/') + 1); 2012 2013 /* Fork the child. */ 2014 if ((pid = fork()) == 0) { 2015 pid = getpid(); 2016 2017 /* Child. Reinitialize the log because the pid has 2018 changed. */ 2019 log_init(av0, options.log_level, options.log_facility, log_stderr); 2020 2021 /* Close the master side of the pseudo tty. */ 2022 close(ptyfd); 2023 2024 /* Make the pseudo tty our controlling tty. */ 2025 pty_make_controlling_tty(&ttyfd, ttyname); 2026 2027 /* Redirect stdin from the pseudo tty. */ 2028 if (dup2(ttyfd, fileno(stdin)) < 0) 2029 error("dup2 stdin failed: %.100s", strerror(errno)); 2030 2031 /* Redirect stdout to the pseudo tty. */ 2032 if (dup2(ttyfd, fileno(stdout)) < 0) 2033 error("dup2 stdin failed: %.100s", strerror(errno)); 2034 2035 /* Redirect stderr to the pseudo tty. */ 2036 if (dup2(ttyfd, fileno(stderr)) < 0) 2037 error("dup2 stdin failed: %.100s", strerror(errno)); 2038 2039 /* Close the extra descriptor for the pseudo tty. */ 2040 close(ttyfd); 2041 2042 /* 2043 * Get IP address of client. This is needed because we want 2044 * to record where the user logged in from. If the 2045 * connection is not a socket, let the ip address be 0.0.0.0. 2046 */ 2047 memset(&from, 0, sizeof(from)); 2048 if (packet_get_connection_in() == packet_get_connection_out()) { 2049 fromlen = sizeof(from); 2050 if (getpeername(packet_get_connection_in(), 2051 (struct sockaddr *) & from, &fromlen) < 0) { 2052 debug("getpeername: %.100s", strerror(errno)); 2053 fatal_cleanup(); 2054 } 2055 } 2056 /* Record that there was a login on that terminal. */ 2057 record_login(pid, ttyname, pw->pw_name, pw->pw_uid, hostname, 2058 (struct sockaddr *)&from); 2059 2060 /* Check if .hushlogin exists. */ 2061 snprintf(line, sizeof line, "%.200s/.hushlogin", pw->pw_dir); 2062 quiet_login = stat(line, &st) >= 0; 2063 2064 /* 2065 * If the user has logged in before, display the time of last 2066 * login. However, don't display anything extra if a command 2067 * has been specified (so that ssh can be used to execute 2068 * commands on a remote machine without users knowing they 2069 * are going to another machine). Login(1) will do this for 2070 * us as well, so check if login(1) is used 2071 */ 2072 if (command == NULL && last_login_time != 0 && !quiet_login && 2073 !options.use_login) { 2074 /* Convert the date to a string. */ 2075 time_string = ctime(&last_login_time); 2076 /* Remove the trailing newline. */ 2077 if (strchr(time_string, '\n')) 2078 *strchr(time_string, '\n') = 0; 2079 /* Display the last login time. Host if displayed 2080 if known. */ 2081 if (strcmp(buf, "") == 0) 2082 printf("Last login: %s\r\n", time_string); 2083 else 2084 printf("Last login: %s from %s\r\n", time_string, buf); 2085 } 2086 /* 2087 * Print /etc/motd unless a command was specified or printing 2088 * it was disabled in server options or login(1) will be 2089 * used. Note that some machines appear to print it in 2090 * /etc/profile or similar. 2091 */ 2092 if (command == NULL && options.print_motd && !quiet_login && 2093 !options.use_login) { 2094 /* Print /etc/motd if it exists. */ 2095 f = fopen("/etc/motd", "r"); 2096 if (f) { 2097 while (fgets(line, sizeof(line), f)) 2098 fputs(line, stdout); 2099 fclose(f); 2100 } 2101 } 2102 /* Do common processing for the child, such as execing the command. */ 2103 do_child(command, pw, term, display, auth_proto, auth_data, ttyname); 2104 /* NOTREACHED */ 2105 } 2106 if (pid < 0) 2107 packet_disconnect("fork failed: %.100s", strerror(errno)); 2108 /* Parent. Close the slave side of the pseudo tty. */ 2109 close(ttyfd); 2110 2111 /* 2112 * Add a cleanup function to clear the utmp entry and record logout 2113 * time in case we call fatal() (e.g., the connection gets closed). 2114 */ 2115 cleanup_context.pid = pid; 2116 cleanup_context.ttyname = ttyname; 2117 fatal_add_cleanup(pty_cleanup_proc, (void *) &cleanup_context); 2118 fatal_remove_cleanup(pty_release_proc, (void *) ttyname); 2119 2120 /* 2121 * Create another descriptor of the pty master side for use as the 2122 * standard input. We could use the original descriptor, but this 2123 * simplifies code in server_loop. The descriptor is bidirectional. 2124 */ 2125 fdout = dup(ptyfd); 2126 if (fdout < 0) 2127 packet_disconnect("dup #1 failed: %.100s", strerror(errno)); 2128 2129 /* we keep a reference to the pty master */ 2130 ptymaster = dup(ptyfd); 2131 if (ptymaster < 0) 2132 packet_disconnect("dup #2 failed: %.100s", strerror(errno)); 2133 2134 /* Enter interactive session. */ 2135 server_loop(pid, ptyfd, fdout, -1); 2136 /* server_loop _has_ closed ptyfd and fdout. */ 2137 2138 /* Cancel the cleanup function. */ 2139 fatal_remove_cleanup(pty_cleanup_proc, (void *) &cleanup_context); 2140 2141 /* Record that the user has logged out. */ 2142 record_logout(pid, ttyname); 2143 2144 /* Release the pseudo-tty. */ 2145 pty_release(ttyname); 2146 2147 /* 2148 * Close the server side of the socket pairs. We must do this after 2149 * the pty cleanup, so that another process doesn't get this pty 2150 * while we're still cleaning up. 2151 */ 2152 if (close(ptymaster) < 0) 2153 error("close(ptymaster): %s", strerror(errno)); 2154} 2155 2156/* 2157 * Sets the value of the given variable in the environment. If the variable 2158 * already exists, its value is overriden. 2159 */ 2160void 2161child_set_env(char ***envp, unsigned int *envsizep, const char *name, 2162 const char *value) 2163{ 2164 unsigned int i, namelen; 2165 char **env; 2166 2167 /* 2168 * Find the slot where the value should be stored. If the variable 2169 * already exists, we reuse the slot; otherwise we append a new slot 2170 * at the end of the array, expanding if necessary. 2171 */ 2172 env = *envp; 2173 namelen = strlen(name); 2174 for (i = 0; env[i]; i++) 2175 if (strncmp(env[i], name, namelen) == 0 && env[i][namelen] == '=') 2176 break; 2177 if (env[i]) { 2178 /* Reuse the slot. */ 2179 xfree(env[i]); 2180 } else { 2181 /* New variable. Expand if necessary. */ 2182 if (i >= (*envsizep) - 1) { 2183 (*envsizep) += 50; 2184 env = (*envp) = xrealloc(env, (*envsizep) * sizeof(char *)); 2185 } 2186 /* Need to set the NULL pointer at end of array beyond the new slot. */ 2187 env[i + 1] = NULL; 2188 } 2189 2190 /* Allocate space and format the variable in the appropriate slot. */ 2191 env[i] = xmalloc(strlen(name) + 1 + strlen(value) + 1); 2192 snprintf(env[i], strlen(name) + 1 + strlen(value) + 1, "%s=%s", name, value); 2193} 2194 2195/* 2196 * Reads environment variables from the given file and adds/overrides them 2197 * into the environment. If the file does not exist, this does nothing. 2198 * Otherwise, it must consist of empty lines, comments (line starts with '#') 2199 * and assignments of the form name=value. No other forms are allowed. 2200 */ 2201void 2202read_environment_file(char ***env, unsigned int *envsize, 2203 const char *filename) 2204{ 2205 FILE *f; 2206 char buf[4096]; 2207 char *cp, *value; 2208 2209 f = fopen(filename, "r"); 2210 if (!f) 2211 return; 2212 2213 while (fgets(buf, sizeof(buf), f)) { 2214 for (cp = buf; *cp == ' ' || *cp == '\t'; cp++) 2215 ; 2216 if (!*cp || *cp == '#' || *cp == '\n') 2217 continue; 2218 if (strchr(cp, '\n')) 2219 *strchr(cp, '\n') = '\0'; 2220 value = strchr(cp, '='); 2221 if (value == NULL) { 2222 fprintf(stderr, "Bad line in %.100s: %.200s\n", filename, buf); 2223 continue; 2224 } 2225 /* Replace the equals sign by nul, and advance value to the value string. */ 2226 *value = '\0'; 2227 value++; 2228 child_set_env(env, envsize, cp, value); 2229 } 2230 fclose(f); 2231} 2232 2233/* 2234 * Performs common processing for the child, such as setting up the 2235 * environment, closing extra file descriptors, setting the user and group 2236 * ids, and executing the command or shell. 2237 */ 2238void 2239do_child(const char *command, struct passwd * pw, const char *term, 2240 const char *display, const char *auth_proto, 2241 const char *auth_data, const char *ttyname) 2242{ 2243 const char *shell, *cp = NULL; 2244 char buf[256]; 2245 FILE *f; 2246 unsigned int envsize, i; 2247 char **env; 2248 extern char **environ; 2249 struct stat st; 2250 char *argv[10]; 2251 2252 f = fopen("/etc/nologin", "r"); 2253 if (f) { 2254 /* /etc/nologin exists. Print its contents and exit. */ 2255 while (fgets(buf, sizeof(buf), f)) 2256 fputs(buf, stderr); 2257 fclose(f); 2258 if (pw->pw_uid != 0) 2259 exit(254); 2260 } 2261 /* Set login name in the kernel. */ 2262 if (setlogin(pw->pw_name) < 0) 2263 error("setlogin failed: %s", strerror(errno)); 2264 2265 /* Set uid, gid, and groups. */ 2266 /* Login(1) does this as well, and it needs uid 0 for the "-h" 2267 switch, so we let login(1) to this for us. */ 2268 if (!options.use_login) { 2269 if (getuid() == 0 || geteuid() == 0) { 2270 if (setgid(pw->pw_gid) < 0) { 2271 perror("setgid"); 2272 exit(1); 2273 } 2274 /* Initialize the group list. */ 2275 if (initgroups(pw->pw_name, pw->pw_gid) < 0) { 2276 perror("initgroups"); 2277 exit(1); 2278 } 2279 endgrent(); 2280 2281 /* Permanently switch to the desired uid. */ 2282 permanently_set_uid(pw->pw_uid); 2283 } 2284 if (getuid() != pw->pw_uid || geteuid() != pw->pw_uid) 2285 fatal("Failed to set uids to %d.", (int) pw->pw_uid); 2286 } 2287 /* 2288 * Get the shell from the password data. An empty shell field is 2289 * legal, and means /bin/sh. 2290 */ 2291 shell = (pw->pw_shell[0] == '\0') ? _PATH_BSHELL : pw->pw_shell; 2292 2293#ifdef AFS 2294 /* Try to get AFS tokens for the local cell. */ 2295 if (k_hasafs()) { 2296 char cell[64]; 2297 2298 if (k_afs_cell_of_file(pw->pw_dir, cell, sizeof(cell)) == 0) 2299 krb_afslog(cell, 0); 2300 2301 krb_afslog(0, 0); 2302 } 2303#endif /* AFS */ 2304 2305 /* Initialize the environment. */ 2306 envsize = 100; 2307 env = xmalloc(envsize * sizeof(char *)); 2308 env[0] = NULL; 2309 2310 if (!options.use_login) { 2311 /* Set basic environment. */ 2312 child_set_env(&env, &envsize, "USER", pw->pw_name); 2313 child_set_env(&env, &envsize, "LOGNAME", pw->pw_name); 2314 child_set_env(&env, &envsize, "HOME", pw->pw_dir); 2315 child_set_env(&env, &envsize, "PATH", _PATH_STDPATH); 2316 2317 snprintf(buf, sizeof buf, "%.200s/%.50s", 2318 _PATH_MAILDIR, pw->pw_name); 2319 child_set_env(&env, &envsize, "MAIL", buf); 2320 2321 /* Normal systems set SHELL by default. */ 2322 child_set_env(&env, &envsize, "SHELL", shell); 2323 } 2324 if (getenv("TZ")) 2325 child_set_env(&env, &envsize, "TZ", getenv("TZ")); 2326 2327 /* Set custom environment options from RSA authentication. */ 2328 while (custom_environment) { 2329 struct envstring *ce = custom_environment; 2330 char *s = ce->s; 2331 int i; 2332 for (i = 0; s[i] != '=' && s[i]; i++); 2333 if (s[i] == '=') { 2334 s[i] = 0; 2335 child_set_env(&env, &envsize, s, s + i + 1); 2336 } 2337 custom_environment = ce->next; 2338 xfree(ce->s); 2339 xfree(ce); 2340 } 2341 2342 snprintf(buf, sizeof buf, "%.50s %d %d", 2343 get_remote_ipaddr(), get_remote_port(), get_local_port()); 2344 child_set_env(&env, &envsize, "SSH_CLIENT", buf); 2345 2346 if (ttyname) 2347 child_set_env(&env, &envsize, "SSH_TTY", ttyname); 2348 if (term) 2349 child_set_env(&env, &envsize, "TERM", term); 2350 if (display) 2351 child_set_env(&env, &envsize, "DISPLAY", display); 2352 2353#ifdef KRB4 2354 { 2355 extern char *ticket; 2356 2357 if (ticket) 2358 child_set_env(&env, &envsize, "KRBTKFILE", ticket); 2359 } 2360#endif /* KRB4 */ 2361 2362 if (xauthfile) 2363 child_set_env(&env, &envsize, "XAUTHORITY", xauthfile); 2364 if (auth_get_socket_name() != NULL) 2365 child_set_env(&env, &envsize, SSH_AUTHSOCKET_ENV_NAME, 2366 auth_get_socket_name()); 2367 2368 /* read $HOME/.ssh/environment. */ 2369 if (!options.use_login) { 2370 snprintf(buf, sizeof buf, "%.200s/.ssh/environment", pw->pw_dir); 2371 read_environment_file(&env, &envsize, buf); 2372 } 2373 if (debug_flag) { 2374 /* dump the environment */ 2375 fprintf(stderr, "Environment:\n"); 2376 for (i = 0; env[i]; i++) 2377 fprintf(stderr, " %.200s\n", env[i]); 2378 } 2379 /* 2380 * Close the connection descriptors; note that this is the child, and 2381 * the server will still have the socket open, and it is important 2382 * that we do not shutdown it. Note that the descriptors cannot be 2383 * closed before building the environment, as we call 2384 * get_remote_ipaddr there. 2385 */ 2386 if (packet_get_connection_in() == packet_get_connection_out()) 2387 close(packet_get_connection_in()); 2388 else { 2389 close(packet_get_connection_in()); 2390 close(packet_get_connection_out()); 2391 } 2392 /* 2393 * Close all descriptors related to channels. They will still remain 2394 * open in the parent. 2395 */ 2396 /* XXX better use close-on-exec? -markus */ 2397 channel_close_all(); 2398 2399 /* 2400 * Close any extra file descriptors. Note that there may still be 2401 * descriptors left by system functions. They will be closed later. 2402 */ 2403 endpwent(); 2404 2405 /* 2406 * Close any extra open file descriptors so that we don\'t have them 2407 * hanging around in clients. Note that we want to do this after 2408 * initgroups, because at least on Solaris 2.3 it leaves file 2409 * descriptors open. 2410 */ 2411 for (i = 3; i < 64; i++) 2412 close(i); 2413 2414 /* Change current directory to the user\'s home directory. */ 2415 if (chdir(pw->pw_dir) < 0) 2416 fprintf(stderr, "Could not chdir to home directory %s: %s\n", 2417 pw->pw_dir, strerror(errno)); 2418 2419 /* 2420 * Must take new environment into use so that .ssh/rc, /etc/sshrc and 2421 * xauth are run in the proper environment. 2422 */ 2423 environ = env; 2424 2425 /* 2426 * Run $HOME/.ssh/rc, /etc/sshrc, or xauth (whichever is found first 2427 * in this order). 2428 */ 2429 if (!options.use_login) { 2430 if (stat(SSH_USER_RC, &st) >= 0) { 2431 if (debug_flag) 2432 fprintf(stderr, "Running /bin/sh %s\n", SSH_USER_RC); 2433 2434 f = popen("/bin/sh " SSH_USER_RC, "w"); 2435 if (f) { 2436 if (auth_proto != NULL && auth_data != NULL) 2437 fprintf(f, "%s %s\n", auth_proto, auth_data); 2438 pclose(f); 2439 } else 2440 fprintf(stderr, "Could not run %s\n", SSH_USER_RC); 2441 } else if (stat(SSH_SYSTEM_RC, &st) >= 0) { 2442 if (debug_flag) 2443 fprintf(stderr, "Running /bin/sh %s\n", SSH_SYSTEM_RC); 2444 2445 f = popen("/bin/sh " SSH_SYSTEM_RC, "w"); 2446 if (f) { 2447 if (auth_proto != NULL && auth_data != NULL) 2448 fprintf(f, "%s %s\n", auth_proto, auth_data); 2449 pclose(f); 2450 } else 2451 fprintf(stderr, "Could not run %s\n", SSH_SYSTEM_RC); 2452 } 2453#ifdef XAUTH_PATH 2454 else { 2455 /* Add authority data to .Xauthority if appropriate. */ 2456 if (auth_proto != NULL && auth_data != NULL) { 2457 if (debug_flag) 2458 fprintf(stderr, "Running %.100s add %.100s %.100s %.100s\n", 2459 XAUTH_PATH, display, auth_proto, auth_data); 2460 2461 f = popen(XAUTH_PATH " -q -", "w"); 2462 if (f) { 2463 fprintf(f, "add %s %s %s\n", display, auth_proto, auth_data); 2464 fclose(f); 2465 } else 2466 fprintf(stderr, "Could not run %s -q -\n", XAUTH_PATH); 2467 } 2468 } 2469#endif /* XAUTH_PATH */ 2470 2471 /* Get the last component of the shell name. */ 2472 cp = strrchr(shell, '/'); 2473 if (cp) 2474 cp++; 2475 else 2476 cp = shell; 2477 } 2478 /* 2479 * If we have no command, execute the shell. In this case, the shell 2480 * name to be passed in argv[0] is preceded by '-' to indicate that 2481 * this is a login shell. 2482 */ 2483 if (!command) { 2484 if (!options.use_login) { 2485 char buf[256]; 2486 2487 /* 2488 * Check for mail if we have a tty and it was enabled 2489 * in server options. 2490 */ 2491 if (ttyname && options.check_mail) { 2492 char *mailbox; 2493 struct stat mailstat; 2494 mailbox = getenv("MAIL"); 2495 if (mailbox != NULL) { 2496 if (stat(mailbox, &mailstat) != 0 || mailstat.st_size == 0) 2497 printf("No mail.\n"); 2498 else if (mailstat.st_mtime < mailstat.st_atime) 2499 printf("You have mail.\n"); 2500 else 2501 printf("You have new mail.\n"); 2502 } 2503 } 2504 /* Start the shell. Set initial character to '-'. */ 2505 buf[0] = '-'; 2506 strncpy(buf + 1, cp, sizeof(buf) - 1); 2507 buf[sizeof(buf) - 1] = 0; 2508 2509 /* Execute the shell. */ 2510 argv[0] = buf; 2511 argv[1] = NULL; 2512 execve(shell, argv, env); 2513 2514 /* Executing the shell failed. */ 2515 perror(shell); 2516 exit(1); 2517 2518 } else { 2519 /* Launch login(1). */ 2520 2521 execl("/usr/bin/login", "login", "-h", get_remote_ipaddr(), 2522 "-p", "-f", "--", pw->pw_name, NULL); 2523 2524 /* Login couldn't be executed, die. */ 2525 2526 perror("login"); 2527 exit(1); 2528 } 2529 } 2530 /* 2531 * Execute the command using the user's shell. This uses the -c 2532 * option to execute the command. 2533 */ 2534 argv[0] = (char *) cp; 2535 argv[1] = "-c"; 2536 argv[2] = (char *) command; 2537 argv[3] = NULL; 2538 execve(shell, argv, env); 2539 perror(shell); 2540 exit(1); 2541} 2542